-
Notifications
You must be signed in to change notification settings - Fork 128
/
nanovega.d
15232 lines (13331 loc) · 550 KB
/
nanovega.d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Would be nice: way to take output of the canvas to an image file (raster and/or svg)
//
//
// Copyright (c) 2013 Mikko Mononen [email protected]
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
// Fork developement, feature integration and new bugs:
// Ketmar // Invisible Vector <[email protected]>
// Contains code from various contributors.
/**
The NanoVega API is modeled loosely on HTML5 canvas API.
If you know canvas, you're up to speed with NanoVega in no time.
$(SIDE_BY_SIDE
$(COLUMN
D code with nanovega:
---
import arsd.nanovega;
import arsd.simpledisplay;
void main () {
// The NVGWindow class creates a window and sets up the nvg context for you
// you can also do these steps yourself, see the other examples in these docs
auto window = new NVGWindow(800, 600, "NanoVega Simple Sample");
window.redrawNVGScene = delegate (nvg) {
nvg.beginPath(); // start new path
nvg.roundedRect(20.5, 30.5, window.width-40, window.height-60, 8); // .5 to draw at pixel center (see NanoVega documentation)
// now set filling mode for our rectangle
// you can create colors using HTML syntax, or with convenient constants
nvg.fillPaint = nvg.linearGradient(20.5, 30.5, window.width-40, window.height-60,
NVGColor("#f70"), NVGColor.green);
// now fill our rect
nvg.fill();
// and draw a nice outline
nvg.strokeColor = NVGColor.white;
nvg.strokeWidth = 2;
nvg.stroke();
// that's all, folks!
};
window.eventLoop(0,
delegate (KeyEvent event) {
if (event == "*-Q" || event == "Escape") { window.close(); return; } // quit on Q, Ctrl+Q, and so on
},
);
}
---
)
$(COLUMN
Javascript code with HTML5 Canvas
```html
<!DOCTYPE html>
<html>
<head>
<title>NanoVega Simple Sample (HTML5 Translation)</title>
<style>
body { background-color: black; }
</style>
</head>
<body>
<canvas id="my-canvas" width="800" height="600"></canvas>
<script>
var canvas = document.getElementById("my-canvas");
var context = canvas.getContext("2d");
context.beginPath();
context.rect(20.5, 30.5, canvas.width - 40, canvas.height - 60);
var gradient = context.createLinearGradient(20.5, 30.5, canvas.width - 40, canvas.height - 60);
gradient.addColorStop(0, "#f70");
gradient.addColorStop(1, "green");
context.fillStyle = gradient;
context.fill();
context.closePath();
context.strokeStyle = "white";
context.lineWidth = 2;
context.stroke();
</script>
</body>
</html>
```
)
)
$(TIP
This library can use either inbuilt or BindBC (external dependency) provided bindings for OpenGL and FreeType.
Former are used by default, latter can be activated by passing the `bindbc` version specifier to the compiler.
)
Creating drawing context
========================
The drawing context is created using platform specific constructor function.
---
NVGContext vg = nvgCreateContext();
---
$(WARNING You must use created context ONLY in that thread where you created it.
There is no way to "transfer" context between threads. Trying to do so
will lead to UB.)
$(WARNING Never issue any commands outside of [beginFrame]/[endFrame]. Trying to
do so will lead to UB.)
Drawing shapes with NanoVega
============================
Drawing a simple shape using NanoVega consists of four steps:
$(LIST
* begin a new shape,
* define the path to draw,
* set fill or stroke,
* and finally fill or stroke the path.
)
---
vg.beginPath();
vg.rect(100, 100, 120, 30);
vg.fillColor(nvgRGBA(255, 192, 0, 255));
vg.fill();
---
Calling [beginPath] will clear any existing paths and start drawing from blank slate.
There are number of number of functions to define the path to draw, such as rectangle,
rounded rectangle and ellipse, or you can use the common moveTo, lineTo, bezierTo and
arcTo API to compose the paths step by step.
Understanding Composite Paths
=============================
Because of the way the rendering backend is built in NanoVega, drawing a composite path,
that is path consisting from multiple paths defining holes and fills, is a bit more
involved. NanoVega uses non-zero filling rule and by default, and paths are wound in counter
clockwise order. Keep that in mind when drawing using the low level draw API. In order to
wind one of the predefined shapes as a hole, you should call `pathWinding(NVGSolidity.Hole)`,
or `pathWinding(NVGSolidity.Solid)` $(B after) defining the path.
---
vg.beginPath();
vg.rect(100, 100, 120, 30);
vg.circle(120, 120, 5);
vg.pathWinding(NVGSolidity.Hole); // mark circle as a hole
vg.fillColor(nvgRGBA(255, 192, 0, 255));
vg.fill();
---
Rendering is wrong, what to do?
===============================
$(LIST
* make sure you have created NanoVega context using [nvgCreateContext] call
* make sure you have initialised OpenGL with $(B stencil buffer)
* make sure you have cleared stencil buffer
* make sure all rendering calls happen between [beginFrame] and [endFrame]
* to enable more checks for OpenGL errors, add `NVGContextFlag.Debug` flag to [nvgCreateContext]
)
OpenGL state touched by the backend
===================================
The OpenGL back-end touches following states:
When textures are uploaded or updated, the following pixel store is set to defaults:
`GL_UNPACK_ALIGNMENT`, `GL_UNPACK_ROW_LENGTH`, `GL_UNPACK_SKIP_PIXELS`, `GL_UNPACK_SKIP_ROWS`.
Texture binding is also affected. Texture updates can happen when the user loads images,
or when new font glyphs are added. Glyphs are added as needed between calls to [beginFrame]
and [endFrame].
The data for the whole frame is buffered and flushed in [endFrame].
The following code illustrates the OpenGL state touched by the rendering code:
---
glUseProgram(prog);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
glFrontFace(GL_CCW);
glEnable(GL_BLEND);
glDisable(GL_DEPTH_TEST);
glDisable(GL_SCISSOR_TEST);
glDisable(GL_COLOR_LOGIC_OP);
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
glStencilMask(0xffffffff);
glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
glStencilFunc(GL_ALWAYS, 0, 0xffffffff);
glActiveTexture(GL_TEXTURE1);
glActiveTexture(GL_TEXTURE0);
glBindBuffer(GL_UNIFORM_BUFFER, buf);
glBindVertexArray(arr);
glBindBuffer(GL_ARRAY_BUFFER, buf);
glBindTexture(GL_TEXTURE_2D, tex);
glUniformBlockBinding(... , GLNVG_FRAG_BINDING);
---
Symbol_groups:
context_management =
## Context Management
Functions to create and destory NanoVega context.
frame_management =
## Frame Management
To start drawing with NanoVega context, you have to "begin frame", and then
"end frame" to flush your rendering commands to GPU.
composite_operation =
## Composite Operation
The composite operations in NanoVega are modeled after HTML Canvas API, and
the blend func is based on OpenGL (see corresponding manuals for more info).
The colors in the blending state have premultiplied alpha.
color_utils =
## Color Utils
Colors in NanoVega are stored as ARGB. Zero alpha means "transparent color".
matrices =
## Matrices and Transformations
The paths, gradients, patterns and scissor region are transformed by an transformation
matrix at the time when they are passed to the API.
The current transformation matrix is an affine matrix:
----------------------
[sx kx tx]
[ky sy ty]
[ 0 0 1]
----------------------
Where: (sx, sy) define scaling, (kx, ky) skewing, and (tx, ty) translation.
The last row is assumed to be (0, 0, 1) and is not stored.
Apart from [resetTransform], each transformation function first creates
specific transformation matrix and pre-multiplies the current transformation by it.
Current coordinate system (transformation) can be saved and restored using [save] and [restore].
The following functions can be used to make calculations on 2x3 transformation matrices.
A 2x3 matrix is represented as float[6].
state_handling =
## State Handling
NanoVega contains state which represents how paths will be rendered.
The state contains transform, fill and stroke styles, text and font styles,
and scissor clipping.
render_styles =
## Render Styles
Fill and stroke render style can be either a solid color or a paint which is a gradient or a pattern.
Solid color is simply defined as a color value, different kinds of paints can be created
using [linearGradient], [boxGradient], [radialGradient] and [imagePattern].
Current render style can be saved and restored using [save] and [restore].
Note that if you want "almost perfect" pixel rendering, you should set aspect ratio to 1,
and use `integerCoord+0.5f` as pixel coordinates.
render_transformations =
## Render Transformations
Transformation matrix management for the current rendering style. Transformations are applied in
backwards order. I.e. if you first translate, and then rotate, your path will be rotated around
it's origin, and then translated to the destination point.
scissoring =
## Scissoring
Scissoring allows you to clip the rendering into a rectangle. This is useful for various
user interface cases like rendering a text edit or a timeline.
images =
## Images
NanoVega allows you to load image files in various formats (if arsd loaders are in place) to be used for rendering.
In addition you can upload your own image.
The parameter imageFlagsList is a list of flags defined in [NVGImageFlag].
If you will use your image as fill pattern, it will be scaled by default. To make it repeat, pass
[NVGImageFlag.RepeatX] and [NVGImageFlag.RepeatY] flags to image creation function respectively.
paints =
## Paints
NanoVega supports four types of paints: linear gradient, box gradient, radial gradient and image pattern.
These can be used as paints for strokes and fills.
gpu_affine =
## Render-Time Affine Transformations
It is possible to set affine transformation matrix for GPU. That matrix will
be applied by the shader code. This can be used to quickly translate and rotate
saved paths. Call this $(B only) between [beginFrame] and [endFrame].
Note that [beginFrame] resets this matrix to identity one.
$(WARNING Don't use this for scaling or skewing, or your image will be heavily distorted!)
paths =
## Paths
Drawing a new shape starts with [beginPath], it clears all the currently defined paths.
Then you define one or more paths and sub-paths which describe the shape. The are functions
to draw common shapes like rectangles and circles, and lower level step-by-step functions,
which allow to define a path curve by curve.
NanoVega uses even-odd fill rule to draw the shapes. Solid shapes should have counter clockwise
winding and holes should have counter clockwise order. To specify winding of a path you can
call [pathWinding]. This is useful especially for the common shapes, which are drawn CCW.
Finally you can fill the path using current fill style by calling [fill], and stroke it
with current stroke style by calling [stroke].
The curve segments and sub-paths are transformed by the current transform.
picking_api =
## Picking API
This is picking API that works directly on paths, without rasterizing them first.
[beginFrame] resets picking state. Then you can create paths as usual, but
there is a possibility to perform hit checks $(B before) rasterizing a path.
Call either id assigning functions ([currFillHitId]/[currStrokeHitId]), or
immediate hit test functions ([hitTestCurrFill]/[hitTestCurrStroke])
before rasterizing (i.e. calling [fill] or [stroke]) to perform hover
effects, for example.
Also note that picking API is ignoring GPU affine transformation matrix.
You can "untransform" picking coordinates before checking with [gpuUntransformPoint].
$(WARNING Picking API completely ignores clipping. If you want to check for
clip regions, you have to manually register them as fill/stroke paths,
and perform the necessary logic. See [hitTestForId] function.)
clipping =
## Clipping with paths
If scissoring is not enough for you, you can clip rendering with arbitrary path,
or with combination of paths. Clip region is saved by [save] and restored by
[restore] NanoVega functions. You can combine clip paths with various logic
operations, see [NVGClipMode].
Note that both [clip] and [clipStroke] are ignoring scissoring (i.e. clip mask
is created as if there was no scissor set). Actual rendering is affected by
scissors, though.
text_api =
## Text
NanoVega allows you to load .ttf files and use the font to render text.
You have to load some font, and set proper font size before doing anything
with text, as there is no "default" font provided by NanoVega. Also, don't
forget to check return value of `createFont()`, 'cause NanoVega won't fail
if it cannot load font, it will silently try to render nothing.
The appearance of the text can be defined by setting the current text style
and by specifying the fill color. Common text and font settings such as
font size, letter spacing and text align are supported. Font blur allows you
to create simple text effects such as drop shadows.
At render time the font face can be set based on the font handles or name.
----------------------
// in initialization:
auto font = ctx.createFont("Roboto", "fonts/Roboto.ttf");
enforce(font != -1, "Failed to load font!");
foreach (fallbackPath; ["fonts/NotoSans.ttf"]) {
auto fallback = ctx.createFont("fallback", fallbackPath);
if (fallback == -1) {
stderr.writeln("Failed to load fallback font ", fallbackPath);
continue;
}
ctx.addFallbackFont(font, fallback);
}
// rendering:
ctx.fontFaceId = font;
//ctx.fontBlur = 3;
//ctx.textAlign = NVGTextAlign.H.Center;
ctx.fontSize = 20;
ctx.fillColor = NVGColor.white;
ctx.text(0, height, text);
----------------------
Font measure functions return values in local space, the calculations are
carried in the same resolution as the final rendering. This is done because
the text glyph positions are snapped to the nearest pixels sharp rendering.
The local space means that values are not rotated or scale as per the current
transformation. For example if you set font size to 12, which would mean that
line height is 16, then regardless of the current scaling and rotation, the
returned line height is always 16. Some measures may vary because of the scaling
since aforementioned pixel snapping.
While this may sound a little odd, the setup allows you to always render the
same way regardless of scaling. I.e. following works regardless of scaling:
----------------------
string txt = "Text me up.";
vg.textBounds(x, y, txt, bounds);
vg.beginPath();
vg.roundedRect(bounds[0], bounds[1], bounds[2]-bounds[0], bounds[3]-bounds[1], 6);
vg.fill();
----------------------
Note: currently only solid color fill is supported for text.
font_stash =
## Low-Level Font Engine (FontStash)
FontStash is used to load fonts, to manage font atlases, and to get various text metrics.
You don't need any graphics context to use FontStash, so you can do things like text
layouting outside of your rendering code. Loaded fonts are refcounted, so it is cheap
to create new FontStash, copy fonts from NanoVega context into it, and use that new
FontStash to do some UI layouting, for example. Also note that you can get text metrics
without creating glyph bitmaps (by using [FONSTextBoundsIterator], for example); this way
you don't need to waste CPU and memory resources to render unneeded images into font atlas,
and you can layout alot of text very fast.
Note that "FontStash" is abbrevated as "FONS". So when you see some API that contains
word "fons" in it, this is not a typo, and it should not read "font" intead.
TODO for Ketmar: write some nice example code here, and finish documenting FontStash API.
*/
module arsd.nanovega;
/// This example shows how to do the NanoVega sample without the [NVGWindow] helper class.
unittest {
import arsd.simpledisplay;
import arsd.nanovega;
void main () {
NVGContext nvg; // our NanoVega context
// we need at least OpenGL3 with GLSL to use NanoVega,
// so let's tell simpledisplay about that
setOpenGLContextVersion(3, 0);
// now create OpenGL window
auto sdmain = new SimpleWindow(800, 600, "NanoVega Simple Sample", OpenGlOptions.yes, Resizability.allowResizing);
// we need to destroy NanoVega context on window close
// stricly speaking, it is not necessary, as nothing fatal
// will happen if you'll forget it, but let's be polite.
// note that we cannot do that *after* our window was closed,
// as we need alive OpenGL context to do proper cleanup.
sdmain.onClosing = delegate () {
nvg.kill();
};
// this is called just before our window will be shown for the first time.
// we must create NanoVega context here, as it needs to initialize
// internal OpenGL subsystem with valid OpenGL context.
sdmain.visibleForTheFirstTime = delegate () {
// yes, that's all
sdmain.setAsCurrentOpenGlContext();
nvg = nvgCreateContext();
if (nvg is null) assert(0, "cannot initialize NanoVega");
};
// this callback will be called when we will need to repaint our window
sdmain.redrawOpenGlScene = delegate () {
// fix viewport (we can do this in resize event, or here, it doesn't matter)
glViewport(0, 0, sdmain.width, sdmain.height);
// clear window
glClearColor(0, 0, 0, 0);
glClear(glNVGClearFlags); // use NanoVega API to get flags for OpenGL call
{
nvg.beginFrame(sdmain.width, sdmain.height); // begin rendering
scope(exit) nvg.endFrame(); // and flush render queue on exit
nvg.beginPath(); // start new path
nvg.roundedRect(20.5, 30.5, sdmain.width-40, sdmain.height-60, 8); // .5 to draw at pixel center (see NanoVega documentation)
// now set filling mode for our rectangle
// you can create colors using HTML syntax, or with convenient constants
nvg.fillPaint = nvg.linearGradient(20.5, 30.5, sdmain.width-40, sdmain.height-60, NVGColor("#f70"), NVGColor.green);
// now fill our rect
nvg.fill();
// and draw a nice outline
nvg.strokeColor = NVGColor.white;
nvg.strokeWidth = 2;
nvg.stroke();
// that's all, folks!
}
};
sdmain.eventLoop(0, // no pulse timer required
delegate (KeyEvent event) {
if (event == "*-Q" || event == "Escape") { sdmain.close(); return; } // quit on Q, Ctrl+Q, and so on
},
);
flushGui(); // let OS do it's cleanup
}
}
private:
version(aliced) {
import iv.meta;
import iv.vfs;
} else {
private alias usize = size_t;
// i fear phobos!
private template Unqual(T) {
static if (is(T U == immutable U)) alias Unqual = U;
else static if (is(T U == shared inout const U)) alias Unqual = U;
else static if (is(T U == shared inout U)) alias Unqual = U;
else static if (is(T U == shared const U)) alias Unqual = U;
else static if (is(T U == shared U)) alias Unqual = U;
else static if (is(T U == inout const U)) alias Unqual = U;
else static if (is(T U == inout U)) alias Unqual = U;
else static if (is(T U == const U)) alias Unqual = U;
else alias Unqual = T;
}
private template isAnyCharType(T, bool unqual=false) {
static if (unqual) private alias UT = Unqual!T; else private alias UT = T;
enum isAnyCharType = is(UT == char) || is(UT == wchar) || is(UT == dchar);
}
private template isWideCharType(T, bool unqual=false) {
static if (unqual) private alias UT = Unqual!T; else private alias UT = T;
enum isWideCharType = is(UT == wchar) || is(UT == dchar);
}
}
version(nanovg_disable_vfs) {
enum NanoVegaHasIVVFS = false;
} else {
static if (is(typeof((){import iv.vfs;}))) {
enum NanoVegaHasIVVFS = true;
import iv.vfs;
} else {
enum NanoVegaHasIVVFS = false;
}
}
// ////////////////////////////////////////////////////////////////////////// //
// engine
// ////////////////////////////////////////////////////////////////////////// //
import core.stdc.stdlib : malloc, realloc, free;
import core.stdc.string : memset, memcpy, strlen;
import std.math : PI;
//version = nanovg_force_stb_ttf;
version(Posix) {
version = nanovg_use_freetype;
} else {
version = nanovg_disable_fontconfig;
}
version (bindbc) {
version = nanovg_builtin_fontconfig_bindings;
version = nanovg_bindbc_opengl_bindings;
version = nanovg_bindbc_freetype_bindings;
version(BindFT_Dynamic)
static assert(0, "AsumFace was too lazy to write the code for the dynamic bindbc freetype bindings");
else {
version(BindFT_Static) {}
else
static assert(0, "well, duh. you got to pass the BindFT_Static version identifier to the compiler");
}
} else version(aliced) {
version = nanovg_default_no_font_aa;
version = nanovg_builtin_fontconfig_bindings;
version = nanovg_builtin_freetype_bindings;
version = nanovg_builtin_opengl_bindings; // use `arsd.simpledisplay` to get basic bindings
} else {
version (neverHave_bindbc_opengl)
version = nanovg_bindbc_opengl_bindings;
else
version = nanovg_builtin_opengl_bindings; // use `arsd.simpledisplay` to get basic bindings
version (neverHave_bindbc_freetype)
version = nanovg_bindbc_freetype_bindings;
else
version = nanovg_builtin_freetype_bindings;
version = nanovg_builtin_fontconfig_bindings;
}
version(nanovg_disable_fontconfig) {
public enum NanoVegaHasFontConfig = false;
} else {
public enum NanoVegaHasFontConfig = true;
version(nanovg_builtin_fontconfig_bindings) {} else import iv.fontconfig;
}
//version = nanovg_bench_flatten;
/++
Annotation to indicate the marked function is compatible with [arsd.script].
Any function that takes a [Color] argument will be passed a string instead.
Scriptable Functions
====================
$(UDA_USES)
$(ALWAYS_DOCUMENT)
+/
private enum scriptable = "arsd_jsvar_compatible";
public:
alias NVG_PI = PI;
enum NanoVegaHasArsdColor = (is(typeof((){ import arsd.color; })));
enum NanoVegaHasArsdImage = (is(typeof((){ import arsd.color; import arsd.image; })));
static if (NanoVegaHasArsdColor) private import arsd.color;
static if (NanoVegaHasArsdImage) {
private import arsd.image;
} else {
void stbi_set_unpremultiply_on_load (int flag_true_if_should_unpremultiply) {}
void stbi_convert_iphone_png_to_rgb (int flag_true_if_should_convert) {}
ubyte* stbi_load (const(char)* filename, int* x, int* y, int* comp, int req_comp) { return null; }
ubyte* stbi_load_from_memory (const(void)* buffer, int len, int* x, int* y, int* comp, int req_comp) { return null; }
void stbi_image_free (void* retval_from_stbi_load) {}
}
version(nanovg_default_no_font_aa) {
__gshared bool NVG_INVERT_FONT_AA = false;
} else {
__gshared bool NVG_INVERT_FONT_AA = true;
}
/// this is branchless for ints on x86, and even for longs on x86_64
public ubyte nvgClampToByte(T) (T n) pure nothrow @safe @nogc if (__traits(isIntegral, T)) {
static if (__VERSION__ > 2067) pragma(inline, true);
static if (T.sizeof == 2 || T.sizeof == 4) {
static if (__traits(isUnsigned, T)) {
return cast(ubyte)(n&0xff|(255-((-cast(int)(n < 256))>>24)));
} else {
n &= -cast(int)(n >= 0);
return cast(ubyte)(n|((255-cast(int)n)>>31));
}
} else static if (T.sizeof == 1) {
static assert(__traits(isUnsigned, T), "clampToByte: signed byte? no, really?");
return cast(ubyte)n;
} else static if (T.sizeof == 8) {
static if (__traits(isUnsigned, T)) {
return cast(ubyte)(n&0xff|(255-((-cast(long)(n < 256))>>56)));
} else {
n &= -cast(long)(n >= 0);
return cast(ubyte)(n|((255-cast(long)n)>>63));
}
} else {
static assert(false, "clampToByte: integer too big");
}
}
/// NanoVega RGBA color
/// Group: color_utils
public align(1) struct NVGColor {
align(1):
public:
float[4] rgba = 0; /// default color is transparent (a=1 is opaque)
public:
@property string toString () const @safe { import std.string : format; return "NVGColor(%s,%s,%s,%s)".format(r, g, b, a); }
public:
enum transparent = NVGColor(0.0f, 0.0f, 0.0f, 0.0f);
enum k8orange = NVGColor(1.0f, 0.5f, 0.0f, 1.0f);
enum aliceblue = NVGColor(240, 248, 255);
enum antiquewhite = NVGColor(250, 235, 215);
enum aqua = NVGColor(0, 255, 255);
enum aquamarine = NVGColor(127, 255, 212);
enum azure = NVGColor(240, 255, 255);
enum beige = NVGColor(245, 245, 220);
enum bisque = NVGColor(255, 228, 196);
enum black = NVGColor(0, 0, 0); // basic color
enum blanchedalmond = NVGColor(255, 235, 205);
enum blue = NVGColor(0, 0, 255); // basic color
enum blueviolet = NVGColor(138, 43, 226);
enum brown = NVGColor(165, 42, 42);
enum burlywood = NVGColor(222, 184, 135);
enum cadetblue = NVGColor(95, 158, 160);
enum chartreuse = NVGColor(127, 255, 0);
enum chocolate = NVGColor(210, 105, 30);
enum coral = NVGColor(255, 127, 80);
enum cornflowerblue = NVGColor(100, 149, 237);
enum cornsilk = NVGColor(255, 248, 220);
enum crimson = NVGColor(220, 20, 60);
enum cyan = NVGColor(0, 255, 255); // basic color
enum darkblue = NVGColor(0, 0, 139);
enum darkcyan = NVGColor(0, 139, 139);
enum darkgoldenrod = NVGColor(184, 134, 11);
enum darkgray = NVGColor(169, 169, 169);
enum darkgreen = NVGColor(0, 100, 0);
enum darkgrey = NVGColor(169, 169, 169);
enum darkkhaki = NVGColor(189, 183, 107);
enum darkmagenta = NVGColor(139, 0, 139);
enum darkolivegreen = NVGColor(85, 107, 47);
enum darkorange = NVGColor(255, 140, 0);
enum darkorchid = NVGColor(153, 50, 204);
enum darkred = NVGColor(139, 0, 0);
enum darksalmon = NVGColor(233, 150, 122);
enum darkseagreen = NVGColor(143, 188, 143);
enum darkslateblue = NVGColor(72, 61, 139);
enum darkslategray = NVGColor(47, 79, 79);
enum darkslategrey = NVGColor(47, 79, 79);
enum darkturquoise = NVGColor(0, 206, 209);
enum darkviolet = NVGColor(148, 0, 211);
enum deeppink = NVGColor(255, 20, 147);
enum deepskyblue = NVGColor(0, 191, 255);
enum dimgray = NVGColor(105, 105, 105);
enum dimgrey = NVGColor(105, 105, 105);
enum dodgerblue = NVGColor(30, 144, 255);
enum firebrick = NVGColor(178, 34, 34);
enum floralwhite = NVGColor(255, 250, 240);
enum forestgreen = NVGColor(34, 139, 34);
enum fuchsia = NVGColor(255, 0, 255);
enum gainsboro = NVGColor(220, 220, 220);
enum ghostwhite = NVGColor(248, 248, 255);
enum gold = NVGColor(255, 215, 0);
enum goldenrod = NVGColor(218, 165, 32);
enum gray = NVGColor(128, 128, 128); // basic color
enum green = NVGColor(0, 128, 0); // basic color
enum greenyellow = NVGColor(173, 255, 47);
enum grey = NVGColor(128, 128, 128); // basic color
enum honeydew = NVGColor(240, 255, 240);
enum hotpink = NVGColor(255, 105, 180);
enum indianred = NVGColor(205, 92, 92);
enum indigo = NVGColor(75, 0, 130);
enum ivory = NVGColor(255, 255, 240);
enum khaki = NVGColor(240, 230, 140);
enum lavender = NVGColor(230, 230, 250);
enum lavenderblush = NVGColor(255, 240, 245);
enum lawngreen = NVGColor(124, 252, 0);
enum lemonchiffon = NVGColor(255, 250, 205);
enum lightblue = NVGColor(173, 216, 230);
enum lightcoral = NVGColor(240, 128, 128);
enum lightcyan = NVGColor(224, 255, 255);
enum lightgoldenrodyellow = NVGColor(250, 250, 210);
enum lightgray = NVGColor(211, 211, 211);
enum lightgreen = NVGColor(144, 238, 144);
enum lightgrey = NVGColor(211, 211, 211);
enum lightpink = NVGColor(255, 182, 193);
enum lightsalmon = NVGColor(255, 160, 122);
enum lightseagreen = NVGColor(32, 178, 170);
enum lightskyblue = NVGColor(135, 206, 250);
enum lightslategray = NVGColor(119, 136, 153);
enum lightslategrey = NVGColor(119, 136, 153);
enum lightsteelblue = NVGColor(176, 196, 222);
enum lightyellow = NVGColor(255, 255, 224);
enum lime = NVGColor(0, 255, 0);
enum limegreen = NVGColor(50, 205, 50);
enum linen = NVGColor(250, 240, 230);
enum magenta = NVGColor(255, 0, 255); // basic color
enum maroon = NVGColor(128, 0, 0);
enum mediumaquamarine = NVGColor(102, 205, 170);
enum mediumblue = NVGColor(0, 0, 205);
enum mediumorchid = NVGColor(186, 85, 211);
enum mediumpurple = NVGColor(147, 112, 219);
enum mediumseagreen = NVGColor(60, 179, 113);
enum mediumslateblue = NVGColor(123, 104, 238);
enum mediumspringgreen = NVGColor(0, 250, 154);
enum mediumturquoise = NVGColor(72, 209, 204);
enum mediumvioletred = NVGColor(199, 21, 133);
enum midnightblue = NVGColor(25, 25, 112);
enum mintcream = NVGColor(245, 255, 250);
enum mistyrose = NVGColor(255, 228, 225);
enum moccasin = NVGColor(255, 228, 181);
enum navajowhite = NVGColor(255, 222, 173);
enum navy = NVGColor(0, 0, 128);
enum oldlace = NVGColor(253, 245, 230);
enum olive = NVGColor(128, 128, 0);
enum olivedrab = NVGColor(107, 142, 35);
enum orange = NVGColor(255, 165, 0);
enum orangered = NVGColor(255, 69, 0);
enum orchid = NVGColor(218, 112, 214);
enum palegoldenrod = NVGColor(238, 232, 170);
enum palegreen = NVGColor(152, 251, 152);
enum paleturquoise = NVGColor(175, 238, 238);
enum palevioletred = NVGColor(219, 112, 147);
enum papayawhip = NVGColor(255, 239, 213);
enum peachpuff = NVGColor(255, 218, 185);
enum peru = NVGColor(205, 133, 63);
enum pink = NVGColor(255, 192, 203);
enum plum = NVGColor(221, 160, 221);
enum powderblue = NVGColor(176, 224, 230);
enum purple = NVGColor(128, 0, 128);
enum red = NVGColor(255, 0, 0); // basic color
enum rosybrown = NVGColor(188, 143, 143);
enum royalblue = NVGColor(65, 105, 225);
enum saddlebrown = NVGColor(139, 69, 19);
enum salmon = NVGColor(250, 128, 114);
enum sandybrown = NVGColor(244, 164, 96);
enum seagreen = NVGColor(46, 139, 87);
enum seashell = NVGColor(255, 245, 238);
enum sienna = NVGColor(160, 82, 45);
enum silver = NVGColor(192, 192, 192);
enum skyblue = NVGColor(135, 206, 235);
enum slateblue = NVGColor(106, 90, 205);
enum slategray = NVGColor(112, 128, 144);
enum slategrey = NVGColor(112, 128, 144);
enum snow = NVGColor(255, 250, 250);
enum springgreen = NVGColor(0, 255, 127);
enum steelblue = NVGColor(70, 130, 180);
enum tan = NVGColor(210, 180, 140);
enum teal = NVGColor(0, 128, 128);
enum thistle = NVGColor(216, 191, 216);
enum tomato = NVGColor(255, 99, 71);
enum turquoise = NVGColor(64, 224, 208);
enum violet = NVGColor(238, 130, 238);
enum wheat = NVGColor(245, 222, 179);
enum white = NVGColor(255, 255, 255); // basic color
enum whitesmoke = NVGColor(245, 245, 245);
enum yellow = NVGColor(255, 255, 0); // basic color
enum yellowgreen = NVGColor(154, 205, 50);
nothrow @safe @nogc:
public:
///
this (ubyte ar, ubyte ag, ubyte ab, ubyte aa=255) pure {
pragma(inline, true);
r = ar/255.0f;
g = ag/255.0f;
b = ab/255.0f;
a = aa/255.0f;
}
///
this (float ar, float ag, float ab, float aa=1.0f) pure {
pragma(inline, true);
r = ar;
g = ag;
b = ab;
a = aa;
}
/// AABBGGRR (same format as little-endian RGBA image, coincidentally, the same as arsd.color)
this (uint c) pure {
pragma(inline, true);
r = (c&0xff)/255.0f;
g = ((c>>8)&0xff)/255.0f;
b = ((c>>16)&0xff)/255.0f;
a = ((c>>24)&0xff)/255.0f;
}
/// Supports: "#rgb", "#rrggbb", "#argb", "#aarrggbb"
this (const(char)[] srgb) {
static int c2d (char ch) pure nothrow @safe @nogc {
pragma(inline, true);
return
ch >= '0' && ch <= '9' ? ch-'0' :
ch >= 'A' && ch <= 'F' ? ch-'A'+10 :
ch >= 'a' && ch <= 'f' ? ch-'a'+10 :
-1;
}
int[8] digs;
int dc = -1;
foreach (immutable char ch; srgb) {
if (ch <= ' ') continue;
if (ch == '#') {
if (dc != -1) { dc = -1; break; }
dc = 0;
} else {
if (dc >= digs.length) { dc = -1; break; }
if ((digs[dc++] = c2d(ch)) < 0) { dc = -1; break; }
}
}
switch (dc) {
case 3: // rgb
a = 1.0f;
r = digs[0]/15.0f;
g = digs[1]/15.0f;
b = digs[2]/15.0f;
break;
case 4: // argb
a = digs[0]/15.0f;
r = digs[1]/15.0f;
g = digs[2]/15.0f;
b = digs[3]/15.0f;
break;
case 6: // rrggbb
a = 1.0f;
r = (digs[0]*16+digs[1])/255.0f;
g = (digs[2]*16+digs[3])/255.0f;
b = (digs[4]*16+digs[5])/255.0f;
break;
case 8: // aarrggbb
a = (digs[0]*16+digs[1])/255.0f;
r = (digs[2]*16+digs[3])/255.0f;
g = (digs[4]*16+digs[5])/255.0f;
b = (digs[6]*16+digs[7])/255.0f;
break;
default:
break;
}
}
/// Is this color completely opaque?
@property bool isOpaque () const pure nothrow @trusted @nogc { pragma(inline, true); return (rgba.ptr[3] >= 1.0f); }
/// Is this color completely transparent?
@property bool isTransparent () const pure nothrow @trusted @nogc { pragma(inline, true); return (rgba.ptr[3] <= 0.0f); }
/// AABBGGRR (same format as little-endian RGBA image, coincidentally, the same as arsd.color)
@property uint asUint () const pure {
pragma(inline, true);
return
cast(uint)(r*255)|
(cast(uint)(g*255)<<8)|
(cast(uint)(b*255)<<16)|
(cast(uint)(a*255)<<24);
}
alias asUintABGR = asUint; /// Ditto.
/// AABBGGRR (same format as little-endian RGBA image, coincidentally, the same as arsd.color)
static NVGColor fromUint (uint c) pure { pragma(inline, true); return NVGColor(c); }
alias fromUintABGR = fromUint; /// Ditto.
/// AARRGGBB
@property uint asUintARGB () const pure {
pragma(inline, true);
return
cast(uint)(b*255)|
(cast(uint)(g*255)<<8)|
(cast(uint)(r*255)<<16)|
(cast(uint)(a*255)<<24);
}
/// AARRGGBB
static NVGColor fromUintARGB (uint c) pure { pragma(inline, true); return NVGColor((c>>16)&0xff, (c>>8)&0xff, c&0xff, (c>>24)&0xff); }
@property ref inout(float) r () inout pure @trusted { pragma(inline, true); return rgba.ptr[0]; } ///
@property ref inout(float) g () inout pure @trusted { pragma(inline, true); return rgba.ptr[1]; } ///
@property ref inout(float) b () inout pure @trusted { pragma(inline, true); return rgba.ptr[2]; } ///
@property ref inout(float) a () inout pure @trusted { pragma(inline, true); return rgba.ptr[3]; } ///
ref NVGColor applyTint() (const scope auto ref NVGColor tint) nothrow @trusted @nogc {
if (tint.a == 0) return this;
foreach (immutable idx, ref float v; rgba[0..4]) {
v = nvg__clamp(v*tint.rgba.ptr[idx], 0.0f, 1.0f);
}
return this;
}
NVGHSL asHSL() (bool useWeightedLightness=false) const { pragma(inline, true); return NVGHSL.fromColor(this, useWeightedLightness); } ///
static fromHSL() (const scope auto ref NVGHSL hsl) { pragma(inline, true); return hsl.asColor; } ///
static if (NanoVegaHasArsdColor) {
Color toArsd () const { pragma(inline, true); return Color(cast(int)(r*255), cast(int)(g*255), cast(int)(b*255), cast(int)(a*255)); } ///
static NVGColor fromArsd (in Color c) { pragma(inline, true); return NVGColor(c.r, c.g, c.b, c.a); } ///
///
this (in Color c) {
version(aliced) pragma(inline, true);
r = c.r/255.0f;
g = c.g/255.0f;
b = c.b/255.0f;
a = c.a/255.0f;
}
}
}
/// NanoVega A-HSL color
/// Group: color_utils
public align(1) struct NVGHSL {
align(1):
float h=0, s=0, l=1, a=1; ///