DISTRHO Plugin Framework
NanoVG.hpp
1 /*
2  * DISTRHO Plugin Framework (DPF)
3  * Copyright (C) 2012-2021 Filipe Coelho <falktx@falktx.com>
4  *
5  * Permission to use, copy, modify, and/or distribute this software for any purpose with
6  * or without fee is hereby granted, provided that the above copyright notice and this
7  * permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
10  * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
11  * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
12  * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
13  * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
14  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15  */
16 
17 #ifndef DGL_NANO_WIDGET_HPP_INCLUDED
18 #define DGL_NANO_WIDGET_HPP_INCLUDED
19 
20 #include "Color.hpp"
21 #include "OpenGL.hpp"
22 #include "SubWidget.hpp"
23 #include "TopLevelWidget.hpp"
24 #include "StandaloneWindow.hpp"
25 
26 #ifndef DGL_NO_SHARED_RESOURCES
27 # define NANOVG_DEJAVU_SANS_TTF "__dpf_dejavusans_ttf__"
28 #endif
29 
30 struct NVGcontext;
31 struct NVGpaint;
32 
33 START_NAMESPACE_DGL
34 
35 // -----------------------------------------------------------------------
36 // Forward class names
37 
38 class BlendishWidget;
39 class NanoVG;
40 
41 // -----------------------------------------------------------------------
42 // NanoImage
43 
44 /**
45  NanoVG Image class.
46 
47  This implements NanoVG images as a C++ class where deletion is handled automatically.
48  Images need to be created within a NanoVG or NanoWidget class.
49  */
50 class NanoImage
51 {
52 private:
53  struct Handle {
54  NVGcontext* context;
55  int imageId;
56 
57  Handle() noexcept
58  : context(nullptr),
59  imageId(0) {}
60 
61  Handle(NVGcontext* c, int id) noexcept
62  : context(c),
63  imageId(id) {}
64  };
65 
66 public:
67  /**
68  Constructor for an invalid/null image.
69  */
70  NanoImage();
71 
72  /**
73  Constructor.
74  */
75  NanoImage(const Handle& handle);
76 
77  /**
78  Destructor.
79  */
80  ~NanoImage();
81 
82  /**
83  Create a new image without recreating the C++ class.
84  */
85  NanoImage& operator=(const Handle& handle);
86 
87  /**
88  Wherever this image is valid.
89  */
90  bool isValid() const noexcept;
91 
92  /**
93  Get size.
94  */
95  Size<uint> getSize() const noexcept;
96 
97  /**
98  Get the OpenGL texture handle.
99  */
100  GLuint getTextureHandle() const;
101 
102 private:
103  Handle fHandle;
104  Size<uint> fSize;
105  friend class NanoVG;
106 
107  /** @internal */
108  void _updateSize();
109 
110  DISTRHO_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(NanoImage)
111 };
112 
113 // -----------------------------------------------------------------------
114 // NanoVG
115 
116 /**
117  NanoVG class.
118 
119  This class exposes the NanoVG drawing API.
120  All calls should be wrapped in beginFrame() and endFrame().
121 
122  @section State Handling
123  NanoVG contains state which represents how paths will be rendered.
124  The state contains transform, fill and stroke styles, text and font styles, and scissor clipping.
125 
126  @section Render styles
127  Fill and stroke render style can be either a solid color or a paint which is a gradient or a pattern.
128  Solid color is simply defined as a color value, different kinds of paints can be created
129  using linearGradient(), boxGradient(), radialGradient() and imagePattern().
130 
131  Current render style can be saved and restored using save() and restore().
132 
133  @section Transforms
134  The paths, gradients, patterns and scissor region are transformed by an transformation
135  matrix at the time when they are passed to the API.
136  The current transformation matrix is a affine matrix:
137  [sx kx tx]
138  [ky sy ty]
139  [ 0 0 1]
140  Where: sx,sy define scaling, kx,ky skewing, and tx,ty translation.
141  The last row is assumed to be 0,0,1 and is not stored.
142 
143  Apart from resetTransform(), each transformation function first creates
144  specific transformation matrix and pre-multiplies the current transformation by it.
145 
146  Current coordinate system (transformation) can be saved and restored using save() and restore().
147 
148  @section Images
149  NanoVG allows you to load jpg, png, psd, tga, pic and gif files to be used for rendering.
150  In addition you can upload your own image. The image loading is provided by stb_image.
151 
152  @section Paints
153  NanoVG supports four types of paints: linear gradient, box gradient, radial gradient and image pattern.
154  These can be used as paints for strokes and fills.
155 
156  @section Scissoring
157  Scissoring allows you to clip the rendering into a rectangle. This is useful for various
158  user interface cases like rendering a text edit or a timeline.
159 
160  @section Paths
161  Drawing a new shape starts with beginPath(), it clears all the currently defined paths.
162  Then you define one or more paths and sub-paths which describe the shape. The are functions
163  to draw common shapes like rectangles and circles, and lower level step-by-step functions,
164  which allow to define a path curve by curve.
165 
166  NanoVG uses even-odd fill rule to draw the shapes. Solid shapes should have counter clockwise
167  winding and holes should have counter clockwise order. To specify winding of a path you can
168  call pathWinding(). This is useful especially for the common shapes, which are drawn CCW.
169 
170  Finally you can fill the path using current fill style by calling fill(), and stroke it
171  with current stroke style by calling stroke().
172 
173  The curve segments and sub-paths are transformed by the current transform.
174 
175  @section Text
176  NanoVG allows you to load .ttf files and use the font to render text.
177 
178  The appearance of the text can be defined by setting the current text style
179  and by specifying the fill color. Common text and font settings such as
180  font size, letter spacing and text align are supported. Font blur allows you
181  to create simple text effects such as drop shadows.
182 
183  At render time the font face can be set based on the font handles or name.
184 
185  Font measure functions return values in local space, the calculations are
186  carried in the same resolution as the final rendering. This is done because
187  the text glyph positions are snapped to the nearest pixels sharp rendering.
188 
189  The local space means that values are not rotated or scale as per the current
190  transformation. For example if you set font size to 12, which would mean that
191  line height is 16, then regardless of the current scaling and rotation, the
192  returned line height is always 16. Some measures may vary because of the scaling
193  since aforementioned pixel snapping.
194 
195  While this may sound a little odd, the setup allows you to always render the
196  same way regardless of scaling. i.e. following works regardless of scaling:
197 
198  @code
199  const char* txt = "Text me up.";
200  vg.textBounds(x,y, txt, NULL, bounds);
201  vg.beginPath();
202  vg.roundedRect(bounds[0], bounds[1], bounds[2]-bounds[0], bounds[3]-bounds[1]);
203  vg.fill();
204  @endcode
205 
206  Note: currently only solid color fill is supported for text.
207  */
208 class NanoVG
209 {
210 public:
211  enum CreateFlags {
212  /**
213  Flag indicating if geometry based anti-aliasing is used (may not be needed when using MSAA).
214  */
216 
217  /**
218  Flag indicating if strokes should be drawn using stencil buffer. The rendering will be a little
219  slower, but path overlaps (i.e. self-intersecting or sharp turns) will be drawn just once.
220  */
222 
223  /**
224  Flag indicating that additional debug checks are done.
225  */
226  CREATE_DEBUG = 1 << 2,
227  };
228 
229  enum ImageFlags {
230  IMAGE_GENERATE_MIPMAPS = 1 << 0, // Generate mipmaps during creation of the image.
231  IMAGE_REPEAT_X = 1 << 1, // Repeat image in X direction.
232  IMAGE_REPEAT_Y = 1 << 2, // Repeat image in Y direction.
233  IMAGE_FLIP_Y = 1 << 3, // Flips (inverses) image in Y direction when rendered.
234  IMAGE_PREMULTIPLIED = 1 << 4 // Image data has premultiplied alpha.
235  };
236 
237  enum Align {
238  // Horizontal align
239  ALIGN_LEFT = 1 << 0, // Align horizontally to left (default).
240  ALIGN_CENTER = 1 << 1, // Align horizontally to center.
241  ALIGN_RIGHT = 1 << 2, // Align horizontally to right.
242  // Vertical align
243  ALIGN_TOP = 1 << 3, // Align vertically to top.
244  ALIGN_MIDDLE = 1 << 4, // Align vertically to middle.
245  ALIGN_BOTTOM = 1 << 5, // Align vertically to bottom.
246  ALIGN_BASELINE = 1 << 6 // Align vertically to baseline (default).
247  };
248 
249  enum LineCap {
250  BUTT,
251  ROUND,
252  SQUARE,
253  BEVEL,
254  MITER
255  };
256 
257  enum Solidity {
258  SOLID = 1, // CCW
259  HOLE = 2 // CW
260  };
261 
262  enum Winding {
263  CCW = 1, // Winding for solid shapes
264  CW = 2 // Winding for holes
265  };
266 
267  struct Paint {
268  float xform[6];
269  float extent[2];
270  float radius;
271  float feather;
272  Color innerColor;
273  Color outerColor;
274  int imageId;
275 
276  Paint() noexcept;
277 
278  /**
279  @internal
280  */
281  Paint(const NVGpaint&) noexcept;
282  operator NVGpaint() const noexcept;
283  };
284 
285  struct GlyphPosition {
286  const char* str; // Position of the glyph in the input string.
287  float x; // The x-coordinate of the logical glyph position.
288  float minx, maxx; // The bounds of the glyph shape.
289  };
290 
291  struct TextRow {
292  const char* start; // Pointer to the input text where the row starts.
293  const char* end; // Pointer to the input text where the row ends (one past the last character).
294  const char* next; // Pointer to the beginning of the next row.
295  float width; // Logical width of the row.
296  float minx, maxx; // Actual bounds of the row. Logical with and bounds can differ because of kerning and some parts over extending.
297  };
298 
299  typedef int FontId;
300 
301  /**
302  Constructor.
303  @see CreateFlags
304  */
305  NanoVG(int flags = CREATE_ANTIALIAS);
306 
307  /**
308  Constructor reusing a NanoVG context, used for subwidgets.
309  */
310  /*
311  NanoVG(NanoWidget* groupWidget);
312  */
313 
314  /**
315  Destructor.
316  */
317  virtual ~NanoVG();
318 
319  /**
320  Get the NanoVG context.
321  You should not need this under normal circumstances.
322  */
323  NVGcontext* getContext() const noexcept
324  {
325  return fContext;
326  }
327 
328  /**
329  Begin drawing a new frame.
330  */
331  void beginFrame(const uint width, const uint height, const float scaleFactor = 1.0f);
332 
333  /**
334  Begin drawing a new frame inside a widget.
335  */
336  void beginFrame(Widget* const widget);
337 
338  /**
339  Cancels drawing the current frame.
340  */
341  void cancelFrame();
342 
343  /**
344  Ends drawing flushing remaining render state.
345  */
346  void endFrame();
347 
348  /* --------------------------------------------------------------------
349  * State Handling */
350 
351  /**
352  Pushes and saves the current render state into a state stack.
353  A matching restore() must be used to restore the state.
354  */
355  void save();
356 
357  /**
358  Pops and restores current render state.
359  */
360  void restore();
361 
362  /**
363  Resets current render state to default values. Does not affect the render state stack.
364  */
365  void reset();
366 
367  /* --------------------------------------------------------------------
368  * Render styles */
369 
370  /**
371  Sets current stroke style to a solid color.
372  */
373  void strokeColor(const Color& color);
374 
375  /**
376  Sets current stroke style to a solid color, made from red, green, blue and alpha numeric values.
377  Values must be in [0..255] range.
378  */
379  void strokeColor(const int red, const int green, const int blue, const int alpha = 255);
380 
381  /**
382  Sets current stroke style to a solid color, made from red, green, blue and alpha numeric values.
383  Values must in [0..1] range.
384  */
385  void strokeColor(const float red, const float green, const float blue, const float alpha = 1.0f);
386 
387  /**
388  Sets current stroke style to a paint, which can be a one of the gradients or a pattern.
389  */
390  void strokePaint(const Paint& paint);
391 
392  /**
393  Sets current fill style to a solid color.
394  */
395  void fillColor(const Color& color);
396 
397  /**
398  Sets current fill style to a solid color, made from red, green, blue and alpha numeric values.
399  Values must be in [0..255] range.
400  */
401  void fillColor(const int red, const int green, const int blue, const int alpha = 255);
402 
403  /**
404  Sets current fill style to a solid color, made from red, green, blue and alpha numeric values.
405  Values must in [0..1] range.
406  */
407  void fillColor(const float red, const float green, const float blue, const float alpha = 1.0f);
408 
409  /**
410  Sets current fill style to a paint, which can be a one of the gradients or a pattern.
411  */
412  void fillPaint(const Paint& paint);
413 
414  /**
415  Sets the miter limit of the stroke style.
416  Miter limit controls when a sharp corner is beveled.
417  */
418  void miterLimit(float limit);
419 
420  /**
421  Sets the stroke width of the stroke style.
422  */
423  void strokeWidth(float size);
424 
425  /**
426  Sets how the end of the line (cap) is drawn,
427  Can be one of: BUTT, ROUND, SQUARE.
428  */
429  void lineCap(LineCap cap = BUTT);
430 
431  /**
432  Sets how sharp path corners are drawn.
433  Can be one of MITER, ROUND, BEVEL.
434  */
435  void lineJoin(LineCap join = MITER);
436 
437  /**
438  Sets the transparency applied to all rendered shapes.
439  Already transparent paths will get proportionally more transparent as well.
440  */
441  void globalAlpha(float alpha);
442 
443  /* --------------------------------------------------------------------
444  * Transforms */
445 
446  /**
447  Resets current transform to a identity matrix.
448  */
449  void resetTransform();
450 
451  /**
452  Pre-multiplies current coordinate system by specified matrix.
453  The parameters are interpreted as matrix as follows:
454  [a c e]
455  [b d f]
456  [0 0 1]
457  */
458  void transform(float a, float b, float c, float d, float e, float f);
459 
460  /**
461  Translates current coordinate system.
462  */
463  void translate(float x, float y);
464 
465  /**
466  Rotates current coordinate system. Angle is specified in radians.
467  */
468  void rotate(float angle);
469 
470  /**
471  Skews the current coordinate system along X axis. Angle is specified in radians.
472  */
473  void skewX(float angle);
474 
475  /**
476  Skews the current coordinate system along Y axis. Angle is specified in radians.
477  */
478  void skewY(float angle);
479 
480  /**
481  Scales the current coordinate system.
482  */
483  void scale(float x, float y);
484 
485  /**
486  Stores the top part (a-f) of the current transformation matrix in to the specified buffer.
487  [a c e]
488  [b d f]
489  [0 0 1]
490  */
491  void currentTransform(float xform[6]);
492 
493  /**
494  The following functions can be used to make calculations on 2x3 transformation matrices.
495  A 2x3 matrix is represented as float[6]. */
496 
497  /**
498  Sets the transform to identity matrix.
499  */
500  static void transformIdentity(float dst[6]);
501 
502  /**
503  Sets the transform to translation matrix
504  */
505  static void transformTranslate(float dst[6], float tx, float ty);
506 
507  /**
508  Sets the transform to scale matrix.
509  */
510  static void transformScale(float dst[6], float sx, float sy);
511 
512  /**
513  Sets the transform to rotate matrix. Angle is specified in radians.
514  */
515  static void transformRotate(float dst[6], float a);
516 
517  /**
518  Sets the transform to skew-x matrix. Angle is specified in radians.
519  */
520  static void transformSkewX(float dst[6], float a);
521 
522  /**
523  Sets the transform to skew-y matrix. Angle is specified in radians.
524  */
525  static void transformSkewY(float dst[6], float a);
526 
527  /**
528  Sets the transform to the result of multiplication of two transforms, of A = A*B.
529  */
530  static void transformMultiply(float dst[6], const float src[6]);
531 
532  /**
533  Sets the transform to the result of multiplication of two transforms, of A = B*A.
534  */
535  static void transformPremultiply(float dst[6], const float src[6]);
536 
537  /**
538  Sets the destination to inverse of specified transform.
539  Returns 1 if the inverse could be calculated, else 0.
540  */
541  static int transformInverse(float dst[6], const float src[6]);
542 
543  /**
544  Transform a point by given transform.
545  */
546  static void transformPoint(float& dstx, float& dsty, const float xform[6], float srcx, float srcy);
547 
548  /**
549  Convert degrees to radians.
550  */
551  static float degToRad(float deg);
552 
553  /**
554  Convert radians to degrees.
555  */
556  static float radToDeg(float rad);
557 
558  /* --------------------------------------------------------------------
559  * Images */
560 
561  /**
562  Creates image by loading it from the disk from specified file name.
563  */
564  NanoImage::Handle createImageFromFile(const char* filename, ImageFlags imageFlags);
565 
566  /**
567  Creates image by loading it from the disk from specified file name.
568  Overloaded function for convenience.
569  @see ImageFlags
570  */
571  NanoImage::Handle createImageFromFile(const char* filename, int imageFlags);
572 
573  /**
574  Creates image by loading it from the specified chunk of memory.
575  */
576  NanoImage::Handle createImageFromMemory(uchar* data, uint dataSize, ImageFlags imageFlags);
577 
578  /**
579  Creates image by loading it from the specified chunk of memory.
580  Overloaded function for convenience.
581  @see ImageFlags
582  */
583  NanoImage::Handle createImageFromMemory(uchar* data, uint dataSize, int imageFlags);
584 
585  /**
586  Creates image from specified image data.
587  */
588  NanoImage::Handle createImageFromRGBA(uint w, uint h, const uchar* data, ImageFlags imageFlags);
589 
590  /**
591  Creates image from specified image data.
592  Overloaded function for convenience.
593  @see ImageFlags
594  */
595  NanoImage::Handle createImageFromRGBA(uint w, uint h, const uchar* data, int imageFlags);
596 
597  /**
598  Creates image from an OpenGL texture handle.
599  */
600  NanoImage::Handle createImageFromTextureHandle(GLuint textureId, uint w, uint h, ImageFlags imageFlags, bool deleteTexture = false);
601 
602  /**
603  Creates image from an OpenGL texture handle.
604  Overloaded function for convenience.
605  @see ImageFlags
606  */
607  NanoImage::Handle createImageFromTextureHandle(GLuint textureId, uint w, uint h, int imageFlags, bool deleteTexture = false);
608 
609  /* --------------------------------------------------------------------
610  * Paints */
611 
612  /**
613  Creates and returns a linear gradient. Parameters (sx,sy)-(ex,ey) specify the start and end coordinates
614  of the linear gradient, icol specifies the start color and ocol the end color.
615  The gradient is transformed by the current transform when it is passed to fillPaint() or strokePaint().
616  */
617  Paint linearGradient(float sx, float sy, float ex, float ey, const Color& icol, const Color& ocol);
618 
619  /**
620  Creates and returns a box gradient. Box gradient is a feathered rounded rectangle, it is useful for rendering
621  drop shadows or highlights for boxes. Parameters (x,y) define the top-left corner of the rectangle,
622  (w,h) define the size of the rectangle, r defines the corner radius, and f feather. Feather defines how blurry
623  the border of the rectangle is. Parameter icol specifies the inner color and ocol the outer color of the gradient.
624  The gradient is transformed by the current transform when it is passed to fillPaint() or strokePaint().
625  */
626  Paint boxGradient(float x, float y, float w, float h, float r, float f, const Color& icol, const Color& ocol);
627 
628  /**
629  Creates and returns a radial gradient. Parameters (cx,cy) specify the center, inr and outr specify
630  the inner and outer radius of the gradient, icol specifies the start color and ocol the end color.
631  The gradient is transformed by the current transform when it is passed to fillPaint() or strokePaint().
632  */
633  Paint radialGradient(float cx, float cy, float inr, float outr, const Color& icol, const Color& ocol);
634 
635  /**
636  Creates and returns an image pattern. Parameters (ox,oy) specify the left-top location of the image pattern,
637  (ex,ey) the size of one image, angle rotation around the top-left corner, image is handle to the image to render.
638  The gradient is transformed by the current transform when it is passed to fillPaint() or strokePaint().
639  */
640  Paint imagePattern(float ox, float oy, float ex, float ey, float angle, const NanoImage& image, float alpha);
641 
642  /* --------------------------------------------------------------------
643  * Scissoring */
644 
645  /**
646  Sets the current scissor rectangle.
647  The scissor rectangle is transformed by the current transform.
648  */
649  void scissor(float x, float y, float w, float h);
650 
651  /**
652  Intersects current scissor rectangle with the specified rectangle.
653  The scissor rectangle is transformed by the current transform.
654  Note: in case the rotation of previous scissor rect differs from
655  the current one, the intersection will be done between the specified
656  rectangle and the previous scissor rectangle transformed in the current
657  transform space. The resulting shape is always rectangle.
658  */
659  void intersectScissor(float x, float y, float w, float h);
660 
661  /**
662  Reset and disables scissoring.
663  */
664  void resetScissor();
665 
666  /* --------------------------------------------------------------------
667  * Paths */
668 
669  /**
670  Clears the current path and sub-paths.
671  */
672  void beginPath();
673 
674  /**
675  Starts new sub-path with specified point as first point.
676  */
677  void moveTo(float x, float y);
678 
679  /**
680  Adds line segment from the last point in the path to the specified point.
681  */
682  void lineTo(float x, float y);
683 
684  /**
685  Adds cubic bezier segment from last point in the path via two control points to the specified point.
686  */
687  void bezierTo(float c1x, float c1y, float c2x, float c2y, float x, float y);
688 
689  /**
690  Adds quadratic bezier segment from last point in the path via a control point to the specified point.
691  */
692  void quadTo(float cx, float cy, float x, float y);
693 
694  /**
695  Adds an arc segment at the corner defined by the last path point, and two specified points.
696  */
697  void arcTo(float x1, float y1, float x2, float y2, float radius);
698 
699  /**
700  Closes current sub-path with a line segment.
701  */
702  void closePath();
703 
704  /**
705  Sets the current sub-path winding.
706  */
707  void pathWinding(Winding dir);
708 
709  /**
710  Creates new circle arc shaped sub-path. The arc center is at cx,cy, the arc radius is r,
711  and the arc is drawn from angle a0 to a1, and swept in direction dir (NVG_CCW or NVG_CW).
712  Angles are specified in radians.
713  */
714  void arc(float cx, float cy, float r, float a0, float a1, Winding dir);
715 
716  /**
717  Creates new rectangle shaped sub-path.
718  */
719  void rect(float x, float y, float w, float h);
720 
721  /**
722  Creates new rounded rectangle shaped sub-path.
723  */
724  void roundedRect(float x, float y, float w, float h, float r);
725 
726  /**
727  Creates new ellipse shaped sub-path.
728  */
729  void ellipse(float cx, float cy, float rx, float ry);
730 
731  /**
732  Creates new circle shaped sub-path.
733  */
734  void circle(float cx, float cy, float r);
735 
736  /**
737  Fills the current path with current fill style.
738  */
739  void fill();
740 
741  /**
742  Fills the current path with current stroke style.
743  */
744  void stroke();
745 
746  /* --------------------------------------------------------------------
747  * Text */
748 
749  /**
750  Creates font by loading it from the disk from specified file name.
751  Returns handle to the font.
752  */
753  FontId createFontFromFile(const char* name, const char* filename);
754 
755  /**
756  Creates font by loading it from the specified memory chunk.
757  Returns handle to the font.
758  */
759  FontId createFontFromMemory(const char* name, const uchar* data, uint dataSize, bool freeData);
760 
761  /**
762  Finds a loaded font of specified name, and returns handle to it, or -1 if the font is not found.
763  */
764  FontId findFont(const char* name);
765 
766  /**
767  Sets the font size of current text style.
768  */
769  void fontSize(float size);
770 
771  /**
772  Sets the blur of current text style.
773  */
774  void fontBlur(float blur);
775 
776  /**
777  Sets the letter spacing of current text style.
778  */
779  void textLetterSpacing(float spacing);
780 
781  /**
782  Sets the proportional line height of current text style. The line height is specified as multiple of font size.
783  */
784  void textLineHeight(float lineHeight);
785 
786  /**
787  Sets the text align of current text style.
788  */
789  void textAlign(Align align);
790 
791  /**
792  Sets the text align of current text style.
793  Overloaded function for convenience.
794  @see Align
795  */
796  void textAlign(int align);
797 
798  /**
799  Sets the font face based on specified id of current text style.
800  */
801  void fontFaceId(FontId font);
802 
803  /**
804  Sets the font face based on specified name of current text style.
805  */
806  void fontFace(const char* font);
807 
808  /**
809  Draws text string at specified location. If end is specified only the sub-string up to the end is drawn.
810  */
811  float text(float x, float y, const char* string, const char* end);
812 
813  /**
814  Draws multi-line text string at specified location wrapped at the specified width.
815  If end is specified only the sub-string up to the end is drawn.
816  White space is stripped at the beginning of the rows, the text is split at word boundaries or when new-line characters are encountered.
817  Words longer than the max width are slit at nearest character (i.e. no hyphenation).
818  */
819  void textBox(float x, float y, float breakRowWidth, const char* string, const char* end = nullptr);
820 
821  /**
822  Measures the specified text string. The bounds value are [xmin,ymin, xmax,ymax].
823  Returns the horizontal advance of the measured text (i.e. where the next character should drawn).
824  Measured values are returned in local coordinate space.
825  */
826  float textBounds(float x, float y, const char* string, const char* end, Rectangle<float>& bounds);
827 
828  /**
829  Measures the specified multi-text string. Parameter bounds should be a pointer to float[4],
830  if the bounding box of the text should be returned. The bounds value are [xmin,ymin, xmax,ymax]
831  Measured values are returned in local coordinate space.
832  */
833  void textBoxBounds(float x, float y, float breakRowWidth, const char* string, const char* end, float bounds[4]);
834 
835  /**
836  Calculates the glyph x positions of the specified text. If end is specified only the sub-string will be used.
837  Measured values are returned in local coordinate space.
838  */
839  int textGlyphPositions(float x, float y, const char* string, const char* end, GlyphPosition& positions, int maxPositions);
840 
841  /**
842  Returns the vertical metrics based on the current text style.
843  Measured values are returned in local coordinate space.
844  */
845  void textMetrics(float* ascender, float* descender, float* lineh);
846 
847  /**
848  Breaks the specified text into lines. If end is specified only the sub-string will be used.
849  White space is stripped at the beginning of the rows, the text is split at word boundaries or when new-line characters are encountered.
850  Words longer than the max width are slit at nearest character (i.e. no hyphenation).
851  */
852  int textBreakLines(const char* string, const char* end, float breakRowWidth, TextRow& rows, int maxRows);
853 
854 #ifndef DGL_NO_SHARED_RESOURCES
855  /**
856  Load DPF's internal shared resources for this NanoVG class.
857  */
858  virtual bool loadSharedResources();
859 #endif
860 
861 private:
862  NVGcontext* const fContext;
863  bool fInFrame;
864  bool fIsSubWidget;
865  friend class BlendishWidget;
866 
867  DISTRHO_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(NanoVG)
868 };
869 
870 // -----------------------------------------------------------------------
871 // NanoWidget
872 
873 /**
874  NanoVG Widget class.
875 
876  This class implements the NanoVG drawing API inside a DGL Widget.
877  The drawing function onDisplay() is implemented internally but a
878  new onNanoDisplay() needs to be overridden instead.
879  */
880 template <class BaseWidget>
881 class NanoBaseWidget : public BaseWidget,
882  public NanoVG
883 {
884 public:
885  /**
886  Constructor for a NanoSubWidget.
887  @see CreateFlags
888  */
889  explicit NanoBaseWidget(Widget* const parentGroupWidget, int flags = CREATE_ANTIALIAS);
890 
891  /**
892  Constructor for a NanoTopLevelWidget.
893  @see CreateFlags
894  */
895  explicit NanoBaseWidget(Window& windowToMapTo, int flags = CREATE_ANTIALIAS);
896 
897  /**
898  Constructor for a NanoStandaloneWindow without parent window.
899  @see CreateFlags
900  */
901  explicit NanoBaseWidget(Application& app, int flags = CREATE_ANTIALIAS);
902 
903  /**
904  Constructor for a NanoStandaloneWindow with parent window.
905  @see CreateFlags
906  */
907  explicit NanoBaseWidget(Application& app, Window& parentWindow, int flags = CREATE_ANTIALIAS);
908 
909  /**
910  Destructor.
911  */
912  virtual ~NanoBaseWidget() {}
913 
914 protected:
915  /**
916  New virtual onDisplay function.
917  @see onDisplay
918  */
919  virtual void onNanoDisplay() = 0;
920 
921 private:
922  /**
923  Widget display function.
924  Implemented internally to wrap begin/endFrame() automatically.
925  */
926  inline void onDisplay() override
927  {
928  NanoVG::beginFrame(BaseWidget::getWidth(), BaseWidget::getHeight());
929  onNanoDisplay();
931  }
932 
933  // these should not be used
934  void beginFrame(uint,uint) {}
935  void beginFrame(uint,uint,float) {}
936  void beginFrame(Widget*) {}
937  void cancelFrame() {}
938  void endFrame() {}
939 
940  DISTRHO_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(NanoBaseWidget)
941 };
942 
946 
947 DISTRHO_DEPRECATED_BY("NanoSubWidget")
948 typedef NanoSubWidget NanoWidget;
949 
950 // -----------------------------------------------------------------------
951 
952 END_NAMESPACE_DGL
953 
954 #endif // DGL_NANO_WIDGET_HPP_INCLUDED
NanoVG::CREATE_ANTIALIAS
@ CREATE_ANTIALIAS
Definition: NanoVG.hpp:215
NanoVG::rotate
void rotate(float angle)
NanoVG::boxGradient
Paint boxGradient(float x, float y, float w, float h, float r, float f, const Color &icol, const Color &ocol)
NanoImage::getTextureHandle
GLuint getTextureHandle() const
NanoVG::skewX
void skewX(float angle)
NanoVG::stroke
void stroke()
NanoVG::radToDeg
static float radToDeg(float rad)
NanoVG::transformMultiply
static void transformMultiply(float dst[6], const float src[6])
NanoVG::currentTransform
void currentTransform(float xform[6])
NanoVG::skewY
void skewY(float angle)
NanoVG::CREATE_STENCIL_STROKES
@ CREATE_STENCIL_STROKES
Definition: NanoVG.hpp:221
NanoVG::textGlyphPositions
int textGlyphPositions(float x, float y, const char *string, const char *end, GlyphPosition &positions, int maxPositions)
NanoBaseWidget
Definition: NanoVG.hpp:881
NanoVG::beginPath
void beginPath()
NanoVG::degToRad
static float degToRad(float deg)
NanoVG::roundedRect
void roundedRect(float x, float y, float w, float h, float r)
NanoVG::textLineHeight
void textLineHeight(float lineHeight)
NanoVG::transformPremultiply
static void transformPremultiply(float dst[6], const float src[6])
NanoVG::transformInverse
static int transformInverse(float dst[6], const float src[6])
NanoVG::resetTransform
void resetTransform()
NanoVG::TextRow
Definition: NanoVG.hpp:291
Window
Definition: Window.hpp:50
NanoVG::rect
void rect(float x, float y, float w, float h)
NanoVG::radialGradient
Paint radialGradient(float cx, float cy, float inr, float outr, const Color &icol, const Color &ocol)
NanoVG::createImageFromRGBA
NanoImage::Handle createImageFromRGBA(uint w, uint h, const uchar *data, ImageFlags imageFlags)
NanoVG::fillColor
void fillColor(const Color &color)
NanoImage::~NanoImage
~NanoImage()
NanoVG::scissor
void scissor(float x, float y, float w, float h)
NanoVG::fontFaceId
void fontFaceId(FontId font)
NanoVG::lineCap
void lineCap(LineCap cap=BUTT)
Size< uint >
Rectangle
Definition: Geometry.hpp:30
Application
Definition: Application.hpp:34
NanoVG::fontSize
void fontSize(float size)
NanoVG::strokeColor
void strokeColor(const Color &color)
NanoVG::loadSharedResources
virtual bool loadSharedResources()
NanoImage
Definition: NanoVG.hpp:50
NanoVG::lineJoin
void lineJoin(LineCap join=MITER)
NanoVG::miterLimit
void miterLimit(float limit)
NanoVG::quadTo
void quadTo(float cx, float cy, float x, float y)
NanoVG::translate
void translate(float x, float y)
NanoVG::scale
void scale(float x, float y)
NanoVG::linearGradient
Paint linearGradient(float sx, float sy, float ex, float ey, const Color &icol, const Color &ocol)
NanoVG::transformSkewX
static void transformSkewX(float dst[6], float a)
NanoVG::fontBlur
void fontBlur(float blur)
NanoVG::CreateFlags
CreateFlags
Definition: NanoVG.hpp:211
NanoVG::pathWinding
void pathWinding(Winding dir)
NanoVG::transform
void transform(float a, float b, float c, float d, float e, float f)
NanoVG::endFrame
void endFrame()
NanoVG::GlyphPosition
Definition: NanoVG.hpp:285
NanoVG::fillPaint
void fillPaint(const Paint &paint)
NanoVG::getContext
NVGcontext * getContext() const noexcept
Definition: NanoVG.hpp:323
NanoVG::transformRotate
static void transformRotate(float dst[6], float a)
NanoVG::beginFrame
void beginFrame(const uint width, const uint height, const float scaleFactor=1.0f)
NanoVG::strokePaint
void strokePaint(const Paint &paint)
NanoVG::createImageFromFile
NanoImage::Handle createImageFromFile(const char *filename, ImageFlags imageFlags)
NanoVG::imagePattern
Paint imagePattern(float ox, float oy, float ex, float ey, float angle, const NanoImage &image, float alpha)
NanoVG::save
void save()
NanoVG::Paint
Definition: NanoVG.hpp:267
NanoVG::textBounds
float textBounds(float x, float y, const char *string, const char *end, Rectangle< float > &bounds)
NanoVG::lineTo
void lineTo(float x, float y)
NanoVG::globalAlpha
void globalAlpha(float alpha)
NanoVG::transformIdentity
static void transformIdentity(float dst[6])
NanoVG::transformSkewY
static void transformSkewY(float dst[6], float a)
NanoVG::resetScissor
void resetScissor()
NanoVG::createImageFromTextureHandle
NanoImage::Handle createImageFromTextureHandle(GLuint textureId, uint w, uint h, ImageFlags imageFlags, bool deleteTexture=false)
NanoVG::createImageFromMemory
NanoImage::Handle createImageFromMemory(uchar *data, uint dataSize, ImageFlags imageFlags)
NanoVG::textBox
void textBox(float x, float y, float breakRowWidth, const char *string, const char *end=nullptr)
NanoVG::fontFace
void fontFace(const char *font)
NanoImage::operator=
NanoImage & operator=(const Handle &handle)
NanoBaseWidget::NanoBaseWidget
NanoBaseWidget(Widget *const parentGroupWidget, int flags=CREATE_ANTIALIAS)
NanoVG::transformPoint
static void transformPoint(float &dstx, float &dsty, const float xform[6], float srcx, float srcy)
NanoVG::restore
void restore()
NanoVG::createFontFromFile
FontId createFontFromFile(const char *name, const char *filename)
NanoVG::transformScale
static void transformScale(float dst[6], float sx, float sy)
NanoVG::CREATE_DEBUG
@ CREATE_DEBUG
Definition: NanoVG.hpp:226
NanoVG::textBreakLines
int textBreakLines(const char *string, const char *end, float breakRowWidth, TextRow &rows, int maxRows)
NanoVG::circle
void circle(float cx, float cy, float r)
NanoVG::arc
void arc(float cx, float cy, float r, float a0, float a1, Winding dir)
NanoVG::createFontFromMemory
FontId createFontFromMemory(const char *name, const uchar *data, uint dataSize, bool freeData)
NanoVG::closePath
void closePath()
NanoVG::strokeWidth
void strokeWidth(float size)
NanoVG::intersectScissor
void intersectScissor(float x, float y, float w, float h)
NanoBaseWidget::onNanoDisplay
virtual void onNanoDisplay()=0
NanoImage::isValid
bool isValid() const noexcept
NanoVG::transformTranslate
static void transformTranslate(float dst[6], float tx, float ty)
NanoVG::textBoxBounds
void textBoxBounds(float x, float y, float breakRowWidth, const char *string, const char *end, float bounds[4])
NanoBaseWidget::~NanoBaseWidget
virtual ~NanoBaseWidget()
Definition: NanoVG.hpp:912
NanoVG::moveTo
void moveTo(float x, float y)
NanoVG::cancelFrame
void cancelFrame()
NanoVG::ellipse
void ellipse(float cx, float cy, float rx, float ry)
NanoVG::text
float text(float x, float y, const char *string, const char *end)
NanoVG::arcTo
void arcTo(float x1, float y1, float x2, float y2, float radius)
NanoVG
Definition: NanoVG.hpp:208
NanoVG::reset
void reset()
NanoVG::fill
void fill()
NanoVG::textLetterSpacing
void textLetterSpacing(float spacing)
NanoVG::NanoVG
NanoVG(int flags=CREATE_ANTIALIAS)
NanoVG::findFont
FontId findFont(const char *name)
NanoVG::textMetrics
void textMetrics(float *ascender, float *descender, float *lineh)
NanoVG::textAlign
void textAlign(Align align)
NanoVG::~NanoVG
virtual ~NanoVG()
Color
Definition: Color.hpp:31
NanoImage::getSize
Size< uint > getSize() const noexcept
NanoImage::NanoImage
NanoImage()
NanoVG::bezierTo
void bezierTo(float c1x, float c1y, float c2x, float c2y, float x, float y)
Widget
Definition: Widget.hpp:53