You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2908 lines
75KB

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