iPlug2 - C++ Audio Plug-in Framework
Loading...
Searching...
No Matches
IGraphicsNanoVG.cpp
1/*
2 ==============================================================================
3
4 This file is part of the iPlug 2 library. Copyright (C) the iPlug 2 developers.
5
6 See LICENSE.txt for more info.
7
8 ==============================================================================
9*/
10
11#include <cmath>
12
13#include "IGraphicsNanoVG.h"
14#include "ITextEntryControl.h"
15
16#if defined IGRAPHICS_GL
17 #if defined OS_MAC
18 #if defined IGRAPHICS_GL2
19 #define NANOVG_GL2_IMPLEMENTATION
20 #elif defined IGRAPHICS_GL3
21 #include <OpenGL/gl3.h>
22 #define NANOVG_GL3_IMPLEMENTATION
23 #elif defined IGRAPHICS_GLES2
24 #include <libGLESv2/angle_gl.h>
25 #define NANOVG_GLES2_IMPLEMENTATION
26 #elif defined IGRAPHICS_GLES3
27 #include <libGLESv2/angle_gl.h>
28 #define NANOVG_GLES3_IMPLEMENTATION
29 #endif
30 #elif defined OS_IOS
31 #if defined IGRAPHICS_GLES2
32 #include <libGLESv2/angle_gl.h>
33 #define NANOVG_GLES2_IMPLEMENTATION
34 #elif defined IGRAPHICS_GLES3
35 #include <libGLESv2/angle_gl.h>
36 #define NANOVG_GLES3_IMPLEMENTATION
37 #else
38 #error Define either IGRAPHICS_GLES2 or IGRAPHICS_GLES3 for IGRAPHICS_NANOVG with OS_IOS
39 #endif
40 #elif defined OS_WIN
41 #pragma comment(lib, "opengl32.lib")
42 #if defined IGRAPHICS_GL2
43 #define NANOVG_GL2_IMPLEMENTATION
44 #elif defined IGRAPHICS_GL3
45 #define NANOVG_GL3_IMPLEMENTATION
46 #else
47 #error Define either IGRAPHICS_GL2 or IGRAPHICS_GL3 when using IGRAPHICS_GL and IGRAPHICS_NANOVG with OS_WIN
48 #endif
49 #elif defined OS_LINUX
50 #if defined IGRAPHICS_GL2
51 #define NANOVG_GL2_IMPLEMENTATION
52 #elif defined IGRAPHICS_GL3
53 #define NANOVG_GL3_IMPLEMENTATION
54 #else
55 #error "Define either IGRAPHICS_GL2 or IGRAPHICS_GL3 when using IGRAPHICS_NANOVG with OS_LINUX"
56 #endif
57 #elif defined OS_WEB
58 #if defined IGRAPHICS_GLES2
59 #define NANOVG_GLES2_IMPLEMENTATION
60 #elif defined IGRAPHICS_GLES3
61 #define NANOVG_GLES3_IMPLEMENTATION
62 #else
63 #error Define either IGRAPHICS_GLES2 or IGRAPHICS_GLES3 when using IGRAPHICS_GL and IGRAPHICS_NANOVG with OS_WEB
64 #endif
65 #endif
66 #include "nanovg_gl.h"
67 #include "nanovg_gl_utils.h"
68#elif defined IGRAPHICS_METAL
69 #include "nanovg_mtl.h"
70 #if defined OS_MAC
71 //even though this is a .cpp we are in an objc(pp) compilation unit
72 #import <Metal/Metal.h>
73 #endif
74#else
75 #error you must define either IGRAPHICS_GL2, IGRAPHICS_GLES2 etc or IGRAPHICS_METAL when using IGRAPHICS_NANOVG
76#endif
77
78#include <string>
79#include <map>
80
81using namespace iplug;
82using namespace igraphics;
83
84#pragma mark - Private Classes and Structs
85
87{
88public:
89 Bitmap(NVGcontext* pContext, const char* path, double sourceScale, int nvgImageID, bool shared = false);
90 Bitmap(IGraphicsNanoVG* pGraphics, NVGcontext* pContext, int width, int height, float scale, float drawScale);
91 Bitmap(NVGcontext* pContext, int width, int height, const uint8_t* pData, float scale, float drawScale);
92 virtual ~Bitmap();
93 NVGframebuffer* GetFBO() const { return mFBO; }
94private:
95 IGraphicsNanoVG *mGraphics = nullptr;
96 NVGcontext* mVG;
97 NVGframebuffer* mFBO = nullptr;
98 bool mSharedTexture = false;
99};
100
101IGraphicsNanoVG::Bitmap::Bitmap(NVGcontext* pContext, const char* path, double sourceScale, int nvgImageID, bool shared)
102{
103 assert(nvgImageID > 0);
104
105 mVG = pContext;
106 mSharedTexture = shared;
107 int w = 0, h = 0;
108 nvgImageSize(mVG, nvgImageID, &w, &h);
109
110 SetBitmap(nvgImageID, w, h, sourceScale, 1.f);
111}
112
113IGraphicsNanoVG::Bitmap::Bitmap(IGraphicsNanoVG* pGraphics, NVGcontext* pContext, int width, int height, float scale, float drawScale)
114{
115 assert(width > 0 && height > 0);
116 mGraphics = pGraphics;
117 mVG = pContext;
118 mFBO = nvgCreateFramebuffer(pContext, width, height, 0);
119
120 nvgBindFramebuffer(mFBO);
121
122#ifdef IGRAPHICS_METAL
123 mnvgClearWithColor(mVG, nvgRGBAf(0, 0, 0, 0));
124#else
125 glViewport(0, 0, width, height);
126 glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
127 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
128#endif
129 nvgBeginFrame(mVG, width, height, 1.f);
130 nvgEndFrame(mVG);
131
132 SetBitmap(mFBO->image, width, height, scale, drawScale);
133}
134
135IGraphicsNanoVG::Bitmap::Bitmap(NVGcontext* pContext, int width, int height, const uint8_t* pData, float scale, float drawScale)
136{
137 int idx = nvgCreateImageRGBA(pContext, width, height, 0, pData);
138 mVG = pContext;
139 SetBitmap(idx, width, height, scale, drawScale);
140}
141
142IGraphicsNanoVG::Bitmap::~Bitmap()
143{
144 if(!mSharedTexture)
145 {
146 if(mFBO)
147 mGraphics->DeleteFBO(mFBO);
148 else
149 nvgDeleteImage(mVG, GetBitmap());
150 }
151}
152
153// Fonts
154static StaticStorage<IFontData> sFontCache;
155
156extern std::map<std::string, MTLTexturePtr> gTextureMap;
157
158// Retrieving pixels
159static void nvgReadPixels(NVGcontext* pContext, int image, int x, int y, int width, int height, void* pData)
160{
161#if defined(IGRAPHICS_GL)
162 glReadPixels(x, y, width, height, GL_RGBA, GL_UNSIGNED_BYTE, pData);
163#elif defined(IGRAPHICS_METAL)
164 mnvgReadPixels(pContext, image, x, y, width, height, pData);
165#endif
166}
167
168#pragma mark - Utilities
169
170BEGIN_IPLUG_NAMESPACE
171BEGIN_IGRAPHICS_NAMESPACE
172
173NVGcolor NanoVGColor(const IColor& color, const IBlend* pBlend)
174{
175 NVGcolor c;
176 c.r = (float) color.R / 255.0f;
177 c.g = (float) color.G / 255.0f;
178 c.b = (float) color.B / 255.0f;
179 c.a = (BlendWeight(pBlend) * color.A) / 255.0f;
180 return c;
181}
182
183void NanoVGRect(NVGcontext* pContext, const IRECT& r)
184{
185 nvgRect(pContext, r.L, r.T, r.W(), r.H());
186}
187
188void NanoVGSetBlendMode(NVGcontext* pContext, const IBlend* pBlend)
189{
190 if (!pBlend)
191 {
192 nvgGlobalCompositeOperation(pContext, NVG_SOURCE_OVER);
193 return;
194 }
195
196 switch (pBlend->mMethod)
197 {
198 case EBlend::SrcOver: nvgGlobalCompositeOperation(pContext, NVG_SOURCE_OVER); break;
199 case EBlend::SrcIn: nvgGlobalCompositeOperation(pContext, NVG_SOURCE_IN); break;
200 case EBlend::SrcOut: nvgGlobalCompositeOperation(pContext, NVG_SOURCE_OUT); break;
201 case EBlend::SrcAtop: nvgGlobalCompositeOperation(pContext, NVG_ATOP); break;
202 case EBlend::DstOver: nvgGlobalCompositeOperation(pContext, NVG_DESTINATION_OVER); break;
203 case EBlend::DstIn: nvgGlobalCompositeOperation(pContext, NVG_DESTINATION_IN); break;
204 case EBlend::DstOut: nvgGlobalCompositeOperation(pContext, NVG_DESTINATION_OUT); break;
205 case EBlend::DstAtop: nvgGlobalCompositeOperation(pContext, NVG_DESTINATION_ATOP); break;
206 case EBlend::Add: nvgGlobalCompositeBlendFunc(pContext, NVG_SRC_ALPHA, NVG_DST_ALPHA); break;
207 case EBlend::XOR: nvgGlobalCompositeOperation(pContext, NVG_XOR); break;
208 }
209}
210
211NVGpaint NanoVGPaint(NVGcontext* pContext, const IPattern& pattern, const IBlend* pBlend)
212{
213 assert(pattern.NStops() > 0);
214
215 double s[2], e[2];
216
217 NVGcolor icol = NanoVGColor(pattern.GetStop(0).mColor, pBlend);
218 NVGcolor ocol = NanoVGColor(pattern.GetStop(pattern.NStops() - 1).mColor, pBlend);
219
220 // Invert transform
221 IMatrix inverse = IMatrix(pattern.mTransform).Invert();
222 inverse.TransformPoint(s[0], s[1], 0.0, 0.0);
223
224 if (pattern.mType == EPatternType::Radial)
225 {
226 return nvgRadialGradient(pContext, s[0], s[1], inverse.mXX * pattern.GetStop(0).mOffset, inverse.mXX, icol, ocol);
227 }
228 else
229 {
230 inverse.TransformPoint(e[0], e[1], 0.0, 1.0);
231
232 return nvgLinearGradient(pContext, s[0], s[1], e[0], e[1], icol, ocol);
233 }
234}
235
236END_IGRAPHICS_NAMESPACE
237END_IPLUG_NAMESPACE
238
239#pragma mark -
240
241IGraphicsNanoVG::IGraphicsNanoVG(IGEditorDelegate& dlg, int w, int h, int fps, float scale)
242: IGraphics(dlg, w, h, fps, scale)
243{
244 DBGMSG("IGraphics NanoVG @ %i FPS\n", fps);
245 StaticStorage<IFontData>::Accessor storage(sFontCache);
246 storage.Retain();
247}
248
249IGraphicsNanoVG::~IGraphicsNanoVG()
250{
251 StaticStorage<IFontData>::Accessor storage(sFontCache);
252 storage.Release();
253 ClearFBOStack();
254}
255
257{
258#if defined IGRAPHICS_METAL
259 return "NanoVG | Metal";
260#else
261 #if defined OS_WEB
262 return "NanoVG | WebGL";
263 #else
264 #if defined IGRAPHICS_GL2
265 return "NanoVG | GL2";
266 #elif defined IGRAPHICS_GL3
267 return "NanoVG | GL3";
268 #elif defined IGRAPHICS_GLES2
269 return "NanoVG | GLES2";
270 #elif defined IGRAPHICS_GLES3
271 return "NanoVG | GLES3";
272 #endif
273 #endif
274#endif
275}
276
278{
279 char extLower[32];
280 ToLower(extLower, ext);
281 return (strstr(extLower, "png") != nullptr) || (strstr(extLower, "jpg") != nullptr) || (strstr(extLower, "jpeg") != nullptr);
282}
283
284IBitmap IGraphicsNanoVG::LoadBitmap(const char* name, int nStates, bool framesAreHorizontal, int targetScale)
285{
286 if (targetScale == 0)
287 targetScale = GetRoundedScreenScale();
288
289 // NanoVG does not use the global static cache, since bitmaps are textures linked to a context
290 StaticStorage<APIBitmap>::Accessor storage(mBitmapCache);
291 APIBitmap* pAPIBitmap = storage.Find(name, targetScale);
292
293 // If the bitmap is not already cached at the targetScale
294 if (!pAPIBitmap)
295 {
296 const char* ext = name + strlen(name) - 1;
297 while (ext >= name && *ext != '.') --ext;
298 ++ext;
299
300 WDL_String fullPathOrResourceID;
301 int sourceScale = 0;
302 EResourceLocation resourceFound = SearchImageResource(name, ext, fullPathOrResourceID, targetScale, sourceScale);
303
304 bool bitmapTypeSupported = BitmapExtSupported(ext); // KTX textures pass this test (if ext is .ktx.png)
305
306 if(resourceFound == EResourceLocation::kNotFound || !bitmapTypeSupported)
307 {
308 assert(0 && "Bitmap not found");
309 return IBitmap(); // return invalid IBitmap
310 }
311
312 pAPIBitmap = LoadAPIBitmap(fullPathOrResourceID.Get(), sourceScale, resourceFound, ext);
313
314 storage.Add(pAPIBitmap, name, sourceScale);
315
316 assert(pAPIBitmap && "Bitmap not loaded");
317 }
318
319 return IBitmap(pAPIBitmap, nStates, framesAreHorizontal, name);
320}
321
322APIBitmap* IGraphicsNanoVG::LoadAPIBitmap(const char* fileNameOrResID, int scale, EResourceLocation location, const char* ext)
323{
324 int idx = 0;
325 int nvgImageFlags = 0;
326
327 // Preloaded textures are only supported with Metal, not ANGLE/GLES
328#if defined OS_IOS && defined IGRAPHICS_METAL
329 if (location == EResourceLocation::kPreloadedTexture)
330 {
331 idx = mnvgCreateImageFromHandle(mVG, gTextureMap[fileNameOrResID], nvgImageFlags);
332 }
333 else
334#endif
335
336#ifdef OS_WIN
337 if (location == EResourceLocation::kWinBinary)
338 {
339 const void* pResData = nullptr;
340
341 int size = 0;
342 pResData = LoadWinResource(fileNameOrResID, ext, size, GetWinModuleHandle());
343
344 if (pResData)
345 {
346 ScopedGLContext scopedGLCtx {this};
347 idx = nvgCreateImageMem(mVG, nvgImageFlags, (unsigned char*) pResData, size);
348 }
349 }
350 else
351#endif
352 if (location == EResourceLocation::kAbsolutePath)
353 {
354 ScopedGLContext scopedGLCtx {this};
355 idx = nvgCreateImage(mVG, fileNameOrResID, nvgImageFlags);
356 }
357
358 return new Bitmap(mVG, fileNameOrResID, scale, idx, location == EResourceLocation::kPreloadedTexture);
359}
360
361APIBitmap* IGraphicsNanoVG::LoadAPIBitmap(const char* name, const void* pData, int dataSize, int scale)
362{
363 StaticStorage<APIBitmap>::Accessor storage(mBitmapCache);
364 APIBitmap* pBitmap = storage.Find(name, scale);
365
366 if (!pBitmap)
367 {
368 int idx = 0;
369 int nvgImageFlags = 0;
370
371 {
372 ScopedGLContext scopedGLCtx {this};
373 idx = nvgCreateImageMem(mVG, nvgImageFlags, (unsigned char*)pData, dataSize);
374 }
375
376 pBitmap = new Bitmap(mVG, name, scale, idx, false);
377
378 storage.Add(pBitmap, name, scale);
379 }
380
381 return pBitmap;
382}
383
384APIBitmap* IGraphicsNanoVG::CreateAPIBitmap(int width, int height, float scale, double drawScale, bool cacheable)
385{
386 if (mInDraw)
387 {
388 nvgEndFrame(mVG);
389 }
390
391 APIBitmap* pAPIBitmap = new Bitmap(this, mVG, width, height, scale, drawScale);
392
393 if (mInDraw)
394 {
395 nvgBindFramebuffer(mMainFrameBuffer); // begin main frame buffer update
396 nvgBeginFrame(mVG, WindowWidth(), WindowHeight(), GetScreenScale());
397 }
398
399 return pAPIBitmap;
400}
401
402void IGraphicsNanoVG::GetLayerBitmapData(const ILayerPtr& layer, RawBitmapData& data)
403{
404 const APIBitmap* pBitmap = layer->GetAPIBitmap();
405 int size = pBitmap->GetWidth() * pBitmap->GetHeight() * 4;
406
407 data.Resize(size);
408
409 if (data.GetSize() >= size)
410 {
411 PushLayer(layer.get());
412 nvgReadPixels(mVG, pBitmap->GetBitmap(), 0, 0, pBitmap->GetWidth(), pBitmap->GetHeight(), data.Get());
413 PopLayer();
414 }
415}
416
417void IGraphicsNanoVG::ApplyShadowMask(ILayerPtr& layer, RawBitmapData& mask, const IShadow& shadow)
418{
419 const APIBitmap* pBitmap = layer->GetAPIBitmap();
420 int width = pBitmap->GetWidth();
421 int height = pBitmap->GetHeight();
422 int size = width * height * 4;
423
424 if (mask.GetSize() >= size)
425 {
426 if (!shadow.mDrawForeground)
427 {
428 PushLayer(layer.get());
429 nvgGlobalCompositeBlendFunc(mVG, NVG_ZERO, NVG_ZERO);
430 PathRect(layer->Bounds());
431 nvgFillColor(mVG, NanoVGColor(COLOR_TRANSPARENT));
432 nvgFill(mVG);
433 PopLayer();
434 }
435
436 IRECT bounds(layer->Bounds());
437
438 Bitmap maskRawBitmap(mVG, width, height, mask.Get(), pBitmap->GetScale(), pBitmap->GetDrawScale());
439 APIBitmap* shadowBitmap = CreateAPIBitmap(width, height, pBitmap->GetScale(), pBitmap->GetDrawScale());
440 IBitmap tempLayerBitmap(shadowBitmap, 1, false);
441 IBitmap maskBitmap(&maskRawBitmap, 1, false);
442 ILayer shadowLayer(shadowBitmap, layer->Bounds(), nullptr, IRECT());
443
445 PushLayer(layer.get());
446 PushLayer(&shadowLayer);
447 DrawBitmap(maskBitmap, bounds, 0, 0, nullptr);
448 IBlend blend1(EBlend::SrcIn, 1.0);
449 PathRect(layer->Bounds());
450 PathTransformTranslate(-shadow.mXOffset, -shadow.mYOffset);
451 PathFill(shadow.mPattern, IFillOptions(), &blend1);
452 PopLayer();
453 IBlend blend2(EBlend::DstOver, shadow.mOpacity);
454 bounds.Translate(shadow.mXOffset, shadow.mYOffset);
455 DrawBitmap(tempLayerBitmap, bounds, 0, 0, &blend2);
456 PopLayer();
458 }
459}
460
462{
463#if defined IGRAPHICS_METAL
464 mVG = nvgCreateContext(pContext, NVG_ANTIALIAS | NVG_TRIPLE_BUFFER); //TODO: NVG_STENCIL_STROKES currently has issues
465#else
466 mVG = nvgCreateContext(NVG_ANTIALIAS /*| NVG_STENCIL_STROKES*/);
467#endif
468
469 if (mVG == nullptr)
470 DBGMSG("Could not init nanovg.\n");
471}
472
474{
475 // need to remove all the controls to free framebuffers, before deleting context
477
478 StaticStorage<APIBitmap>::Accessor storage(mBitmapCache);
479 storage.Clear();
480
481 if(mMainFrameBuffer != nullptr)
482 nvgDeleteFramebuffer(mMainFrameBuffer);
483
484 mMainFrameBuffer = nullptr;
485
486 if(mVG)
487 nvgDeleteContext(mVG);
488
489 mVG = nullptr;
490}
491
493{
494 ScopedGLContext scopedGLCtx {this};
495
496 if (mMainFrameBuffer != nullptr)
497 {
498 nvgDeleteFramebuffer(mMainFrameBuffer);
499 mMainFrameBuffer = nullptr;
500 }
501
502 if (mVG)
503 {
504#if defined OS_LINUX && defined IGRAPHICS_GL
505 // Flush and sync all pending GL commands, and drain any accumulated GL
506 // errors, before creating the FBO. On llvmpipe/Xwayland, NanoVG shader
507 // setup and font loading leave stale GL error state that causes
508 // glCheckFramebufferStatus to fail unless cleared first.
509 glFinish();
510 while (glGetError() != GL_NO_ERROR) {}
511#endif
512 int w = (int)(WindowWidth() * GetScreenScale());
513 int h = (int)(WindowHeight() * GetScreenScale());
514 mMainFrameBuffer = nvgCreateFramebuffer(mVG, w, h, 0);
515
516 if (mMainFrameBuffer == nullptr)
517 DBGMSG("Could not init FBO (w=%d h=%d).\n", w, h);
518 }
519}
520
522{
523 mInDraw = true;
524 IGraphics::BeginFrame(); // start perf graph timing
525
526#ifdef IGRAPHICS_GL
527 glViewport(0, 0, WindowWidth() * GetScreenScale(), WindowHeight() * GetScreenScale());
528 glClearColor(0.f, 0.f, 0.f, 0.f);
529 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
530 #if defined OS_MAC || defined OS_IOS
531 glGetIntegerv(GL_FRAMEBUFFER_BINDING, &mInitialFBO); // stash apple fbo
532 #endif
533#endif
534
535 nvgBindFramebuffer(mMainFrameBuffer); // begin main frame buffer update
536 nvgBeginFrame(mVG, WindowWidth(), WindowHeight(), GetScreenScale());
537}
538
540{
541 nvgEndFrame(mVG); // end main frame buffer update
542
543 // When the FBO is unavailable (e.g. llvmpipe/Xwayland software renderer),
544 // BeginFrame rendered directly to the window framebuffer, so no compositing
545 // pass is needed. Skip the second nvgBeginFrame/EndFrame entirely.
546 if (mMainFrameBuffer == nullptr)
547 {
548 mInDraw = false;
549 ClearFBOStack();
550 return;
551 }
552
553 nvgBindFramebuffer(nullptr);
554 nvgBeginFrame(mVG, WindowWidth(), WindowHeight(), GetScreenScale());
555
556 NVGpaint img = nvgImagePattern(mVG, 0, 0, WindowWidth(), WindowHeight(), 0, mMainFrameBuffer->image, 1.0f);
557
558 nvgSave(mVG);
559 nvgResetTransform(mVG);
560 nvgTranslate(mVG, mXTranslation, mYTranslation);
561 nvgBeginPath(mVG);
562 nvgRect(mVG, 0, 0, WindowWidth(), WindowHeight());
563 nvgFillPaint(mVG, img);
564 nvgFill(mVG);
565 nvgRestore(mVG);
566
567#if (defined OS_MAC || defined OS_IOS) && defined IGRAPHICS_GL
568 glBindFramebuffer(GL_FRAMEBUFFER, mInitialFBO); // restore apple fbo
569#endif
570
571 nvgEndFrame(mVG);
572
573 mInDraw = false;
574 ClearFBOStack();
575}
576
577void IGraphicsNanoVG::DrawBitmap(const IBitmap& bitmap, const IRECT& dest, int srcX, int srcY, const IBlend* pBlend)
578{
579 APIBitmap* pAPIBitmap = bitmap.GetAPIBitmap();
580
581 assert(pAPIBitmap);
582
583 // First generate a scaled image paint
584 NVGpaint imgPaint;
585 double scale = 1.0 / (pAPIBitmap->GetScale() * pAPIBitmap->GetDrawScale());
586
587 nvgTransformScale(imgPaint.xform, scale, scale);
588
589 imgPaint.xform[4] = dest.L - srcX;
590 imgPaint.xform[5] = dest.T - srcY;
591 imgPaint.extent[0] = bitmap.W() * bitmap.GetScale();
592 imgPaint.extent[1] = bitmap.H() * bitmap.GetScale();
593 imgPaint.image = pAPIBitmap->GetBitmap();
594 imgPaint.radius = imgPaint.feather = 0.f;
595 imgPaint.innerColor = imgPaint.outerColor = nvgRGBAf(1, 1, 1, BlendWeight(pBlend));
596
597 // Now draw
598
599 nvgBeginPath(mVG); // Clears any existing path
600 nvgRect(mVG, dest.L, dest.T, dest.W(), dest.H());
601 nvgFillPaint(mVG, imgPaint);
602 NanoVGSetBlendMode(mVG, pBlend);
603 nvgFill(mVG);
604 nvgGlobalCompositeOperation(mVG, NVG_SOURCE_OVER);
605 nvgBeginPath(mVG); // Clears the bitmap rect from the path state
606}
607
609{
610 nvgBeginPath(mVG);
611}
612
614{
615 nvgClosePath(mVG);
616}
617
618void IGraphicsNanoVG::PathArc(float cx, float cy, float r, float a1, float a2, EWinding winding)
619{
620 nvgArc(mVG, cx, cy, r, DegToRad(a1 - 90.f), DegToRad(a2 - 90.f), winding == EWinding::CW ? NVG_CW : NVG_CCW);
621}
622
623void IGraphicsNanoVG::PathMoveTo(float x, float y)
624{
625 nvgMoveTo(mVG, x, y);
626}
627
628void IGraphicsNanoVG::PathLineTo(float x, float y)
629{
630 nvgLineTo(mVG, x, y);
631}
632
633void IGraphicsNanoVG::PathCubicBezierTo(float c1x, float c1y, float c2x, float c2y, float x2, float y2)
634{
635 nvgBezierTo(mVG, c1x, c1y, c2x, c2y, x2, y2);
636}
637
638void IGraphicsNanoVG::PathQuadraticBezierTo(float cx, float cy, float x2, float y2)
639{
640 nvgQuadTo(mVG, cx, cy, x2, y2);
641}
642
644{
645 nvgPathWinding(mVG, clockwise ? NVG_CW : NVG_CCW);
646}
647
649{
650 return COLOR_BLACK; //TODO:
651}
652
653void IGraphicsNanoVG::PrepareAndMeasureText(const IText& text, const char* str, IRECT& r, double& x, double & y) const
654{
655 float fbounds[4];
656
657 assert(nvgFindFont(mVG, text.mFont) != -1 && "No font found - did you forget to load it?");
658
659 nvgFontBlur(mVG, 0);
660 nvgFontSize(mVG, text.mSize);
661 nvgFontFace(mVG, text.mFont);
662
663 int align = 0;
664
665 switch (text.mAlign)
666 {
667 case EAlign::Near: align = NVG_ALIGN_LEFT; x = r.L; break;
668 case EAlign::Center: align = NVG_ALIGN_CENTER; x = r.MW(); break;
669 case EAlign::Far: align = NVG_ALIGN_RIGHT; x = r.R; break;
670 }
671
672 switch (text.mVAlign)
673 {
674 case EVAlign::Top: align |= NVG_ALIGN_TOP; y = r.T; break;
675 case EVAlign::Middle: align |= NVG_ALIGN_MIDDLE; y = r.MH(); break;
676 case EVAlign::Bottom: align |= NVG_ALIGN_BOTTOM; y = r.B; break;
677 }
678
679 nvgTextAlign(mVG, align);
680 nvgTextBounds(mVG, x, y, str, NULL, fbounds);
681
682 r = IRECT(fbounds[0], fbounds[1], fbounds[2], fbounds[3]);
683}
684
685float IGraphicsNanoVG::DoMeasureText(const IText& text, const char* str, IRECT& bounds) const
686{
687 IRECT r = bounds;
688 double x, y;
689 PrepareAndMeasureText(text, str, bounds, x, y);
690 DoMeasureTextRotation(text, r, bounds);
691
692 return bounds.W();
693}
694
695void IGraphicsNanoVG::DoDrawText(const IText& text, const char* str, const IRECT& bounds, const IBlend* pBlend)
696{
697 IRECT measured = bounds;
698 double x, y;
699
700 PrepareAndMeasureText(text, str, measured, x, y);
702 DoTextRotation(text, bounds, measured);
703 nvgFillColor(mVG, NanoVGColor(text.mFGColor, pBlend));
704 NanoVGSetBlendMode(mVG, pBlend);
705 nvgText(mVG, x, y, str, NULL);
706 nvgGlobalCompositeOperation(mVG, NVG_SOURCE_OVER);
708}
709
710void IGraphicsNanoVG::PathStroke(const IPattern& pattern, float thickness, const IStrokeOptions& options, const IBlend* pBlend)
711{
712 // First set options
713 switch (options.mCapOption)
714 {
715 case ELineCap::Butt: nvgLineCap(mVG, NVG_BUTT); break;
716 case ELineCap::Round: nvgLineCap(mVG, NVG_ROUND); break;
717 case ELineCap::Square: nvgLineCap(mVG, NVG_SQUARE); break;
718 }
719
720 switch (options.mJoinOption)
721 {
722 case ELineJoin::Miter: nvgLineJoin(mVG, NVG_MITER); break;
723 case ELineJoin::Round: nvgLineJoin(mVG, NVG_ROUND); break;
724 case ELineJoin::Bevel: nvgLineJoin(mVG, NVG_BEVEL); break;
725 }
726
727 nvgMiterLimit(mVG, options.mMiterLimit);
728 nvgStrokeWidth(mVG, thickness);
729
730 // NanoVG does not support dashed paths
731 if (pattern.mType == EPatternType::Solid)
732 nvgStrokeColor(mVG, NanoVGColor(pattern.GetStop(0).mColor, pBlend));
733 else
734 nvgStrokePaint(mVG, NanoVGPaint(mVG, pattern, pBlend));
735
736 nvgPathWinding(mVG, NVG_CCW);
737 NanoVGSetBlendMode(mVG, pBlend);
738 nvgStroke(mVG);
739 nvgGlobalCompositeOperation(mVG, NVG_SOURCE_OVER);
740
741 if (!options.mPreserve)
742 nvgBeginPath(mVG); // Clears the path state
743}
744
745void IGraphicsNanoVG::PathFill(const IPattern& pattern, const IFillOptions& options, const IBlend* pBlend)
746{
747 switch(options.mFillRule)
748 {
749 // This concept of fill vs. even/odd winding does not really translate to nanovg.
750 // Instead the caller is responsible for settting winding correctly for each subpath
751 // based on whether it's a solid (NVG_CCW) or hole (NVG_CW).
752 case EFillRule::Winding:
753 nvgPathWinding(mVG, NVG_CCW);
754 break;
755 case EFillRule::EvenOdd:
756 nvgPathWinding(mVG, NVG_CW);
757 break;
758 case EFillRule::Preserve:
759 // don't set a winding rule for the path, to preserve individual windings on subpaths
760 default:
761 break;
762 }
763
764 if (pattern.mType == EPatternType::Solid)
765 nvgFillColor(mVG, NanoVGColor(pattern.GetStop(0).mColor, pBlend));
766 else
767 nvgFillPaint(mVG, NanoVGPaint(mVG, pattern, pBlend));
768
769 NanoVGSetBlendMode(mVG, pBlend);
770 nvgFill(mVG);
771 nvgGlobalCompositeOperation(mVG, NVG_SOURCE_OVER);
772
773 if (!options.mPreserve)
774 nvgBeginPath(mVG); // Clears the path state
775}
776
777bool IGraphicsNanoVG::LoadAPIFont(const char* fontID, const PlatformFontPtr& font)
778{
779 StaticStorage<IFontData>::Accessor storage(sFontCache);
780 IFontData* cached = storage.Find(fontID);
781
782 if (cached)
783 {
784 nvgCreateFontFaceMem(mVG, fontID, cached->Get(), cached->GetSize(), cached->GetFaceIdx(), 0);
785 return true;
786 }
787
788 IFontDataPtr data = font->GetFontData();
789
790 if (data->IsValid() && nvgCreateFontFaceMem(mVG, fontID, data->Get(), data->GetSize(), data->GetFaceIdx(), 0) != -1)
791 {
792 storage.Add(data.release(), fontID);
793 return true;
794 }
795
796 return false;
797}
798
799void IGraphicsNanoVG::UpdateLayer()
800{
801 if (mLayers.empty())
802 {
803 nvgEndFrame(mVG);
804#ifdef IGRAPHICS_GL
805 glViewport(0, 0, WindowWidth() * GetScreenScale(), WindowHeight() * GetScreenScale());
806#endif
807 nvgBindFramebuffer(mMainFrameBuffer);
808 nvgBeginFrame(mVG, WindowWidth(), WindowHeight(), GetScreenScale());
809 }
810 else
811 {
812 nvgEndFrame(mVG);
813#ifdef IGRAPHICS_GL
814 const double scale = GetBackingPixelScale();
815 glViewport(0, 0, mLayers.top()->Bounds().W() * scale, mLayers.top()->Bounds().H() * scale);
816#endif
817 nvgBindFramebuffer(dynamic_cast<const Bitmap*>(mLayers.top()->GetAPIBitmap())->GetFBO());
818 nvgBeginFrame(mVG, mLayers.top()->Bounds().W() * GetDrawScale(), mLayers.top()->Bounds().H() * GetDrawScale(), GetScreenScale());
819 }
820}
821
822void IGraphicsNanoVG::PathTransformSetMatrix(const IMatrix& m)
823{
824 double xTranslate = 0.0;
825 double yTranslate = 0.0;
826
827 if (!mLayers.empty())
828 {
829 IRECT bounds = mLayers.top()->Bounds();
830
831 xTranslate = -bounds.L;
832 yTranslate = -bounds.T;
833 }
834
835 nvgResetTransform(mVG);
836 nvgScale(mVG, GetDrawScale(), GetDrawScale());
837 nvgTranslate(mVG, xTranslate, yTranslate);
838 nvgTransform(mVG, m.mXX, m.mYX, m.mXY, m.mYY, m.mTX, m.mTY);
839}
840
841void IGraphicsNanoVG::SetClipRegion(const IRECT& r)
842{
843 nvgScissor(mVG, r.L, r.T, r.W(), r.H());
844}
845
846void IGraphicsNanoVG::DrawDottedLine(const IColor& color, float x1, float y1, float x2, float y2, const IBlend* pBlend, float thickness, float dashLen)
847{
848 const float xd = x1 - x2;
849 const float yd = y1 - y2;
850 const float len = std::sqrt(xd * xd + yd * yd);
851
852 const float segs = std::round(len / dashLen);
853 const float incr = 1.f / segs;
854
855 float xs = x1;
856 float ys = y1;
857
858 PathMoveTo(xs, ys);
859
860 for (int i = 1; i < static_cast<int>(segs); i+=2)
861 {
862 float progress = incr * static_cast<float>(i);
863
864 float xe = x1 + progress * (x2 - x1);
865 float ye = y1 + progress * (y2 - y1);
866
867 PathLineTo(xe, ye);
868
869 progress += incr;
870
871 xs = x1 + progress * (x2 - x1);
872 ys = y1 + progress * (y2 - y1);
873
874 PathMoveTo(xs, ys);
875 }
876
877 PathStroke(color, thickness, IStrokeOptions(), pBlend);
878}
879
880void IGraphicsNanoVG::DrawDottedRect(const IColor& color, const IRECT& bounds, const IBlend* pBlend, float thickness, float dashLen)
881{
882 const int xsegs = static_cast<int>(std::ceil(bounds.W() / (dashLen * 2.f)));
883 const int ysegs = static_cast<int>(std::ceil(bounds.H() / (dashLen * 2.f)));
884
885 float x1 = bounds.L;
886 float y1 = bounds.T;
887
888 float x2 = x1;
889 float y2 = y1;
890
891 PathMoveTo(x1, y1);
892
893 for(int j = 0; j < 2; j++)
894 {
895 for (int i = 0; i < xsegs; i++)
896 {
897 x2 = Clip(x1 + dashLen, bounds.L, bounds.R);
898 PathLineTo(x2, y2);
899 x1 = Clip(x2 + dashLen, bounds.L, bounds.R);
900 PathMoveTo(x1, y1);
901 }
902
903 x2 = x1;
904
905 for (int i = 0; i < ysegs; i++)
906 {
907 y2 = Clip(y1 + dashLen, bounds.T, bounds.B);
908 PathLineTo(x2, y2);
909 y1 = Clip(y2 + dashLen, bounds.T, bounds.B);
910 PathMoveTo(x1, y1);
911 }
912
913 y2 = y1;
914
915 dashLen = -dashLen;
916 }
917
918 PathStroke(color, thickness, IStrokeOptions(), pBlend);
919}
920
921void IGraphicsNanoVG::DeleteFBO(NVGframebuffer* pBuffer)
922{
923 if (!mInDraw)
924 nvgDeleteFramebuffer(pBuffer);
925 else
926 {
927 WDL_MutexLock lock(&mFBOMutex);
928 mFBOStack.push(pBuffer);
929 }
930}
931
932void IGraphicsNanoVG::ClearFBOStack()
933{
934 WDL_MutexLock lock(&mFBOMutex);
935 while (!mFBOStack.empty())
936 {
937 nvgDeleteFramebuffer(mFBOStack.top());
938 mFBOStack.pop();
939 }
940}
941
942void IGraphicsNanoVG::DrawFastDropShadow(const IRECT& innerBounds, const IRECT& outerBounds, float xyDrop, float roundness, float blur, IBlend* pBlend)
943{
944 NVGpaint shadowPaint = nvgBoxGradient(mVG, innerBounds.L + xyDrop, innerBounds.T + xyDrop, innerBounds.W(), innerBounds.H(), roundness, blur, NanoVGColor(COLOR_BLACK_DROP_SHADOW, pBlend), NanoVGColor(COLOR_TRANSPARENT, nullptr));
945 nvgBeginPath(mVG);
946 nvgRect(mVG, outerBounds.L, outerBounds.T, outerBounds.W(), outerBounds.H());
947 nvgFillPaint(mVG, shadowPaint);
948 nvgGlobalCompositeOperation(mVG, NVG_SOURCE_OVER);
949 nvgFill(mVG);
950 nvgBeginPath(mVG);
951}
952
953void IGraphicsNanoVG::DrawMultiLineText(const IText& text, const char* str, const IRECT& bounds, const IBlend* pBlend)
954{
955 nvgSave(mVG);
956 nvgFontSize(mVG, text.mSize);
957 nvgFontFace(mVG, text.mFont);
958
959 float x = 0.0, y = 0.0;
960 const float width = bounds.W();
961 int align = 0;
962 float yOffsetScale = 0.0;
963
964 switch (text.mAlign)
965 {
966 case EAlign::Near: align = NVG_ALIGN_LEFT; x = bounds.L; break;
967 case EAlign::Center: align = NVG_ALIGN_CENTER; x = bounds.MW(); break;
968 case EAlign::Far: align = NVG_ALIGN_RIGHT; x = bounds.R; break;
969 }
970
971 switch (text.mVAlign)
972 {
973 case EVAlign::Top:
974 {
975 align |= NVG_ALIGN_TOP;
976 y = bounds.T;
977 yOffsetScale = 0.0;
978 break;
979 }
980 case EVAlign::Middle:
981 {
982 align |= NVG_ALIGN_MIDDLE;
983 y = bounds.MH();
984 yOffsetScale = 0.5;
985 break;
986 }
987 case EVAlign::Bottom:
988 {
989 align |= NVG_ALIGN_BOTTOM;
990 y = bounds.B;
991 yOffsetScale = 1.0;
992 break;
993 }
994 }
995
996 nvgTextAlign(mVG, align);
997
998 NVGtextRow rows[3];
999 const char* start;
1000 const char* end;
1001 int nRows = 0;
1002 int lines = 0;
1003 float lineHeight;
1004 nvgTextMetrics(mVG, NULL, NULL, &lineHeight);
1005 nvgFillColor(mVG, NanoVGColor(text.mFGColor, pBlend));
1006
1007 for (auto run : {0, 1})
1008 {
1009 start = str;
1010 end = str + strlen(str);
1011 while ((nRows = nvgTextBreakLines(mVG, start, end, width, rows, 3))) {
1012 for (int i = 0; i < nRows; i++) {
1013 if (run == 0)
1014 {
1015 lines++;
1016 }
1017 else
1018 {
1019 NVGtextRow* row = &rows[i];
1020 nvgText(mVG, x, y - ((lines*lineHeight)*yOffsetScale), row->start, row->end);
1021 y += lineHeight;
1022 }
1023 }
1024 start = rows[nRows-1].next;
1025 }
1026 }
1027
1028 nvgRestore(mVG);
1029}
const void * LoadWinResource(const char *resID, const char *type, int &sizeInBytes, void *pHInstance)
Load a resource from the binary (windows only).
A Text entry widget drawn by IGraphics to optionally override platform text entries.
A base class interface for a bitmap abstraction around the different drawing back end bitmap represen...
float GetScale() const
BitmapData GetBitmap() const
void SetBitmap(BitmapData pBitmap, int w, int h, float scale, float drawScale)
Used to initialise the members after construction.
int GetHeight() const
float GetDrawScale() const
int GetWidth() const
User-facing bitmap abstraction that you use to manage bitmap data, independant of draw class/platform...
int W() const
float GetScale() const
int H() const
APIBitmap * GetAPIBitmap() const
An editor delegate base class that uses IGraphics for the UI.
The lowest level base class of an IGraphics context.
Definition: IGraphics.h:86
ILayer * PopLayer()
Pop a layer off the stack.
Definition: IGraphics.cpp:2053
void PathTransformTranslate(float x, float y)
Apply a translation transform to the current path.
Definition: IGraphics.cpp:2769
void PathRect(const IRECT &bounds)
Add a rectangle to the current path.
Definition: IGraphics.cpp:2674
virtual float GetBackingPixelScale() const
Definition: IGraphics.h:1809
void DoMeasureTextRotation(const IText &text, const IRECT &bounds, IRECT &rect) const
Measures text bounds accounting for rotation.
Definition: IGraphics.cpp:2266
int WindowWidth() const
Gets the width of the graphics context including draw scaling.
Definition: IGraphics.h:1106
EResourceLocation SearchImageResource(const char *fileName, const char *type, WDL_String &result, int targetScale, int &sourceScale)
Search for a bitmap image resource matching the target scale.
Definition: IGraphics.cpp:1913
void PathTransformRestore()
Restore the affine transform of the current path, to the previously saved state.
Definition: IGraphics.cpp:2747
void PushLayer(ILayer *pLayer)
Push a layer on to the stack.
Definition: IGraphics.cpp:2044
int GetRoundedScreenScale() const
Gets the screen/display scaling factor, rounded up.
Definition: IGraphics.h:1126
void RemoveAllControls()
Removes all regular IControls from the control list, as well as special controls (frees memory).
Definition: IGraphics.cpp:207
virtual void * GetWinModuleHandle()
Definition: IGraphics.h:926
float GetScreenScale() const
Gets the screen/display scaling factor, e.g.
Definition: IGraphics.h:1122
void PathTransformSave()
Save the current affine transform of the current path.
Definition: IGraphics.cpp:2742
float GetDrawScale() const
Gets the graphics context scaling factor.
Definition: IGraphics.h:1118
int WindowHeight() const
Gets the height of the graphics context including draw scaling.
Definition: IGraphics.h:1110
virtual void BeginFrame()
Called at the beginning of drawing.
Definition: IGraphics.cpp:901
IGraphics draw class using NanoVG
const char * GetDrawingAPIStr() override
void ApplyShadowMask(ILayerPtr &layer, RawBitmapData &mask, const IShadow &shadow) override
Implemented by a graphics backend to apply a calculated shadow mask to a layer, according to the shad...
void DrawResize() override
Called to update the drawing surface after a resize.
void PathClear() override
Clear the stack of path drawing commands.
IBitmap LoadBitmap(const char *name, int nStates, bool framesAreHorizontal, int targetScale) override
Load a bitmap image from disk or from windows resource.
void PathFill(const IPattern &pattern, const IFillOptions &options, const IBlend *pBlend) override
Fill the current current path.
void GetLayerBitmapData(const ILayerPtr &layer, RawBitmapData &data) override
Get the contents of a layer as Raw RGBA bitmap data NOTE: you should only call this within IControl::...
void DrawDottedRect(const IColor &color, const IRECT &bounds, const IBlend *pBlend, float thickness, float dashLen) override
Draw a dotted rectangle to the graphics context.
void PathSetWinding(bool clockwise) override
NanoVG only.
APIBitmap * LoadAPIBitmap(const char *fileNameOrResID, int scale, EResourceLocation location, const char *ext) override
Drawing API method to load a bitmap, called internally.
void PathStroke(const IPattern &pattern, float thickness, const IStrokeOptions &options, const IBlend *pBlend) override
Stroke the current current path.
void PathArc(float cx, float cy, float r, float a1, float a2, EWinding winding) override
Add an arc to the current path.
void PathLineTo(float x, float y) override
Add a line to the current path from the current point to the specified location.
void OnViewDestroyed() override
Called after a platform view is destroyed, so that drawing classes can e.g.
void DrawMultiLineText(const IText &text, const char *str, const IRECT &bounds, const IBlend *pBlend) override
Draw some multi-line text to the graphics context in a specific rectangle (NanoVG only)
void DrawDottedLine(const IColor &color, float x1, float y1, float x2, float y2, const IBlend *pBlend, float thickness, float dashLen) override
Draw a dotted line to the graphics context.
void PathCubicBezierTo(float c1x, float c1y, float c2x, float c2y, float x2, float y2) override
Add a cubic bezier to the current path from the current point to the specified location.
IColor GetPoint(int x, int y) override
Get the color at an X, Y location in the graphics context.
bool LoadAPIFont(const char *fontID, const PlatformFontPtr &font) override
Drawing API method to load a font from a PlatformFontPtr, called internally.
void PathClose() override
Close the path that is being specified.
void DoDrawText(const IText &text, const char *str, const IRECT &bounds, const IBlend *pBlend) override
Internal method to draw text.
void DrawFastDropShadow(const IRECT &innerBounds, const IRECT &outerBounds, float xyDrop=5.f, float roundness=0.f, float blur=10.f, IBlend *pBlend=nullptr) override
NanoVG only.
void PathMoveTo(float x, float y) override
Move the current point in the current path.
void OnViewInitialized(void *pContext) override
Called after platform view initialization, so that drawing classes can e.g.
void BeginFrame() override
Called at the beginning of drawing.
void EndFrame() override
Called by some drawing API classes to finally blit the draw bitmap onto the screen or perform other c...
APIBitmap * CreateAPIBitmap(int width, int height, float scale, double drawScale, bool cacheable=false) override
Creates a new API bitmap, either in memory or as a GPU texture.
void PathQuadraticBezierTo(float cx, float cy, float x2, float y2) override
Add a quadratic bezier to the current path from the current point to the specified location.
bool BitmapExtSupported(const char *ext) override
Checks a file extension and reports whether this drawing API supports loading that extension.
float DoMeasureText(const IText &text, const char *str, IRECT &bounds) const override
Internal method to measure text dimensions.
void DrawBitmap(const IBitmap &bitmap, const IRECT &dest, int srcX, int srcY, const IBlend *pBlend) override
Draw a bitmap (raster) image to the graphics context.
An abstraction that is used to store a temporary raster image/framebuffer.
std::unique_ptr< ILayer > ILayerPtr
ILayerPtr is a managed pointer for transferring the ownership of layers.
float BlendWeight(const IBlend *pBlend)
Helper function to extract the blend weight value from an IBlend ptr if it is valid.
Used to manage stroke behaviour for path based drawing back ends.
BEGIN_IPLUG_NAMESPACE T Clip(T x, T lo, T hi)
Clips the value x between lo and hi.
static void ToLower(char *cDest, const char *cSrc)
Converts a C string to lowercase.
Used to manage composite/blend operations, independent of draw class/platform.
Used to manage color data, independent of draw class/platform.
Used to manage fill behaviour.
Used to store transformation matrices.
IMatrix & Invert()
Changes the matrix to be the inverse of its original value.
void TransformPoint(double &x, double &y, double x0, double y0) const
Transforms a point using this matrix.
Used to store pattern information for gradients.
const IColorStop & GetStop(int idx) const
Get the IColorStop at a particular index (will crash if out of bounds)
int NStops() const
Used to manage a rectangular area, independent of draw class/platform.
float MH() const
float W() const
float H() const
void Translate(float x, float y)
Translate this rectangle.
float MW() const
Used to specify properties of a drop-shadow to a layer.
IText is used to manage font and text/text entry style for a piece of text on the UI,...