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