1 //
2 // Copyright (c) 2013 Mikko Mononen memon@inside.org
3 //
4 // This software is provided 'as-is', without any express or implied
5 // warranty.  In no event will the authors be held liable for any damages
6 // arising from the use of this software.
7 // Permission is granted to anyone to use this software for any purpose,
8 // including commercial applications, and to alter it and redistribute it
9 // freely, subject to the following restrictions:
10 // 1. The origin of this software must not be misrepresented; you must not
11 //    claim that you wrote the original software. If you use this software
12 //    in a product, an acknowledgment in the product documentation would be
13 //    appreciated but is not required.
14 // 2. Altered source versions must be plainly marked as such, and must not be
15 //    misrepresented as being the original software.
16 // 3. This notice may not be removed or altered from any source distribution.
17 //
18 
19 #include <stdlib.h>
20 #include <stdio.h>
21 #include <math.h>
22 #include <memory.h>
23 
24 #include "nanovg.h"
25 #pragma GCC diagnostic push
26 #pragma GCC diagnostic ignored "-Wmisleading-indentation"
27 #pragma GCC diagnostic ignored "-Wimplicit-fallthrough="
28 #pragma GCC diagnostic ignored "-Wshift-negative-value"
29 #pragma GCC diagnostic ignored "-Wunused-parameter"
30 #pragma GCC diagnostic ignored "-Wsign-compare"
31 #define FONTSTASH_IMPLEMENTATION
32 #include "fontstash.h"
33 #define STB_IMAGE_IMPLEMENTATION
34 #include "stb_image.h"
35 #pragma GCC diagnostic pop
36 
37 #ifdef _MSC_VER
38 #pragma warning(disable: 4100)  // unreferenced formal parameter
39 #pragma warning(disable: 4127)  // conditional expression is constant
40 #pragma warning(disable: 4204)  // nonstandard extension used : non-constant aggregate initializer
41 #pragma warning(disable: 4706)  // assignment within conditional expression
42 #endif
43 
44 #define NVG_INIT_FONTIMAGE_SIZE  512
45 #define NVG_MAX_FONTIMAGE_SIZE   2048
46 #define NVG_MAX_FONTIMAGES       4
47 
48 #define NVG_INIT_COMMANDS_SIZE 256
49 #define NVG_INIT_POINTS_SIZE 128
50 #define NVG_INIT_PATHS_SIZE 16
51 #define NVG_INIT_VERTS_SIZE 256
52 #define NVG_MAX_STATES 32
53 
54 #define NVG_KAPPA90 0.5522847493f	// Length proportional to radius of a cubic bezier handle for 90deg arcs.
55 
56 #define NVG_COUNTOF(arr) (sizeof(arr) / sizeof(0[arr]))
57 
58 
59 enum NVGcommands {
60 	NVG_MOVETO = 0,
61 	NVG_LINETO = 1,
62 	NVG_BEZIERTO = 2,
63 	NVG_CLOSE = 3,
64 	NVG_WINDING = 4,
65 };
66 
67 enum NVGpointFlags
68 {
69 	NVG_PT_CORNER = 0x01,
70 	NVG_PT_LEFT = 0x02,
71 	NVG_PT_BEVEL = 0x04,
72 	NVG_PR_INNERBEVEL = 0x08,
73 };
74 
75 struct NVGstate {
76 	NVGcompositeOperationState compositeOperation;
77 	int shapeAntiAlias;
78 	NVGpaint fill;
79 	NVGpaint stroke;
80 	float strokeWidth;
81 	float miterLimit;
82 	int lineJoin;
83 	int lineCap;
84 	float alpha;
85 	float xform[6];
86 	NVGscissor scissor;
87 	float fontSize;
88 	float letterSpacing;
89 	float lineHeight;
90 	float fontBlur;
91 	int textAlign;
92 	int fontId;
93 };
94 typedef struct NVGstate NVGstate;
95 
96 struct NVGpoint {
97 	float x,y;
98 	float dx, dy;
99 	float len;
100 	float dmx, dmy;
101 	unsigned char flags;
102 };
103 typedef struct NVGpoint NVGpoint;
104 
105 struct NVGpathCache {
106 	NVGpoint* points;
107 	int npoints;
108 	int cpoints;
109 	NVGpath* paths;
110 	int npaths;
111 	int cpaths;
112 	NVGvertex* verts;
113 	int nverts;
114 	int cverts;
115 	float bounds[4];
116 };
117 typedef struct NVGpathCache NVGpathCache;
118 
119 struct NVGcontext {
120 	NVGparams params;
121 	float* commands;
122 	int ccommands;
123 	int ncommands;
124 	float commandx, commandy;
125 	NVGstate states[NVG_MAX_STATES];
126 	int nstates;
127 	NVGpathCache* cache;
128 	float tessTol;
129 	float distTol;
130 	float fringeWidth;
131 	float devicePxRatio;
132 	struct FONScontext* fs;
133 	int fontImages[NVG_MAX_FONTIMAGES];
134 	int fontImageIdx;
135 	int drawCallCount;
136 	int fillTriCount;
137 	int strokeTriCount;
138 	int textTriCount;
139 };
140 
nvg__sqrtf(float a)141 static float nvg__sqrtf(float a) { return sqrtf(a); }
nvg__modf(float a,float b)142 static float nvg__modf(float a, float b) { return fmodf(a, b); }
nvg__sinf(float a)143 static float nvg__sinf(float a) { return sinf(a); }
nvg__cosf(float a)144 static float nvg__cosf(float a) { return cosf(a); }
nvg__tanf(float a)145 static float nvg__tanf(float a) { return tanf(a); }
nvg__atan2f(float a,float b)146 static float nvg__atan2f(float a,float b) { return atan2f(a, b); }
nvg__acosf(float a)147 static float nvg__acosf(float a) { return acosf(a); }
148 
nvg__mini(int a,int b)149 static int nvg__mini(int a, int b) { return a < b ? a : b; }
nvg__maxi(int a,int b)150 static int nvg__maxi(int a, int b) { return a > b ? a : b; }
nvg__clampi(int a,int mn,int mx)151 static int nvg__clampi(int a, int mn, int mx) { return a < mn ? mn : (a > mx ? mx : a); }
nvg__minf(float a,float b)152 static float nvg__minf(float a, float b) { return a < b ? a : b; }
nvg__maxf(float a,float b)153 static float nvg__maxf(float a, float b) { return a > b ? a : b; }
nvg__absf(float a)154 static float nvg__absf(float a) { return a >= 0.0f ? a : -a; }
nvg__signf(float a)155 static float nvg__signf(float a) { return a >= 0.0f ? 1.0f : -1.0f; }
nvg__clampf(float a,float mn,float mx)156 static float nvg__clampf(float a, float mn, float mx) { return a < mn ? mn : (a > mx ? mx : a); }
nvg__cross(float dx0,float dy0,float dx1,float dy1)157 static float nvg__cross(float dx0, float dy0, float dx1, float dy1) { return dx1*dy0 - dx0*dy1; }
158 
nvg__normalize(float * x,float * y)159 static float nvg__normalize(float *x, float* y)
160 {
161 	float d = nvg__sqrtf((*x)*(*x) + (*y)*(*y));
162 	if (d > 1e-6f) {
163 		float id = 1.0f / d;
164 		*x *= id;
165 		*y *= id;
166 	}
167 	return d;
168 }
169 
170 
nvg__deletePathCache(NVGpathCache * c)171 static void nvg__deletePathCache(NVGpathCache* c)
172 {
173 	if (c == NULL) return;
174 	if (c->points != NULL) free(c->points);
175 	if (c->paths != NULL) free(c->paths);
176 	if (c->verts != NULL) free(c->verts);
177 	free(c);
178 }
179 
nvg__allocPathCache(void)180 static NVGpathCache* nvg__allocPathCache(void)
181 {
182 	NVGpathCache* c = (NVGpathCache*)malloc(sizeof(NVGpathCache));
183 	if (c == NULL) goto error;
184 	memset(c, 0, sizeof(NVGpathCache));
185 
186 	c->points = (NVGpoint*)malloc(sizeof(NVGpoint)*NVG_INIT_POINTS_SIZE);
187 	if (!c->points) goto error;
188 	c->npoints = 0;
189 	c->cpoints = NVG_INIT_POINTS_SIZE;
190 
191 	c->paths = (NVGpath*)malloc(sizeof(NVGpath)*NVG_INIT_PATHS_SIZE);
192 	if (!c->paths) goto error;
193 	c->npaths = 0;
194 	c->cpaths = NVG_INIT_PATHS_SIZE;
195 
196 	c->verts = (NVGvertex*)malloc(sizeof(NVGvertex)*NVG_INIT_VERTS_SIZE);
197 	if (!c->verts) goto error;
198 	c->nverts = 0;
199 	c->cverts = NVG_INIT_VERTS_SIZE;
200 
201 	return c;
202 error:
203 	nvg__deletePathCache(c);
204 	return NULL;
205 }
206 
nvg__setDevicePixelRatio(NVGcontext * ctx,float ratio)207 static void nvg__setDevicePixelRatio(NVGcontext* ctx, float ratio)
208 {
209 	ctx->tessTol = 0.25f / ratio;
210 	ctx->distTol = 0.01f / ratio;
211 	ctx->fringeWidth = 1.0f / ratio;
212 	ctx->devicePxRatio = ratio;
213 }
214 
nvg__compositeOperationState(int op)215 static NVGcompositeOperationState nvg__compositeOperationState(int op)
216 {
217 	int sfactor, dfactor;
218 
219 	if (op == NVG_SOURCE_OVER)
220 	{
221 		sfactor = NVG_ONE;
222 		dfactor = NVG_ONE_MINUS_SRC_ALPHA;
223 	}
224 	else if (op == NVG_SOURCE_IN)
225 	{
226 		sfactor = NVG_DST_ALPHA;
227 		dfactor = NVG_ZERO;
228 	}
229 	else if (op == NVG_SOURCE_OUT)
230 	{
231 		sfactor = NVG_ONE_MINUS_DST_ALPHA;
232 		dfactor = NVG_ZERO;
233 	}
234 	else if (op == NVG_ATOP)
235 	{
236 		sfactor = NVG_DST_ALPHA;
237 		dfactor = NVG_ONE_MINUS_SRC_ALPHA;
238 	}
239 	else if (op == NVG_DESTINATION_OVER)
240 	{
241 		sfactor = NVG_ONE_MINUS_DST_ALPHA;
242 		dfactor = NVG_ONE;
243 	}
244 	else if (op == NVG_DESTINATION_IN)
245 	{
246 		sfactor = NVG_ZERO;
247 		dfactor = NVG_SRC_ALPHA;
248 	}
249 	else if (op == NVG_DESTINATION_OUT)
250 	{
251 		sfactor = NVG_ZERO;
252 		dfactor = NVG_ONE_MINUS_SRC_ALPHA;
253 	}
254 	else if (op == NVG_DESTINATION_ATOP)
255 	{
256 		sfactor = NVG_ONE_MINUS_DST_ALPHA;
257 		dfactor = NVG_SRC_ALPHA;
258 	}
259 	else if (op == NVG_LIGHTER)
260 	{
261 		sfactor = NVG_ONE;
262 		dfactor = NVG_ONE;
263 	}
264 	else if (op == NVG_COPY)
265 	{
266 		sfactor = NVG_ONE;
267 		dfactor = NVG_ZERO;
268 	}
269 	else if (op == NVG_XOR)
270 	{
271 		sfactor = NVG_ONE_MINUS_DST_ALPHA;
272 		dfactor = NVG_ONE_MINUS_SRC_ALPHA;
273 	}
274 	else
275 	{
276 		sfactor = NVG_ONE;
277 		dfactor = NVG_ZERO;
278 	}
279 
280 	NVGcompositeOperationState state;
281 	state.srcRGB = sfactor;
282 	state.dstRGB = dfactor;
283 	state.srcAlpha = sfactor;
284 	state.dstAlpha = dfactor;
285 	return state;
286 }
287 
nvg__getState(NVGcontext * ctx)288 static NVGstate* nvg__getState(NVGcontext* ctx)
289 {
290 	return &ctx->states[ctx->nstates-1];
291 }
292 
nvgCreateInternal(NVGparams * params)293 NVGcontext* nvgCreateInternal(NVGparams* params)
294 {
295 	FONSparams fontParams;
296 	NVGcontext* ctx = (NVGcontext*)malloc(sizeof(NVGcontext));
297 	int i;
298 	if (ctx == NULL) goto error;
299 	memset(ctx, 0, sizeof(NVGcontext));
300 
301 	ctx->params = *params;
302 	for (i = 0; i < NVG_MAX_FONTIMAGES; i++)
303 		ctx->fontImages[i] = 0;
304 
305 	ctx->commands = (float*)malloc(sizeof(float)*NVG_INIT_COMMANDS_SIZE);
306 	if (!ctx->commands) goto error;
307 	ctx->ncommands = 0;
308 	ctx->ccommands = NVG_INIT_COMMANDS_SIZE;
309 
310 	ctx->cache = nvg__allocPathCache();
311 	if (ctx->cache == NULL) goto error;
312 
313 	nvgSave(ctx);
314 	nvgReset(ctx);
315 
316 	nvg__setDevicePixelRatio(ctx, 1.0f);
317 
318 	if (ctx->params.renderCreate(ctx->params.userPtr) == 0) goto error;
319 
320 	// Init font rendering
321 	memset(&fontParams, 0, sizeof(fontParams));
322 	fontParams.width = NVG_INIT_FONTIMAGE_SIZE;
323 	fontParams.height = NVG_INIT_FONTIMAGE_SIZE;
324 	fontParams.flags = FONS_ZERO_TOPLEFT;
325 	fontParams.renderCreate = NULL;
326 	fontParams.renderUpdate = NULL;
327 	fontParams.renderDraw = NULL;
328 	fontParams.renderDelete = NULL;
329 	fontParams.userPtr = NULL;
330 	ctx->fs = fonsCreateInternal(&fontParams);
331 	if (ctx->fs == NULL) goto error;
332 
333 	// Create font texture
334 	ctx->fontImages[0] = ctx->params.renderCreateTexture(ctx->params.userPtr, NVG_TEXTURE_ALPHA, fontParams.width, fontParams.height, 0, NULL);
335 	if (ctx->fontImages[0] == 0) goto error;
336 	ctx->fontImageIdx = 0;
337 
338 	return ctx;
339 
340 error:
341 	nvgDeleteInternal(ctx);
342 	return 0;
343 }
344 
nvgInternalParams(NVGcontext * ctx)345 NVGparams* nvgInternalParams(NVGcontext* ctx)
346 {
347     return &ctx->params;
348 }
349 
nvgDeleteInternal(NVGcontext * ctx)350 void nvgDeleteInternal(NVGcontext* ctx)
351 {
352 	int i;
353 	if (ctx == NULL) return;
354 	if (ctx->commands != NULL) free(ctx->commands);
355 	if (ctx->cache != NULL) nvg__deletePathCache(ctx->cache);
356 
357 	if (ctx->fs)
358 		fonsDeleteInternal(ctx->fs);
359 
360 	for (i = 0; i < NVG_MAX_FONTIMAGES; i++) {
361 		if (ctx->fontImages[i] != 0) {
362 			nvgDeleteImage(ctx, ctx->fontImages[i]);
363 			ctx->fontImages[i] = 0;
364 		}
365 	}
366 
367 	if (ctx->params.renderDelete != NULL)
368 		ctx->params.renderDelete(ctx->params.userPtr);
369 
370 	free(ctx);
371 }
372 
nvgBeginFrame(NVGcontext * ctx,float windowWidth,float windowHeight,float devicePixelRatio)373 void nvgBeginFrame(NVGcontext* ctx, float windowWidth, float windowHeight, float devicePixelRatio)
374 {
375 /*	printf("Tris: draws:%d  fill:%d  stroke:%d  text:%d  TOT:%d\n",
376 		ctx->drawCallCount, ctx->fillTriCount, ctx->strokeTriCount, ctx->textTriCount,
377 		ctx->fillTriCount+ctx->strokeTriCount+ctx->textTriCount);*/
378 
379 	ctx->nstates = 0;
380 	nvgSave(ctx);
381 	nvgReset(ctx);
382 
383 	nvg__setDevicePixelRatio(ctx, devicePixelRatio);
384 
385 	ctx->params.renderViewport(ctx->params.userPtr, windowWidth, windowHeight, devicePixelRatio);
386 
387 	ctx->drawCallCount = 0;
388 	ctx->fillTriCount = 0;
389 	ctx->strokeTriCount = 0;
390 	ctx->textTriCount = 0;
391 }
392 
nvgCancelFrame(NVGcontext * ctx)393 void nvgCancelFrame(NVGcontext* ctx)
394 {
395 	ctx->params.renderCancel(ctx->params.userPtr);
396 }
397 
nvgEndFrame(NVGcontext * ctx)398 void nvgEndFrame(NVGcontext* ctx)
399 {
400 	ctx->params.renderFlush(ctx->params.userPtr);
401 	if (ctx->fontImageIdx != 0) {
402 		int fontImage = ctx->fontImages[ctx->fontImageIdx];
403 		int i, j, iw, ih;
404 		// delete images that smaller than current one
405 		if (fontImage == 0)
406 			return;
407 		nvgImageSize(ctx, fontImage, &iw, &ih);
408 		for (i = j = 0; i < ctx->fontImageIdx; i++) {
409 			if (ctx->fontImages[i] != 0) {
410 				int nw, nh;
411 				nvgImageSize(ctx, ctx->fontImages[i], &nw, &nh);
412 				if (nw < iw || nh < ih)
413 					nvgDeleteImage(ctx, ctx->fontImages[i]);
414 				else
415 					ctx->fontImages[j++] = ctx->fontImages[i];
416 			}
417 		}
418 		// make current font image to first
419 		ctx->fontImages[j++] = ctx->fontImages[0];
420 		ctx->fontImages[0] = fontImage;
421 		ctx->fontImageIdx = 0;
422 		// clear all images after j
423 		for (i = j; i < NVG_MAX_FONTIMAGES; i++)
424 			ctx->fontImages[i] = 0;
425 	}
426 }
427 
nvgRGB(unsigned char r,unsigned char g,unsigned char b)428 NVGcolor nvgRGB(unsigned char r, unsigned char g, unsigned char b)
429 {
430 	return nvgRGBA(r,g,b,255);
431 }
432 
nvgRGBf(float r,float g,float b)433 NVGcolor nvgRGBf(float r, float g, float b)
434 {
435 	return nvgRGBAf(r,g,b,1.0f);
436 }
437 
nvgRGBA(unsigned char r,unsigned char g,unsigned char b,unsigned char a)438 NVGcolor nvgRGBA(unsigned char r, unsigned char g, unsigned char b, unsigned char a)
439 {
440 	NVGcolor color;
441 	// Use longer initialization to suppress warning.
442 	color.r = r / 255.0f;
443 	color.g = g / 255.0f;
444 	color.b = b / 255.0f;
445 	color.a = a / 255.0f;
446 	return color;
447 }
448 
nvgRGBAf(float r,float g,float b,float a)449 NVGcolor nvgRGBAf(float r, float g, float b, float a)
450 {
451 	NVGcolor color;
452 	// Use longer initialization to suppress warning.
453 	color.r = r;
454 	color.g = g;
455 	color.b = b;
456 	color.a = a;
457 	return color;
458 }
459 
nvgTransRGBA(NVGcolor c,unsigned char a)460 NVGcolor nvgTransRGBA(NVGcolor c, unsigned char a)
461 {
462 	c.a = a / 255.0f;
463 	return c;
464 }
465 
nvgTransRGBAf(NVGcolor c,float a)466 NVGcolor nvgTransRGBAf(NVGcolor c, float a)
467 {
468 	c.a = a;
469 	return c;
470 }
471 
nvgLerpRGBA(NVGcolor c0,NVGcolor c1,float u)472 NVGcolor nvgLerpRGBA(NVGcolor c0, NVGcolor c1, float u)
473 {
474 	int i;
475 	float oneminu;
476 	NVGcolor cint = {{{0}}};
477 
478 	u = nvg__clampf(u, 0.0f, 1.0f);
479 	oneminu = 1.0f - u;
480 	for( i = 0; i <4; i++ )
481 	{
482 		cint.rgba[i] = c0.rgba[i] * oneminu + c1.rgba[i] * u;
483 	}
484 
485 	return cint;
486 }
487 
nvgHSL(float h,float s,float l)488 NVGcolor nvgHSL(float h, float s, float l)
489 {
490 	return nvgHSLA(h,s,l,255);
491 }
492 
nvg__hue(float h,float m1,float m2)493 static float nvg__hue(float h, float m1, float m2)
494 {
495 	if (h < 0) h += 1;
496 	if (h > 1) h -= 1;
497 	if (h < 1.0f/6.0f)
498 		return m1 + (m2 - m1) * h * 6.0f;
499 	else if (h < 3.0f/6.0f)
500 		return m2;
501 	else if (h < 4.0f/6.0f)
502 		return m1 + (m2 - m1) * (2.0f/3.0f - h) * 6.0f;
503 	return m1;
504 }
505 
nvgHSLA(float h,float s,float l,unsigned char a)506 NVGcolor nvgHSLA(float h, float s, float l, unsigned char a)
507 {
508 	float m1, m2;
509 	NVGcolor col;
510 	h = nvg__modf(h, 1.0f);
511 	if (h < 0.0f) h += 1.0f;
512 	s = nvg__clampf(s, 0.0f, 1.0f);
513 	l = nvg__clampf(l, 0.0f, 1.0f);
514 	m2 = l <= 0.5f ? (l * (1 + s)) : (l + s - l * s);
515 	m1 = 2 * l - m2;
516 	col.r = nvg__clampf(nvg__hue(h + 1.0f/3.0f, m1, m2), 0.0f, 1.0f);
517 	col.g = nvg__clampf(nvg__hue(h, m1, m2), 0.0f, 1.0f);
518 	col.b = nvg__clampf(nvg__hue(h - 1.0f/3.0f, m1, m2), 0.0f, 1.0f);
519 	col.a = a/255.0f;
520 	return col;
521 }
522 
nvgTransformIdentity(float * t)523 void nvgTransformIdentity(float* t)
524 {
525 	t[0] = 1.0f; t[1] = 0.0f;
526 	t[2] = 0.0f; t[3] = 1.0f;
527 	t[4] = 0.0f; t[5] = 0.0f;
528 }
529 
nvgTransformTranslate(float * t,float tx,float ty)530 void nvgTransformTranslate(float* t, float tx, float ty)
531 {
532 	t[0] = 1.0f; t[1] = 0.0f;
533 	t[2] = 0.0f; t[3] = 1.0f;
534 	t[4] = tx; t[5] = ty;
535 }
536 
nvgTransformScale(float * t,float sx,float sy)537 void nvgTransformScale(float* t, float sx, float sy)
538 {
539 	t[0] = sx; t[1] = 0.0f;
540 	t[2] = 0.0f; t[3] = sy;
541 	t[4] = 0.0f; t[5] = 0.0f;
542 }
543 
nvgTransformRotate(float * t,float a)544 void nvgTransformRotate(float* t, float a)
545 {
546 	float cs = nvg__cosf(a), sn = nvg__sinf(a);
547 	t[0] = cs; t[1] = sn;
548 	t[2] = -sn; t[3] = cs;
549 	t[4] = 0.0f; t[5] = 0.0f;
550 }
551 
nvgTransformSkewX(float * t,float a)552 void nvgTransformSkewX(float* t, float a)
553 {
554 	t[0] = 1.0f; t[1] = 0.0f;
555 	t[2] = nvg__tanf(a); t[3] = 1.0f;
556 	t[4] = 0.0f; t[5] = 0.0f;
557 }
558 
nvgTransformSkewY(float * t,float a)559 void nvgTransformSkewY(float* t, float a)
560 {
561 	t[0] = 1.0f; t[1] = nvg__tanf(a);
562 	t[2] = 0.0f; t[3] = 1.0f;
563 	t[4] = 0.0f; t[5] = 0.0f;
564 }
565 
nvgTransformMultiply(float * t,const float * s)566 void nvgTransformMultiply(float* t, const float* s)
567 {
568 	float t0 = t[0] * s[0] + t[1] * s[2];
569 	float t2 = t[2] * s[0] + t[3] * s[2];
570 	float t4 = t[4] * s[0] + t[5] * s[2] + s[4];
571 	t[1] = t[0] * s[1] + t[1] * s[3];
572 	t[3] = t[2] * s[1] + t[3] * s[3];
573 	t[5] = t[4] * s[1] + t[5] * s[3] + s[5];
574 	t[0] = t0;
575 	t[2] = t2;
576 	t[4] = t4;
577 }
578 
nvgTransformPremultiply(float * t,const float * s)579 void nvgTransformPremultiply(float* t, const float* s)
580 {
581 	float s2[6];
582 	memcpy(s2, s, sizeof(float)*6);
583 	nvgTransformMultiply(s2, t);
584 	memcpy(t, s2, sizeof(float)*6);
585 }
586 
nvgTransformInverse(float * inv,const float * t)587 int nvgTransformInverse(float* inv, const float* t)
588 {
589 	double invdet, det = (double)t[0] * t[3] - (double)t[2] * t[1];
590 	if (det > -1e-6 && det < 1e-6) {
591 		nvgTransformIdentity(inv);
592 		return 0;
593 	}
594 	invdet = 1.0 / det;
595 	inv[0] = (float)(t[3] * invdet);
596 	inv[2] = (float)(-t[2] * invdet);
597 	inv[4] = (float)(((double)t[2] * t[5] - (double)t[3] * t[4]) * invdet);
598 	inv[1] = (float)(-t[1] * invdet);
599 	inv[3] = (float)(t[0] * invdet);
600 	inv[5] = (float)(((double)t[1] * t[4] - (double)t[0] * t[5]) * invdet);
601 	return 1;
602 }
603 
nvgTransformPoint(float * dx,float * dy,const float * t,float sx,float sy)604 void nvgTransformPoint(float* dx, float* dy, const float* t, float sx, float sy)
605 {
606 	*dx = sx*t[0] + sy*t[2] + t[4];
607 	*dy = sx*t[1] + sy*t[3] + t[5];
608 }
609 
nvgDegToRad(float deg)610 float nvgDegToRad(float deg)
611 {
612 	return deg / 180.0f * NVG_PI;
613 }
614 
nvgRadToDeg(float rad)615 float nvgRadToDeg(float rad)
616 {
617 	return rad / NVG_PI * 180.0f;
618 }
619 
nvg__setPaintColor(NVGpaint * p,NVGcolor color)620 static void nvg__setPaintColor(NVGpaint* p, NVGcolor color)
621 {
622 	memset(p, 0, sizeof(*p));
623 	nvgTransformIdentity(p->xform);
624 	p->radius = 0.0f;
625 	p->feather = 1.0f;
626 	p->innerColor = color;
627 	p->outerColor = color;
628 }
629 
630 
631 // State handling
nvgSave(NVGcontext * ctx)632 void nvgSave(NVGcontext* ctx)
633 {
634 	if (ctx->nstates >= NVG_MAX_STATES)
635 		return;
636 	if (ctx->nstates > 0)
637 		memcpy(&ctx->states[ctx->nstates], &ctx->states[ctx->nstates-1], sizeof(NVGstate));
638 	ctx->nstates++;
639 }
640 
nvgRestore(NVGcontext * ctx)641 void nvgRestore(NVGcontext* ctx)
642 {
643 	if (ctx->nstates <= 1)
644 		return;
645 	ctx->nstates--;
646 }
647 
nvgReset(NVGcontext * ctx)648 void nvgReset(NVGcontext* ctx)
649 {
650 	NVGstate* state = nvg__getState(ctx);
651 	memset(state, 0, sizeof(*state));
652 
653 	nvg__setPaintColor(&state->fill, nvgRGBA(255,255,255,255));
654 	nvg__setPaintColor(&state->stroke, nvgRGBA(0,0,0,255));
655 	state->compositeOperation = nvg__compositeOperationState(NVG_SOURCE_OVER);
656 	state->shapeAntiAlias = 1;
657 	state->strokeWidth = 1.0f;
658 	state->miterLimit = 10.0f;
659 	state->lineCap = NVG_BUTT;
660 	state->lineJoin = NVG_MITER;
661 	state->alpha = 1.0f;
662 	nvgTransformIdentity(state->xform);
663 
664 	state->scissor.extent[0] = -1.0f;
665 	state->scissor.extent[1] = -1.0f;
666 
667 	state->fontSize = 16.0f;
668 	state->letterSpacing = 0.0f;
669 	state->lineHeight = 1.0f;
670 	state->fontBlur = 0.0f;
671 	state->textAlign = NVG_ALIGN_LEFT | NVG_ALIGN_BASELINE;
672 	state->fontId = 0;
673 }
674 
675 // State setting
nvgShapeAntiAlias(NVGcontext * ctx,int enabled)676 void nvgShapeAntiAlias(NVGcontext* ctx, int enabled)
677 {
678 	NVGstate* state = nvg__getState(ctx);
679 	state->shapeAntiAlias = enabled;
680 }
681 
nvgStrokeWidth(NVGcontext * ctx,float width)682 void nvgStrokeWidth(NVGcontext* ctx, float width)
683 {
684 	NVGstate* state = nvg__getState(ctx);
685 	state->strokeWidth = width;
686 }
687 
nvgMiterLimit(NVGcontext * ctx,float limit)688 void nvgMiterLimit(NVGcontext* ctx, float limit)
689 {
690 	NVGstate* state = nvg__getState(ctx);
691 	state->miterLimit = limit;
692 }
693 
nvgLineCap(NVGcontext * ctx,int cap)694 void nvgLineCap(NVGcontext* ctx, int cap)
695 {
696 	NVGstate* state = nvg__getState(ctx);
697 	state->lineCap = cap;
698 }
699 
nvgLineJoin(NVGcontext * ctx,int join)700 void nvgLineJoin(NVGcontext* ctx, int join)
701 {
702 	NVGstate* state = nvg__getState(ctx);
703 	state->lineJoin = join;
704 }
705 
nvgGlobalAlpha(NVGcontext * ctx,float alpha)706 void nvgGlobalAlpha(NVGcontext* ctx, float alpha)
707 {
708 	NVGstate* state = nvg__getState(ctx);
709 	state->alpha = alpha;
710 }
711 
nvgTransform(NVGcontext * ctx,float a,float b,float c,float d,float e,float f)712 void nvgTransform(NVGcontext* ctx, float a, float b, float c, float d, float e, float f)
713 {
714 	NVGstate* state = nvg__getState(ctx);
715 	float t[6] = { a, b, c, d, e, f };
716 	nvgTransformPremultiply(state->xform, t);
717 }
718 
nvgResetTransform(NVGcontext * ctx)719 void nvgResetTransform(NVGcontext* ctx)
720 {
721 	NVGstate* state = nvg__getState(ctx);
722 	nvgTransformIdentity(state->xform);
723 }
724 
nvgTranslate(NVGcontext * ctx,float x,float y)725 void nvgTranslate(NVGcontext* ctx, float x, float y)
726 {
727 	NVGstate* state = nvg__getState(ctx);
728 	float t[6];
729 	nvgTransformTranslate(t, x,y);
730 	nvgTransformPremultiply(state->xform, t);
731 }
732 
nvgRotate(NVGcontext * ctx,float angle)733 void nvgRotate(NVGcontext* ctx, float angle)
734 {
735 	NVGstate* state = nvg__getState(ctx);
736 	float t[6];
737 	nvgTransformRotate(t, angle);
738 	nvgTransformPremultiply(state->xform, t);
739 }
740 
nvgSkewX(NVGcontext * ctx,float angle)741 void nvgSkewX(NVGcontext* ctx, float angle)
742 {
743 	NVGstate* state = nvg__getState(ctx);
744 	float t[6];
745 	nvgTransformSkewX(t, angle);
746 	nvgTransformPremultiply(state->xform, t);
747 }
748 
nvgSkewY(NVGcontext * ctx,float angle)749 void nvgSkewY(NVGcontext* ctx, float angle)
750 {
751 	NVGstate* state = nvg__getState(ctx);
752 	float t[6];
753 	nvgTransformSkewY(t, angle);
754 	nvgTransformPremultiply(state->xform, t);
755 }
756 
nvgScale(NVGcontext * ctx,float x,float y)757 void nvgScale(NVGcontext* ctx, float x, float y)
758 {
759 	NVGstate* state = nvg__getState(ctx);
760 	float t[6];
761 	nvgTransformScale(t, x,y);
762 	nvgTransformPremultiply(state->xform, t);
763 }
764 
nvgCurrentTransform(NVGcontext * ctx,float * xform)765 void nvgCurrentTransform(NVGcontext* ctx, float* xform)
766 {
767 	NVGstate* state = nvg__getState(ctx);
768 	if (xform == NULL) return;
769 	memcpy(xform, state->xform, sizeof(float)*6);
770 }
771 
nvgStrokeColor(NVGcontext * ctx,NVGcolor color)772 void nvgStrokeColor(NVGcontext* ctx, NVGcolor color)
773 {
774 	NVGstate* state = nvg__getState(ctx);
775 	nvg__setPaintColor(&state->stroke, color);
776 }
777 
nvgStrokePaint(NVGcontext * ctx,NVGpaint paint)778 void nvgStrokePaint(NVGcontext* ctx, NVGpaint paint)
779 {
780 	NVGstate* state = nvg__getState(ctx);
781 	state->stroke = paint;
782 	nvgTransformMultiply(state->stroke.xform, state->xform);
783 }
784 
nvgFillColor(NVGcontext * ctx,NVGcolor color)785 void nvgFillColor(NVGcontext* ctx, NVGcolor color)
786 {
787 	NVGstate* state = nvg__getState(ctx);
788 	nvg__setPaintColor(&state->fill, color);
789 }
790 
nvgFillPaint(NVGcontext * ctx,NVGpaint paint)791 void nvgFillPaint(NVGcontext* ctx, NVGpaint paint)
792 {
793 	NVGstate* state = nvg__getState(ctx);
794 	state->fill = paint;
795 	nvgTransformMultiply(state->fill.xform, state->xform);
796 }
797 
nvgCreateImage(NVGcontext * ctx,const char * filename,int imageFlags)798 int nvgCreateImage(NVGcontext* ctx, const char* filename, int imageFlags)
799 {
800 	int w, h, n, image;
801 	unsigned char* img;
802 	stbi_set_unpremultiply_on_load(1);
803 	stbi_convert_iphone_png_to_rgb(1);
804 	img = stbi_load(filename, &w, &h, &n, 4);
805 	if (img == NULL) {
806 //		printf("Failed to load %s - %s\n", filename, stbi_failure_reason());
807 		return 0;
808 	}
809 	image = nvgCreateImageRGBA(ctx, w, h, imageFlags, img);
810 	stbi_image_free(img);
811 	return image;
812 }
813 
nvgCreateImageMem(NVGcontext * ctx,int imageFlags,unsigned char * data,int ndata)814 int nvgCreateImageMem(NVGcontext* ctx, int imageFlags, unsigned char* data, int ndata)
815 {
816 	int w, h, n, image;
817 	unsigned char* img = stbi_load_from_memory(data, ndata, &w, &h, &n, 4);
818 	if (img == NULL) {
819 //		printf("Failed to load %s - %s\n", filename, stbi_failure_reason());
820 		return 0;
821 	}
822 	image = nvgCreateImageRGBA(ctx, w, h, imageFlags, img);
823 	stbi_image_free(img);
824 	return image;
825 }
826 
nvgCreateImageRGBA(NVGcontext * ctx,int w,int h,int imageFlags,const unsigned char * data)827 int nvgCreateImageRGBA(NVGcontext* ctx, int w, int h, int imageFlags, const unsigned char* data)
828 {
829 	return ctx->params.renderCreateTexture(ctx->params.userPtr, NVG_TEXTURE_RGBA, w, h, imageFlags, data);
830 }
831 
nvgCreateImageARGB(NVGcontext * ctx,int w,int h,int imageFlags,const unsigned char * data)832 int nvgCreateImageARGB(NVGcontext* ctx, int w, int h, int imageFlags, const unsigned char* data)
833 {
834 	return ctx->params.renderCreateTexture(ctx->params.userPtr, NVG_TEXTURE_ARGB, w, h, imageFlags, data);
835 }
836 
nvgUpdateImage(NVGcontext * ctx,int image,const unsigned char * data)837 void nvgUpdateImage(NVGcontext* ctx, int image, const unsigned char* data)
838 {
839 	int w, h;
840 	ctx->params.renderGetTextureSize(ctx->params.userPtr, image, &w, &h);
841 	ctx->params.renderUpdateTexture(ctx->params.userPtr, image, 0,0, w,h, data);
842 }
843 
nvgUpdateSubImage(NVGcontext * ctx,int image,const unsigned char * data,int x,int y,int w,int h)844 void nvgUpdateSubImage(NVGcontext* ctx, int image, const unsigned char* data, int x, int y, int w, int h)
845 {
846 	ctx->params.renderUpdateTexture(ctx->params.userPtr, image, x,y, w,h, data);
847 }
848 
nvgImageSize(NVGcontext * ctx,int image,int * w,int * h)849 void nvgImageSize(NVGcontext* ctx, int image, int* w, int* h)
850 {
851 	ctx->params.renderGetTextureSize(ctx->params.userPtr, image, w, h);
852 }
853 
nvgDeleteImage(NVGcontext * ctx,int image)854 void nvgDeleteImage(NVGcontext* ctx, int image)
855 {
856 	ctx->params.renderDeleteTexture(ctx->params.userPtr, image);
857 }
858 
nvgLinearGradient(NVGcontext * ctx,float sx,float sy,float ex,float ey,NVGcolor icol,NVGcolor ocol)859 NVGpaint nvgLinearGradient(NVGcontext* ctx,
860 								  float sx, float sy, float ex, float ey,
861 								  NVGcolor icol, NVGcolor ocol)
862 {
863 	NVGpaint p;
864 	float dx, dy, d;
865 	const float large = 1e5;
866 	NVG_NOTUSED(ctx);
867 	memset(&p, 0, sizeof(p));
868 
869 	// Calculate transform aligned to the line
870 	dx = ex - sx;
871 	dy = ey - sy;
872 	d = sqrtf(dx*dx + dy*dy);
873 	if (d > 0.0001f) {
874 		dx /= d;
875 		dy /= d;
876 	} else {
877 		dx = 0;
878 		dy = 1;
879 	}
880 
881 	p.xform[0] = dy; p.xform[1] = -dx;
882 	p.xform[2] = dx; p.xform[3] = dy;
883 	p.xform[4] = sx - dx*large; p.xform[5] = sy - dy*large;
884 
885 	p.extent[0] = large;
886 	p.extent[1] = large + d*0.5f;
887 
888 	p.radius = 0.0f;
889 
890 	p.feather = nvg__maxf(1.0f, d);
891 
892 	p.innerColor = icol;
893 	p.outerColor = ocol;
894 
895 	return p;
896 }
897 
nvgRadialGradient(NVGcontext * ctx,float cx,float cy,float inr,float outr,NVGcolor icol,NVGcolor ocol)898 NVGpaint nvgRadialGradient(NVGcontext* ctx,
899 								  float cx, float cy, float inr, float outr,
900 								  NVGcolor icol, NVGcolor ocol)
901 {
902 	NVGpaint p;
903 	float r = (inr+outr)*0.5f;
904 	float f = (outr-inr);
905 	NVG_NOTUSED(ctx);
906 	memset(&p, 0, sizeof(p));
907 
908 	nvgTransformIdentity(p.xform);
909 	p.xform[4] = cx;
910 	p.xform[5] = cy;
911 
912 	p.extent[0] = r;
913 	p.extent[1] = r;
914 
915 	p.radius = r;
916 
917 	p.feather = nvg__maxf(1.0f, f);
918 
919 	p.innerColor = icol;
920 	p.outerColor = ocol;
921 
922 	return p;
923 }
924 
nvgBoxGradient(NVGcontext * ctx,float x,float y,float w,float h,float r,float f,NVGcolor icol,NVGcolor ocol)925 NVGpaint nvgBoxGradient(NVGcontext* ctx,
926 							   float x, float y, float w, float h, float r, float f,
927 							   NVGcolor icol, NVGcolor ocol)
928 {
929 	NVGpaint p;
930 	NVG_NOTUSED(ctx);
931 	memset(&p, 0, sizeof(p));
932 
933 	nvgTransformIdentity(p.xform);
934 	p.xform[4] = x+w*0.5f;
935 	p.xform[5] = y+h*0.5f;
936 
937 	p.extent[0] = w*0.5f;
938 	p.extent[1] = h*0.5f;
939 
940 	p.radius = r;
941 
942 	p.feather = nvg__maxf(1.0f, f);
943 
944 	p.innerColor = icol;
945 	p.outerColor = ocol;
946 
947 	return p;
948 }
949 
950 
nvgImagePattern(NVGcontext * ctx,float cx,float cy,float w,float h,float angle,int image,float alpha)951 NVGpaint nvgImagePattern(NVGcontext* ctx,
952 								float cx, float cy, float w, float h, float angle,
953 								int image, float alpha)
954 {
955 	NVGpaint p;
956 	NVG_NOTUSED(ctx);
957 	memset(&p, 0, sizeof(p));
958 
959 	nvgTransformRotate(p.xform, angle);
960 	p.xform[4] = cx;
961 	p.xform[5] = cy;
962 
963 	p.extent[0] = w;
964 	p.extent[1] = h;
965 
966 	p.image = image;
967 
968 	p.innerColor = p.outerColor = nvgRGBAf(1,1,1,alpha);
969 
970 	return p;
971 }
972 
973 // Scissoring
nvgScissor(NVGcontext * ctx,float x,float y,float w,float h)974 void nvgScissor(NVGcontext* ctx, float x, float y, float w, float h)
975 {
976 	NVGstate* state = nvg__getState(ctx);
977 
978 	w = nvg__maxf(0.0f, w);
979 	h = nvg__maxf(0.0f, h);
980 
981 	nvgTransformIdentity(state->scissor.xform);
982 	state->scissor.xform[4] = x+w*0.5f;
983 	state->scissor.xform[5] = y+h*0.5f;
984 	nvgTransformMultiply(state->scissor.xform, state->xform);
985 
986 	state->scissor.extent[0] = w*0.5f;
987 	state->scissor.extent[1] = h*0.5f;
988 }
989 
nvg__isectRects(float * dst,float ax,float ay,float aw,float ah,float bx,float by,float bw,float bh)990 static void nvg__isectRects(float* dst,
991 							float ax, float ay, float aw, float ah,
992 							float bx, float by, float bw, float bh)
993 {
994 	float minx = nvg__maxf(ax, bx);
995 	float miny = nvg__maxf(ay, by);
996 	float maxx = nvg__minf(ax+aw, bx+bw);
997 	float maxy = nvg__minf(ay+ah, by+bh);
998 	dst[0] = minx;
999 	dst[1] = miny;
1000 	dst[2] = nvg__maxf(0.0f, maxx - minx);
1001 	dst[3] = nvg__maxf(0.0f, maxy - miny);
1002 }
1003 
nvgIntersectScissor(NVGcontext * ctx,float x,float y,float w,float h)1004 void nvgIntersectScissor(NVGcontext* ctx, float x, float y, float w, float h)
1005 {
1006 	NVGstate* state = nvg__getState(ctx);
1007 	float pxform[6], invxorm[6];
1008 	float rect[4];
1009 	float ex, ey, tex, tey;
1010 
1011 	// If no previous scissor has been set, set the scissor as current scissor.
1012 	if (state->scissor.extent[0] < 0) {
1013 		nvgScissor(ctx, x, y, w, h);
1014 		return;
1015 	}
1016 
1017 	// Transform the current scissor rect into current transform space.
1018 	// If there is difference in rotation, this will be approximation.
1019 	memcpy(pxform, state->scissor.xform, sizeof(float)*6);
1020 	ex = state->scissor.extent[0];
1021 	ey = state->scissor.extent[1];
1022 	nvgTransformInverse(invxorm, state->xform);
1023 	nvgTransformMultiply(pxform, invxorm);
1024 	tex = ex*nvg__absf(pxform[0]) + ey*nvg__absf(pxform[2]);
1025 	tey = ex*nvg__absf(pxform[1]) + ey*nvg__absf(pxform[3]);
1026 
1027 	// Intersect rects.
1028 	nvg__isectRects(rect, pxform[4]-tex,pxform[5]-tey,tex*2,tey*2, x,y,w,h);
1029 
1030 	nvgScissor(ctx, rect[0], rect[1], rect[2], rect[3]);
1031 }
1032 
nvgResetScissor(NVGcontext * ctx)1033 void nvgResetScissor(NVGcontext* ctx)
1034 {
1035 	NVGstate* state = nvg__getState(ctx);
1036 	memset(state->scissor.xform, 0, sizeof(state->scissor.xform));
1037 	state->scissor.extent[0] = -1.0f;
1038 	state->scissor.extent[1] = -1.0f;
1039 }
1040 
1041 // Global composite operation.
nvgGlobalCompositeOperation(NVGcontext * ctx,int op)1042 void nvgGlobalCompositeOperation(NVGcontext* ctx, int op)
1043 {
1044 	NVGstate* state = nvg__getState(ctx);
1045 	state->compositeOperation = nvg__compositeOperationState(op);
1046 }
1047 
nvgGlobalCompositeBlendFunc(NVGcontext * ctx,int sfactor,int dfactor)1048 void nvgGlobalCompositeBlendFunc(NVGcontext* ctx, int sfactor, int dfactor)
1049 {
1050 	nvgGlobalCompositeBlendFuncSeparate(ctx, sfactor, dfactor, sfactor, dfactor);
1051 }
1052 
nvgGlobalCompositeBlendFuncSeparate(NVGcontext * ctx,int srcRGB,int dstRGB,int srcAlpha,int dstAlpha)1053 void nvgGlobalCompositeBlendFuncSeparate(NVGcontext* ctx, int srcRGB, int dstRGB, int srcAlpha, int dstAlpha)
1054 {
1055 	NVGcompositeOperationState op;
1056 	op.srcRGB = srcRGB;
1057 	op.dstRGB = dstRGB;
1058 	op.srcAlpha = srcAlpha;
1059 	op.dstAlpha = dstAlpha;
1060 
1061 	NVGstate* state = nvg__getState(ctx);
1062 	state->compositeOperation = op;
1063 }
1064 
nvg__ptEquals(float x1,float y1,float x2,float y2,float tol)1065 static int nvg__ptEquals(float x1, float y1, float x2, float y2, float tol)
1066 {
1067 	float dx = x2 - x1;
1068 	float dy = y2 - y1;
1069 	return dx*dx + dy*dy < tol*tol;
1070 }
1071 
nvg__distPtSeg(float x,float y,float px,float py,float qx,float qy)1072 static float nvg__distPtSeg(float x, float y, float px, float py, float qx, float qy)
1073 {
1074 	float pqx, pqy, dx, dy, d, t;
1075 	pqx = qx-px;
1076 	pqy = qy-py;
1077 	dx = x-px;
1078 	dy = y-py;
1079 	d = pqx*pqx + pqy*pqy;
1080 	t = pqx*dx + pqy*dy;
1081 	if (d > 0) t /= d;
1082 	if (t < 0) t = 0;
1083 	else if (t > 1) t = 1;
1084 	dx = px + t*pqx - x;
1085 	dy = py + t*pqy - y;
1086 	return dx*dx + dy*dy;
1087 }
1088 
nvg__appendCommands(NVGcontext * ctx,float * vals,int nvals)1089 static void nvg__appendCommands(NVGcontext* ctx, float* vals, int nvals)
1090 {
1091 	NVGstate* state = nvg__getState(ctx);
1092 	int i;
1093 
1094 	if (ctx->ncommands+nvals > ctx->ccommands) {
1095 		float* commands;
1096 		int ccommands = ctx->ncommands+nvals + ctx->ccommands/2;
1097 		commands = (float*)realloc(ctx->commands, sizeof(float)*ccommands);
1098 		if (commands == NULL) return;
1099 		ctx->commands = commands;
1100 		ctx->ccommands = ccommands;
1101 	}
1102 
1103 	if ((int)vals[0] != NVG_CLOSE && (int)vals[0] != NVG_WINDING) {
1104 		ctx->commandx = vals[nvals-2];
1105 		ctx->commandy = vals[nvals-1];
1106 	}
1107 
1108 	// transform commands
1109 	i = 0;
1110 	while (i < nvals) {
1111 		int cmd = (int)vals[i];
1112 		switch (cmd) {
1113 		case NVG_MOVETO:
1114 			nvgTransformPoint(&vals[i+1],&vals[i+2], state->xform, vals[i+1],vals[i+2]);
1115 			i += 3;
1116 			break;
1117 		case NVG_LINETO:
1118 			nvgTransformPoint(&vals[i+1],&vals[i+2], state->xform, vals[i+1],vals[i+2]);
1119 			i += 3;
1120 			break;
1121 		case NVG_BEZIERTO:
1122 			nvgTransformPoint(&vals[i+1],&vals[i+2], state->xform, vals[i+1],vals[i+2]);
1123 			nvgTransformPoint(&vals[i+3],&vals[i+4], state->xform, vals[i+3],vals[i+4]);
1124 			nvgTransformPoint(&vals[i+5],&vals[i+6], state->xform, vals[i+5],vals[i+6]);
1125 			i += 7;
1126 			break;
1127 		case NVG_CLOSE:
1128 			i++;
1129 			break;
1130 		case NVG_WINDING:
1131 			i += 2;
1132 			break;
1133 		default:
1134 			i++;
1135 		}
1136 	}
1137 
1138 	memcpy(&ctx->commands[ctx->ncommands], vals, nvals*sizeof(float));
1139 
1140 	ctx->ncommands += nvals;
1141 }
1142 
1143 
nvg__clearPathCache(NVGcontext * ctx)1144 static void nvg__clearPathCache(NVGcontext* ctx)
1145 {
1146 	ctx->cache->npoints = 0;
1147 	ctx->cache->npaths = 0;
1148 }
1149 
nvg__lastPath(NVGcontext * ctx)1150 static NVGpath* nvg__lastPath(NVGcontext* ctx)
1151 {
1152 	if (ctx->cache->npaths > 0)
1153 		return &ctx->cache->paths[ctx->cache->npaths-1];
1154 	return NULL;
1155 }
1156 
nvg__addPath(NVGcontext * ctx)1157 static void nvg__addPath(NVGcontext* ctx)
1158 {
1159 	NVGpath* path;
1160 	if (ctx->cache->npaths+1 > ctx->cache->cpaths) {
1161 		NVGpath* paths;
1162 		int cpaths = ctx->cache->npaths+1 + ctx->cache->cpaths/2;
1163 		paths = (NVGpath*)realloc(ctx->cache->paths, sizeof(NVGpath)*cpaths);
1164 		if (paths == NULL) return;
1165 		ctx->cache->paths = paths;
1166 		ctx->cache->cpaths = cpaths;
1167 	}
1168 	path = &ctx->cache->paths[ctx->cache->npaths];
1169 	memset(path, 0, sizeof(*path));
1170 	path->first = ctx->cache->npoints;
1171 	path->winding = NVG_CCW;
1172 
1173 	ctx->cache->npaths++;
1174 }
1175 
nvg__lastPoint(NVGcontext * ctx)1176 static NVGpoint* nvg__lastPoint(NVGcontext* ctx)
1177 {
1178 	if (ctx->cache->npoints > 0)
1179 		return &ctx->cache->points[ctx->cache->npoints-1];
1180 	return NULL;
1181 }
1182 
nvg__addPoint(NVGcontext * ctx,float x,float y,int flags)1183 static void nvg__addPoint(NVGcontext* ctx, float x, float y, int flags)
1184 {
1185 	NVGpath* path = nvg__lastPath(ctx);
1186 	NVGpoint* pt;
1187 	if (path == NULL) return;
1188 
1189 	if (path->count > 0 && ctx->cache->npoints > 0) {
1190 		pt = nvg__lastPoint(ctx);
1191 		if (nvg__ptEquals(pt->x,pt->y, x,y, ctx->distTol)) {
1192 			pt->flags |= flags;
1193 			return;
1194 		}
1195 	}
1196 
1197 	if (ctx->cache->npoints+1 > ctx->cache->cpoints) {
1198 		NVGpoint* points;
1199 		int cpoints = ctx->cache->npoints+1 + ctx->cache->cpoints/2;
1200 		points = (NVGpoint*)realloc(ctx->cache->points, sizeof(NVGpoint)*cpoints);
1201 		if (points == NULL) return;
1202 		ctx->cache->points = points;
1203 		ctx->cache->cpoints = cpoints;
1204 	}
1205 
1206 	pt = &ctx->cache->points[ctx->cache->npoints];
1207 	memset(pt, 0, sizeof(*pt));
1208 	pt->x = x;
1209 	pt->y = y;
1210 	pt->flags = (unsigned char)flags;
1211 
1212 	ctx->cache->npoints++;
1213 	path->count++;
1214 }
1215 
nvg__closePath(NVGcontext * ctx)1216 static void nvg__closePath(NVGcontext* ctx)
1217 {
1218 	NVGpath* path = nvg__lastPath(ctx);
1219 	if (path == NULL) return;
1220 	path->closed = 1;
1221 }
1222 
nvg__pathWinding(NVGcontext * ctx,int winding)1223 static void nvg__pathWinding(NVGcontext* ctx, int winding)
1224 {
1225 	NVGpath* path = nvg__lastPath(ctx);
1226 	if (path == NULL) return;
1227 	path->winding = winding;
1228 }
1229 
nvg__getAverageScale(float * t)1230 static float nvg__getAverageScale(float *t)
1231 {
1232 	float sx = sqrtf(t[0]*t[0] + t[2]*t[2]);
1233 	float sy = sqrtf(t[1]*t[1] + t[3]*t[3]);
1234 	return (sx + sy) * 0.5f;
1235 }
1236 
nvg__allocTempVerts(NVGcontext * ctx,int nverts)1237 static NVGvertex* nvg__allocTempVerts(NVGcontext* ctx, int nverts)
1238 {
1239 	if (nverts > ctx->cache->cverts) {
1240 		NVGvertex* verts;
1241 		int cverts = (nverts + 0xff) & ~0xff; // Round up to prevent allocations when things change just slightly.
1242 		verts = (NVGvertex*)realloc(ctx->cache->verts, sizeof(NVGvertex)*cverts);
1243 		if (verts == NULL) return NULL;
1244 		ctx->cache->verts = verts;
1245 		ctx->cache->cverts = cverts;
1246 	}
1247 
1248 	return ctx->cache->verts;
1249 }
1250 
nvg__triarea2(float ax,float ay,float bx,float by,float cx,float cy)1251 static float nvg__triarea2(float ax, float ay, float bx, float by, float cx, float cy)
1252 {
1253 	float abx = bx - ax;
1254 	float aby = by - ay;
1255 	float acx = cx - ax;
1256 	float acy = cy - ay;
1257 	return acx*aby - abx*acy;
1258 }
1259 
nvg__polyArea(NVGpoint * pts,int npts)1260 static float nvg__polyArea(NVGpoint* pts, int npts)
1261 {
1262 	int i;
1263 	float area = 0;
1264 	for (i = 2; i < npts; i++) {
1265 		NVGpoint* a = &pts[0];
1266 		NVGpoint* b = &pts[i-1];
1267 		NVGpoint* c = &pts[i];
1268 		area += nvg__triarea2(a->x,a->y, b->x,b->y, c->x,c->y);
1269 	}
1270 	return area * 0.5f;
1271 }
1272 
nvg__polyReverse(NVGpoint * pts,int npts)1273 static void nvg__polyReverse(NVGpoint* pts, int npts)
1274 {
1275 	NVGpoint tmp;
1276 	int i = 0, j = npts-1;
1277 	while (i < j) {
1278 		tmp = pts[i];
1279 		pts[i] = pts[j];
1280 		pts[j] = tmp;
1281 		i++;
1282 		j--;
1283 	}
1284 }
1285 
1286 
nvg__vset(NVGvertex * vtx,float x,float y,float u,float v)1287 static void nvg__vset(NVGvertex* vtx, float x, float y, float u, float v)
1288 {
1289 	vtx->x = x;
1290 	vtx->y = y;
1291 	vtx->u = u;
1292 	vtx->v = v;
1293 }
1294 
nvg__tesselateBezier(NVGcontext * ctx,float x1,float y1,float x2,float y2,float x3,float y3,float x4,float y4,int level,int type)1295 static void nvg__tesselateBezier(NVGcontext* ctx,
1296 								 float x1, float y1, float x2, float y2,
1297 								 float x3, float y3, float x4, float y4,
1298 								 int level, int type)
1299 {
1300 	float x12,y12,x23,y23,x34,y34,x123,y123,x234,y234,x1234,y1234;
1301 	float dx,dy,d2,d3;
1302 
1303 	if (level > 10) return;
1304 
1305 	x12 = (x1+x2)*0.5f;
1306 	y12 = (y1+y2)*0.5f;
1307 	x23 = (x2+x3)*0.5f;
1308 	y23 = (y2+y3)*0.5f;
1309 	x34 = (x3+x4)*0.5f;
1310 	y34 = (y3+y4)*0.5f;
1311 	x123 = (x12+x23)*0.5f;
1312 	y123 = (y12+y23)*0.5f;
1313 
1314 	dx = x4 - x1;
1315 	dy = y4 - y1;
1316 	d2 = nvg__absf(((x2 - x4) * dy - (y2 - y4) * dx));
1317 	d3 = nvg__absf(((x3 - x4) * dy - (y3 - y4) * dx));
1318 
1319 	if ((d2 + d3)*(d2 + d3) < ctx->tessTol * (dx*dx + dy*dy)) {
1320 		nvg__addPoint(ctx, x4, y4, type);
1321 		return;
1322 	}
1323 
1324 /*	if (nvg__absf(x1+x3-x2-x2) + nvg__absf(y1+y3-y2-y2) + nvg__absf(x2+x4-x3-x3) + nvg__absf(y2+y4-y3-y3) < ctx->tessTol) {
1325 		nvg__addPoint(ctx, x4, y4, type);
1326 		return;
1327 	}*/
1328 
1329 	x234 = (x23+x34)*0.5f;
1330 	y234 = (y23+y34)*0.5f;
1331 	x1234 = (x123+x234)*0.5f;
1332 	y1234 = (y123+y234)*0.5f;
1333 
1334 	nvg__tesselateBezier(ctx, x1,y1, x12,y12, x123,y123, x1234,y1234, level+1, 0);
1335 	nvg__tesselateBezier(ctx, x1234,y1234, x234,y234, x34,y34, x4,y4, level+1, type);
1336 }
1337 
nvg__flattenPaths(NVGcontext * ctx)1338 static void nvg__flattenPaths(NVGcontext* ctx)
1339 {
1340 	NVGpathCache* cache = ctx->cache;
1341 //	NVGstate* state = nvg__getState(ctx);
1342 	NVGpoint* last;
1343 	NVGpoint* p0;
1344 	NVGpoint* p1;
1345 	NVGpoint* pts;
1346 	NVGpath* path;
1347 	int i, j;
1348 	float* cp1;
1349 	float* cp2;
1350 	float* p;
1351 	float area;
1352 
1353 	if (cache->npaths > 0)
1354 		return;
1355 
1356 	// Flatten
1357 	i = 0;
1358 	while (i < ctx->ncommands) {
1359 		int cmd = (int)ctx->commands[i];
1360 		switch (cmd) {
1361 		case NVG_MOVETO:
1362 			nvg__addPath(ctx);
1363 			p = &ctx->commands[i+1];
1364 			nvg__addPoint(ctx, p[0], p[1], NVG_PT_CORNER);
1365 			i += 3;
1366 			break;
1367 		case NVG_LINETO:
1368 			p = &ctx->commands[i+1];
1369 			nvg__addPoint(ctx, p[0], p[1], NVG_PT_CORNER);
1370 			i += 3;
1371 			break;
1372 		case NVG_BEZIERTO:
1373 			last = nvg__lastPoint(ctx);
1374 			if (last != NULL) {
1375 				cp1 = &ctx->commands[i+1];
1376 				cp2 = &ctx->commands[i+3];
1377 				p = &ctx->commands[i+5];
1378 				nvg__tesselateBezier(ctx, last->x,last->y, cp1[0],cp1[1], cp2[0],cp2[1], p[0],p[1], 0, NVG_PT_CORNER);
1379 			}
1380 			i += 7;
1381 			break;
1382 		case NVG_CLOSE:
1383 			nvg__closePath(ctx);
1384 			i++;
1385 			break;
1386 		case NVG_WINDING:
1387 			nvg__pathWinding(ctx, (int)ctx->commands[i+1]);
1388 			i += 2;
1389 			break;
1390 		default:
1391 			i++;
1392 		}
1393 	}
1394 
1395 	cache->bounds[0] = cache->bounds[1] = 1e6f;
1396 	cache->bounds[2] = cache->bounds[3] = -1e6f;
1397 
1398 	// Calculate the direction and length of line segments.
1399 	for (j = 0; j < cache->npaths; j++) {
1400 		path = &cache->paths[j];
1401 		pts = &cache->points[path->first];
1402 
1403 		// If the first and last points are the same, remove the last, mark as closed path.
1404 		p0 = &pts[path->count-1];
1405 		p1 = &pts[0];
1406 		if (nvg__ptEquals(p0->x,p0->y, p1->x,p1->y, ctx->distTol)) {
1407 			path->count--;
1408 			p0 = &pts[path->count-1];
1409 			path->closed = 1;
1410 		}
1411 
1412 		// Enforce winding.
1413 		if (path->count > 2) {
1414 			area = nvg__polyArea(pts, path->count);
1415 			if (path->winding == NVG_CCW && area < 0.0f)
1416 				nvg__polyReverse(pts, path->count);
1417 			if (path->winding == NVG_CW && area > 0.0f)
1418 				nvg__polyReverse(pts, path->count);
1419 		}
1420 
1421 		for(i = 0; i < path->count; i++) {
1422 			// Calculate segment direction and length
1423 			p0->dx = p1->x - p0->x;
1424 			p0->dy = p1->y - p0->y;
1425 			p0->len = nvg__normalize(&p0->dx, &p0->dy);
1426 			// Update bounds
1427 			cache->bounds[0] = nvg__minf(cache->bounds[0], p0->x);
1428 			cache->bounds[1] = nvg__minf(cache->bounds[1], p0->y);
1429 			cache->bounds[2] = nvg__maxf(cache->bounds[2], p0->x);
1430 			cache->bounds[3] = nvg__maxf(cache->bounds[3], p0->y);
1431 			// Advance
1432 			p0 = p1++;
1433 		}
1434 	}
1435 }
1436 
nvg__curveDivs(float r,float arc,float tol)1437 static int nvg__curveDivs(float r, float arc, float tol)
1438 {
1439 	float da = acosf(r / (r + tol)) * 2.0f;
1440 	return nvg__maxi(2, (int)ceilf(arc / da));
1441 }
1442 
nvg__chooseBevel(int bevel,NVGpoint * p0,NVGpoint * p1,float w,float * x0,float * y0,float * x1,float * y1)1443 static void nvg__chooseBevel(int bevel, NVGpoint* p0, NVGpoint* p1, float w,
1444 							float* x0, float* y0, float* x1, float* y1)
1445 {
1446 	if (bevel) {
1447 		*x0 = p1->x + p0->dy * w;
1448 		*y0 = p1->y - p0->dx * w;
1449 		*x1 = p1->x + p1->dy * w;
1450 		*y1 = p1->y - p1->dx * w;
1451 	} else {
1452 		*x0 = p1->x + p1->dmx * w;
1453 		*y0 = p1->y + p1->dmy * w;
1454 		*x1 = p1->x + p1->dmx * w;
1455 		*y1 = p1->y + p1->dmy * w;
1456 	}
1457 }
1458 
nvg__roundJoin(NVGvertex * dst,NVGpoint * p0,NVGpoint * p1,float lw,float rw,float lu,float ru,int ncap,float fringe)1459 static NVGvertex* nvg__roundJoin(NVGvertex* dst, NVGpoint* p0, NVGpoint* p1,
1460 								 float lw, float rw, float lu, float ru, int ncap,
1461 								 float fringe)
1462 {
1463 	int i, n;
1464 	float dlx0 = p0->dy;
1465 	float dly0 = -p0->dx;
1466 	float dlx1 = p1->dy;
1467 	float dly1 = -p1->dx;
1468 	NVG_NOTUSED(fringe);
1469 
1470 	if (p1->flags & NVG_PT_LEFT) {
1471 		float lx0,ly0,lx1,ly1,a0,a1;
1472 		nvg__chooseBevel(p1->flags & NVG_PR_INNERBEVEL, p0, p1, lw, &lx0,&ly0, &lx1,&ly1);
1473 		a0 = atan2f(-dly0, -dlx0);
1474 		a1 = atan2f(-dly1, -dlx1);
1475 		if (a1 > a0) a1 -= NVG_PI*2;
1476 
1477 		nvg__vset(dst, lx0, ly0, lu,1); dst++;
1478 		nvg__vset(dst, p1->x - dlx0*rw, p1->y - dly0*rw, ru,1); dst++;
1479 
1480 		n = nvg__clampi((int)ceilf(((a0 - a1) / NVG_PI) * ncap), 2, ncap);
1481 		for (i = 0; i < n; i++) {
1482 			float u = i/(float)(n-1);
1483 			float a = a0 + u*(a1-a0);
1484 			float rx = p1->x + cosf(a) * rw;
1485 			float ry = p1->y + sinf(a) * rw;
1486 			nvg__vset(dst, p1->x, p1->y, 0.5f,1); dst++;
1487 			nvg__vset(dst, rx, ry, ru,1); dst++;
1488 		}
1489 
1490 		nvg__vset(dst, lx1, ly1, lu,1); dst++;
1491 		nvg__vset(dst, p1->x - dlx1*rw, p1->y - dly1*rw, ru,1); dst++;
1492 
1493 	} else {
1494 		float rx0,ry0,rx1,ry1,a0,a1;
1495 		nvg__chooseBevel(p1->flags & NVG_PR_INNERBEVEL, p0, p1, -rw, &rx0,&ry0, &rx1,&ry1);
1496 		a0 = atan2f(dly0, dlx0);
1497 		a1 = atan2f(dly1, dlx1);
1498 		if (a1 < a0) a1 += NVG_PI*2;
1499 
1500 		nvg__vset(dst, p1->x + dlx0*rw, p1->y + dly0*rw, lu,1); dst++;
1501 		nvg__vset(dst, rx0, ry0, ru,1); dst++;
1502 
1503 		n = nvg__clampi((int)ceilf(((a1 - a0) / NVG_PI) * ncap), 2, ncap);
1504 		for (i = 0; i < n; i++) {
1505 			float u = i/(float)(n-1);
1506 			float a = a0 + u*(a1-a0);
1507 			float lx = p1->x + cosf(a) * lw;
1508 			float ly = p1->y + sinf(a) * lw;
1509 			nvg__vset(dst, lx, ly, lu,1); dst++;
1510 			nvg__vset(dst, p1->x, p1->y, 0.5f,1); dst++;
1511 		}
1512 
1513 		nvg__vset(dst, p1->x + dlx1*rw, p1->y + dly1*rw, lu,1); dst++;
1514 		nvg__vset(dst, rx1, ry1, ru,1); dst++;
1515 
1516 	}
1517 	return dst;
1518 }
1519 
nvg__bevelJoin(NVGvertex * dst,NVGpoint * p0,NVGpoint * p1,float lw,float rw,float lu,float ru,float fringe)1520 static NVGvertex* nvg__bevelJoin(NVGvertex* dst, NVGpoint* p0, NVGpoint* p1,
1521 										float lw, float rw, float lu, float ru, float fringe)
1522 {
1523 	float rx0,ry0,rx1,ry1;
1524 	float lx0,ly0,lx1,ly1;
1525 	float dlx0 = p0->dy;
1526 	float dly0 = -p0->dx;
1527 	float dlx1 = p1->dy;
1528 	float dly1 = -p1->dx;
1529 	NVG_NOTUSED(fringe);
1530 
1531 	if (p1->flags & NVG_PT_LEFT) {
1532 		nvg__chooseBevel(p1->flags & NVG_PR_INNERBEVEL, p0, p1, lw, &lx0,&ly0, &lx1,&ly1);
1533 
1534 		nvg__vset(dst, lx0, ly0, lu,1); dst++;
1535 		nvg__vset(dst, p1->x - dlx0*rw, p1->y - dly0*rw, ru,1); dst++;
1536 
1537 		if (p1->flags & NVG_PT_BEVEL) {
1538 			nvg__vset(dst, lx0, ly0, lu,1); dst++;
1539 			nvg__vset(dst, p1->x - dlx0*rw, p1->y - dly0*rw, ru,1); dst++;
1540 
1541 			nvg__vset(dst, lx1, ly1, lu,1); dst++;
1542 			nvg__vset(dst, p1->x - dlx1*rw, p1->y - dly1*rw, ru,1); dst++;
1543 		} else {
1544 			rx0 = p1->x - p1->dmx * rw;
1545 			ry0 = p1->y - p1->dmy * rw;
1546 
1547 			nvg__vset(dst, p1->x, p1->y, 0.5f,1); dst++;
1548 			nvg__vset(dst, p1->x - dlx0*rw, p1->y - dly0*rw, ru,1); dst++;
1549 
1550 			nvg__vset(dst, rx0, ry0, ru,1); dst++;
1551 			nvg__vset(dst, rx0, ry0, ru,1); dst++;
1552 
1553 			nvg__vset(dst, p1->x, p1->y, 0.5f,1); dst++;
1554 			nvg__vset(dst, p1->x - dlx1*rw, p1->y - dly1*rw, ru,1); dst++;
1555 		}
1556 
1557 		nvg__vset(dst, lx1, ly1, lu,1); dst++;
1558 		nvg__vset(dst, p1->x - dlx1*rw, p1->y - dly1*rw, ru,1); dst++;
1559 
1560 	} else {
1561 		nvg__chooseBevel(p1->flags & NVG_PR_INNERBEVEL, p0, p1, -rw, &rx0,&ry0, &rx1,&ry1);
1562 
1563 		nvg__vset(dst, p1->x + dlx0*lw, p1->y + dly0*lw, lu,1); dst++;
1564 		nvg__vset(dst, rx0, ry0, ru,1); dst++;
1565 
1566 		if (p1->flags & NVG_PT_BEVEL) {
1567 			nvg__vset(dst, p1->x + dlx0*lw, p1->y + dly0*lw, lu,1); dst++;
1568 			nvg__vset(dst, rx0, ry0, ru,1); dst++;
1569 
1570 			nvg__vset(dst, p1->x + dlx1*lw, p1->y + dly1*lw, lu,1); dst++;
1571 			nvg__vset(dst, rx1, ry1, ru,1); dst++;
1572 		} else {
1573 			lx0 = p1->x + p1->dmx * lw;
1574 			ly0 = p1->y + p1->dmy * lw;
1575 
1576 			nvg__vset(dst, p1->x + dlx0*lw, p1->y + dly0*lw, lu,1); dst++;
1577 			nvg__vset(dst, p1->x, p1->y, 0.5f,1); dst++;
1578 
1579 			nvg__vset(dst, lx0, ly0, lu,1); dst++;
1580 			nvg__vset(dst, lx0, ly0, lu,1); dst++;
1581 
1582 			nvg__vset(dst, p1->x + dlx1*lw, p1->y + dly1*lw, lu,1); dst++;
1583 			nvg__vset(dst, p1->x, p1->y, 0.5f,1); dst++;
1584 		}
1585 
1586 		nvg__vset(dst, p1->x + dlx1*lw, p1->y + dly1*lw, lu,1); dst++;
1587 		nvg__vset(dst, rx1, ry1, ru,1); dst++;
1588 	}
1589 
1590 	return dst;
1591 }
1592 
nvg__buttCapStart(NVGvertex * dst,NVGpoint * p,float dx,float dy,float w,float d,float aa,float u0,float u1)1593 static NVGvertex* nvg__buttCapStart(NVGvertex* dst, NVGpoint* p,
1594 									float dx, float dy, float w, float d,
1595 									float aa, float u0, float u1)
1596 {
1597 	float px = p->x - dx*d;
1598 	float py = p->y - dy*d;
1599 	float dlx = dy;
1600 	float dly = -dx;
1601 	nvg__vset(dst, px + dlx*w - dx*aa, py + dly*w - dy*aa, u0,0); dst++;
1602 	nvg__vset(dst, px - dlx*w - dx*aa, py - dly*w - dy*aa, u1,0); dst++;
1603 	nvg__vset(dst, px + dlx*w, py + dly*w, u0,1); dst++;
1604 	nvg__vset(dst, px - dlx*w, py - dly*w, u1,1); dst++;
1605 	return dst;
1606 }
1607 
nvg__buttCapEnd(NVGvertex * dst,NVGpoint * p,float dx,float dy,float w,float d,float aa,float u0,float u1)1608 static NVGvertex* nvg__buttCapEnd(NVGvertex* dst, NVGpoint* p,
1609 								  float dx, float dy, float w, float d,
1610 								  float aa, float u0, float u1)
1611 {
1612 	float px = p->x + dx*d;
1613 	float py = p->y + dy*d;
1614 	float dlx = dy;
1615 	float dly = -dx;
1616 	nvg__vset(dst, px + dlx*w, py + dly*w, u0,1); dst++;
1617 	nvg__vset(dst, px - dlx*w, py - dly*w, u1,1); dst++;
1618 	nvg__vset(dst, px + dlx*w + dx*aa, py + dly*w + dy*aa, u0,0); dst++;
1619 	nvg__vset(dst, px - dlx*w + dx*aa, py - dly*w + dy*aa, u1,0); dst++;
1620 	return dst;
1621 }
1622 
1623 
nvg__roundCapStart(NVGvertex * dst,NVGpoint * p,float dx,float dy,float w,int ncap,float aa,float u0,float u1)1624 static NVGvertex* nvg__roundCapStart(NVGvertex* dst, NVGpoint* p,
1625 									 float dx, float dy, float w, int ncap,
1626 									 float aa, float u0, float u1)
1627 {
1628 	int i;
1629 	float px = p->x;
1630 	float py = p->y;
1631 	float dlx = dy;
1632 	float dly = -dx;
1633 	NVG_NOTUSED(aa);
1634 	for (i = 0; i < ncap; i++) {
1635 		float a = i/(float)(ncap-1)*NVG_PI;
1636 		float ax = cosf(a) * w, ay = sinf(a) * w;
1637 		nvg__vset(dst, px - dlx*ax - dx*ay, py - dly*ax - dy*ay, u0,1); dst++;
1638 		nvg__vset(dst, px, py, 0.5f,1); dst++;
1639 	}
1640 	nvg__vset(dst, px + dlx*w, py + dly*w, u0,1); dst++;
1641 	nvg__vset(dst, px - dlx*w, py - dly*w, u1,1); dst++;
1642 	return dst;
1643 }
1644 
nvg__roundCapEnd(NVGvertex * dst,NVGpoint * p,float dx,float dy,float w,int ncap,float aa,float u0,float u1)1645 static NVGvertex* nvg__roundCapEnd(NVGvertex* dst, NVGpoint* p,
1646 								   float dx, float dy, float w, int ncap,
1647 								   float aa, float u0, float u1)
1648 {
1649 	int i;
1650 	float px = p->x;
1651 	float py = p->y;
1652 	float dlx = dy;
1653 	float dly = -dx;
1654 	NVG_NOTUSED(aa);
1655 	nvg__vset(dst, px + dlx*w, py + dly*w, u0,1); dst++;
1656 	nvg__vset(dst, px - dlx*w, py - dly*w, u1,1); dst++;
1657 	for (i = 0; i < ncap; i++) {
1658 		float a = i/(float)(ncap-1)*NVG_PI;
1659 		float ax = cosf(a) * w, ay = sinf(a) * w;
1660 		nvg__vset(dst, px, py, 0.5f,1); dst++;
1661 		nvg__vset(dst, px - dlx*ax + dx*ay, py - dly*ax + dy*ay, u0,1); dst++;
1662 	}
1663 	return dst;
1664 }
1665 
1666 
nvg__calculateJoins(NVGcontext * ctx,float w,int lineJoin,float miterLimit)1667 static void nvg__calculateJoins(NVGcontext* ctx, float w, int lineJoin, float miterLimit)
1668 {
1669 	NVGpathCache* cache = ctx->cache;
1670 	int i, j;
1671 	float iw = 0.0f;
1672 
1673 	if (w > 0.0f) iw = 1.0f / w;
1674 
1675 	// Calculate which joins needs extra vertices to append, and gather vertex count.
1676 	for (i = 0; i < cache->npaths; i++) {
1677 		NVGpath* path = &cache->paths[i];
1678 		NVGpoint* pts = &cache->points[path->first];
1679 		NVGpoint* p0 = &pts[path->count-1];
1680 		NVGpoint* p1 = &pts[0];
1681 		int nleft = 0;
1682 
1683 		path->nbevel = 0;
1684 
1685 		for (j = 0; j < path->count; j++) {
1686 			float dlx0, dly0, dlx1, dly1, dmr2, cross, limit;
1687 			dlx0 = p0->dy;
1688 			dly0 = -p0->dx;
1689 			dlx1 = p1->dy;
1690 			dly1 = -p1->dx;
1691 			// Calculate extrusions
1692 			p1->dmx = (dlx0 + dlx1) * 0.5f;
1693 			p1->dmy = (dly0 + dly1) * 0.5f;
1694 			dmr2 = p1->dmx*p1->dmx + p1->dmy*p1->dmy;
1695 			if (dmr2 > 0.000001f) {
1696 				float scale = 1.0f / dmr2;
1697 				if (scale > 600.0f) {
1698 					scale = 600.0f;
1699 				}
1700 				p1->dmx *= scale;
1701 				p1->dmy *= scale;
1702 			}
1703 
1704 			// Clear flags, but keep the corner.
1705 			p1->flags = (p1->flags & NVG_PT_CORNER) ? NVG_PT_CORNER : 0;
1706 
1707 			// Keep track of left turns.
1708 			cross = p1->dx * p0->dy - p0->dx * p1->dy;
1709 			if (cross > 0.0f) {
1710 				nleft++;
1711 				p1->flags |= NVG_PT_LEFT;
1712 			}
1713 
1714 			// Calculate if we should use bevel or miter for inner join.
1715 			limit = nvg__maxf(1.01f, nvg__minf(p0->len, p1->len) * iw);
1716 			if ((dmr2 * limit*limit) < 1.0f)
1717 				p1->flags |= NVG_PR_INNERBEVEL;
1718 
1719 			// Check to see if the corner needs to be beveled.
1720 			if (p1->flags & NVG_PT_CORNER) {
1721 				if ((dmr2 * miterLimit*miterLimit) < 1.0f || lineJoin == NVG_BEVEL || lineJoin == NVG_ROUND) {
1722 					p1->flags |= NVG_PT_BEVEL;
1723 				}
1724 			}
1725 
1726 			if ((p1->flags & (NVG_PT_BEVEL | NVG_PR_INNERBEVEL)) != 0)
1727 				path->nbevel++;
1728 
1729 			p0 = p1++;
1730 		}
1731 
1732 		path->convex = (nleft == path->count) ? 1 : 0;
1733 	}
1734 }
1735 
1736 
nvg__expandStroke(NVGcontext * ctx,float w,float fringe,int lineCap,int lineJoin,float miterLimit)1737 static int nvg__expandStroke(NVGcontext* ctx, float w, float fringe, int lineCap, int lineJoin, float miterLimit)
1738 {
1739 	NVGpathCache* cache = ctx->cache;
1740 	NVGvertex* verts;
1741 	NVGvertex* dst;
1742 	int cverts, i, j;
1743 	float aa = fringe;//ctx->fringeWidth;
1744 	float u0 = 0.0f, u1 = 1.0f;
1745 	int ncap = nvg__curveDivs(w, NVG_PI, ctx->tessTol);	// Calculate divisions per half circle.
1746 
1747 	w += aa * 0.5f;
1748 
1749 	// Disable the gradient used for antialiasing when antialiasing is not used.
1750 	if (aa == 0.0f) {
1751 		u0 = 0.5f;
1752 		u1 = 0.5f;
1753 	}
1754 
1755 	nvg__calculateJoins(ctx, w, lineJoin, miterLimit);
1756 
1757 	// Calculate max vertex usage.
1758 	cverts = 0;
1759 	for (i = 0; i < cache->npaths; i++) {
1760 		NVGpath* path = &cache->paths[i];
1761 		int loop = (path->closed == 0) ? 0 : 1;
1762 		if (lineJoin == NVG_ROUND)
1763 			cverts += (path->count + path->nbevel*(ncap+2) + 1) * 2; // plus one for loop
1764 		else
1765 			cverts += (path->count + path->nbevel*5 + 1) * 2; // plus one for loop
1766 		if (loop == 0) {
1767 			// space for caps
1768 			if (lineCap == NVG_ROUND) {
1769 				cverts += (ncap*2 + 2)*2;
1770 			} else {
1771 				cverts += (3+3)*2;
1772 			}
1773 		}
1774 	}
1775 
1776 	verts = nvg__allocTempVerts(ctx, cverts);
1777 	if (verts == NULL) return 0;
1778 
1779 	for (i = 0; i < cache->npaths; i++) {
1780 		NVGpath* path = &cache->paths[i];
1781 		NVGpoint* pts = &cache->points[path->first];
1782 		NVGpoint* p0;
1783 		NVGpoint* p1;
1784 		int s, e, loop;
1785 		float dx, dy;
1786 
1787 		path->fill = 0;
1788 		path->nfill = 0;
1789 
1790 		// Calculate fringe or stroke
1791 		loop = (path->closed == 0) ? 0 : 1;
1792 		dst = verts;
1793 		path->stroke = dst;
1794 
1795 		if (loop) {
1796 			// Looping
1797 			p0 = &pts[path->count-1];
1798 			p1 = &pts[0];
1799 			s = 0;
1800 			e = path->count;
1801 		} else {
1802 			// Add cap
1803 			p0 = &pts[0];
1804 			p1 = &pts[1];
1805 			s = 1;
1806 			e = path->count-1;
1807 		}
1808 
1809 		if (loop == 0) {
1810 			// Add cap
1811 			dx = p1->x - p0->x;
1812 			dy = p1->y - p0->y;
1813 			nvg__normalize(&dx, &dy);
1814 			if (lineCap == NVG_BUTT)
1815 				dst = nvg__buttCapStart(dst, p0, dx, dy, w, -aa*0.5f, aa, u0, u1);
1816 			else if (lineCap == NVG_BUTT || lineCap == NVG_SQUARE)
1817 				dst = nvg__buttCapStart(dst, p0, dx, dy, w, w-aa, aa, u0, u1);
1818 			else if (lineCap == NVG_ROUND)
1819 				dst = nvg__roundCapStart(dst, p0, dx, dy, w, ncap, aa, u0, u1);
1820 		}
1821 
1822 		for (j = s; j < e; ++j) {
1823 			if ((p1->flags & (NVG_PT_BEVEL | NVG_PR_INNERBEVEL)) != 0) {
1824 				if (lineJoin == NVG_ROUND) {
1825 					dst = nvg__roundJoin(dst, p0, p1, w, w, u0, u1, ncap, aa);
1826 				} else {
1827 					dst = nvg__bevelJoin(dst, p0, p1, w, w, u0, u1, aa);
1828 				}
1829 			} else {
1830 				nvg__vset(dst, p1->x + (p1->dmx * w), p1->y + (p1->dmy * w), u0,1); dst++;
1831 				nvg__vset(dst, p1->x - (p1->dmx * w), p1->y - (p1->dmy * w), u1,1); dst++;
1832 			}
1833 			p0 = p1++;
1834 		}
1835 
1836 		if (loop) {
1837 			// Loop it
1838 			nvg__vset(dst, verts[0].x, verts[0].y, u0,1); dst++;
1839 			nvg__vset(dst, verts[1].x, verts[1].y, u1,1); dst++;
1840 		} else {
1841 			// Add cap
1842 			dx = p1->x - p0->x;
1843 			dy = p1->y - p0->y;
1844 			nvg__normalize(&dx, &dy);
1845 			if (lineCap == NVG_BUTT)
1846 				dst = nvg__buttCapEnd(dst, p1, dx, dy, w, -aa*0.5f, aa, u0, u1);
1847 			else if (lineCap == NVG_BUTT || lineCap == NVG_SQUARE)
1848 				dst = nvg__buttCapEnd(dst, p1, dx, dy, w, w-aa, aa, u0, u1);
1849 			else if (lineCap == NVG_ROUND)
1850 				dst = nvg__roundCapEnd(dst, p1, dx, dy, w, ncap, aa, u0, u1);
1851 		}
1852 
1853 		path->nstroke = (int)(dst - verts);
1854 
1855 		verts = dst;
1856 	}
1857 
1858 	return 1;
1859 }
1860 
nvg__expandFill(NVGcontext * ctx,float w,int lineJoin,float miterLimit)1861 static int nvg__expandFill(NVGcontext* ctx, float w, int lineJoin, float miterLimit)
1862 {
1863 	NVGpathCache* cache = ctx->cache;
1864 	NVGvertex* verts;
1865 	NVGvertex* dst;
1866 	int cverts, convex, i, j;
1867 	float aa = ctx->fringeWidth;
1868 	int fringe = w > 0.0f;
1869 
1870 	nvg__calculateJoins(ctx, w, lineJoin, miterLimit);
1871 
1872 	// Calculate max vertex usage.
1873 	cverts = 0;
1874 	for (i = 0; i < cache->npaths; i++) {
1875 		NVGpath* path = &cache->paths[i];
1876 		cverts += path->count + path->nbevel + 1;
1877 		if (fringe)
1878 			cverts += (path->count + path->nbevel*5 + 1) * 2; // plus one for loop
1879 	}
1880 
1881 	verts = nvg__allocTempVerts(ctx, cverts);
1882 	if (verts == NULL) return 0;
1883 
1884 	convex = cache->npaths == 1 && cache->paths[0].convex;
1885 
1886 	for (i = 0; i < cache->npaths; i++) {
1887 		NVGpath* path = &cache->paths[i];
1888 		NVGpoint* pts = &cache->points[path->first];
1889 		NVGpoint* p0;
1890 		NVGpoint* p1;
1891 		float rw, lw, woff;
1892 		float ru, lu;
1893 
1894 		// Calculate shape vertices.
1895 		woff = 0.5f*aa;
1896 		dst = verts;
1897 		path->fill = dst;
1898 
1899 		if (fringe) {
1900 			// Looping
1901 			p0 = &pts[path->count-1];
1902 			p1 = &pts[0];
1903 			for (j = 0; j < path->count; ++j) {
1904 				if (p1->flags & NVG_PT_BEVEL) {
1905 					float dlx0 = p0->dy;
1906 					float dly0 = -p0->dx;
1907 					float dlx1 = p1->dy;
1908 					float dly1 = -p1->dx;
1909 					if (p1->flags & NVG_PT_LEFT) {
1910 						float lx = p1->x + p1->dmx * woff;
1911 						float ly = p1->y + p1->dmy * woff;
1912 						nvg__vset(dst, lx, ly, 0.5f,1); dst++;
1913 					} else {
1914 						float lx0 = p1->x + dlx0 * woff;
1915 						float ly0 = p1->y + dly0 * woff;
1916 						float lx1 = p1->x + dlx1 * woff;
1917 						float ly1 = p1->y + dly1 * woff;
1918 						nvg__vset(dst, lx0, ly0, 0.5f,1); dst++;
1919 						nvg__vset(dst, lx1, ly1, 0.5f,1); dst++;
1920 					}
1921 				} else {
1922 					nvg__vset(dst, p1->x + (p1->dmx * woff), p1->y + (p1->dmy * woff), 0.5f,1); dst++;
1923 				}
1924 				p0 = p1++;
1925 			}
1926 		} else {
1927 			for (j = 0; j < path->count; ++j) {
1928 				nvg__vset(dst, pts[j].x, pts[j].y, 0.5f,1);
1929 				dst++;
1930 			}
1931 		}
1932 
1933 		path->nfill = (int)(dst - verts);
1934 		verts = dst;
1935 
1936 		// Calculate fringe
1937 		if (fringe) {
1938 			lw = w + woff;
1939 			rw = w - woff;
1940 			lu = 0;
1941 			ru = 1;
1942 			dst = verts;
1943 			path->stroke = dst;
1944 
1945 			// Create only half a fringe for convex shapes so that
1946 			// the shape can be rendered without stenciling.
1947 			if (convex) {
1948 				lw = woff;	// This should generate the same vertex as fill inset above.
1949 				lu = 0.5f;	// Set outline fade at middle.
1950 			}
1951 
1952 			// Looping
1953 			p0 = &pts[path->count-1];
1954 			p1 = &pts[0];
1955 
1956 			for (j = 0; j < path->count; ++j) {
1957 				if ((p1->flags & (NVG_PT_BEVEL | NVG_PR_INNERBEVEL)) != 0) {
1958 					dst = nvg__bevelJoin(dst, p0, p1, lw, rw, lu, ru, ctx->fringeWidth);
1959 				} else {
1960 					nvg__vset(dst, p1->x + (p1->dmx * lw), p1->y + (p1->dmy * lw), lu,1); dst++;
1961 					nvg__vset(dst, p1->x - (p1->dmx * rw), p1->y - (p1->dmy * rw), ru,1); dst++;
1962 				}
1963 				p0 = p1++;
1964 			}
1965 
1966 			// Loop it
1967 			nvg__vset(dst, verts[0].x, verts[0].y, lu,1); dst++;
1968 			nvg__vset(dst, verts[1].x, verts[1].y, ru,1); dst++;
1969 
1970 			path->nstroke = (int)(dst - verts);
1971 			verts = dst;
1972 		} else {
1973 			path->stroke = NULL;
1974 			path->nstroke = 0;
1975 		}
1976 	}
1977 
1978 	return 1;
1979 }
1980 
1981 
1982 // Draw
nvgBeginPath(NVGcontext * ctx)1983 void nvgBeginPath(NVGcontext* ctx)
1984 {
1985 	ctx->ncommands = 0;
1986 	nvg__clearPathCache(ctx);
1987 }
1988 
nvgMoveTo(NVGcontext * ctx,float x,float y)1989 void nvgMoveTo(NVGcontext* ctx, float x, float y)
1990 {
1991 	float vals[] = { NVG_MOVETO, x, y };
1992 	nvg__appendCommands(ctx, vals, NVG_COUNTOF(vals));
1993 }
1994 
nvgLineTo(NVGcontext * ctx,float x,float y)1995 void nvgLineTo(NVGcontext* ctx, float x, float y)
1996 {
1997 	float vals[] = { NVG_LINETO, x, y };
1998 	nvg__appendCommands(ctx, vals, NVG_COUNTOF(vals));
1999 }
2000 
nvgBezierTo(NVGcontext * ctx,float c1x,float c1y,float c2x,float c2y,float x,float y)2001 void nvgBezierTo(NVGcontext* ctx, float c1x, float c1y, float c2x, float c2y, float x, float y)
2002 {
2003 	float vals[] = { NVG_BEZIERTO, c1x, c1y, c2x, c2y, x, y };
2004 	nvg__appendCommands(ctx, vals, NVG_COUNTOF(vals));
2005 }
2006 
nvgQuadTo(NVGcontext * ctx,float cx,float cy,float x,float y)2007 void nvgQuadTo(NVGcontext* ctx, float cx, float cy, float x, float y)
2008 {
2009     float x0 = ctx->commandx;
2010     float y0 = ctx->commandy;
2011     float vals[] = { NVG_BEZIERTO,
2012         x0 + 2.0f/3.0f*(cx - x0), y0 + 2.0f/3.0f*(cy - y0),
2013         x + 2.0f/3.0f*(cx - x), y + 2.0f/3.0f*(cy - y),
2014         x, y };
2015     nvg__appendCommands(ctx, vals, NVG_COUNTOF(vals));
2016 }
2017 
nvgArcTo(NVGcontext * ctx,float x1,float y1,float x2,float y2,float radius)2018 void nvgArcTo(NVGcontext* ctx, float x1, float y1, float x2, float y2, float radius)
2019 {
2020 	float x0 = ctx->commandx;
2021 	float y0 = ctx->commandy;
2022 	float dx0,dy0, dx1,dy1, a, d, cx,cy, a0,a1;
2023 	int dir;
2024 
2025 	if (ctx->ncommands == 0) {
2026 		return;
2027 	}
2028 
2029 	// Handle degenerate cases.
2030 	if (nvg__ptEquals(x0,y0, x1,y1, ctx->distTol) ||
2031 		nvg__ptEquals(x1,y1, x2,y2, ctx->distTol) ||
2032 		nvg__distPtSeg(x1,y1, x0,y0, x2,y2) < ctx->distTol*ctx->distTol ||
2033 		radius < ctx->distTol) {
2034 		nvgLineTo(ctx, x1,y1);
2035 		return;
2036 	}
2037 
2038 	// Calculate tangential circle to lines (x0,y0)-(x1,y1) and (x1,y1)-(x2,y2).
2039 	dx0 = x0-x1;
2040 	dy0 = y0-y1;
2041 	dx1 = x2-x1;
2042 	dy1 = y2-y1;
2043 	nvg__normalize(&dx0,&dy0);
2044 	nvg__normalize(&dx1,&dy1);
2045 	a = nvg__acosf(dx0*dx1 + dy0*dy1);
2046 	d = radius / nvg__tanf(a/2.0f);
2047 
2048 //	printf("a=%f° d=%f\n", a/NVG_PI*180.0f, d);
2049 
2050 	if (d > 10000.0f) {
2051 		nvgLineTo(ctx, x1,y1);
2052 		return;
2053 	}
2054 
2055 	if (nvg__cross(dx0,dy0, dx1,dy1) > 0.0f) {
2056 		cx = x1 + dx0*d + dy0*radius;
2057 		cy = y1 + dy0*d + -dx0*radius;
2058 		a0 = nvg__atan2f(dx0, -dy0);
2059 		a1 = nvg__atan2f(-dx1, dy1);
2060 		dir = NVG_CW;
2061 //		printf("CW c=(%f, %f) a0=%f° a1=%f°\n", cx, cy, a0/NVG_PI*180.0f, a1/NVG_PI*180.0f);
2062 	} else {
2063 		cx = x1 + dx0*d + -dy0*radius;
2064 		cy = y1 + dy0*d + dx0*radius;
2065 		a0 = nvg__atan2f(-dx0, dy0);
2066 		a1 = nvg__atan2f(dx1, -dy1);
2067 		dir = NVG_CCW;
2068 //		printf("CCW c=(%f, %f) a0=%f° a1=%f°\n", cx, cy, a0/NVG_PI*180.0f, a1/NVG_PI*180.0f);
2069 	}
2070 
2071 	nvgArc(ctx, cx, cy, radius, a0, a1, dir);
2072 }
2073 
nvgClosePath(NVGcontext * ctx)2074 void nvgClosePath(NVGcontext* ctx)
2075 {
2076 	float vals[] = { NVG_CLOSE };
2077 	nvg__appendCommands(ctx, vals, NVG_COUNTOF(vals));
2078 }
2079 
nvgPathWinding(NVGcontext * ctx,int dir)2080 void nvgPathWinding(NVGcontext* ctx, int dir)
2081 {
2082 	float vals[] = { NVG_WINDING, (float)dir };
2083 	nvg__appendCommands(ctx, vals, NVG_COUNTOF(vals));
2084 }
2085 
nvgArc(NVGcontext * ctx,float cx,float cy,float r,float a0,float a1,int dir)2086 void nvgArc(NVGcontext* ctx, float cx, float cy, float r, float a0, float a1, int dir)
2087 {
2088 	float a = 0, da = 0, hda = 0, kappa = 0;
2089 	float dx = 0, dy = 0, x = 0, y = 0, tanx = 0, tany = 0;
2090 	float px = 0, py = 0, ptanx = 0, ptany = 0;
2091 	float vals[3 + 5*7 + 100];
2092 	int i, ndivs, nvals;
2093 	int move = ctx->ncommands > 0 ? NVG_LINETO : NVG_MOVETO;
2094 
2095 	// Clamp angles
2096 	da = a1 - a0;
2097 	if (dir == NVG_CW) {
2098 		if (nvg__absf(da) >= NVG_PI*2) {
2099 			da = NVG_PI*2;
2100 		} else {
2101 			while (da < 0.0f) da += NVG_PI*2;
2102 		}
2103 	} else {
2104 		if (nvg__absf(da) >= NVG_PI*2) {
2105 			da = -NVG_PI*2;
2106 		} else {
2107 			while (da > 0.0f) da -= NVG_PI*2;
2108 		}
2109 	}
2110 
2111 	// Split arc into max 90 degree segments.
2112 	ndivs = nvg__maxi(1, nvg__mini((int)(nvg__absf(da) / (NVG_PI*0.5f) + 0.5f), 5));
2113 	hda = (da / (float)ndivs) / 2.0f;
2114 	kappa = nvg__absf(4.0f / 3.0f * (1.0f - nvg__cosf(hda)) / nvg__sinf(hda));
2115 
2116 	if (dir == NVG_CCW)
2117 		kappa = -kappa;
2118 
2119 	nvals = 0;
2120 	for (i = 0; i <= ndivs; i++) {
2121 		a = a0 + da * (i/(float)ndivs);
2122 		dx = nvg__cosf(a);
2123 		dy = nvg__sinf(a);
2124 		x = cx + dx*r;
2125 		y = cy + dy*r;
2126 		tanx = -dy*r*kappa;
2127 		tany = dx*r*kappa;
2128 
2129 		if (i == 0) {
2130 			vals[nvals++] = (float)move;
2131 			vals[nvals++] = x;
2132 			vals[nvals++] = y;
2133 		} else {
2134 			vals[nvals++] = NVG_BEZIERTO;
2135 			vals[nvals++] = px+ptanx;
2136 			vals[nvals++] = py+ptany;
2137 			vals[nvals++] = x-tanx;
2138 			vals[nvals++] = y-tany;
2139 			vals[nvals++] = x;
2140 			vals[nvals++] = y;
2141 		}
2142 		px = x;
2143 		py = y;
2144 		ptanx = tanx;
2145 		ptany = tany;
2146 	}
2147 
2148 	nvg__appendCommands(ctx, vals, nvals);
2149 }
2150 
nvgRect(NVGcontext * ctx,float x,float y,float w,float h)2151 void nvgRect(NVGcontext* ctx, float x, float y, float w, float h)
2152 {
2153 	float vals[] = {
2154 		NVG_MOVETO, x,y,
2155 		NVG_LINETO, x,y+h,
2156 		NVG_LINETO, x+w,y+h,
2157 		NVG_LINETO, x+w,y,
2158 		NVG_CLOSE
2159 	};
2160 	nvg__appendCommands(ctx, vals, NVG_COUNTOF(vals));
2161 }
2162 
nvgRoundedRect(NVGcontext * ctx,float x,float y,float w,float h,float r)2163 void nvgRoundedRect(NVGcontext* ctx, float x, float y, float w, float h, float r)
2164 {
2165 	nvgRoundedRectVarying(ctx, x, y, w, h, r, r, r, r);
2166 }
2167 
nvgRoundedRectVarying(NVGcontext * ctx,float x,float y,float w,float h,float radTopLeft,float radTopRight,float radBottomRight,float radBottomLeft)2168 void nvgRoundedRectVarying(NVGcontext* ctx, float x, float y, float w, float h, float radTopLeft, float radTopRight, float radBottomRight, float radBottomLeft)
2169 {
2170 	if(radTopLeft < 0.1f && radTopRight < 0.1f && radBottomRight < 0.1f && radBottomLeft < 0.1f) {
2171 		nvgRect(ctx, x, y, w, h);
2172 		return;
2173 	} else {
2174 		float halfw = nvg__absf(w)*0.5f;
2175 		float halfh = nvg__absf(h)*0.5f;
2176 		float rxBL = nvg__minf(radBottomLeft, halfw) * nvg__signf(w), ryBL = nvg__minf(radBottomLeft, halfh) * nvg__signf(h);
2177 		float rxBR = nvg__minf(radBottomRight, halfw) * nvg__signf(w), ryBR = nvg__minf(radBottomRight, halfh) * nvg__signf(h);
2178 		float rxTR = nvg__minf(radTopRight, halfw) * nvg__signf(w), ryTR = nvg__minf(radTopRight, halfh) * nvg__signf(h);
2179 		float rxTL = nvg__minf(radTopLeft, halfw) * nvg__signf(w), ryTL = nvg__minf(radTopLeft, halfh) * nvg__signf(h);
2180 		float vals[] = {
2181 			NVG_MOVETO, x, y + ryTL,
2182 			NVG_LINETO, x, y + h - ryBL,
2183 			NVG_BEZIERTO, x, y + h - ryBL*(1 - NVG_KAPPA90), x + rxBL*(1 - NVG_KAPPA90), y + h, x + rxBL, y + h,
2184 			NVG_LINETO, x + w - rxBR, y + h,
2185 			NVG_BEZIERTO, x + w - rxBR*(1 - NVG_KAPPA90), y + h, x + w, y + h - ryBR*(1 - NVG_KAPPA90), x + w, y + h - ryBR,
2186 			NVG_LINETO, x + w, y + ryTR,
2187 			NVG_BEZIERTO, x + w, y + ryTR*(1 - NVG_KAPPA90), x + w - rxTR*(1 - NVG_KAPPA90), y, x + w - rxTR, y,
2188 			NVG_LINETO, x + rxTL, y,
2189 			NVG_BEZIERTO, x + rxTL*(1 - NVG_KAPPA90), y, x, y + ryTL*(1 - NVG_KAPPA90), x, y + ryTL,
2190 			NVG_CLOSE
2191 		};
2192 		nvg__appendCommands(ctx, vals, NVG_COUNTOF(vals));
2193 	}
2194 }
2195 
nvgEllipse(NVGcontext * ctx,float cx,float cy,float rx,float ry)2196 void nvgEllipse(NVGcontext* ctx, float cx, float cy, float rx, float ry)
2197 {
2198 	float vals[] = {
2199 		NVG_MOVETO, cx-rx, cy,
2200 		NVG_BEZIERTO, cx-rx, cy+ry*NVG_KAPPA90, cx-rx*NVG_KAPPA90, cy+ry, cx, cy+ry,
2201 		NVG_BEZIERTO, cx+rx*NVG_KAPPA90, cy+ry, cx+rx, cy+ry*NVG_KAPPA90, cx+rx, cy,
2202 		NVG_BEZIERTO, cx+rx, cy-ry*NVG_KAPPA90, cx+rx*NVG_KAPPA90, cy-ry, cx, cy-ry,
2203 		NVG_BEZIERTO, cx-rx*NVG_KAPPA90, cy-ry, cx-rx, cy-ry*NVG_KAPPA90, cx-rx, cy,
2204 		NVG_CLOSE
2205 	};
2206 	nvg__appendCommands(ctx, vals, NVG_COUNTOF(vals));
2207 }
2208 
nvgCircle(NVGcontext * ctx,float cx,float cy,float r)2209 void nvgCircle(NVGcontext* ctx, float cx, float cy, float r)
2210 {
2211 	nvgEllipse(ctx, cx,cy, r,r);
2212 }
2213 
nvgDebugDumpPathCache(NVGcontext * ctx)2214 void nvgDebugDumpPathCache(NVGcontext* ctx)
2215 {
2216 	const NVGpath* path;
2217 	int i, j;
2218 
2219 	printf("Dumping %d cached paths\n", ctx->cache->npaths);
2220 	for (i = 0; i < ctx->cache->npaths; i++) {
2221 		path = &ctx->cache->paths[i];
2222 		printf(" - Path %d\n", i);
2223 		if (path->nfill) {
2224 			printf("   - fill: %d\n", path->nfill);
2225 			for (j = 0; j < path->nfill; j++)
2226 				printf("%f\t%f\n", path->fill[j].x, path->fill[j].y);
2227 		}
2228 		if (path->nstroke) {
2229 			printf("   - stroke: %d\n", path->nstroke);
2230 			for (j = 0; j < path->nstroke; j++)
2231 				printf("%f\t%f\n", path->stroke[j].x, path->stroke[j].y);
2232 		}
2233 	}
2234 }
2235 
nvgFill(NVGcontext * ctx)2236 void nvgFill(NVGcontext* ctx)
2237 {
2238 	NVGstate* state = nvg__getState(ctx);
2239 	const NVGpath* path;
2240 	NVGpaint fillPaint = state->fill;
2241 	int i;
2242 
2243 	nvg__flattenPaths(ctx);
2244 	if (ctx->params.edgeAntiAlias && state->shapeAntiAlias)
2245 		nvg__expandFill(ctx, ctx->fringeWidth, NVG_MITER, 2.4f);
2246 	else
2247 		nvg__expandFill(ctx, 0.0f, NVG_MITER, 2.4f);
2248 
2249 	// Apply global alpha
2250 	fillPaint.innerColor.a *= state->alpha;
2251 	fillPaint.outerColor.a *= state->alpha;
2252 
2253 	ctx->params.renderFill(ctx->params.userPtr, &fillPaint, state->compositeOperation, &state->scissor, ctx->fringeWidth,
2254 						   ctx->cache->bounds, ctx->cache->paths, ctx->cache->npaths);
2255 
2256 	// Count triangles
2257 	for (i = 0; i < ctx->cache->npaths; i++) {
2258 		path = &ctx->cache->paths[i];
2259 		ctx->fillTriCount += path->nfill-2;
2260 		ctx->fillTriCount += path->nstroke-2;
2261 		ctx->drawCallCount += 2;
2262 	}
2263 }
2264 
nvgStroke(NVGcontext * ctx)2265 void nvgStroke(NVGcontext* ctx)
2266 {
2267 	NVGstate* state = nvg__getState(ctx);
2268 	float scale = nvg__getAverageScale(state->xform);
2269 	float strokeWidth = nvg__clampf(state->strokeWidth * scale, 0.0f, 200.0f);
2270 	NVGpaint strokePaint = state->stroke;
2271 	const NVGpath* path;
2272 	int i;
2273 
2274 
2275 	if (strokeWidth < ctx->fringeWidth) {
2276 		// If the stroke width is less than pixel size, use alpha to emulate coverage.
2277 		// Since coverage is area, scale by alpha*alpha.
2278 		float alpha = nvg__clampf(strokeWidth / ctx->fringeWidth, 0.0f, 1.0f);
2279 		strokePaint.innerColor.a *= alpha*alpha;
2280 		strokePaint.outerColor.a *= alpha*alpha;
2281 		strokeWidth = ctx->fringeWidth;
2282 	}
2283 
2284 	// Apply global alpha
2285 	strokePaint.innerColor.a *= state->alpha;
2286 	strokePaint.outerColor.a *= state->alpha;
2287 
2288 	nvg__flattenPaths(ctx);
2289 
2290 	if (ctx->params.edgeAntiAlias && state->shapeAntiAlias)
2291 		nvg__expandStroke(ctx, strokeWidth*0.5f, ctx->fringeWidth, state->lineCap, state->lineJoin, state->miterLimit);
2292 	else
2293 		nvg__expandStroke(ctx, strokeWidth*0.5f, 0.0f, state->lineCap, state->lineJoin, state->miterLimit);
2294 
2295 	ctx->params.renderStroke(ctx->params.userPtr, &strokePaint, state->compositeOperation, &state->scissor, ctx->fringeWidth,
2296 							 strokeWidth, ctx->cache->paths, ctx->cache->npaths);
2297 
2298 	// Count triangles
2299 	for (i = 0; i < ctx->cache->npaths; i++) {
2300 		path = &ctx->cache->paths[i];
2301 		ctx->strokeTriCount += path->nstroke-2;
2302 		ctx->drawCallCount++;
2303 	}
2304 }
2305 
2306 // Add fonts
nvgCreateFont(NVGcontext * ctx,const char * name,const char * path)2307 int nvgCreateFont(NVGcontext* ctx, const char* name, const char* path)
2308 {
2309 	return fonsAddFont(ctx->fs, name, path);
2310 }
2311 
nvgCreateFontMem(NVGcontext * ctx,const char * name,unsigned char * data,int ndata,int freeData)2312 int nvgCreateFontMem(NVGcontext* ctx, const char* name, unsigned char* data, int ndata, int freeData)
2313 {
2314 	return fonsAddFontMem(ctx->fs, name, data, ndata, freeData);
2315 }
2316 
nvgFindFont(NVGcontext * ctx,const char * name)2317 int nvgFindFont(NVGcontext* ctx, const char* name)
2318 {
2319 	if (name == NULL) return -1;
2320 	return fonsGetFontByName(ctx->fs, name);
2321 }
2322 
2323 
nvgAddFallbackFontId(NVGcontext * ctx,int baseFont,int fallbackFont)2324 int nvgAddFallbackFontId(NVGcontext* ctx, int baseFont, int fallbackFont)
2325 {
2326 	if(baseFont == -1 || fallbackFont == -1) return 0;
2327 	return fonsAddFallbackFont(ctx->fs, baseFont, fallbackFont);
2328 }
2329 
nvgAddFallbackFont(NVGcontext * ctx,const char * baseFont,const char * fallbackFont)2330 int nvgAddFallbackFont(NVGcontext* ctx, const char* baseFont, const char* fallbackFont)
2331 {
2332 	return nvgAddFallbackFontId(ctx, nvgFindFont(ctx, baseFont), nvgFindFont(ctx, fallbackFont));
2333 }
2334 
2335 // State setting
nvgFontSize(NVGcontext * ctx,float size)2336 void nvgFontSize(NVGcontext* ctx, float size)
2337 {
2338 	NVGstate* state = nvg__getState(ctx);
2339 	state->fontSize = size;
2340 }
2341 
nvgFontBlur(NVGcontext * ctx,float blur)2342 void nvgFontBlur(NVGcontext* ctx, float blur)
2343 {
2344 	NVGstate* state = nvg__getState(ctx);
2345 	state->fontBlur = blur;
2346 }
2347 
nvgTextLetterSpacing(NVGcontext * ctx,float spacing)2348 void nvgTextLetterSpacing(NVGcontext* ctx, float spacing)
2349 {
2350 	NVGstate* state = nvg__getState(ctx);
2351 	state->letterSpacing = spacing;
2352 }
2353 
nvgTextLineHeight(NVGcontext * ctx,float lineHeight)2354 void nvgTextLineHeight(NVGcontext* ctx, float lineHeight)
2355 {
2356 	NVGstate* state = nvg__getState(ctx);
2357 	state->lineHeight = lineHeight;
2358 }
2359 
nvgTextAlign(NVGcontext * ctx,int align)2360 void nvgTextAlign(NVGcontext* ctx, int align)
2361 {
2362 	NVGstate* state = nvg__getState(ctx);
2363 	state->textAlign = align;
2364 }
2365 
nvgFontFaceId(NVGcontext * ctx,int font)2366 void nvgFontFaceId(NVGcontext* ctx, int font)
2367 {
2368 	NVGstate* state = nvg__getState(ctx);
2369 	state->fontId = font;
2370 }
2371 
nvgFontFace(NVGcontext * ctx,const char * font)2372 void nvgFontFace(NVGcontext* ctx, const char* font)
2373 {
2374 	NVGstate* state = nvg__getState(ctx);
2375 	state->fontId = fonsGetFontByName(ctx->fs, font);
2376 }
2377 
nvg__quantize(float a,float d)2378 static float nvg__quantize(float a, float d)
2379 {
2380 	return ((int)(a / d + 0.5f)) * d;
2381 }
2382 
nvg__getFontScale(NVGstate * state)2383 static float nvg__getFontScale(NVGstate* state)
2384 {
2385 	return nvg__minf(nvg__quantize(nvg__getAverageScale(state->xform), 0.01f), 4.0f);
2386 }
2387 
nvg__flushTextTexture(NVGcontext * ctx)2388 static void nvg__flushTextTexture(NVGcontext* ctx)
2389 {
2390 	int dirty[4];
2391 
2392 	if (fonsValidateTexture(ctx->fs, dirty)) {
2393 		int fontImage = ctx->fontImages[ctx->fontImageIdx];
2394 		// Update texture
2395 		if (fontImage != 0) {
2396 			int iw, ih;
2397 			const unsigned char* data = fonsGetTextureData(ctx->fs, &iw, &ih);
2398 			int x = dirty[0];
2399 			int y = dirty[1];
2400 			int w = dirty[2] - dirty[0];
2401 			int h = dirty[3] - dirty[1];
2402 			ctx->params.renderUpdateTexture(ctx->params.userPtr, fontImage, x,y, w,h, data);
2403 		}
2404 	}
2405 }
2406 
nvg__allocTextAtlas(NVGcontext * ctx)2407 static int nvg__allocTextAtlas(NVGcontext* ctx)
2408 {
2409 	int iw, ih;
2410 	nvg__flushTextTexture(ctx);
2411 	if (ctx->fontImageIdx >= NVG_MAX_FONTIMAGES-1)
2412 		return 0;
2413 	// if next fontImage already have a texture
2414 	if (ctx->fontImages[ctx->fontImageIdx+1] != 0)
2415 		nvgImageSize(ctx, ctx->fontImages[ctx->fontImageIdx+1], &iw, &ih);
2416 	else { // calculate the new font image size and create it.
2417 		nvgImageSize(ctx, ctx->fontImages[ctx->fontImageIdx], &iw, &ih);
2418 		if (iw > ih)
2419 			ih *= 2;
2420 		else
2421 			iw *= 2;
2422 		if (iw > NVG_MAX_FONTIMAGE_SIZE || ih > NVG_MAX_FONTIMAGE_SIZE)
2423 			iw = ih = NVG_MAX_FONTIMAGE_SIZE;
2424 		ctx->fontImages[ctx->fontImageIdx+1] = ctx->params.renderCreateTexture(ctx->params.userPtr, NVG_TEXTURE_ALPHA, iw, ih, 0, NULL);
2425 	}
2426 	++ctx->fontImageIdx;
2427 	fonsResetAtlas(ctx->fs, iw, ih);
2428 	return 1;
2429 }
2430 
nvg__renderText(NVGcontext * ctx,NVGvertex * verts,int nverts)2431 static void nvg__renderText(NVGcontext* ctx, NVGvertex* verts, int nverts)
2432 {
2433 	NVGstate* state = nvg__getState(ctx);
2434 	NVGpaint paint = state->fill;
2435 
2436 	// Render triangles.
2437 	paint.image = ctx->fontImages[ctx->fontImageIdx];
2438 
2439 	// Apply global alpha
2440 	paint.innerColor.a *= state->alpha;
2441 	paint.outerColor.a *= state->alpha;
2442 
2443 	ctx->params.renderTriangles(ctx->params.userPtr, &paint, state->compositeOperation, &state->scissor, verts, nverts);
2444 
2445 	ctx->drawCallCount++;
2446 	ctx->textTriCount += nverts/3;
2447 }
2448 
nvgText(NVGcontext * ctx,float x,float y,const char * string,const char * end)2449 float nvgText(NVGcontext* ctx, float x, float y, const char* string, const char* end)
2450 {
2451 	NVGstate* state = nvg__getState(ctx);
2452 	FONStextIter iter, prevIter;
2453 	FONSquad q;
2454 	NVGvertex* verts;
2455 	float scale = nvg__getFontScale(state) * ctx->devicePxRatio;
2456 	float invscale = 1.0f / scale;
2457 	int cverts = 0;
2458 	int nverts = 0;
2459 
2460 	if (end == NULL)
2461 		end = string + strlen(string);
2462 
2463 	if (state->fontId == FONS_INVALID) return x;
2464 
2465 	fonsSetSize(ctx->fs, state->fontSize*scale);
2466 	fonsSetSpacing(ctx->fs, state->letterSpacing*scale);
2467 	fonsSetBlur(ctx->fs, state->fontBlur*scale);
2468 	fonsSetAlign(ctx->fs, state->textAlign);
2469 	fonsSetFont(ctx->fs, state->fontId);
2470 
2471 	cverts = nvg__maxi(2, (int)(end - string)) * 6; // conservative estimate.
2472 	verts = nvg__allocTempVerts(ctx, cverts);
2473 	if (verts == NULL) return x;
2474 
2475 	fonsTextIterInit(ctx->fs, &iter, x*scale, y*scale, string, end, FONS_GLYPH_BITMAP_REQUIRED);
2476 	prevIter = iter;
2477 	while (fonsTextIterNext(ctx->fs, &iter, &q)) {
2478 		float c[4*2];
2479 		if (iter.prevGlyphIndex == -1) { // can not retrieve glyph?
2480 			if (nverts != 0) {
2481 				nvg__renderText(ctx, verts, nverts);
2482 				nverts = 0;
2483 			}
2484 			if (!nvg__allocTextAtlas(ctx))
2485 				break; // no memory :(
2486 			iter = prevIter;
2487 			fonsTextIterNext(ctx->fs, &iter, &q); // try again
2488 			if (iter.prevGlyphIndex == -1) // still can not find glyph?
2489 				break;
2490 		}
2491 		prevIter = iter;
2492 		// Transform corners.
2493 		nvgTransformPoint(&c[0],&c[1], state->xform, q.x0*invscale, q.y0*invscale);
2494 		nvgTransformPoint(&c[2],&c[3], state->xform, q.x1*invscale, q.y0*invscale);
2495 		nvgTransformPoint(&c[4],&c[5], state->xform, q.x1*invscale, q.y1*invscale);
2496 		nvgTransformPoint(&c[6],&c[7], state->xform, q.x0*invscale, q.y1*invscale);
2497 		// Create triangles
2498 		if (nverts+6 <= cverts) {
2499 			nvg__vset(&verts[nverts], c[0], c[1], q.s0, q.t0); nverts++;
2500 			nvg__vset(&verts[nverts], c[4], c[5], q.s1, q.t1); nverts++;
2501 			nvg__vset(&verts[nverts], c[2], c[3], q.s1, q.t0); nverts++;
2502 			nvg__vset(&verts[nverts], c[0], c[1], q.s0, q.t0); nverts++;
2503 			nvg__vset(&verts[nverts], c[6], c[7], q.s0, q.t1); nverts++;
2504 			nvg__vset(&verts[nverts], c[4], c[5], q.s1, q.t1); nverts++;
2505 		}
2506 	}
2507 
2508 	// TODO: add back-end bit to do this just once per frame.
2509 	nvg__flushTextTexture(ctx);
2510 
2511 	nvg__renderText(ctx, verts, nverts);
2512 
2513 	return iter.nextx / scale;
2514 }
2515 
nvgTextBox(NVGcontext * ctx,float x,float y,float breakRowWidth,const char * string,const char * end)2516 void nvgTextBox(NVGcontext* ctx, float x, float y, float breakRowWidth, const char* string, const char* end)
2517 {
2518 	NVGstate* state = nvg__getState(ctx);
2519 	NVGtextRow rows[2];
2520 	int nrows = 0, i;
2521 	int oldAlign = state->textAlign;
2522 	int haling = state->textAlign & (NVG_ALIGN_LEFT | NVG_ALIGN_CENTER | NVG_ALIGN_RIGHT);
2523 	int valign = state->textAlign & (NVG_ALIGN_TOP | NVG_ALIGN_MIDDLE | NVG_ALIGN_BOTTOM | NVG_ALIGN_BASELINE);
2524 	float lineh = 0;
2525 
2526 	if (state->fontId == FONS_INVALID) return;
2527 
2528 	nvgTextMetrics(ctx, NULL, NULL, &lineh);
2529 
2530 	state->textAlign = NVG_ALIGN_LEFT | valign;
2531 
2532 	while ((nrows = nvgTextBreakLines(ctx, string, end, breakRowWidth, rows, 2))) {
2533 		for (i = 0; i < nrows; i++) {
2534 			NVGtextRow* row = &rows[i];
2535 			if (haling & NVG_ALIGN_LEFT)
2536 				nvgText(ctx, x, y, row->start, row->end);
2537 			else if (haling & NVG_ALIGN_CENTER)
2538 				nvgText(ctx, x + breakRowWidth*0.5f - row->width*0.5f, y, row->start, row->end);
2539 			else if (haling & NVG_ALIGN_RIGHT)
2540 				nvgText(ctx, x + breakRowWidth - row->width, y, row->start, row->end);
2541 			y += lineh * state->lineHeight;
2542 		}
2543 		string = rows[nrows-1].next;
2544 	}
2545 
2546 	state->textAlign = oldAlign;
2547 }
2548 
nvgTextGlyphPositions(NVGcontext * ctx,float x,float y,const char * string,const char * end,NVGglyphPosition * positions,int maxPositions)2549 int nvgTextGlyphPositions(NVGcontext* ctx, float x, float y, const char* string, const char* end, NVGglyphPosition* positions, int maxPositions)
2550 {
2551 	NVGstate* state = nvg__getState(ctx);
2552 	float scale = nvg__getFontScale(state) * ctx->devicePxRatio;
2553 	float invscale = 1.0f / scale;
2554 	FONStextIter iter, prevIter;
2555 	FONSquad q;
2556 	int npos = 0;
2557 
2558 	if (state->fontId == FONS_INVALID) return 0;
2559 
2560 	if (end == NULL)
2561 		end = string + strlen(string);
2562 
2563 	if (string == end)
2564 		return 0;
2565 
2566 	fonsSetSize(ctx->fs, state->fontSize*scale);
2567 	fonsSetSpacing(ctx->fs, state->letterSpacing*scale);
2568 	fonsSetBlur(ctx->fs, state->fontBlur*scale);
2569 	fonsSetAlign(ctx->fs, state->textAlign);
2570 	fonsSetFont(ctx->fs, state->fontId);
2571 
2572 	fonsTextIterInit(ctx->fs, &iter, x*scale, y*scale, string, end, FONS_GLYPH_BITMAP_OPTIONAL);
2573 	prevIter = iter;
2574 	while (fonsTextIterNext(ctx->fs, &iter, &q)) {
2575 		if (iter.prevGlyphIndex < 0 && nvg__allocTextAtlas(ctx)) { // can not retrieve glyph?
2576 			iter = prevIter;
2577 			fonsTextIterNext(ctx->fs, &iter, &q); // try again
2578 		}
2579 		prevIter = iter;
2580 		positions[npos].str = iter.str;
2581 		positions[npos].x = iter.x * invscale;
2582 		positions[npos].minx = nvg__minf(iter.x, q.x0) * invscale;
2583 		positions[npos].maxx = nvg__maxf(iter.nextx, q.x1) * invscale;
2584 		npos++;
2585 		if (npos >= maxPositions)
2586 			break;
2587 	}
2588 
2589 	return npos;
2590 }
2591 
2592 enum NVGcodepointType {
2593 	NVG_SPACE,
2594 	NVG_NEWLINE,
2595 	NVG_CHAR,
2596 	NVG_CJK_CHAR,
2597 };
2598 
nvgTextBreakLines(NVGcontext * ctx,const char * string,const char * end,float breakRowWidth,NVGtextRow * rows,int maxRows)2599 int nvgTextBreakLines(NVGcontext* ctx, const char* string, const char* end, float breakRowWidth, NVGtextRow* rows, int maxRows)
2600 {
2601 	NVGstate* state = nvg__getState(ctx);
2602 	float scale = nvg__getFontScale(state) * ctx->devicePxRatio;
2603 	float invscale = 1.0f / scale;
2604 	FONStextIter iter, prevIter;
2605 	FONSquad q;
2606 	int nrows = 0;
2607 	float rowStartX = 0;
2608 	float rowWidth = 0;
2609 	float rowMinX = 0;
2610 	float rowMaxX = 0;
2611 	const char* rowStart = NULL;
2612 	const char* rowEnd = NULL;
2613 	const char* wordStart = NULL;
2614 	float wordStartX = 0;
2615 	float wordMinX = 0;
2616 	const char* breakEnd = NULL;
2617 	float breakWidth = 0;
2618 	float breakMaxX = 0;
2619 	int type = NVG_SPACE, ptype = NVG_SPACE;
2620 	unsigned int pcodepoint = 0;
2621 
2622 	if (maxRows == 0) return 0;
2623 	if (state->fontId == FONS_INVALID) return 0;
2624 
2625 	if (end == NULL)
2626 		end = string + strlen(string);
2627 
2628 	if (string == end) return 0;
2629 
2630 	fonsSetSize(ctx->fs, state->fontSize*scale);
2631 	fonsSetSpacing(ctx->fs, state->letterSpacing*scale);
2632 	fonsSetBlur(ctx->fs, state->fontBlur*scale);
2633 	fonsSetAlign(ctx->fs, state->textAlign);
2634 	fonsSetFont(ctx->fs, state->fontId);
2635 
2636 	breakRowWidth *= scale;
2637 
2638 	fonsTextIterInit(ctx->fs, &iter, 0, 0, string, end, FONS_GLYPH_BITMAP_OPTIONAL);
2639 	prevIter = iter;
2640 	while (fonsTextIterNext(ctx->fs, &iter, &q)) {
2641 		if (iter.prevGlyphIndex < 0 && nvg__allocTextAtlas(ctx)) { // can not retrieve glyph?
2642 			iter = prevIter;
2643 			fonsTextIterNext(ctx->fs, &iter, &q); // try again
2644 		}
2645 		prevIter = iter;
2646 		switch (iter.codepoint) {
2647 			case 9:			// \t
2648 			case 11:		// \v
2649 			case 12:		// \f
2650 			case 32:		// space
2651 			case 0x00a0:	// NBSP
2652 				type = NVG_SPACE;
2653 				break;
2654 			case 10:		// \n
2655 				type = pcodepoint == 13 ? NVG_SPACE : NVG_NEWLINE;
2656 				break;
2657 			case 13:		// \r
2658 				type = pcodepoint == 10 ? NVG_SPACE : NVG_NEWLINE;
2659 				break;
2660 			case 0x0085:	// NEL
2661 				type = NVG_NEWLINE;
2662 				break;
2663 			default:
2664 				if ((iter.codepoint >= 0x4E00 && iter.codepoint <= 0x9FFF) ||
2665 					(iter.codepoint >= 0x3000 && iter.codepoint <= 0x30FF) ||
2666 					(iter.codepoint >= 0xFF00 && iter.codepoint <= 0xFFEF) ||
2667 					(iter.codepoint >= 0x1100 && iter.codepoint <= 0x11FF) ||
2668 					(iter.codepoint >= 0x3130 && iter.codepoint <= 0x318F) ||
2669 					(iter.codepoint >= 0xAC00 && iter.codepoint <= 0xD7AF))
2670 					type = NVG_CJK_CHAR;
2671 				else
2672 					type = NVG_CHAR;
2673 				break;
2674 		}
2675 
2676 		if (type == NVG_NEWLINE) {
2677 			// Always handle new lines.
2678 			rows[nrows].start = rowStart != NULL ? rowStart : iter.str;
2679 			rows[nrows].end = rowEnd != NULL ? rowEnd : iter.str;
2680 			rows[nrows].width = rowWidth * invscale;
2681 			rows[nrows].minx = rowMinX * invscale;
2682 			rows[nrows].maxx = rowMaxX * invscale;
2683 			rows[nrows].next = iter.next;
2684 			nrows++;
2685 			if (nrows >= maxRows)
2686 				return nrows;
2687 			// Set null break point
2688 			breakEnd = rowStart;
2689 			breakWidth = 0.0;
2690 			breakMaxX = 0.0;
2691 			// Indicate to skip the white space at the beginning of the row.
2692 			rowStart = NULL;
2693 			rowEnd = NULL;
2694 			rowWidth = 0;
2695 			rowMinX = rowMaxX = 0;
2696 		} else {
2697 			if (rowStart == NULL) {
2698 				// Skip white space until the beginning of the line
2699 				if (type == NVG_CHAR || type == NVG_CJK_CHAR) {
2700 					// The current char is the row so far
2701 					rowStartX = iter.x;
2702 					rowStart = iter.str;
2703 					rowEnd = iter.next;
2704 					rowWidth = iter.nextx - rowStartX; // q.x1 - rowStartX;
2705 					rowMinX = q.x0 - rowStartX;
2706 					rowMaxX = q.x1 - rowStartX;
2707 					wordStart = iter.str;
2708 					wordStartX = iter.x;
2709 					wordMinX = q.x0 - rowStartX;
2710 					// Set null break point
2711 					breakEnd = rowStart;
2712 					breakWidth = 0.0;
2713 					breakMaxX = 0.0;
2714 				}
2715 			} else {
2716 				float nextWidth = iter.nextx - rowStartX;
2717 
2718 				// track last non-white space character
2719 				if (type == NVG_CHAR || type == NVG_CJK_CHAR) {
2720 					rowEnd = iter.next;
2721 					rowWidth = iter.nextx - rowStartX;
2722 					rowMaxX = q.x1 - rowStartX;
2723 				}
2724 				// track last end of a word
2725 				if (((ptype == NVG_CHAR || ptype == NVG_CJK_CHAR) && type == NVG_SPACE) || type == NVG_CJK_CHAR) {
2726 					breakEnd = iter.str;
2727 					breakWidth = rowWidth;
2728 					breakMaxX = rowMaxX;
2729 				}
2730 				// track last beginning of a word
2731 				if ((ptype == NVG_SPACE && (type == NVG_CHAR || type == NVG_CJK_CHAR)) || type == NVG_CJK_CHAR) {
2732 					wordStart = iter.str;
2733 					wordStartX = iter.x;
2734 					wordMinX = q.x0 - rowStartX;
2735 				}
2736 
2737 				// Break to new line when a character is beyond break width.
2738 				if ((type == NVG_CHAR || type == NVG_CJK_CHAR) && nextWidth > breakRowWidth) {
2739 					// The run length is too long, need to break to new line.
2740 					if (breakEnd == rowStart) {
2741 						// The current word is longer than the row length, just break it from here.
2742 						rows[nrows].start = rowStart;
2743 						rows[nrows].end = iter.str;
2744 						rows[nrows].width = rowWidth * invscale;
2745 						rows[nrows].minx = rowMinX * invscale;
2746 						rows[nrows].maxx = rowMaxX * invscale;
2747 						rows[nrows].next = iter.str;
2748 						nrows++;
2749 						if (nrows >= maxRows)
2750 							return nrows;
2751 						rowStartX = iter.x;
2752 						rowStart = iter.str;
2753 						rowEnd = iter.next;
2754 						rowWidth = iter.nextx - rowStartX;
2755 						rowMinX = q.x0 - rowStartX;
2756 						rowMaxX = q.x1 - rowStartX;
2757 						wordStart = iter.str;
2758 						wordStartX = iter.x;
2759 						wordMinX = q.x0 - rowStartX;
2760 					} else {
2761 						// Break the line from the end of the last word, and start new line from the beginning of the new.
2762 						rows[nrows].start = rowStart;
2763 						rows[nrows].end = breakEnd;
2764 						rows[nrows].width = breakWidth * invscale;
2765 						rows[nrows].minx = rowMinX * invscale;
2766 						rows[nrows].maxx = breakMaxX * invscale;
2767 						rows[nrows].next = wordStart;
2768 						nrows++;
2769 						if (nrows >= maxRows)
2770 							return nrows;
2771 						rowStartX = wordStartX;
2772 						rowStart = wordStart;
2773 						rowEnd = iter.next;
2774 						rowWidth = iter.nextx - rowStartX;
2775 						rowMinX = wordMinX;
2776 						rowMaxX = q.x1 - rowStartX;
2777 						// No change to the word start
2778 					}
2779 					// Set null break point
2780 					breakEnd = rowStart;
2781 					breakWidth = 0.0;
2782 					breakMaxX = 0.0;
2783 				}
2784 			}
2785 		}
2786 
2787 		pcodepoint = iter.codepoint;
2788 		ptype = type;
2789 	}
2790 
2791 	// Break the line from the end of the last word, and start new line from the beginning of the new.
2792 	if (rowStart != NULL) {
2793 		rows[nrows].start = rowStart;
2794 		rows[nrows].end = rowEnd;
2795 		rows[nrows].width = rowWidth * invscale;
2796 		rows[nrows].minx = rowMinX * invscale;
2797 		rows[nrows].maxx = rowMaxX * invscale;
2798 		rows[nrows].next = end;
2799 		nrows++;
2800 	}
2801 
2802 	return nrows;
2803 }
2804 
nvgTextBounds(NVGcontext * ctx,float x,float y,const char * string,const char * end,float * bounds)2805 float nvgTextBounds(NVGcontext* ctx, float x, float y, const char* string, const char* end, float* bounds)
2806 {
2807 	NVGstate* state = nvg__getState(ctx);
2808 	float scale = nvg__getFontScale(state) * ctx->devicePxRatio;
2809 	float invscale = 1.0f / scale;
2810 	float width;
2811 
2812 	if (state->fontId == FONS_INVALID) return 0;
2813 
2814 	fonsSetSize(ctx->fs, state->fontSize*scale);
2815 	fonsSetSpacing(ctx->fs, state->letterSpacing*scale);
2816 	fonsSetBlur(ctx->fs, state->fontBlur*scale);
2817 	fonsSetAlign(ctx->fs, state->textAlign);
2818 	fonsSetFont(ctx->fs, state->fontId);
2819 
2820 	width = fonsTextBounds(ctx->fs, x*scale, y*scale, string, end, bounds);
2821 	if (bounds != NULL) {
2822 		// Use line bounds for height.
2823 		fonsLineBounds(ctx->fs, y*scale, &bounds[1], &bounds[3]);
2824 		bounds[0] *= invscale;
2825 		bounds[1] *= invscale;
2826 		bounds[2] *= invscale;
2827 		bounds[3] *= invscale;
2828 	}
2829 	return width * invscale;
2830 }
2831 
nvgTextBoxBounds(NVGcontext * ctx,float x,float y,float breakRowWidth,const char * string,const char * end,float * bounds)2832 void nvgTextBoxBounds(NVGcontext* ctx, float x, float y, float breakRowWidth, const char* string, const char* end, float* bounds)
2833 {
2834 	NVGstate* state = nvg__getState(ctx);
2835 	NVGtextRow rows[2];
2836 	float scale = nvg__getFontScale(state) * ctx->devicePxRatio;
2837 	float invscale = 1.0f / scale;
2838 	int nrows = 0, i;
2839 	int oldAlign = state->textAlign;
2840 	int haling = state->textAlign & (NVG_ALIGN_LEFT | NVG_ALIGN_CENTER | NVG_ALIGN_RIGHT);
2841 	int valign = state->textAlign & (NVG_ALIGN_TOP | NVG_ALIGN_MIDDLE | NVG_ALIGN_BOTTOM | NVG_ALIGN_BASELINE);
2842 	float lineh = 0, rminy = 0, rmaxy = 0;
2843 	float minx, miny, maxx, maxy;
2844 
2845 	if (state->fontId == FONS_INVALID) {
2846 		if (bounds != NULL)
2847 			bounds[0] = bounds[1] = bounds[2] = bounds[3] = 0.0f;
2848 		return;
2849 	}
2850 
2851 	nvgTextMetrics(ctx, NULL, NULL, &lineh);
2852 
2853 	state->textAlign = NVG_ALIGN_LEFT | valign;
2854 
2855 	minx = maxx = x;
2856 	miny = maxy = y;
2857 
2858 	fonsSetSize(ctx->fs, state->fontSize*scale);
2859 	fonsSetSpacing(ctx->fs, state->letterSpacing*scale);
2860 	fonsSetBlur(ctx->fs, state->fontBlur*scale);
2861 	fonsSetAlign(ctx->fs, state->textAlign);
2862 	fonsSetFont(ctx->fs, state->fontId);
2863 	fonsLineBounds(ctx->fs, 0, &rminy, &rmaxy);
2864 	rminy *= invscale;
2865 	rmaxy *= invscale;
2866 
2867 	while ((nrows = nvgTextBreakLines(ctx, string, end, breakRowWidth, rows, 2))) {
2868 		for (i = 0; i < nrows; i++) {
2869 			NVGtextRow* row = &rows[i];
2870 			float rminx, rmaxx, dx = 0;
2871 			// Horizontal bounds
2872 			if (haling & NVG_ALIGN_LEFT)
2873 				dx = 0;
2874 			else if (haling & NVG_ALIGN_CENTER)
2875 				dx = breakRowWidth*0.5f - row->width*0.5f;
2876 			else if (haling & NVG_ALIGN_RIGHT)
2877 				dx = breakRowWidth - row->width;
2878 			rminx = x + row->minx + dx;
2879 			rmaxx = x + row->maxx + dx;
2880 			minx = nvg__minf(minx, rminx);
2881 			maxx = nvg__maxf(maxx, rmaxx);
2882 			// Vertical bounds.
2883 			miny = nvg__minf(miny, y + rminy);
2884 			maxy = nvg__maxf(maxy, y + rmaxy);
2885 
2886 			y += lineh * state->lineHeight;
2887 		}
2888 		string = rows[nrows-1].next;
2889 	}
2890 
2891 	state->textAlign = oldAlign;
2892 
2893 	if (bounds != NULL) {
2894 		bounds[0] = minx;
2895 		bounds[1] = miny;
2896 		bounds[2] = maxx;
2897 		bounds[3] = maxy;
2898 	}
2899 }
2900 
nvgTextMetrics(NVGcontext * ctx,float * ascender,float * descender,float * lineh)2901 void nvgTextMetrics(NVGcontext* ctx, float* ascender, float* descender, float* lineh)
2902 {
2903 	NVGstate* state = nvg__getState(ctx);
2904 	float scale = nvg__getFontScale(state) * ctx->devicePxRatio;
2905 	float invscale = 1.0f / scale;
2906 
2907 	if (state->fontId == FONS_INVALID) return;
2908 
2909 	fonsSetSize(ctx->fs, state->fontSize*scale);
2910 	fonsSetSpacing(ctx->fs, state->letterSpacing*scale);
2911 	fonsSetBlur(ctx->fs, state->fontBlur*scale);
2912 	fonsSetAlign(ctx->fs, state->textAlign);
2913 	fonsSetFont(ctx->fs, state->fontId);
2914 
2915 	fonsVertMetrics(ctx->fs, ascender, descender, lineh);
2916 	if (ascender != NULL)
2917 		*ascender *= invscale;
2918 	if (descender != NULL)
2919 		*descender *= invscale;
2920 	if (lineh != NULL)
2921 		*lineh *= invscale;
2922 }
2923 // vim: ft=c nu noet ts=4
2924