-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathnanovg_gl.h
1868 lines (1707 loc) · 64 KB
/
nanovg_gl.h
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
//
// Copyright (c) 2020 Stylus Labs - see LICENSE.txt
// based on nanovg:
// Copyright (c) 2013 Mikko Mononen [email protected]
//
#ifndef NANOVG_GL_H
#define NANOVG_GL_H
#ifdef IDE_INCLUDES
// defines and includes to make IDE useful
#include "../example/platform.h"
#define NANOVG_GLES3_IMPLEMENTATION
#include "nanovg.h"
#endif
#ifdef __cplusplus
extern "C" {
#endif
// Create flags
enum NVGLcreateFlags {
// Flag indicating that additional debug checks are done.
NVGL_DEBUG = 1<<2, // This value is hardcoded in Write's config - don't change!
// disable GL_EXT_shader_framebuffer_fetch (FB fetch is slower than FB swap on Intel GPUs)
NVGL_NO_FB_FETCH = 1<<4,
// disable GL_OES_shader_image_atomic/GL_ARB_shader_image_load_store
NVGL_NO_IMG_ATOMIC = 1<<5,
};
//#if defined NANOVG_GL2_IMPLEMENTATION
//# define NANOVG_GL2 1
//# define NANOVG_GL_IMPLEMENTATION 1
//#elif defined NANOVG_GLES2_IMPLEMENTATION
//# define NANOVG_GLES2 1
//# define NANOVG_GL_IMPLEMENTATION 1
#if defined NANOVG_GL3_IMPLEMENTATION
# define NANOVG_GL3 1
# define NANOVG_GL_IMPLEMENTATION 1
# define NANOVG_GLU_IMPLEMENTATION 1
# define NANOVG_GL_USE_UNIFORMBUFFER 1 // uniform buffers avail in OpenGL 3.1+
#elif defined NANOVG_GLES3_IMPLEMENTATION
# define NANOVG_GLES3 1
# define NANOVG_GL_IMPLEMENTATION 1
# define NANOVG_GLU_IMPLEMENTATION 1
# define NANOVG_GL_USE_UNIFORMBUFFER 0 // uniform buffer slower, at least on desktop and iPhone 6S
#endif
#ifndef NVG_HAS_EXT
#ifdef __glad_h_
#define NVG_HAS_EXT(ext) (GLAD_GL_##ext)
#elif defined(GLEW_VERSION)
#define NVG_HAS_EXT(ext) (GLEW_##ext)
#elif defined(__APPLE__) && (TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE)
// assumes GL_##ext is defined
#define NVG_HAS_EXT(ext) (1)
#else
#define NVG_HAS_EXT(ext) (strstr((const char*)glGetString(GL_EXTENSIONS), #ext) != NULL)
#endif
#endif
#define NANOVG_GL_USE_STATE_FILTER (0)
// Create a NanoVG context; flags should be combination of the create flags above.
NVGcontext* nvglCreate(int flags);
void nvglDelete(NVGcontext* ctx);
int nvglCreateImageFromHandle(NVGcontext* ctx, GLuint textureId, int w, int h, int flags);
GLuint nvglImageHandle(NVGcontext* ctx, int image);
// These are additional flags on top of NVGimageFlags.
enum NVGimageFlagsGL {
NVG_IMAGE_NODELETE = 1<<16, // Do not delete GL texture handle.
};
#ifdef __cplusplus
}
#endif
#endif /* NANOVG_GL_H */
#ifdef NANOVG_GL_IMPLEMENTATION
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "nanovg.h"
enum GLNVGuniformLoc {
GLNVG_LOC_VIEWSIZE,
GLNVG_LOC_TEX,
GLNVG_LOC_TYPE,
GLNVG_LOC_WINDINGTEX,
GLNVG_LOC_WINDINGYMIN,
GLNVG_LOC_FRAG,
GLNVG_LOC_IMGPARAMS,
GLNVG_LOC_WINDINGIMG,
GLNVG_MAX_LOCS
};
enum GLNVGshaderType {
NSVG_SHADER_WINDINGCLEAR = 0,
NSVG_SHADER_WINDINGCALC = 1,
NSVG_SHADER_FILLSOLID = 2,
NSVG_SHADER_FILLGRAD = 3,
NSVG_SHADER_FILLIMG = 4,
NSVG_SHADER_TEXT = 5
};
enum GLNVGrenderMethod {
NVGL_RENDER_FB_SWAP = 0,
NVGL_RENDER_FB_FETCH = 1,
NVGL_RENDER_IMG_ATOMIC = 2
};
#if NANOVG_GL_USE_UNIFORMBUFFER
enum GLNVGuniformBindings {
GLNVG_FRAG_BINDING = 0,
};
#endif
struct GLNVGshader {
GLuint prog;
GLuint frag;
GLuint vert;
GLint loc[GLNVG_MAX_LOCS];
};
typedef struct GLNVGshader GLNVGshader;
struct GLNVGtexture {
int id;
GLuint tex;
int width, height;
int type;
int flags;
};
typedef struct GLNVGtexture GLNVGtexture;
struct GLNVGblend
{
GLenum srcRGB;
GLenum dstRGB;
GLenum srcAlpha;
GLenum dstAlpha;
};
typedef struct GLNVGblend GLNVGblend;
enum GLNVGcallType {
GLNVG_NONE = 0,
GLNVG_FILL,
GLNVG_CONVEXFILL,
GLNVG_TRIANGLES,
};
struct GLNVGcall {
int type;
int fragType;
int image;
int pathOffset;
int pathCount;
int triangleOffset;
int triangleCount;
int uniformOffset;
int imgOffset;
int bounds[4];
GLNVGblend blendFunc;
};
typedef struct GLNVGcall GLNVGcall;
struct GLNVGpath {
int fillOffset;
int fillCount;
float yMin; // for winding number calc
};
typedef struct GLNVGpath GLNVGpath;
struct NVGLcolor {
float r,g,b,a;
};
typedef struct NVGLcolor NVGLcolor;
struct GLNVGfragUniforms {
#if NANOVG_GL_USE_UNIFORMBUFFER
float scissorMat[12]; // matrices are actually 3 vec4s
float paintMat[12];
NVGLcolor innerCol;
NVGLcolor outerCol;
float scissorExt[2];
float scissorScale[2];
float extent[2];
float radius;
float feather;
float strokeMult;
float strokeThr;
int texType;
int fillMode;
#else
// note: after modifying layout or size of uniform array,
// don't forget to also update the fragment shader source!
#define NANOVG_GL_UNIFORMARRAY_SIZE 11
union {
struct {
float scissorMat[12]; // matrices are actually 3 vec4s
float paintMat[12];
NVGLcolor innerCol;
NVGLcolor outerCol;
float scissorExt[2];
float scissorScale[2];
float extent[2];
float radius;
float feather;
float strokeMult;
float strokeThr;
float texType;
float fillMode;
};
float uniformArray[NANOVG_GL_UNIFORMARRAY_SIZE][4];
};
#endif
};
typedef struct GLNVGfragUniforms GLNVGfragUniforms;
struct GLNVGcontext {
GLNVGshader shader;
GLNVGtexture* textures;
float view[2];
int ntextures;
int ctextures;
int textureId;
GLuint vertBuf;
#if defined NANOVG_GL3
GLuint vertArr;
#endif
#if NANOVG_GL_USE_UNIFORMBUFFER
GLuint fragBuf;
#endif
GLuint fbUser;
GLuint fbWinding;
GLuint texWinding;
GLuint texColor; // only for GL_EXT_shader_framebuffer_fetch case
float devicePixelRatio;
int fragSize;
int flags;
int renderMethod;
// Per frame buffers
GLNVGcall* calls;
int ccalls;
int ncalls;
GLNVGpath* paths;
int cpaths;
int npaths;
struct NVGvertex* verts;
int cverts;
int nverts;
unsigned char* uniforms;
int cuniforms;
int nuniforms;
int imgWindingOffset;
int imgWindingSize;
// cached state
#if NANOVG_GL_USE_STATE_FILTER
GLuint boundTexture;
GLNVGblend blendFunc;
#endif
};
typedef struct GLNVGcontext GLNVGcontext;
#ifndef NVG_LOG
#include <stdio.h>
#define NVG_LOG(...) fprintf(stderr, __VA_ARGS__)
#endif
static int glnvg__maxi(int a, int b) { return a > b ? a : b; }
static int glnvg__clampi(int a, int mn, int mx) { return a < mn ? mn : (a > mx ? mx : a); }
#ifdef NANOVG_GLES2
static unsigned int glnvg__nearestPow2(unsigned int num)
{
unsigned n = num > 0 ? num - 1 : 0;
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
n++;
return n;
}
#endif
static void glnvg__bindTexture(GLNVGcontext* gl, GLuint tex)
{
#if NANOVG_GL_USE_STATE_FILTER
if (gl->boundTexture != tex) {
gl->boundTexture = tex;
glBindTexture(GL_TEXTURE_2D, tex);
}
#else
glBindTexture(GL_TEXTURE_2D, tex);
#endif
}
static void glnvg__blendFuncSeparate(GLNVGcontext* gl, const GLNVGblend* blend)
{
#if NANOVG_GL_USE_STATE_FILTER
if ((gl->blendFunc.srcRGB != blend->srcRGB) ||
(gl->blendFunc.dstRGB != blend->dstRGB) ||
(gl->blendFunc.srcAlpha != blend->srcAlpha) ||
(gl->blendFunc.dstAlpha != blend->dstAlpha)) {
gl->blendFunc = *blend;
glBlendFuncSeparate(blend->srcRGB, blend->dstRGB, blend->srcAlpha,blend->dstAlpha);
}
#else
glBlendFuncSeparate(blend->srcRGB, blend->dstRGB, blend->srcAlpha,blend->dstAlpha);
#endif
}
static GLNVGtexture* glnvg__allocTexture(GLNVGcontext* gl)
{
GLNVGtexture* tex = NULL;
int i;
for (i = 0; i < gl->ntextures; i++) {
if (gl->textures[i].id == 0) {
tex = &gl->textures[i];
break;
}
}
if (tex == NULL) {
if (gl->ntextures+1 > gl->ctextures) {
GLNVGtexture* textures;
int ctextures = glnvg__maxi(gl->ntextures+1, 4) + gl->ctextures/2; // 1.5x Overallocate
textures = (GLNVGtexture*)realloc(gl->textures, sizeof(GLNVGtexture)*ctextures);
if (textures == NULL) return NULL;
gl->textures = textures;
gl->ctextures = ctextures;
}
tex = &gl->textures[gl->ntextures++];
}
memset(tex, 0, sizeof(*tex));
tex->id = ++gl->textureId;
return tex;
}
static GLNVGtexture* glnvg__findTexture(GLNVGcontext* gl, int id)
{
int i;
if (!id) return NULL;
for (i = 0; i < gl->ntextures; i++)
if (gl->textures[i].id == id)
return &gl->textures[i];
return NULL;
}
static int glnvg__deleteTexture(GLNVGcontext* gl, int id)
{
int i;
for (i = 0; i < gl->ntextures; i++) {
if (gl->textures[i].id == id) {
if (gl->textures[i].tex != 0 && (gl->textures[i].flags & NVG_IMAGE_NODELETE) == 0)
glDeleteTextures(1, &gl->textures[i].tex);
memset(&gl->textures[i], 0, sizeof(gl->textures[i]));
return 1;
}
}
return 0;
}
static void glnvg__checkError(GLNVGcontext* gl, const char* str)
{
GLenum err;
if ((gl->flags & NVGL_DEBUG) == 0) return;
while ((err = glGetError()) != GL_NO_ERROR) {
NVG_LOG("Error 0x%08x after %s\n", err, str);
}
}
static int glnvg__compileShader(GLuint shader, const char* source[], int nsource)
{
GLint status;
glShaderSource(shader, nsource, source, 0);
glCompileShader(shader);
glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
if(status != GL_TRUE) {
GLchar str[512+1];
GLsizei len = 0;
glGetShaderInfoLog(shader, 512, &len, str);
str[len > 512 ? 512 : len] = '\0';
NVG_LOG("Shader error:\n%s\n", str);
#ifndef NDEBUG
NVG_LOG("Shader source:\n");
for(int ii = 0; ii < nsource; ++ii)
NVG_LOG(source[ii]);
#endif
return 0;
}
return 1;
}
static int glnvg__createProgram(GLNVGshader* shader, const char* vertsrc[], int nvertsrc, const char* fragsrc[], int nfragsrc)
{
GLint status;
shader->prog = glCreateProgram();
shader->vert = glCreateShader(GL_VERTEX_SHADER);
shader->frag = glCreateShader(GL_FRAGMENT_SHADER);
if(glnvg__compileShader(shader->vert, vertsrc, nvertsrc) == 0)
return 0;
if(glnvg__compileShader(shader->frag, fragsrc, nfragsrc) == 0)
return 0;
glAttachShader(shader->prog, shader->vert);
glAttachShader(shader->prog, shader->frag);
glBindAttribLocation(shader->prog, 0, "va_in");
glBindAttribLocation(shader->prog, 1, "vb_in");
glLinkProgram(shader->prog);
glGetProgramiv(shader->prog, GL_LINK_STATUS, &status);
if(status != GL_TRUE) {
GLchar str[512+1];
GLsizei len = 0;
glGetProgramInfoLog(shader->prog, 512, &len, str);
str[len > 512 ? 512 : len] = '\0';
NVG_LOG("Program error:\n%s\n", str);
return 0;
}
return 1;
}
static void glnvg__deleteShader(GLNVGshader* shader)
{
if (shader->prog != 0)
glDeleteProgram(shader->prog);
if (shader->vert != 0)
glDeleteShader(shader->vert);
if (shader->frag != 0)
glDeleteShader(shader->frag);
}
static void glnvg__getUniforms(GLNVGshader* shader)
{
shader->loc[GLNVG_LOC_VIEWSIZE] = glGetUniformLocation(shader->prog, "viewSize");
shader->loc[GLNVG_LOC_TEX] = glGetUniformLocation(shader->prog, "tex");
shader->loc[GLNVG_LOC_TYPE] = glGetUniformLocation(shader->prog, "type");
shader->loc[GLNVG_LOC_WINDINGTEX] = glGetUniformLocation(shader->prog, "windingTex");
shader->loc[GLNVG_LOC_WINDINGYMIN] = glGetUniformLocation(shader->prog, "pathYMin");
shader->loc[GLNVG_LOC_IMGPARAMS] = glGetUniformLocation(shader->prog, "imgParams");
shader->loc[GLNVG_LOC_WINDINGIMG] = glGetUniformLocation(shader->prog, "windingImg");
#if NANOVG_GL_USE_UNIFORMBUFFER
shader->loc[GLNVG_LOC_FRAG] = glGetUniformBlockIndex(shader->prog, "frag");
#else
shader->loc[GLNVG_LOC_FRAG] = glGetUniformLocation(shader->prog, "frag");
#endif
}
/* Consider a directed line segment va -> vb of the path being rendered:
^ Y v=(v0.x - 0.55, ymax + 0.55)
| ymax ^ v1
| n=(-1,1) XXXXX/| n=(1,1) -> v=(v1.x + 0.55, ymax + 0.55)
| XXXX/#|
| XXX/##|
| XX/###|
| X/####| v0,v1 = va,vb if va.x < vb.x else vb,va
| /#####|
| v0|#####|
| |#####|
| pathYmin__|#####|__
| n=(-1,-1) n=(1,-1) -> v=(v1.x + 0.55, pathYmin - 0.55)
| ^ v=(v0.x - 0.55, pathYmin - 0.55)
+---------------------> X
nanovg.c converts all paths to polygons by converting strokes to fills and approximating curves w/ line
segments. For each path, the minimum y value (i.e. bottom of AABB) is passed to the VS as pathYmin.
VS: for each line segment of the polygon, 1 quad = 2 triangles = 6 vertices (4 unique) are generated; the
vertices are distinguished by "normal_in" in the VS (n=... in the figure). The VS outputs vertices (v=... in
the figure) to create the quad '#' + 'X', expanding the edges of the quad by 0.55px (0.5px wasn't sufficient
in some cases on iOS ... why?) to ensure partially convered pixels are included (triangle must cover center
of a pixel for the pixel to be included by OpenGL rasterization). Note that the expansion will not be
considered part of '#' + 'X' in the discussion below.
1st FS pass: With fpos being the center of the pixel, areaEdge2(vb - fpos, va - fpos) in the fragment shader
calculates the signed area of the intersection of trapezoid '#' with the 1px x 1px square for the pixel.
The area will be zero if va.x == vb.x or if the pixel lies entirely in the 'X' region. Otherwise, it will
be positive if va.x > vb.x and negative of va.x < vb.x. This is converted to a fixed point value and added
to the accumulated area from all trapezoids (i.e., edges) for the pixel, stored in the framebuffer for
framebuffer fetch or swap, or in an iimage2D for image load/store. In the latter case, pixels of the
bounding boxes of each polygon are mapped to sequential runs of pixels in the iimage2D.
2nd FS pass: The intersection area (i.e. pixel coverage) is read using framebuffer fetch or image load/store
and multiplied by the input RGBA color (solid color, gradient, or color from image - usually not antialiased!)
*/
// makes editing easier, but disadvantage is that commas can only be used inside ()
#define NVG_QUOTE(s) #s
static int glnvg__renderCreate(void* uptr)
{
static const char* shaderHeader =
#if defined NANOVG_GL2
"#define NANOVG_GL2 1\n"
#elif defined NANOVG_GL3
"#version 330 core\n" //"#version 150 core\n"
"#define NANOVG_GL3 1\n"
#elif defined NANOVG_GLES2
"#version 100\n"
"#define NANOVG_GL2 1\n"
#elif defined NANOVG_GLES3 && defined GL_ES_VERSION_3_1
"#version 310 es\n"
"#define NANOVG_GL3 1\n"
#elif defined NANOVG_GLES3
"#version 300 es\n"
"#define NANOVG_GL3 1\n"
#endif
// append uniform buffer string
#if NANOVG_GL_USE_UNIFORMBUFFER
"#define USE_UNIFORMBUFFER 1\n"
#else
"#define UNIFORMARRAY_SIZE 11\n"
#endif
"\n";
static const char* fillVertShader = NVG_QUOTE(
\n #ifdef NANOVG_GL3
\n #define attribute in
\n #define varying out
\n #endif
\n
\n uniform vec2 viewSize;
\n uniform float pathYMin;
\n uniform int type;
\n
\n //attribute vec2 normal_in;
\n attribute vec2 va_in;
\n attribute vec2 vb_in;
\n
\n varying vec2 va;
\n varying vec2 vb;
\n
\n const vec2 qverts[6] = vec2[](
\n vec2(-1.0f, 1.0f),
\n vec2( 1.0f, 1.0f),
\n vec2( 1.0f, -1.0f),
\n vec2(-1.0f, 1.0f),
\n vec2( 1.0f, -1.0f),
\n vec2(-1.0f, -1.0f));
\n
\n void main()
\n {
\n // nanovg passes vertices in screen coords!
\n va = va_in; //0.5f*view_wh*(vec2(1.0f) + va_in);
\n vb = vb_in; //0.5f*view_wh*(vec2(1.0f) + vb_in);
\n
\n vec2 norm = qverts[gl_VertexID % 6];
\n
\n // normal.x > 0: we are right, otherwise left
\n vec2 pos = (norm.x > 0.0f) == (va_in.x > vb_in.x) ? va_in : vb_in;
\n
\n // trapezoid will have less overdraw in some (most?) cases, but more complicated calc, so make a rectangle
\n float y_max = max(va_in.y, vb_in.y);
\n pos.y = norm.y > 0.0f ? y_max : pathYMin;
\n
\n // expand and handle special case: normal == 0 -> va is position, vb is texture coord
\n vec2 pos_ex = (type != 1) ? va_in : (pos + 0.55f*norm);
\n
\n // convert from screen coords to clip coords
\n //gl_Position = vec4(2.0f*pos_ex/viewSize - 1.0f, 0.0f, 1.0f);
\n gl_Position = vec4(2.0f*pos_ex.x/viewSize.x - 1.0f, 1.0f - 2.0f*pos_ex.y/viewSize.y, 0.0f, 1.0f);
\n }
);
// Use github.com/KhronosGroup/glslang (apt install glslang-tools) to validate shader source
static const char* fillFragShader = NVG_QUOTE
(
\n #ifdef USE_FRAMEBUFFER_FETCH
\n // #extension must come before any other statements, including precision
\n #extension GL_EXT_shader_framebuffer_fetch : require
\n #elif defined(USE_IMAGE_LOADSTORE)
\n #ifdef GL_ES
\n #extension GL_OES_shader_image_atomic : require
\n #else
\n #extension GL_ARB_shader_image_load_store : require
\n #endif
\n #endif
\n
\n #ifdef GL_ES
\n #if defined(GL_FRAGMENT_PRECISION_HIGH) || defined(NANOVG_GL3)
\n precision highp float;
\n precision highp int;
\n precision highp sampler2D;
\n #else
\n precision mediump float;
\n #endif
\n #endif
\n
\n #ifdef NANOVG_GL3
\n #define texture2D texture
\n #define varying in
\n #endif
\n
\n // these must match NVGpathFlags
\n #define NVG_PATH_EVENODD 0x1
\n #define NVG_PATH_NO_AA 0x2
\n #define NVG_PATH_CONVEX 0x4
\n
\n #ifdef USE_FRAMEBUFFER_FETCH
\n layout (location = 0) inout vec4 outColor;
\n layout (location = 1) inout int inoutWinding;
\n #elif defined(NANOVG_GL3)
\n layout (location = 0) out vec4 outColor;
\n #else
\n #define outColor gl_FragData[0]
\n #endif
\n
\n #define WINDING_SCALE 65536.0
\n #ifdef USE_IMAGE_LOADSTORE
\n #ifdef GL_ES
\n layout(binding = 0, r32i) coherent uniform highp iimage2D windingImg;
\n #else
\n layout(r32i) coherent uniform highp iimage2D windingImg; // binding = 0 ... GLES 3.1 or GL 4.2+ only
\n #endif
\n uniform ivec4 imgParams;
\n #define imgOffset imgParams.x
\n #define imgQuadStride imgParams.y
\n #define imgStride imgParams.z
\n #define disableAA (imgParams.w != 0)
\n #elif !defined(USE_FRAMEBUFFER_FETCH)
\n uniform sampler2D windingTex;
\n #endif
\n
\n #ifdef USE_UNIFORMBUFFER
\n layout(std140) uniform frag {
\n mat3 scissorMat;
\n mat3 paintMat;
\n vec4 innerCol;
\n vec4 outerCol;
\n vec2 scissorExt;
\n vec2 scissorScale;
\n vec2 extent;
\n float radius;
\n float feather;
\n float strokeMult;
\n float strokeThr;
\n int texType;
\n int fillMode;
\n };
\n #else
\n uniform vec4 frag[UNIFORMARRAY_SIZE];
\n #define scissorMat mat3(frag[0].xyz, frag[1].xyz, frag[2].xyz)
\n #define paintMat mat3(frag[3].xyz, frag[4].xyz, frag[5].xyz)
\n #define innerCol frag[6]
\n #define outerCol frag[7]
\n #define scissorExt frag[8].xy
\n #define scissorScale frag[8].zw
\n #define extent frag[9].xy
\n #define radius frag[9].z
\n #define feather frag[9].w
\n #define strokeMult frag[10].x
\n #define strokeThr frag[10].y
\n #define texType int(frag[10].z)
\n #define fillMode int(frag[10].w)
\n #endif
\n #ifndef USE_IMAGE_LOADSTORE
\n #define disableAA ((fillMode & NVG_PATH_NO_AA) != 0)
\n #endif
\n uniform sampler2D tex;
\n uniform vec2 viewSize;
\n uniform int type;
\n
\n varying vec2 va;
\n varying vec2 vb;
\n //#define fpos va
\n #define ftcoord vb
\n
\n float coversCenter(vec2 v0, vec2 v1)
\n {
\n // no AA - just determine if center of pixel (0,0) is inside trapezoid
\n if(v1.x <= 0.0f || v0.x > 0.0f || v0.x == v1.x)
\n return 0.0f;
\n return v0.y*(v1.x - v0.x) - v0.x*(v1.y - v0.y) > 0.0f ? 1.0f : 0.0f;
\n }
\n
\n // unlike areaEdge(), this assumes pixel center is (0,0), not (0.5, 0.5)
\n float areaEdge2(vec2 v0, vec2 v1)
\n {
\n if(disableAA)
\n return v1.x < v0.x ? coversCenter(v1, v0) : -coversCenter(v0, v1);
\n vec2 window = clamp(vec2(v0.x, v1.x), -0.5f, 0.5f);
\n float width = window.y - window.x;
\n //if(v0.y > 0.5f && v1.y > 0.5f) -- didn't see a significant effect on Windows
\n // return -width;
\n vec2 dv = v1 - v0;
\n float slope = dv.y/dv.x;
\n float midx = 0.5f*(window.x + window.y);
\n float y = v0.y + (midx - v0.x)*slope; // y value at middle of window
\n float dy = abs(slope*width);
\n // credit for this to https://git.sr.ht/~eliasnaur/gio/tree/master/gpu/shaders/stencil.frag
\n // if width == 1 (so midx == 0), the components of sides are: y crossing of right edge of frag, y crossing
\n // of left edge, x crossing of top edge, x crossing of bottom edge. Since we only consider positive slope
\n // (note abs() above), there are five cases (below, bottom-right, left-right, left-top, above) - the area
\n // formula below reduces to these cases thanks to the clamping of the other values to 0 or 1.
\n // I haven't thought carefully about the width < 1 case, but experimentally it matches areaEdge()
\n vec4 sides = vec4(y + 0.5f*dy, y - 0.5f*dy, (0.5f - y)/dy, (-0.5f - y)/dy); //ry, ly, tx, bx
\n sides = clamp(sides + 0.5f, 0.0f, 1.0f); // shift from -0.5..0.5 to 0..1 for area calc
\n float area = 0.5f*(sides.z - sides.z*sides.y - 1.0f - sides.x + sides.x*sides.w);
\n return width == 0.0f ? 0.0f : area * width;
\n }
\n
\n #ifdef USE_IMAGE_LOADSTORE
\n // imageBuffer image type allows for 1D buffer, but max size may be very small on some GPUs
\n ivec2 imgCoords()
\n {
\n int idx = imgOffset + int(gl_FragCoord.x) + int(gl_FragCoord.y)*imgQuadStride;
\n int y = idx/imgStride;
\n return ivec2(idx - y*imgStride, y);
\n }
\n #endif
\n
\n float coverage()
\n {
\n if((fillMode & NVG_PATH_CONVEX) != 0)
\n return 1.0f;
\n #ifdef USE_FRAMEBUFFER_FETCH
\n float W = float(inoutWinding)/WINDING_SCALE;
\n #elif defined(USE_IMAGE_LOADSTORE)
\n float W = float(imageAtomicExchange(windingImg, imgCoords(), 0))/WINDING_SCALE;
\n #else
\n float W = texelFetch(windingTex, ivec2(gl_FragCoord.xy), 0).r;
\n //float W = texture2D(windingTex, gl_FragCoord.xy/viewSize).r; // note .r (first) component
\n #endif
\n // even-odd fill if bit 0 set, otherwise winding fill
\n return ((fillMode & NVG_PATH_EVENODD) == 0) ? min(abs(W), 1.0f) : (1.0f - abs(mod(W, 2.0f) - 1.0f));
\n // previous incorrect calculation for no AA case wrapped these in round(x) := floor(x + 0.5f)
\n }
\n
\n float sdroundrect(vec2 pt, vec2 ext, float rad)
\n {
\n vec2 ext2 = ext - vec2(rad,rad);
\n vec2 d = abs(pt) - ext2;
\n return min(max(d.x,d.y),0.0) + length(max(d,0.0)) - rad;
\n }
\n
\n // Scissoring
\n float scissorMask(vec2 p)
\n {
\n vec2 sc = (abs((scissorMat * vec3(p,1.0)).xy) - scissorExt);
\n sc = vec2(0.5,0.5) - sc * scissorScale;
\n return clamp(sc.x,0.0,1.0) * clamp(sc.y,0.0,1.0);
\n }
\n
\n #ifdef USE_SDF_TEXT
\n // Super-sampled SDF text rendering - super-sampling gives big improvement at very small sizes; quality is
\n // comparable to summed text; w/ supersamping, FPS is actually slightly lower
\n float sdfCov(float D, float sdfscale)
\n {
\n // Could we use derivative info (and/or distance at pixel center) to improve?
\n return D > 0.0f ? clamp((D - 0.5f)/sdfscale + radius, 0.0f, 1.0f) : 0.0f; //+ 0.25f
\n }
\n
\n float superSDF(sampler2D tex, vec2 st)
\n {
\n vec2 tex_wh = vec2(textureSize(tex, 0)); // convert from ivec2 to vec2
\n //st = st + vec2(4.0)/tex_wh; // account for 4 pixel padding in SDF
\n float s = (32.0f/255.0f)*paintMat[0][0]; // 32/255 is STBTT pixel_dist_scale
\n //return sdfCov(texture2D(tex, st).r, s); // single sample
\n s = 0.5f*s; // we're sampling 4 0.5x0.5 subpixels
\n float dx = paintMat[0][0]/tex_wh.x/4.0f;
\n float dy = paintMat[1][1]/tex_wh.y/4.0f;
\n
\n //vec2 stextent = extent/tex_wh; ... clamping doesn't seem to be necessary
\n //vec2 stmin = floor(st*stextent)*stextent;
\n //vec2 stmax = stmin + stextent - vec2(1.0f);
\n float d11 = texture2D(tex, st + vec2(dx, dy)).r; // clamp(st + ..., stmin, stmax)
\n float d10 = texture2D(tex, st + vec2(dx,-dy)).r;
\n float d01 = texture2D(tex, st + vec2(-dx, dy)).r;
\n float d00 = texture2D(tex, st + vec2(-dx,-dy)).r;
\n return 0.25f*(sdfCov(d11, s) + sdfCov(d10, s) + sdfCov(d01, s) + sdfCov(d00, s));
\n }
\n #else
\n // artifacts w/ GL_LINEAR on Intel GPU and GLES doesn't support texture filtering for f32, so do it ourselves
\n // also, min/mag filter must be set to GL_NEAREST for float texture or texelFetch() will fail on Mali GPUs
\n float texFetchLerp(sampler2D texture, vec2 ij, vec2 ijmin, vec2 ijmax)
\n {
\n vec2 ij00 = clamp(ij, ijmin, ijmax);
\n vec2 ij11 = clamp(ij + vec2(1.0f), ijmin, ijmax);
\n float t00 = texelFetch(texture, ivec2(ij00.x, ij00.y), 0).r; // implicit floor()
\n float t10 = texelFetch(texture, ivec2(ij11.x, ij00.y), 0).r;
\n float t01 = texelFetch(texture, ivec2(ij00.x, ij11.y), 0).r;
\n float t11 = texelFetch(texture, ivec2(ij11.x, ij11.y), 0).r;
\n vec2 f = ij - floor(ij);
\n //return mix(mix(t00, t10, f.x), mix(t01, t11, f.x), f.y);
\n float t0 = t00 + f.x*(t10 - t00);
\n float t1 = t01 + f.x*(t11 - t01);
\n return t0 + f.y*(t1 - t0);
\n }
\n
\n float summedTextCov(sampler2D texture, vec2 st)
\n {
\n ivec2 tex_wh = textureSize(texture, 0);
\n vec2 ij = st*vec2(tex_wh); // - vec2(1.0f) -- now done after finding ijmin,max
\n vec2 ijmin = floor(ij/extent)*extent;
\n vec2 ijmax = ijmin + extent - vec2(1.0f);
\n // for some reason, we need to shift by an extra (-0.5, -0.5) for summed case (here or in fons__getQuad)
\n ij -= vec2(0.999999f);
\n float dx = paintMat[0][0]/2.0f;
\n float dy = paintMat[1][1]/2.0f;
\n float s11 = texFetchLerp(texture, ij + vec2(dx, dy), ijmin, ijmax);
\n float s01 = texFetchLerp(texture, ij + vec2(-dx, dy), ijmin, ijmax);
\n float s10 = texFetchLerp(texture, ij + vec2(dx,-dy), ijmin, ijmax);
\n float s00 = texFetchLerp(texture, ij + vec2(-dx,-dy), ijmin, ijmax);
\n float cov = (s11 - s01 - s10 + s00)/(255.0f*4.0f*dx*dy);
\n return clamp(cov, 0.0f, 1.0f);
\n }
\n #endif
\n
\n void main(void)
\n {
\n vec4 result;
\n vec2 fpos = vec2(gl_FragCoord.x, viewSize.y - gl_FragCoord.y);
\n int winding = 0;
\n if (type == 0) { // clear winding number (not used in USE_FRAMEBUFFER_FETCH case)
\n result = vec4(0.0f);
\n } else if (type == 1) { // calculate winding
\n float W = areaEdge2(vb - fpos, va - fpos);
\n #ifdef USE_FRAMEBUFFER_FETCH
\n result = vec4(0.0f);
\n winding = int(W*WINDING_SCALE) + inoutWinding;
\n #elif defined(USE_IMAGE_LOADSTORE)
\n result = vec4(0.0f);
\n imageAtomicAdd(windingImg, imgCoords(), int(W*WINDING_SCALE));
\n //discard; -- doesn't seem to affect performance
\n #else
\n result = vec4(W);
\n #endif
\n } else if (type == 2) { // Solid color
\n result = innerCol*(scissorMask(fpos)*coverage());
\n } else if (type == 3) { // Gradient
\n // Calculate gradient color using box gradient
\n vec2 pt = (paintMat * vec3(fpos,1.0)).xy;
\n float d = clamp((sdroundrect(pt, extent, radius) + feather*0.5) / feather, 0.0, 1.0);
\n vec4 color = texType > 0 ? texture2D(tex, vec2(d,0)) : mix(innerCol,outerCol,d);
\n if (texType == 1) color = vec4(color.rgb*color.a, color.a);
\n // Combine alpha
\n result = color*(scissorMask(fpos)*coverage());
\n } else if (type == 4) { // Image
\n // Calculate color from texture
\n vec2 pt = (paintMat * vec3(fpos,1.0)).xy / extent;
\n vec4 color = texture2D(tex, pt);
\n if (texType == 1) color = vec4(color.rgb*color.a, color.a);
\n else if (texType == 2) color = vec4(color.r);
\n // Apply color tint and alpha.
\n color *= innerCol;
\n // Combine alpha
\n result = color*(scissorMask(fpos)*coverage());
\n } else if (type == 5) { // Textured tris - only used for text, so no need for coverage()
\n #ifdef USE_SDF_TEXT
\n float cov = scissorMask(fpos)*superSDF(tex, ftcoord);
\n #else
\n float cov = scissorMask(fpos)*summedTextCov(tex, ftcoord);
\n #endif
\n result = vec4(cov) * innerCol;
\n // this is wrong - see alternative outColor calc below for correct text gamma handling
\n //result = innerCol*pow(vec4(cov), vec4(1.5,1.5,1.5,0.5));
\n }
\n #ifdef USE_FRAMEBUFFER_FETCH
\n outColor = result + (1.0f - result.a)*outColor;
\n //outColor.rgb = pow(pow(result.rgb, vec3(1.5/2.2)) + (1.0f - result.a)*pow(outColor.rgb, vec3(1.5/2.2)), vec3(2.2/1.5));
\n inoutWinding = winding;
\n #else
\n outColor = result;
\n #endif
\n }
);
GLNVGcontext* gl = (GLNVGcontext*)uptr;
int align = 4;
const char* shaderOpts = "";
glnvg__checkError(gl, "init");
gl->renderMethod = NVGL_RENDER_FB_SWAP; // default
#if defined(GL_EXT_shader_framebuffer_fetch)
if (!(gl->flags & NVGL_NO_FB_FETCH)) {
if (NVG_HAS_EXT(EXT_shader_framebuffer_fetch))
gl->renderMethod = NVGL_RENDER_FB_FETCH;
}
#endif
// image load/store is faster than FB fetch on desktop (at least Intel GPUs)
if(!(gl->flags & NVGL_NO_IMG_ATOMIC)) {
#ifdef GL_ARB_shader_image_load_store // desktop GL only
if(NVG_HAS_EXT(ARB_shader_image_load_store))
gl->renderMethod = NVGL_RENDER_IMG_ATOMIC;
#elif defined(GL_ES_VERSION_3_1) //defined(GL_OES_shader_image_atomic) || defined(GL_ES_VERSION_3_2)
// basically every GLES3.1 impl seems to include GL_OES_shader_image_atomic
// I think we may want to prefer FB fetch over image load/store on mobile, but some Qualcomm GPUs (Adreno)
// apparently don't implement it correctly, so give priority to image load/store for now
gl->renderMethod = NVGL_RENDER_IMG_ATOMIC;
#else
#define NANOVG_GL_NO_IMG_ATOMIC 1 // disable code if no possibility of support on current platform
#endif
}
if(gl->renderMethod == NVGL_RENDER_FB_FETCH) {
shaderOpts = "#define USE_FRAMEBUFFER_FETCH\n";
NVG_LOG("nvg2: using GL_EXT_shader_framebuffer_fetch\n");
} else if(gl->renderMethod == NVGL_RENDER_IMG_ATOMIC) {
shaderOpts = "#define USE_IMAGE_LOADSTORE\n";
NVG_LOG("nvg2: using GL_ARB_shader_image_load_store/GL_OES_shader_image_atomic\n");
} else {
NVG_LOG("nvg2: no extensions in use\n");
}
{
const char* sdfDef = (gl->flags & NVG_SDF_TEXT) ? "#define USE_SDF_TEXT 1\n" : "";
const char* vertsrc[] = { shaderHeader, shaderOpts, sdfDef, fillVertShader };
const char* fragsrc[] = { shaderHeader, shaderOpts, sdfDef, fillFragShader };
if(glnvg__createProgram(&gl->shader, vertsrc, 4, fragsrc, 4) == 0)
return 0;
}
glnvg__checkError(gl, "uniform locations");
glnvg__getUniforms(&gl->shader);
// Create dynamic vertex array
#if defined NANOVG_GL3
glGenVertexArrays(1, &gl->vertArr);
#endif
glGenBuffers(1, &gl->vertBuf);
#if NANOVG_GL_USE_UNIFORMBUFFER
// Create UBOs
glUniformBlockBinding(gl->shader.prog, gl->shader.loc[GLNVG_LOC_FRAG], GLNVG_FRAG_BINDING);
glGenBuffers(1, &gl->fragBuf);
glGetIntegerv(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, &align);
#endif
gl->fragSize = sizeof(GLNVGfragUniforms) + align - sizeof(GLNVGfragUniforms) % align;
// alloc framebuffer for winding accum; will be inited in renderViewport when viewport size is known
glGenFramebuffers(1, &gl->fbWinding);
glnvg__checkError(gl, "create done");
glFinish();
return 1;
}
static int glnvg__renderCreateTexture(void* uptr, int type, int w, int h, int imageFlags, const void* data)
{
GLNVGcontext* gl = (GLNVGcontext*)uptr;
GLNVGtexture* tex = glnvg__allocTexture(gl);
GLint magfilt, mipfilt, minfilt, wrapx, wrapy;
if (tex == NULL) return 0;
#ifdef NANOVG_GLES2
// Check for non-power of 2.
if (glnvg__nearestPow2(w) != (unsigned int)w || glnvg__nearestPow2(h) != (unsigned int)h) {
// No repeat
if ((imageFlags & NVG_IMAGE_REPEATX) != 0 || (imageFlags & NVG_IMAGE_REPEATY) != 0) {
NVG_LOG("Repeat X/Y is not supported for non power-of-two textures (%d x %d)\n", w, h);
imageFlags &= ~(NVG_IMAGE_REPEATX | NVG_IMAGE_REPEATY);
}
// No mips.
if (imageFlags & NVG_IMAGE_GENERATE_MIPMAPS) {
NVG_LOG("Mip-maps is not support for non power-of-two textures (%d x %d)\n", w, h);
imageFlags &= ~NVG_IMAGE_GENERATE_MIPMAPS;
}
}
#endif
glGenTextures(1, &tex->tex);
tex->width = w;
tex->height = h;
tex->type = type;
tex->flags = imageFlags;
glnvg__bindTexture(gl, tex->tex);
glPixelStorei(GL_UNPACK_ALIGNMENT,1);
#ifndef NANOVG_GLES2
glPixelStorei(GL_UNPACK_ROW_LENGTH, tex->width);
glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
#endif
#if defined (NANOVG_GL2)
// GL 1.4 and later has support for generating mipmaps using a tex parameter.
if (imageFlags & NVG_IMAGE_GENERATE_MIPMAPS) {
glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE);
}
#endif
if (type == NVG_TEXTURE_RGBA) {
GLint internalfmt = imageFlags & NVG_IMAGE_SRGB ? GL_SRGB8_ALPHA8 : GL_RGBA8;
glTexImage2D(GL_TEXTURE_2D, 0, internalfmt, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
} else if (type == NVG_TEXTURE_FLOAT) {