Updated NanoSVG to latest version (22 April 2019)
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / third-party / nanosvg / nanosvg.cc
1 /*
2  * Copyright (c) 2013-14 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  *
8  * Permission is granted to anyone to use this software for any purpose,
9  * including commercial applications, and to alter it and redistribute it
10  * freely, subject to the following restrictions:
11  *
12  * 1. The origin of this software must not be misrepresented; you must not
13  * claim that you wrote the original software. If you use this software
14  * in a product, an acknowledgment in the product documentation would be
15  * appreciated but is not required.
16  * 2. Altered source versions must be plainly marked as such, and must not be
17  * misrepresented as being the original software.
18  * 3. This notice may not be removed or altered from any source distribution.
19  *
20  * The SVG parser is based on Anti-Grain Geometry 2.4 SVG example
21  * Copyright (C) 2002-2004 Maxim Shemanarev (McSeem) (http://www.antigrain.com/)
22  *
23  * Arc calculation code based on canvg (https://code.google.com/p/canvg/)
24  *
25  * Bounding box calculation based on http://blog.hackers-cafe.net/2009/06/how-to-calculate-bezier-curves-bounding.html
26  *
27  */
28
29 #include "nanosvg.h"
30
31 /**
32  * In the original software, The nanosvg implementation was included in the header file.
33  * We have separated the implementation to source file here.
34  */
35
36 #include <stdio.h>
37 #include <string.h>
38 #include <stdlib.h>
39 #include <math.h>
40
41 #define NSVG_PI (3.14159265358979323846264338327f)
42 #define NSVG_KAPPA90 (0.5522847493f)    // Length proportional to radius of a cubic bezier handle for 90deg arcs.
43
44 #define NSVG_ALIGN_MIN 0
45 #define NSVG_ALIGN_MID 1
46 #define NSVG_ALIGN_MAX 2
47 #define NSVG_ALIGN_NONE 0
48 #define NSVG_ALIGN_MEET 1
49 #define NSVG_ALIGN_SLICE 2
50
51 #define NSVG_NOTUSED(v) do { (void)(1 ? (void)0 : ( (void)(v) ) ); } while(0)
52 #define NSVG_RGB(r, g, b) (((unsigned int)r) | ((unsigned int)g << 8) | ((unsigned int)b << 16))
53
54 #ifdef _MSC_VER
55         #pragma warning (disable: 4996) // Switch off security warnings
56         #pragma warning (disable: 4100) // Switch off unreferenced formal parameter warnings
57         #ifdef __cplusplus
58         #define NSVG_INLINE inline
59         #else
60         #define NSVG_INLINE
61         #endif
62 #else
63         #define NSVG_INLINE inline
64 #endif
65
66
67 static int nsvg__isspace(char c)
68 {
69         return strchr(" \t\n\v\f\r", c) != 0;
70 }
71
72 static int nsvg__isdigit(char c)
73 {
74         return c >= '0' && c <= '9';
75 }
76
77 static int nsvg__isnum(char c)
78 {
79         return strchr("0123456789+-.eE", c) != 0;
80 }
81
82 static NSVG_INLINE float nsvg__minf(float a, float b) { return a < b ? a : b; }
83 static NSVG_INLINE float nsvg__maxf(float a, float b) { return a > b ? a : b; }
84
85
86 // Simple XML parser
87
88 #define NSVG_XML_TAG 1
89 #define NSVG_XML_CONTENT 2
90 #define NSVG_XML_MAX_ATTRIBS 256
91
92 static void nsvg__parseContent(char* s,
93                                                            void (*contentCb)(void* ud, const char* s),
94                                                            void* ud)
95 {
96         // Trim start white spaces
97         while (*s && nsvg__isspace(*s)) s++;
98         if (!*s) return;
99
100         if (contentCb)
101                 (*contentCb)(ud, s);
102 }
103
104 static void nsvg__parseElement(char* s,
105                                                            void (*startelCb)(void* ud, const char* el, const char** attr),
106                                                            void (*endelCb)(void* ud, const char* el),
107                                                            void* ud)
108 {
109         const char* attr[NSVG_XML_MAX_ATTRIBS];
110         int nattr = 0;
111         char* name;
112         int start = 0;
113         int end = 0;
114         char quote;
115
116         // Skip white space after the '<'
117         while (*s && nsvg__isspace(*s)) s++;
118
119         // Check if the tag is end tag
120         if (*s == '/') {
121                 s++;
122                 end = 1;
123         } else {
124                 start = 1;
125         }
126
127         // Skip comments, data and preprocessor stuff.
128         if (!*s || *s == '?' || *s == '!')
129                 return;
130
131         // Get tag name
132         name = s;
133         while (*s && !nsvg__isspace(*s)) s++;
134         if (*s) { *s++ = '\0'; }
135
136         // Get attribs
137         while (!end && *s && nattr < NSVG_XML_MAX_ATTRIBS-3) {
138                 char* name = NULL;
139                 char* value = NULL;
140
141                 // Skip white space before the attrib name
142                 while (*s && nsvg__isspace(*s)) s++;
143                 if (!*s) break;
144                 if (*s == '/') {
145                         end = 1;
146                         break;
147                 }
148                 name = s;
149                 // Find end of the attrib name.
150                 while (*s && !nsvg__isspace(*s) && *s != '=') s++;
151                 if (*s) { *s++ = '\0'; }
152                 // Skip until the beginning of the value.
153                 while (*s && *s != '\"' && *s != '\'') s++;
154                 if (!*s) break;
155                 quote = *s;
156                 s++;
157                 // Store value and find the end of it.
158                 value = s;
159                 while (*s && *s != quote) s++;
160                 if (*s) { *s++ = '\0'; }
161
162                 // Store only well formed attributes
163                 if (name && value) {
164                         attr[nattr++] = name;
165                         attr[nattr++] = value;
166                 }
167         }
168
169         // List terminator
170         attr[nattr++] = 0;
171         attr[nattr++] = 0;
172
173         // Call callbacks.
174         if (start && startelCb)
175                 (*startelCb)(ud, name, attr);
176         if (end && endelCb)
177                 (*endelCb)(ud, name);
178 }
179
180 int nsvg__parseXML(char* input,
181                                    void (*startelCb)(void* ud, const char* el, const char** attr),
182                                    void (*endelCb)(void* ud, const char* el),
183                                    void (*contentCb)(void* ud, const char* s),
184                                    void* ud)
185 {
186         char* s = input;
187         char* mark = s;
188         int state = NSVG_XML_CONTENT;
189         while (*s) {
190                 if (*s == '<' && state == NSVG_XML_CONTENT) {
191                         // Start of a tag
192                         *s++ = '\0';
193                         nsvg__parseContent(mark, contentCb, ud);
194                         mark = s;
195                         state = NSVG_XML_TAG;
196                 } else if (*s == '>' && state == NSVG_XML_TAG) {
197                         // Start of a content or new tag.
198                         *s++ = '\0';
199                         nsvg__parseElement(mark, startelCb, endelCb, ud);
200                         mark = s;
201                         state = NSVG_XML_CONTENT;
202                 } else {
203                         s++;
204                 }
205         }
206
207         return 1;
208 }
209
210
211 /* Simple SVG parser. */
212
213 #define NSVG_MAX_ATTR 128
214
215 enum NSVGgradientUnits {
216         NSVG_USER_SPACE = 0,
217         NSVG_OBJECT_SPACE = 1
218 };
219
220 #define NSVG_MAX_DASHES 8
221
222 enum NSVGunits {
223         NSVG_UNITS_USER,
224         NSVG_UNITS_PX,
225         NSVG_UNITS_PT,
226         NSVG_UNITS_PC,
227         NSVG_UNITS_MM,
228         NSVG_UNITS_CM,
229         NSVG_UNITS_IN,
230         NSVG_UNITS_PERCENT,
231         NSVG_UNITS_EM,
232         NSVG_UNITS_EX
233 };
234
235 typedef struct NSVGcoordinate {
236         float value;
237         int units;
238 } NSVGcoordinate;
239
240 typedef struct NSVGlinearData {
241         NSVGcoordinate x1, y1, x2, y2;
242 } NSVGlinearData;
243
244 typedef struct NSVGradialData {
245         NSVGcoordinate cx, cy, r, fx, fy;
246 } NSVGradialData;
247
248 typedef struct NSVGgradientData
249 {
250         char id[64];
251         char ref[64];
252   /**
253    * In the original file, using char type (without signed or unsigned) can be interpreted
254    * as 'unsigned char' in some build environments, like ARM architecture.
255    * To prevent the unexpected behavior, we replace 'char type' with 'signed char type' here.
256    */
257     signed char type;
258         union {
259                 NSVGlinearData linear;
260                 NSVGradialData radial;
261         };
262         char spread;
263         /**
264          * In the original file, using char type (without signed or unsigned) can be interpreted
265          * as 'unsigned char' in some build environments, like ARM architecture.
266          * To prevent the unexpected behavior, we replace 'char units' with 'signed char units' here.
267          */
268     signed char units;
269         float xform[6];
270         int nstops;
271         NSVGgradientStop* stops;
272         struct NSVGgradientData* next;
273 } NSVGgradientData;
274
275 typedef struct NSVGattrib
276 {
277         char id[64];
278         float xform[6];
279         unsigned int fillColor;
280         unsigned int strokeColor;
281         float opacity;
282         float fillOpacity;
283         float strokeOpacity;
284         char fillGradient[64];
285         char strokeGradient[64];
286         float strokeWidth;
287         float strokeDashOffset;
288         float strokeDashArray[NSVG_MAX_DASHES];
289         int strokeDashCount;
290         char strokeLineJoin;
291         char strokeLineCap;
292         float miterLimit;
293         char fillRule;
294         float fontSize;
295         unsigned int stopColor;
296         float stopOpacity;
297         float stopOffset;
298         char hasFill;
299         char hasStroke;
300         char visible;
301 } NSVGattrib;
302
303 typedef struct NSVGparser
304 {
305         NSVGattrib attr[NSVG_MAX_ATTR];
306         int attrHead;
307         float* pts;
308         int npts;
309         int cpts;
310         NSVGpath* plist;
311         NSVGimage* image;
312         NSVGgradientData* gradients;
313         NSVGshape* shapesTail;
314         float viewMinx, viewMiny, viewWidth, viewHeight;
315         int alignX, alignY, alignType;
316         float dpi;
317         char pathFlag;
318         char defsFlag;
319 } NSVGparser;
320
321 static void nsvg__xformIdentity(float* t)
322 {
323         t[0] = 1.0f; t[1] = 0.0f;
324         t[2] = 0.0f; t[3] = 1.0f;
325         t[4] = 0.0f; t[5] = 0.0f;
326 }
327
328 static void nsvg__xformSetTranslation(float* t, float tx, float ty)
329 {
330         t[0] = 1.0f; t[1] = 0.0f;
331         t[2] = 0.0f; t[3] = 1.0f;
332         t[4] = tx; t[5] = ty;
333 }
334
335 static void nsvg__xformSetScale(float* t, float sx, float sy)
336 {
337         t[0] = sx; t[1] = 0.0f;
338         t[2] = 0.0f; t[3] = sy;
339         t[4] = 0.0f; t[5] = 0.0f;
340 }
341
342 static void nsvg__xformSetSkewX(float* t, float a)
343 {
344         t[0] = 1.0f; t[1] = 0.0f;
345         t[2] = tanf(a); t[3] = 1.0f;
346         t[4] = 0.0f; t[5] = 0.0f;
347 }
348
349 static void nsvg__xformSetSkewY(float* t, float a)
350 {
351         t[0] = 1.0f; t[1] = tanf(a);
352         t[2] = 0.0f; t[3] = 1.0f;
353         t[4] = 0.0f; t[5] = 0.0f;
354 }
355
356 static void nsvg__xformSetRotation(float* t, float a)
357 {
358         float cs = cosf(a), sn = sinf(a);
359         t[0] = cs; t[1] = sn;
360         t[2] = -sn; t[3] = cs;
361         t[4] = 0.0f; t[5] = 0.0f;
362 }
363
364 static void nsvg__xformMultiply(float* t, float* s)
365 {
366         float t0 = t[0] * s[0] + t[1] * s[2];
367         float t2 = t[2] * s[0] + t[3] * s[2];
368         float t4 = t[4] * s[0] + t[5] * s[2] + s[4];
369         t[1] = t[0] * s[1] + t[1] * s[3];
370         t[3] = t[2] * s[1] + t[3] * s[3];
371         t[5] = t[4] * s[1] + t[5] * s[3] + s[5];
372         t[0] = t0;
373         t[2] = t2;
374         t[4] = t4;
375 }
376
377 static void nsvg__xformInverse(float* inv, float* t)
378 {
379         double invdet, det = (double)t[0] * t[3] - (double)t[2] * t[1];
380         if (det > -1e-6 && det < 1e-6) {
381                 nsvg__xformIdentity(t);
382                 return;
383         }
384         invdet = 1.0 / det;
385         inv[0] = (float)(t[3] * invdet);
386         inv[2] = (float)(-t[2] * invdet);
387         inv[4] = (float)(((double)t[2] * t[5] - (double)t[3] * t[4]) * invdet);
388         inv[1] = (float)(-t[1] * invdet);
389         inv[3] = (float)(t[0] * invdet);
390         inv[5] = (float)(((double)t[1] * t[4] - (double)t[0] * t[5]) * invdet);
391 }
392
393 static void nsvg__xformPremultiply(float* t, float* s)
394 {
395         float s2[6];
396         memcpy(s2, s, sizeof(float)*6);
397         nsvg__xformMultiply(s2, t);
398         memcpy(t, s2, sizeof(float)*6);
399 }
400
401 static void nsvg__xformPoint(float* dx, float* dy, float x, float y, float* t)
402 {
403         *dx = x*t[0] + y*t[2] + t[4];
404         *dy = x*t[1] + y*t[3] + t[5];
405 }
406
407 static void nsvg__xformVec(float* dx, float* dy, float x, float y, float* t)
408 {
409         *dx = x*t[0] + y*t[2];
410         *dy = x*t[1] + y*t[3];
411 }
412
413 #define NSVG_EPSILON (1e-12)
414
415 static int nsvg__ptInBounds(float* pt, float* bounds)
416 {
417         return pt[0] >= bounds[0] && pt[0] <= bounds[2] && pt[1] >= bounds[1] && pt[1] <= bounds[3];
418 }
419
420
421 static double nsvg__evalBezier(double t, double p0, double p1, double p2, double p3)
422 {
423         double it = 1.0-t;
424         return it*it*it*p0 + 3.0*it*it*t*p1 + 3.0*it*t*t*p2 + t*t*t*p3;
425 }
426
427 static void nsvg__curveBounds(float* bounds, float* curve)
428 {
429         int i, j, count;
430         double roots[2], a, b, c, b2ac, t, v;
431         float* v0 = &curve[0];
432         float* v1 = &curve[2];
433         float* v2 = &curve[4];
434         float* v3 = &curve[6];
435
436         // Start the bounding box by end points
437         bounds[0] = nsvg__minf(v0[0], v3[0]);
438         bounds[1] = nsvg__minf(v0[1], v3[1]);
439         bounds[2] = nsvg__maxf(v0[0], v3[0]);
440         bounds[3] = nsvg__maxf(v0[1], v3[1]);
441
442         // Bezier curve fits inside the convex hull of it's control points.
443         // If control points are inside the bounds, we're done.
444         if (nsvg__ptInBounds(v1, bounds) && nsvg__ptInBounds(v2, bounds))
445                 return;
446
447         // Add bezier curve inflection points in X and Y.
448         for (i = 0; i < 2; i++) {
449                 a = -3.0 * v0[i] + 9.0 * v1[i] - 9.0 * v2[i] + 3.0 * v3[i];
450                 b = 6.0 * v0[i] - 12.0 * v1[i] + 6.0 * v2[i];
451                 c = 3.0 * v1[i] - 3.0 * v0[i];
452                 count = 0;
453                 if (fabs(a) < NSVG_EPSILON) {
454                         if (fabs(b) > NSVG_EPSILON) {
455                                 t = -c / b;
456                                 if (t > NSVG_EPSILON && t < 1.0-NSVG_EPSILON)
457                                         roots[count++] = t;
458                         }
459                 } else {
460                         b2ac = b*b - 4.0*c*a;
461                         if (b2ac > NSVG_EPSILON) {
462                                 t = (-b + sqrt(b2ac)) / (2.0 * a);
463                                 if (t > NSVG_EPSILON && t < 1.0-NSVG_EPSILON)
464                                         roots[count++] = t;
465                                 t = (-b - sqrt(b2ac)) / (2.0 * a);
466                                 if (t > NSVG_EPSILON && t < 1.0-NSVG_EPSILON)
467                                         roots[count++] = t;
468                         }
469                 }
470                 for (j = 0; j < count; j++) {
471                         v = nsvg__evalBezier(roots[j], v0[i], v1[i], v2[i], v3[i]);
472                         bounds[0+i] = nsvg__minf(bounds[0+i], (float)v);
473                         bounds[2+i] = nsvg__maxf(bounds[2+i], (float)v);
474                 }
475         }
476 }
477
478 static NSVGparser* nsvg__createParser()
479 {
480         NSVGparser* p;
481         p = (NSVGparser*)malloc(sizeof(NSVGparser));
482         if (p == NULL) goto error;
483         memset(p, 0, sizeof(NSVGparser));
484
485         p->image = (NSVGimage*)malloc(sizeof(NSVGimage));
486         if (p->image == NULL) goto error;
487         memset(p->image, 0, sizeof(NSVGimage));
488
489         // Init style
490         nsvg__xformIdentity(p->attr[0].xform);
491         memset(p->attr[0].id, 0, sizeof p->attr[0].id);
492         p->attr[0].fillColor = NSVG_RGB(0,0,0);
493         p->attr[0].strokeColor = NSVG_RGB(0,0,0);
494         p->attr[0].opacity = 1;
495         p->attr[0].fillOpacity = 1;
496         p->attr[0].strokeOpacity = 1;
497         p->attr[0].stopOpacity = 1;
498         p->attr[0].strokeWidth = 1;
499         p->attr[0].strokeLineJoin = NSVG_JOIN_MITER;
500         p->attr[0].strokeLineCap = NSVG_CAP_BUTT;
501         p->attr[0].miterLimit = 4;
502         p->attr[0].fillRule = NSVG_FILLRULE_NONZERO;
503         p->attr[0].hasFill = 1;
504         p->attr[0].visible = 1;
505
506         return p;
507
508 error:
509         if (p) {
510                 if (p->image) free(p->image);
511                 free(p);
512         }
513         return NULL;
514 }
515
516 static void nsvg__deletePaths(NSVGpath* path)
517 {
518         while (path) {
519                 NSVGpath *next = path->next;
520                 if (path->pts != NULL)
521                         free(path->pts);
522                 free(path);
523                 path = next;
524         }
525 }
526
527 static void nsvg__deletePaint(NSVGpaint* paint)
528 {
529         if (paint->type == NSVG_PAINT_LINEAR_GRADIENT || paint->type == NSVG_PAINT_RADIAL_GRADIENT)
530                 free(paint->gradient);
531 }
532
533 static void nsvg__deleteGradientData(NSVGgradientData* grad)
534 {
535         NSVGgradientData* next;
536         while (grad != NULL) {
537                 next = grad->next;
538                 free(grad->stops);
539                 free(grad);
540                 grad = next;
541         }
542 }
543
544 static void nsvg__deleteParser(NSVGparser* p)
545 {
546         if (p != NULL) {
547                 nsvg__deletePaths(p->plist);
548                 nsvg__deleteGradientData(p->gradients);
549                 nsvgDelete(p->image);
550                 free(p->pts);
551                 free(p);
552         }
553 }
554
555 static void nsvg__resetPath(NSVGparser* p)
556 {
557         p->npts = 0;
558 }
559
560 static void nsvg__addPoint(NSVGparser* p, float x, float y)
561 {
562         if (p->npts+1 > p->cpts) {
563                 p->cpts = p->cpts ? p->cpts*2 : 8;
564                 p->pts = (float*)realloc(p->pts, p->cpts*2*sizeof(float));
565                 if (!p->pts) return;
566         }
567         p->pts[p->npts*2+0] = x;
568         p->pts[p->npts*2+1] = y;
569         p->npts++;
570 }
571
572 static void nsvg__moveTo(NSVGparser* p, float x, float y)
573 {
574         if (p->npts > 0) {
575                 p->pts[(p->npts-1)*2+0] = x;
576                 p->pts[(p->npts-1)*2+1] = y;
577         } else {
578                 nsvg__addPoint(p, x, y);
579         }
580 }
581
582 static void nsvg__lineTo(NSVGparser* p, float x, float y)
583 {
584         float px,py, dx,dy;
585         if (p->npts > 0) {
586                 px = p->pts[(p->npts-1)*2+0];
587                 py = p->pts[(p->npts-1)*2+1];
588                 dx = x - px;
589                 dy = y - py;
590                 nsvg__addPoint(p, px + dx/3.0f, py + dy/3.0f);
591                 nsvg__addPoint(p, x - dx/3.0f, y - dy/3.0f);
592                 nsvg__addPoint(p, x, y);
593         }
594 }
595
596 static void nsvg__cubicBezTo(NSVGparser* p, float cpx1, float cpy1, float cpx2, float cpy2, float x, float y)
597 {
598         nsvg__addPoint(p, cpx1, cpy1);
599         nsvg__addPoint(p, cpx2, cpy2);
600         nsvg__addPoint(p, x, y);
601 }
602
603 static NSVGattrib* nsvg__getAttr(NSVGparser* p)
604 {
605         return &p->attr[p->attrHead];
606 }
607
608 static void nsvg__pushAttr(NSVGparser* p)
609 {
610         if (p->attrHead < NSVG_MAX_ATTR-1) {
611                 p->attrHead++;
612                 memcpy(&p->attr[p->attrHead], &p->attr[p->attrHead-1], sizeof(NSVGattrib));
613         }
614 }
615
616 static void nsvg__popAttr(NSVGparser* p)
617 {
618         if (p->attrHead > 0)
619                 p->attrHead--;
620 }
621
622 static float nsvg__actualOrigX(NSVGparser* p)
623 {
624         return p->viewMinx;
625 }
626
627 static float nsvg__actualOrigY(NSVGparser* p)
628 {
629         return p->viewMiny;
630 }
631
632 static float nsvg__actualWidth(NSVGparser* p)
633 {
634         return p->viewWidth;
635 }
636
637 static float nsvg__actualHeight(NSVGparser* p)
638 {
639         return p->viewHeight;
640 }
641
642 static float nsvg__actualLength(NSVGparser* p)
643 {
644         float w = nsvg__actualWidth(p), h = nsvg__actualHeight(p);
645         return sqrtf(w*w + h*h) / sqrtf(2.0f);
646 }
647
648 static float nsvg__convertToPixels(NSVGparser* p, NSVGcoordinate c, float orig, float length)
649 {
650         NSVGattrib* attr = nsvg__getAttr(p);
651         switch (c.units) {
652                 case NSVG_UNITS_USER:           return c.value;
653                 case NSVG_UNITS_PX:                     return c.value;
654                 case NSVG_UNITS_PT:                     return c.value / 72.0f * p->dpi;
655                 case NSVG_UNITS_PC:                     return c.value / 6.0f * p->dpi;
656                 case NSVG_UNITS_MM:                     return c.value / 25.4f * p->dpi;
657                 case NSVG_UNITS_CM:                     return c.value / 2.54f * p->dpi;
658                 case NSVG_UNITS_IN:                     return c.value * p->dpi;
659                 case NSVG_UNITS_EM:                     return c.value * attr->fontSize;
660                 case NSVG_UNITS_EX:                     return c.value * attr->fontSize * 0.52f; // x-height of Helvetica.
661                 case NSVG_UNITS_PERCENT:        return orig + c.value / 100.0f * length;
662                 default:                                        return c.value;
663         }
664         return c.value;
665 }
666
667 static NSVGgradientData* nsvg__findGradientData(NSVGparser* p, const char* id)
668 {
669         NSVGgradientData* grad = p->gradients;
670         while (grad) {
671                 if (strcmp(grad->id, id) == 0)
672                         return grad;
673                 grad = grad->next;
674         }
675         return NULL;
676 }
677
678 /**
679  * In the original file, using char type (without signed or unsigned) can be interpreted
680  * as 'unsigned char' in some build environments, like ARM architecture.
681  * To prevent the unexpected behavior, we replace 'char paintType' with 'signed char paintType' here.
682  */
683 static NSVGgradient* nsvg__createGradient(NSVGparser* p, const char* id, const float* localBounds, signed char* paintType)
684 {
685         NSVGattrib* attr = nsvg__getAttr(p);
686         NSVGgradientData* data = NULL;
687         NSVGgradientData* ref = NULL;
688         NSVGgradientStop* stops = NULL;
689         NSVGgradient* grad;
690         float ox, oy, sw, sh, sl;
691         int nstops = 0;
692
693         data = nsvg__findGradientData(p, id);
694         if (data == NULL) return NULL;
695
696         // TODO: use ref to fill in all unset values too.
697         ref = data;
698         while (ref != NULL) {
699                 if (stops == NULL && ref->stops != NULL) {
700                         stops = ref->stops;
701                         nstops = ref->nstops;
702                         break;
703                 }
704                 ref = nsvg__findGradientData(p, ref->ref);
705         }
706         if (stops == NULL) return NULL;
707
708         grad = (NSVGgradient*)malloc(sizeof(NSVGgradient) + sizeof(NSVGgradientStop)*(nstops-1));
709         if (grad == NULL) return NULL;
710
711         // The shape width and height.
712         if (data->units == NSVG_OBJECT_SPACE) {
713                 ox = localBounds[0];
714                 oy = localBounds[1];
715                 sw = localBounds[2] - localBounds[0];
716                 sh = localBounds[3] - localBounds[1];
717         } else {
718                 ox = nsvg__actualOrigX(p);
719                 oy = nsvg__actualOrigY(p);
720                 sw = nsvg__actualWidth(p);
721                 sh = nsvg__actualHeight(p);
722         }
723         sl = sqrtf(sw*sw + sh*sh) / sqrtf(2.0f);
724
725         if (data->type == NSVG_PAINT_LINEAR_GRADIENT) {
726                 float x1, y1, x2, y2, dx, dy;
727                 x1 = nsvg__convertToPixels(p, data->linear.x1, ox, sw);
728                 y1 = nsvg__convertToPixels(p, data->linear.y1, oy, sh);
729                 x2 = nsvg__convertToPixels(p, data->linear.x2, ox, sw);
730                 y2 = nsvg__convertToPixels(p, data->linear.y2, oy, sh);
731                 // Calculate transform aligned to the line
732                 dx = x2 - x1;
733                 dy = y2 - y1;
734                 grad->xform[0] = dy; grad->xform[1] = -dx;
735                 grad->xform[2] = dx; grad->xform[3] = dy;
736                 grad->xform[4] = x1; grad->xform[5] = y1;
737         } else {
738                 float cx, cy, fx, fy, r;
739                 cx = nsvg__convertToPixels(p, data->radial.cx, ox, sw);
740                 cy = nsvg__convertToPixels(p, data->radial.cy, oy, sh);
741                 fx = nsvg__convertToPixels(p, data->radial.fx, ox, sw);
742                 fy = nsvg__convertToPixels(p, data->radial.fy, oy, sh);
743                 r = nsvg__convertToPixels(p, data->radial.r, 0, sl);
744                 // Calculate transform aligned to the circle
745                 grad->xform[0] = r; grad->xform[1] = 0;
746                 grad->xform[2] = 0; grad->xform[3] = r;
747                 grad->xform[4] = cx; grad->xform[5] = cy;
748                 grad->fx = fx / r;
749                 grad->fy = fy / r;
750         }
751
752         nsvg__xformMultiply(grad->xform, data->xform);
753         nsvg__xformMultiply(grad->xform, attr->xform);
754
755         grad->spread = data->spread;
756         memcpy(grad->stops, stops, nstops*sizeof(NSVGgradientStop));
757         grad->nstops = nstops;
758
759         *paintType = data->type;
760
761         return grad;
762 }
763
764 static float nsvg__getAverageScale(float* t)
765 {
766         float sx = sqrtf(t[0]*t[0] + t[2]*t[2]);
767         float sy = sqrtf(t[1]*t[1] + t[3]*t[3]);
768         return (sx + sy) * 0.5f;
769 }
770
771 static void nsvg__getLocalBounds(float* bounds, NSVGshape *shape, float* xform)
772 {
773         NSVGpath* path;
774         float curve[4*2], curveBounds[4];
775         int i, first = 1;
776         for (path = shape->paths; path != NULL; path = path->next) {
777                 nsvg__xformPoint(&curve[0], &curve[1], path->pts[0], path->pts[1], xform);
778                 for (i = 0; i < path->npts-1; i += 3) {
779                         nsvg__xformPoint(&curve[2], &curve[3], path->pts[(i+1)*2], path->pts[(i+1)*2+1], xform);
780                         nsvg__xformPoint(&curve[4], &curve[5], path->pts[(i+2)*2], path->pts[(i+2)*2+1], xform);
781                         nsvg__xformPoint(&curve[6], &curve[7], path->pts[(i+3)*2], path->pts[(i+3)*2+1], xform);
782                         nsvg__curveBounds(curveBounds, curve);
783                         if (first) {
784                                 bounds[0] = curveBounds[0];
785                                 bounds[1] = curveBounds[1];
786                                 bounds[2] = curveBounds[2];
787                                 bounds[3] = curveBounds[3];
788                                 first = 0;
789                         } else {
790                                 bounds[0] = nsvg__minf(bounds[0], curveBounds[0]);
791                                 bounds[1] = nsvg__minf(bounds[1], curveBounds[1]);
792                                 bounds[2] = nsvg__maxf(bounds[2], curveBounds[2]);
793                                 bounds[3] = nsvg__maxf(bounds[3], curveBounds[3]);
794                         }
795                         curve[0] = curve[6];
796                         curve[1] = curve[7];
797                 }
798         }
799 }
800
801 static void nsvg__addShape(NSVGparser* p)
802 {
803         NSVGattrib* attr = nsvg__getAttr(p);
804         float scale = 1.0f;
805         NSVGshape* shape;
806         NSVGpath* path;
807         int i;
808
809         if (p->plist == NULL)
810                 return;
811
812         shape = (NSVGshape*)malloc(sizeof(NSVGshape));
813         if (shape == NULL) goto error;
814         memset(shape, 0, sizeof(NSVGshape));
815
816         memcpy(shape->id, attr->id, sizeof shape->id);
817         scale = nsvg__getAverageScale(attr->xform);
818         shape->strokeWidth = attr->strokeWidth * scale;
819         shape->strokeDashOffset = attr->strokeDashOffset * scale;
820         shape->strokeDashCount = (char)attr->strokeDashCount;
821         for (i = 0; i < attr->strokeDashCount; i++)
822                 shape->strokeDashArray[i] = attr->strokeDashArray[i] * scale;
823         shape->strokeLineJoin = attr->strokeLineJoin;
824         shape->strokeLineCap = attr->strokeLineCap;
825         shape->miterLimit = attr->miterLimit;
826         shape->fillRule = attr->fillRule;
827         shape->opacity = attr->opacity;
828
829         shape->paths = p->plist;
830         p->plist = NULL;
831
832         // Calculate shape bounds
833         shape->bounds[0] = shape->paths->bounds[0];
834         shape->bounds[1] = shape->paths->bounds[1];
835         shape->bounds[2] = shape->paths->bounds[2];
836         shape->bounds[3] = shape->paths->bounds[3];
837         for (path = shape->paths->next; path != NULL; path = path->next) {
838                 shape->bounds[0] = nsvg__minf(shape->bounds[0], path->bounds[0]);
839                 shape->bounds[1] = nsvg__minf(shape->bounds[1], path->bounds[1]);
840                 shape->bounds[2] = nsvg__maxf(shape->bounds[2], path->bounds[2]);
841                 shape->bounds[3] = nsvg__maxf(shape->bounds[3], path->bounds[3]);
842         }
843
844         // Set fill
845         if (attr->hasFill == 0) {
846                 shape->fill.type = NSVG_PAINT_NONE;
847         } else if (attr->hasFill == 1) {
848                 shape->fill.type = NSVG_PAINT_COLOR;
849                 shape->fill.color = attr->fillColor;
850                 shape->fill.color |= (unsigned int)(attr->fillOpacity*255) << 24;
851         } else if (attr->hasFill == 2) {
852                 float inv[6], localBounds[4];
853                 nsvg__xformInverse(inv, attr->xform);
854                 nsvg__getLocalBounds(localBounds, shape, inv);
855                 shape->fill.gradient = nsvg__createGradient(p, attr->fillGradient, localBounds, &shape->fill.type);
856                 if (shape->fill.gradient == NULL) {
857                         shape->fill.type = NSVG_PAINT_NONE;
858                 }
859         }
860
861         // Set stroke
862         if (attr->hasStroke == 0) {
863                 shape->stroke.type = NSVG_PAINT_NONE;
864         } else if (attr->hasStroke == 1) {
865                 shape->stroke.type = NSVG_PAINT_COLOR;
866                 shape->stroke.color = attr->strokeColor;
867                 shape->stroke.color |= (unsigned int)(attr->strokeOpacity*255) << 24;
868         } else if (attr->hasStroke == 2) {
869                 float inv[6], localBounds[4];
870                 nsvg__xformInverse(inv, attr->xform);
871                 nsvg__getLocalBounds(localBounds, shape, inv);
872                 shape->stroke.gradient = nsvg__createGradient(p, attr->strokeGradient, localBounds, &shape->stroke.type);
873                 if (shape->stroke.gradient == NULL)
874                         shape->stroke.type = NSVG_PAINT_NONE;
875         }
876
877         // Set flags
878         shape->flags = (attr->visible ? NSVG_FLAGS_VISIBLE : 0x00);
879
880         // Add to tail
881         if (p->image->shapes == NULL)
882                 p->image->shapes = shape;
883         else
884                 p->shapesTail->next = shape;
885         p->shapesTail = shape;
886
887         return;
888
889 error:
890         if (shape) free(shape);
891 }
892
893 static void nsvg__addPath(NSVGparser* p, char closed)
894 {
895         NSVGattrib* attr = nsvg__getAttr(p);
896         NSVGpath* path = NULL;
897         float bounds[4];
898         float* curve;
899         int i;
900
901         if (p->npts < 4)
902                 return;
903
904         if (closed)
905                 nsvg__lineTo(p, p->pts[0], p->pts[1]);
906
907         path = (NSVGpath*)malloc(sizeof(NSVGpath));
908         if (path == NULL) goto error;
909         memset(path, 0, sizeof(NSVGpath));
910
911         path->pts = (float*)malloc(p->npts*2*sizeof(float));
912         if (path->pts == NULL) goto error;
913         path->closed = closed;
914         path->npts = p->npts;
915
916         // Transform path.
917         for (i = 0; i < p->npts; ++i)
918                 nsvg__xformPoint(&path->pts[i*2], &path->pts[i*2+1], p->pts[i*2], p->pts[i*2+1], attr->xform);
919
920         // Find bounds
921         for (i = 0; i < path->npts-1; i += 3) {
922                 curve = &path->pts[i*2];
923                 nsvg__curveBounds(bounds, curve);
924                 if (i == 0) {
925                         path->bounds[0] = bounds[0];
926                         path->bounds[1] = bounds[1];
927                         path->bounds[2] = bounds[2];
928                         path->bounds[3] = bounds[3];
929                 } else {
930                         path->bounds[0] = nsvg__minf(path->bounds[0], bounds[0]);
931                         path->bounds[1] = nsvg__minf(path->bounds[1], bounds[1]);
932                         path->bounds[2] = nsvg__maxf(path->bounds[2], bounds[2]);
933                         path->bounds[3] = nsvg__maxf(path->bounds[3], bounds[3]);
934                 }
935         }
936
937         path->next = p->plist;
938         p->plist = path;
939
940         return;
941
942 error:
943         if (path != NULL) {
944                 if (path->pts != NULL) free(path->pts);
945                 free(path);
946         }
947 }
948
949 // We roll our own string to float because the std library one uses locale and messes things up.
950 static double nsvg__atof(const char* s)
951 {
952         char* cur = (char*)s;
953         char* end = NULL;
954         double res = 0.0, sign = 1.0;
955         long long intPart = 0, fracPart = 0;
956         char hasIntPart = 0, hasFracPart = 0;
957
958         // Parse optional sign
959         if (*cur == '+') {
960                 cur++;
961         } else if (*cur == '-') {
962                 sign = -1;
963                 cur++;
964         }
965
966         // Parse integer part
967         if (nsvg__isdigit(*cur)) {
968                 // Parse digit sequence
969                 intPart = strtoll(cur, &end, 10);
970                 if (cur != end) {
971                         res = (double)intPart;
972                         hasIntPart = 1;
973                         cur = end;
974                 }
975         }
976
977         // Parse fractional part.
978         if (*cur == '.') {
979                 cur++; // Skip '.'
980                 if (nsvg__isdigit(*cur)) {
981                         // Parse digit sequence
982                         fracPart = strtoll(cur, &end, 10);
983                         if (cur != end) {
984                                 res += (double)fracPart / pow(10.0, (double)(end - cur));
985                                 hasFracPart = 1;
986                                 cur = end;
987                         }
988                 }
989         }
990
991         // A valid number should have integer or fractional part.
992         if (!hasIntPart && !hasFracPart)
993                 return 0.0;
994
995         // Parse optional exponent
996         if (*cur == 'e' || *cur == 'E') {
997                 long expPart = 0;
998                 cur++; // skip 'E'
999                 expPart = strtol(cur, &end, 10); // Parse digit sequence with sign
1000                 if (cur != end) {
1001                         res *= pow(10.0, (double)expPart);
1002                 }
1003         }
1004
1005         return res * sign;
1006 }
1007
1008
1009 static const char* nsvg__parseNumber(const char* s, char* it, const int size)
1010 {
1011         const int last = size-1;
1012         int i = 0;
1013
1014         // sign
1015         if (*s == '-' || *s == '+') {
1016                 if (i < last) it[i++] = *s;
1017                 s++;
1018         }
1019         // integer part
1020         while (*s && nsvg__isdigit(*s)) {
1021                 if (i < last) it[i++] = *s;
1022                 s++;
1023         }
1024         if (*s == '.') {
1025                 // decimal point
1026                 if (i < last) it[i++] = *s;
1027                 s++;
1028                 // fraction part
1029                 while (*s && nsvg__isdigit(*s)) {
1030                         if (i < last) it[i++] = *s;
1031                         s++;
1032                 }
1033         }
1034         // exponent
1035         if ((*s == 'e' || *s == 'E') && (s[1] != 'm' && s[1] != 'x')) {
1036                 if (i < last) it[i++] = *s;
1037                 s++;
1038                 if (*s == '-' || *s == '+') {
1039                         if (i < last) it[i++] = *s;
1040                         s++;
1041                 }
1042                 while (*s && nsvg__isdigit(*s)) {
1043                         if (i < last) it[i++] = *s;
1044                         s++;
1045                 }
1046         }
1047         it[i] = '\0';
1048
1049         return s;
1050 }
1051
1052 static const char* nsvg__getNextPathItem(const char* s, char* it)
1053 {
1054         it[0] = '\0';
1055         // Skip white spaces and commas
1056         while (*s && (nsvg__isspace(*s) || *s == ',')) s++;
1057         if (!*s) return s;
1058         if (*s == '-' || *s == '+' || *s == '.' || nsvg__isdigit(*s)) {
1059                 s = nsvg__parseNumber(s, it, 64);
1060         } else {
1061                 // Parse command
1062                 it[0] = *s++;
1063                 it[1] = '\0';
1064                 return s;
1065         }
1066
1067         return s;
1068 }
1069
1070 static unsigned int nsvg__parseColorHex(const char* str)
1071 {
1072         unsigned int c = 0, r = 0, g = 0, b = 0;
1073         int n = 0;
1074         str++; // skip #
1075         // Calculate number of characters.
1076         while(str[n] && !nsvg__isspace(str[n]))
1077                 n++;
1078         if (n == 6) {
1079                 sscanf(str, "%x", &c);
1080         } else if (n == 3) {
1081                 sscanf(str, "%x", &c);
1082                 c = (c&0xf) | ((c&0xf0) << 4) | ((c&0xf00) << 8);
1083                 c |= c<<4;
1084         }
1085         r = (c >> 16) & 0xff;
1086         g = (c >> 8) & 0xff;
1087         b = c & 0xff;
1088         return NSVG_RGB(r,g,b);
1089 }
1090
1091 static unsigned int nsvg__parseColorRGB(const char* str)
1092 {
1093         int r = -1, g = -1, b = -1;
1094         char s1[33]="", s2[33]="";
1095         /**
1096          * In the original file, the formatted data reading did not specify the string with width limitation.
1097          * To prevent the possible overflow, we replace '%s' with '%32s' here.
1098          */
1099         sscanf(str + 4, "%d%32[%%, \t]%d%32[%%, \t]%d", &r, s1, &g, s2, &b);
1100         if (strchr(s1, '%')) {
1101                 return NSVG_RGB((r*255)/100,(g*255)/100,(b*255)/100);
1102         } else {
1103                 return NSVG_RGB(r,g,b);
1104         }
1105 }
1106
1107 typedef struct NSVGNamedColor {
1108         const char* name;
1109         unsigned int color;
1110 } NSVGNamedColor;
1111
1112 NSVGNamedColor nsvg__colors[] = {
1113
1114         { "red", NSVG_RGB(255, 0, 0) },
1115         { "green", NSVG_RGB( 0, 128, 0) },
1116         { "blue", NSVG_RGB( 0, 0, 255) },
1117         { "yellow", NSVG_RGB(255, 255, 0) },
1118         { "cyan", NSVG_RGB( 0, 255, 255) },
1119         { "magenta", NSVG_RGB(255, 0, 255) },
1120         { "black", NSVG_RGB( 0, 0, 0) },
1121         { "grey", NSVG_RGB(128, 128, 128) },
1122         { "gray", NSVG_RGB(128, 128, 128) },
1123         { "white", NSVG_RGB(255, 255, 255) },
1124
1125 /**
1126  * In the original software, it needs to define "NANOSVG_ALL_COLOR_KEYWORDS" in order to support
1127  * the following colors. We have removed this because we want to support all the colors.
1128  */
1129         { "aliceblue", NSVG_RGB(240, 248, 255) },
1130         { "antiquewhite", NSVG_RGB(250, 235, 215) },
1131         { "aqua", NSVG_RGB( 0, 255, 255) },
1132         { "aquamarine", NSVG_RGB(127, 255, 212) },
1133         { "azure", NSVG_RGB(240, 255, 255) },
1134         { "beige", NSVG_RGB(245, 245, 220) },
1135         { "bisque", NSVG_RGB(255, 228, 196) },
1136         { "blanchedalmond", NSVG_RGB(255, 235, 205) },
1137         { "blueviolet", NSVG_RGB(138, 43, 226) },
1138         { "brown", NSVG_RGB(165, 42, 42) },
1139         { "burlywood", NSVG_RGB(222, 184, 135) },
1140         { "cadetblue", NSVG_RGB( 95, 158, 160) },
1141         { "chartreuse", NSVG_RGB(127, 255, 0) },
1142         { "chocolate", NSVG_RGB(210, 105, 30) },
1143         { "coral", NSVG_RGB(255, 127, 80) },
1144         { "cornflowerblue", NSVG_RGB(100, 149, 237) },
1145         { "cornsilk", NSVG_RGB(255, 248, 220) },
1146         { "crimson", NSVG_RGB(220, 20, 60) },
1147         { "darkblue", NSVG_RGB( 0, 0, 139) },
1148         { "darkcyan", NSVG_RGB( 0, 139, 139) },
1149         { "darkgoldenrod", NSVG_RGB(184, 134, 11) },
1150         { "darkgray", NSVG_RGB(169, 169, 169) },
1151         { "darkgreen", NSVG_RGB( 0, 100, 0) },
1152         { "darkgrey", NSVG_RGB(169, 169, 169) },
1153         { "darkkhaki", NSVG_RGB(189, 183, 107) },
1154         { "darkmagenta", NSVG_RGB(139, 0, 139) },
1155         { "darkolivegreen", NSVG_RGB( 85, 107, 47) },
1156         { "darkorange", NSVG_RGB(255, 140, 0) },
1157         { "darkorchid", NSVG_RGB(153, 50, 204) },
1158         { "darkred", NSVG_RGB(139, 0, 0) },
1159         { "darksalmon", NSVG_RGB(233, 150, 122) },
1160         { "darkseagreen", NSVG_RGB(143, 188, 143) },
1161         { "darkslateblue", NSVG_RGB( 72, 61, 139) },
1162         { "darkslategray", NSVG_RGB( 47, 79, 79) },
1163         { "darkslategrey", NSVG_RGB( 47, 79, 79) },
1164         { "darkturquoise", NSVG_RGB( 0, 206, 209) },
1165         { "darkviolet", NSVG_RGB(148, 0, 211) },
1166         { "deeppink", NSVG_RGB(255, 20, 147) },
1167         { "deepskyblue", NSVG_RGB( 0, 191, 255) },
1168         { "dimgray", NSVG_RGB(105, 105, 105) },
1169         { "dimgrey", NSVG_RGB(105, 105, 105) },
1170         { "dodgerblue", NSVG_RGB( 30, 144, 255) },
1171         { "firebrick", NSVG_RGB(178, 34, 34) },
1172         { "floralwhite", NSVG_RGB(255, 250, 240) },
1173         { "forestgreen", NSVG_RGB( 34, 139, 34) },
1174         { "fuchsia", NSVG_RGB(255, 0, 255) },
1175         { "gainsboro", NSVG_RGB(220, 220, 220) },
1176         { "ghostwhite", NSVG_RGB(248, 248, 255) },
1177         { "gold", NSVG_RGB(255, 215, 0) },
1178         { "goldenrod", NSVG_RGB(218, 165, 32) },
1179         { "greenyellow", NSVG_RGB(173, 255, 47) },
1180         { "honeydew", NSVG_RGB(240, 255, 240) },
1181         { "hotpink", NSVG_RGB(255, 105, 180) },
1182         { "indianred", NSVG_RGB(205, 92, 92) },
1183         { "indigo", NSVG_RGB( 75, 0, 130) },
1184         { "ivory", NSVG_RGB(255, 255, 240) },
1185         { "khaki", NSVG_RGB(240, 230, 140) },
1186         { "lavender", NSVG_RGB(230, 230, 250) },
1187         { "lavenderblush", NSVG_RGB(255, 240, 245) },
1188         { "lawngreen", NSVG_RGB(124, 252, 0) },
1189         { "lemonchiffon", NSVG_RGB(255, 250, 205) },
1190         { "lightblue", NSVG_RGB(173, 216, 230) },
1191         { "lightcoral", NSVG_RGB(240, 128, 128) },
1192         { "lightcyan", NSVG_RGB(224, 255, 255) },
1193         { "lightgoldenrodyellow", NSVG_RGB(250, 250, 210) },
1194         { "lightgray", NSVG_RGB(211, 211, 211) },
1195         { "lightgreen", NSVG_RGB(144, 238, 144) },
1196         { "lightgrey", NSVG_RGB(211, 211, 211) },
1197         { "lightpink", NSVG_RGB(255, 182, 193) },
1198         { "lightsalmon", NSVG_RGB(255, 160, 122) },
1199         { "lightseagreen", NSVG_RGB( 32, 178, 170) },
1200         { "lightskyblue", NSVG_RGB(135, 206, 250) },
1201         { "lightslategray", NSVG_RGB(119, 136, 153) },
1202         { "lightslategrey", NSVG_RGB(119, 136, 153) },
1203         { "lightsteelblue", NSVG_RGB(176, 196, 222) },
1204         { "lightyellow", NSVG_RGB(255, 255, 224) },
1205         { "lime", NSVG_RGB( 0, 255, 0) },
1206         { "limegreen", NSVG_RGB( 50, 205, 50) },
1207         { "linen", NSVG_RGB(250, 240, 230) },
1208         { "maroon", NSVG_RGB(128, 0, 0) },
1209         { "mediumaquamarine", NSVG_RGB(102, 205, 170) },
1210         { "mediumblue", NSVG_RGB( 0, 0, 205) },
1211         { "mediumorchid", NSVG_RGB(186, 85, 211) },
1212         { "mediumpurple", NSVG_RGB(147, 112, 219) },
1213         { "mediumseagreen", NSVG_RGB( 60, 179, 113) },
1214         { "mediumslateblue", NSVG_RGB(123, 104, 238) },
1215         { "mediumspringgreen", NSVG_RGB( 0, 250, 154) },
1216         { "mediumturquoise", NSVG_RGB( 72, 209, 204) },
1217         { "mediumvioletred", NSVG_RGB(199, 21, 133) },
1218         { "midnightblue", NSVG_RGB( 25, 25, 112) },
1219         { "mintcream", NSVG_RGB(245, 255, 250) },
1220         { "mistyrose", NSVG_RGB(255, 228, 225) },
1221         { "moccasin", NSVG_RGB(255, 228, 181) },
1222         { "navajowhite", NSVG_RGB(255, 222, 173) },
1223         { "navy", NSVG_RGB( 0, 0, 128) },
1224         { "oldlace", NSVG_RGB(253, 245, 230) },
1225         { "olive", NSVG_RGB(128, 128, 0) },
1226         { "olivedrab", NSVG_RGB(107, 142, 35) },
1227         { "orange", NSVG_RGB(255, 165, 0) },
1228         { "orangered", NSVG_RGB(255, 69, 0) },
1229         { "orchid", NSVG_RGB(218, 112, 214) },
1230         { "palegoldenrod", NSVG_RGB(238, 232, 170) },
1231         { "palegreen", NSVG_RGB(152, 251, 152) },
1232         { "paleturquoise", NSVG_RGB(175, 238, 238) },
1233         { "palevioletred", NSVG_RGB(219, 112, 147) },
1234         { "papayawhip", NSVG_RGB(255, 239, 213) },
1235         { "peachpuff", NSVG_RGB(255, 218, 185) },
1236         { "peru", NSVG_RGB(205, 133, 63) },
1237         { "pink", NSVG_RGB(255, 192, 203) },
1238         { "plum", NSVG_RGB(221, 160, 221) },
1239         { "powderblue", NSVG_RGB(176, 224, 230) },
1240         { "purple", NSVG_RGB(128, 0, 128) },
1241         { "rosybrown", NSVG_RGB(188, 143, 143) },
1242         { "royalblue", NSVG_RGB( 65, 105, 225) },
1243         { "saddlebrown", NSVG_RGB(139, 69, 19) },
1244         { "salmon", NSVG_RGB(250, 128, 114) },
1245         { "sandybrown", NSVG_RGB(244, 164, 96) },
1246         { "seagreen", NSVG_RGB( 46, 139, 87) },
1247         { "seashell", NSVG_RGB(255, 245, 238) },
1248         { "sienna", NSVG_RGB(160, 82, 45) },
1249         { "silver", NSVG_RGB(192, 192, 192) },
1250         { "skyblue", NSVG_RGB(135, 206, 235) },
1251         { "slateblue", NSVG_RGB(106, 90, 205) },
1252         { "slategray", NSVG_RGB(112, 128, 144) },
1253         { "slategrey", NSVG_RGB(112, 128, 144) },
1254         { "snow", NSVG_RGB(255, 250, 250) },
1255         { "springgreen", NSVG_RGB( 0, 255, 127) },
1256         { "steelblue", NSVG_RGB( 70, 130, 180) },
1257         { "tan", NSVG_RGB(210, 180, 140) },
1258         { "teal", NSVG_RGB( 0, 128, 128) },
1259         { "thistle", NSVG_RGB(216, 191, 216) },
1260         { "tomato", NSVG_RGB(255, 99, 71) },
1261         { "turquoise", NSVG_RGB( 64, 224, 208) },
1262         { "violet", NSVG_RGB(238, 130, 238) },
1263         { "wheat", NSVG_RGB(245, 222, 179) },
1264         { "whitesmoke", NSVG_RGB(245, 245, 245) },
1265         { "yellowgreen", NSVG_RGB(154, 205, 50) },
1266 };
1267
1268 static unsigned int nsvg__parseColorName(const char* str)
1269 {
1270         int i, ncolors = sizeof(nsvg__colors) / sizeof(NSVGNamedColor);
1271
1272         for (i = 0; i < ncolors; i++) {
1273                 if (strcmp(nsvg__colors[i].name, str) == 0) {
1274                         return nsvg__colors[i].color;
1275                 }
1276         }
1277
1278         return NSVG_RGB(128, 128, 128);
1279 }
1280
1281 static unsigned int nsvg__parseColor(const char* str)
1282 {
1283         size_t len = 0;
1284         while(*str == ' ') ++str;
1285         len = strlen(str);
1286         if (len >= 1 && *str == '#')
1287                 return nsvg__parseColorHex(str);
1288         else if (len >= 4 && str[0] == 'r' && str[1] == 'g' && str[2] == 'b' && str[3] == '(')
1289                 return nsvg__parseColorRGB(str);
1290         return nsvg__parseColorName(str);
1291 }
1292
1293 static float nsvg__parseOpacity(const char* str)
1294 {
1295         float val = nsvg__atof(str);
1296         if (val < 0.0f) val = 0.0f;
1297         if (val > 1.0f) val = 1.0f;
1298         return val;
1299 }
1300
1301 static float nsvg__parseMiterLimit(const char* str)
1302 {
1303         float val = nsvg__atof(str);
1304         if (val < 0.0f) val = 0.0f;
1305         return val;
1306 }
1307
1308 static int nsvg__parseUnits(const char* units)
1309 {
1310         if (units[0] == 'p' && units[1] == 'x')
1311                 return NSVG_UNITS_PX;
1312         else if (units[0] == 'p' && units[1] == 't')
1313                 return NSVG_UNITS_PT;
1314         else if (units[0] == 'p' && units[1] == 'c')
1315                 return NSVG_UNITS_PC;
1316         else if (units[0] == 'm' && units[1] == 'm')
1317                 return NSVG_UNITS_MM;
1318         else if (units[0] == 'c' && units[1] == 'm')
1319                 return NSVG_UNITS_CM;
1320         else if (units[0] == 'i' && units[1] == 'n')
1321                 return NSVG_UNITS_IN;
1322         else if (units[0] == '%')
1323                 return NSVG_UNITS_PERCENT;
1324         else if (units[0] == 'e' && units[1] == 'm')
1325                 return NSVG_UNITS_EM;
1326         else if (units[0] == 'e' && units[1] == 'x')
1327                 return NSVG_UNITS_EX;
1328         return NSVG_UNITS_USER;
1329 }
1330
1331 static NSVGcoordinate nsvg__parseCoordinateRaw(const char* str)
1332 {
1333         NSVGcoordinate coord = {0, NSVG_UNITS_USER};
1334         char buf[64];
1335         coord.units = nsvg__parseUnits(nsvg__parseNumber(str, buf, 64));
1336         coord.value = nsvg__atof(buf);
1337         return coord;
1338 }
1339
1340 static NSVGcoordinate nsvg__coord(float v, int units)
1341 {
1342         NSVGcoordinate coord = {v, units};
1343         return coord;
1344 }
1345
1346 static float nsvg__parseCoordinate(NSVGparser* p, const char* str, float orig, float length)
1347 {
1348         NSVGcoordinate coord = nsvg__parseCoordinateRaw(str);
1349         return nsvg__convertToPixels(p, coord, orig, length);
1350 }
1351
1352 static int nsvg__parseTransformArgs(const char* str, float* args, int maxNa, int* na)
1353 {
1354         const char* end;
1355         const char* ptr;
1356         char it[64];
1357
1358         *na = 0;
1359         ptr = str;
1360         while (*ptr && *ptr != '(') ++ptr;
1361         if (*ptr == 0)
1362                 return 1;
1363         end = ptr;
1364         while (*end && *end != ')') ++end;
1365         if (*end == 0)
1366                 return 1;
1367
1368         while (ptr < end) {
1369                 if (*ptr == '-' || *ptr == '+' || *ptr == '.' || nsvg__isdigit(*ptr)) {
1370                         if (*na >= maxNa) return 0;
1371                         ptr = nsvg__parseNumber(ptr, it, 64);
1372                         args[(*na)++] = (float)nsvg__atof(it);
1373                 } else {
1374                         ++ptr;
1375                 }
1376         }
1377         return (int)(end - str);
1378 }
1379
1380
1381 static int nsvg__parseMatrix(float* xform, const char* str)
1382 {
1383         float t[6];
1384         int na = 0;
1385         int len = nsvg__parseTransformArgs(str, t, 6, &na);
1386         if (na != 6) return len;
1387         memcpy(xform, t, sizeof(float)*6);
1388         return len;
1389 }
1390
1391 static int nsvg__parseTranslate(float* xform, const char* str)
1392 {
1393         float args[2];
1394         float t[6];
1395         int na = 0;
1396         int len = nsvg__parseTransformArgs(str, args, 2, &na);
1397         if (na == 1) args[1] = 0.0;
1398
1399         nsvg__xformSetTranslation(t, args[0], args[1]);
1400         memcpy(xform, t, sizeof(float)*6);
1401         return len;
1402 }
1403
1404 static int nsvg__parseScale(float* xform, const char* str)
1405 {
1406         float args[2];
1407         int na = 0;
1408         float t[6];
1409         int len = nsvg__parseTransformArgs(str, args, 2, &na);
1410         if (na == 1) args[1] = args[0];
1411         nsvg__xformSetScale(t, args[0], args[1]);
1412         memcpy(xform, t, sizeof(float)*6);
1413         return len;
1414 }
1415
1416 static int nsvg__parseSkewX(float* xform, const char* str)
1417 {
1418         float args[1];
1419         int na = 0;
1420         float t[6];
1421         int len = nsvg__parseTransformArgs(str, args, 1, &na);
1422         nsvg__xformSetSkewX(t, args[0]/180.0f*NSVG_PI);
1423         memcpy(xform, t, sizeof(float)*6);
1424         return len;
1425 }
1426
1427 static int nsvg__parseSkewY(float* xform, const char* str)
1428 {
1429         float args[1];
1430         int na = 0;
1431         float t[6];
1432         int len = nsvg__parseTransformArgs(str, args, 1, &na);
1433         nsvg__xformSetSkewY(t, args[0]/180.0f*NSVG_PI);
1434         memcpy(xform, t, sizeof(float)*6);
1435         return len;
1436 }
1437
1438 static int nsvg__parseRotate(float* xform, const char* str)
1439 {
1440         float args[3];
1441         int na = 0;
1442         float m[6];
1443         float t[6];
1444         int len = nsvg__parseTransformArgs(str, args, 3, &na);
1445         if (na == 1)
1446                 args[1] = args[2] = 0.0f;
1447         nsvg__xformIdentity(m);
1448
1449         if (na > 1) {
1450                 nsvg__xformSetTranslation(t, -args[1], -args[2]);
1451                 nsvg__xformMultiply(m, t);
1452         }
1453
1454         nsvg__xformSetRotation(t, args[0]/180.0f*NSVG_PI);
1455         nsvg__xformMultiply(m, t);
1456
1457         if (na > 1) {
1458                 nsvg__xformSetTranslation(t, args[1], args[2]);
1459                 nsvg__xformMultiply(m, t);
1460         }
1461
1462         memcpy(xform, m, sizeof(float)*6);
1463
1464         return len;
1465 }
1466
1467 static void nsvg__parseTransform(float* xform, const char* str)
1468 {
1469         float t[6];
1470         nsvg__xformIdentity(xform);
1471         while (*str)
1472         {
1473                 if (strncmp(str, "matrix", 6) == 0)
1474                         str += nsvg__parseMatrix(t, str);
1475                 else if (strncmp(str, "translate", 9) == 0)
1476                         str += nsvg__parseTranslate(t, str);
1477                 else if (strncmp(str, "scale", 5) == 0)
1478                         str += nsvg__parseScale(t, str);
1479                 else if (strncmp(str, "rotate", 6) == 0)
1480                         str += nsvg__parseRotate(t, str);
1481                 else if (strncmp(str, "skewX", 5) == 0)
1482                         str += nsvg__parseSkewX(t, str);
1483                 else if (strncmp(str, "skewY", 5) == 0)
1484                         str += nsvg__parseSkewY(t, str);
1485                 else{
1486                         ++str;
1487                         continue;
1488                 }
1489
1490                 nsvg__xformPremultiply(xform, t);
1491         }
1492 }
1493
1494 static void nsvg__parseUrl(char* id, const char* str)
1495 {
1496         int i = 0;
1497         str += 4; // "url(";
1498         if (*str == '#')
1499                 str++;
1500         while (i < 63 && *str != ')') {
1501                 id[i] = *str++;
1502                 i++;
1503         }
1504         id[i] = '\0';
1505 }
1506
1507 static char nsvg__parseLineCap(const char* str)
1508 {
1509         if (strcmp(str, "butt") == 0)
1510                 return NSVG_CAP_BUTT;
1511         else if (strcmp(str, "round") == 0)
1512                 return NSVG_CAP_ROUND;
1513         else if (strcmp(str, "square") == 0)
1514                 return NSVG_CAP_SQUARE;
1515         // TODO: handle inherit.
1516         return NSVG_CAP_BUTT;
1517 }
1518
1519 static char nsvg__parseLineJoin(const char* str)
1520 {
1521         if (strcmp(str, "miter") == 0)
1522                 return NSVG_JOIN_MITER;
1523         else if (strcmp(str, "round") == 0)
1524                 return NSVG_JOIN_ROUND;
1525         else if (strcmp(str, "bevel") == 0)
1526                 return NSVG_JOIN_BEVEL;
1527         // TODO: handle inherit.
1528         return NSVG_JOIN_MITER;
1529 }
1530
1531 static char nsvg__parseFillRule(const char* str)
1532 {
1533         if (strcmp(str, "nonzero") == 0)
1534                 return NSVG_FILLRULE_NONZERO;
1535         else if (strcmp(str, "evenodd") == 0)
1536                 return NSVG_FILLRULE_EVENODD;
1537         // TODO: handle inherit.
1538         return NSVG_FILLRULE_NONZERO;
1539 }
1540
1541 static const char* nsvg__getNextDashItem(const char* s, char* it)
1542 {
1543         int n = 0;
1544         it[0] = '\0';
1545         // Skip white spaces and commas
1546         while (*s && (nsvg__isspace(*s) || *s == ',')) s++;
1547         // Advance until whitespace, comma or end.
1548         while (*s && (!nsvg__isspace(*s) && *s != ',')) {
1549                 if (n < 63)
1550                         it[n++] = *s;
1551                 s++;
1552         }
1553         it[n++] = '\0';
1554         return s;
1555 }
1556
1557 static int nsvg__parseStrokeDashArray(NSVGparser* p, const char* str, float* strokeDashArray)
1558 {
1559         char item[64];
1560         int count = 0, i;
1561         float sum = 0.0f;
1562
1563         // Handle "none"
1564         if (str[0] == 'n')
1565                 return 0;
1566
1567         // Parse dashes
1568         while (*str) {
1569                 str = nsvg__getNextDashItem(str, item);
1570                 if (!*item) break;
1571                 if (count < NSVG_MAX_DASHES)
1572                         strokeDashArray[count++] = fabsf(nsvg__parseCoordinate(p, item, 0.0f, nsvg__actualLength(p)));
1573         }
1574
1575         for (i = 0; i < count; i++)
1576                 sum += strokeDashArray[i];
1577         if (sum <= 1e-6f)
1578                 count = 0;
1579
1580         return count;
1581 }
1582
1583 static void nsvg__parseStyle(NSVGparser* p, const char* str);
1584
1585 static int nsvg__parseAttr(NSVGparser* p, const char* name, const char* value)
1586 {
1587         float xform[6];
1588         NSVGattrib* attr = nsvg__getAttr(p);
1589         if (!attr) return 0;
1590
1591         if (strcmp(name, "style") == 0) {
1592                 nsvg__parseStyle(p, value);
1593         } else if (strcmp(name, "display") == 0) {
1594                 if (strcmp(value, "none") == 0)
1595                         attr->visible = 0;
1596                 // Don't reset ->visible on display:inline, one display:none hides the whole subtree
1597
1598         } else if (strcmp(name, "fill") == 0) {
1599                 if (strcmp(value, "none") == 0) {
1600                         attr->hasFill = 0;
1601                 } else if (strncmp(value, "url(", 4) == 0) {
1602                         attr->hasFill = 2;
1603                         nsvg__parseUrl(attr->fillGradient, value);
1604                 } else {
1605                         attr->hasFill = 1;
1606                         attr->fillColor = nsvg__parseColor(value);
1607                 }
1608         } else if (strcmp(name, "opacity") == 0) {
1609                 attr->opacity = nsvg__parseOpacity(value);
1610         } else if (strcmp(name, "fill-opacity") == 0) {
1611                 attr->fillOpacity = nsvg__parseOpacity(value);
1612         } else if (strcmp(name, "stroke") == 0) {
1613                 if (strcmp(value, "none") == 0) {
1614                         attr->hasStroke = 0;
1615                 } else if (strncmp(value, "url(", 4) == 0) {
1616                         attr->hasStroke = 2;
1617                         nsvg__parseUrl(attr->strokeGradient, value);
1618                 } else {
1619                         attr->hasStroke = 1;
1620                         attr->strokeColor = nsvg__parseColor(value);
1621                 }
1622         } else if (strcmp(name, "stroke-width") == 0) {
1623                 attr->strokeWidth = nsvg__parseCoordinate(p, value, 0.0f, nsvg__actualLength(p));
1624         } else if (strcmp(name, "stroke-dasharray") == 0) {
1625                 attr->strokeDashCount = nsvg__parseStrokeDashArray(p, value, attr->strokeDashArray);
1626         } else if (strcmp(name, "stroke-dashoffset") == 0) {
1627                 attr->strokeDashOffset = nsvg__parseCoordinate(p, value, 0.0f, nsvg__actualLength(p));
1628         } else if (strcmp(name, "stroke-opacity") == 0) {
1629                 attr->strokeOpacity = nsvg__parseOpacity(value);
1630         } else if (strcmp(name, "stroke-linecap") == 0) {
1631                 attr->strokeLineCap = nsvg__parseLineCap(value);
1632         } else if (strcmp(name, "stroke-linejoin") == 0) {
1633                 attr->strokeLineJoin = nsvg__parseLineJoin(value);
1634         } else if (strcmp(name, "stroke-miterlimit") == 0) {
1635                 attr->miterLimit = nsvg__parseMiterLimit(value);
1636         } else if (strcmp(name, "fill-rule") == 0) {
1637                 attr->fillRule = nsvg__parseFillRule(value);
1638         } else if (strcmp(name, "font-size") == 0) {
1639                 attr->fontSize = nsvg__parseCoordinate(p, value, 0.0f, nsvg__actualLength(p));
1640         } else if (strcmp(name, "transform") == 0) {
1641                 nsvg__parseTransform(xform, value);
1642                 nsvg__xformPremultiply(attr->xform, xform);
1643         } else if (strcmp(name, "stop-color") == 0) {
1644                 attr->stopColor = nsvg__parseColor(value);
1645         } else if (strcmp(name, "stop-opacity") == 0) {
1646                 attr->stopOpacity = nsvg__parseOpacity(value);
1647         } else if (strcmp(name, "offset") == 0) {
1648                 attr->stopOffset = nsvg__parseCoordinate(p, value, 0.0f, 1.0f);
1649         } else if (strcmp(name, "id") == 0) {
1650                 strncpy(attr->id, value, 63);
1651                 attr->id[63] = '\0';
1652         } else {
1653                 return 0;
1654         }
1655         return 1;
1656 }
1657
1658 static int nsvg__parseNameValue(NSVGparser* p, const char* start, const char* end)
1659 {
1660         const char* str;
1661         const char* val;
1662         char name[512];
1663         char value[512];
1664         int n;
1665
1666         str = start;
1667         while (str < end && *str != ':') ++str;
1668
1669         val = str;
1670
1671         // Right Trim
1672         while (str > start &&  (*str == ':' || nsvg__isspace(*str))) --str;
1673         ++str;
1674
1675         n = (int)(str - start);
1676         if (n > 511) n = 511;
1677         if (n) memcpy(name, start, n);
1678         name[n] = 0;
1679
1680         while (val < end && (*val == ':' || nsvg__isspace(*val))) ++val;
1681
1682         n = (int)(end - val);
1683         if (n > 511) n = 511;
1684         if (n) memcpy(value, val, n);
1685         value[n] = 0;
1686
1687         return nsvg__parseAttr(p, name, value);
1688 }
1689
1690 static void nsvg__parseStyle(NSVGparser* p, const char* str)
1691 {
1692         const char* start;
1693         const char* end;
1694
1695         while (*str) {
1696                 // Left Trim
1697                 while(*str && nsvg__isspace(*str)) ++str;
1698                 start = str;
1699                 while(*str && *str != ';') ++str;
1700                 end = str;
1701
1702                 // Right Trim
1703                 while (end > start &&  (*end == ';' || nsvg__isspace(*end))) --end;
1704                 ++end;
1705
1706                 nsvg__parseNameValue(p, start, end);
1707                 if (*str) ++str;
1708         }
1709 }
1710
1711 static void nsvg__parseAttribs(NSVGparser* p, const char** attr)
1712 {
1713         int i;
1714         for (i = 0; attr[i]; i += 2)
1715         {
1716                 if (strcmp(attr[i], "style") == 0)
1717                         nsvg__parseStyle(p, attr[i + 1]);
1718                 else
1719                         nsvg__parseAttr(p, attr[i], attr[i + 1]);
1720         }
1721 }
1722
1723 static int nsvg__getArgsPerElement(char cmd)
1724 {
1725         switch (cmd) {
1726                 case 'v':
1727                 case 'V':
1728                 case 'h':
1729                 case 'H':
1730                         return 1;
1731                 case 'm':
1732                 case 'M':
1733                 case 'l':
1734                 case 'L':
1735                 case 't':
1736                 case 'T':
1737                         return 2;
1738                 case 'q':
1739                 case 'Q':
1740                 case 's':
1741                 case 'S':
1742                         return 4;
1743                 case 'c':
1744                 case 'C':
1745                         return 6;
1746                 case 'a':
1747                 case 'A':
1748                         return 7;
1749         }
1750         return 0;
1751 }
1752
1753 static void nsvg__pathMoveTo(NSVGparser* p, float* cpx, float* cpy, float* args, int rel)
1754 {
1755         if (rel) {
1756                 *cpx += args[0];
1757                 *cpy += args[1];
1758         } else {
1759                 *cpx = args[0];
1760                 *cpy = args[1];
1761         }
1762         nsvg__moveTo(p, *cpx, *cpy);
1763 }
1764
1765 static void nsvg__pathLineTo(NSVGparser* p, float* cpx, float* cpy, float* args, int rel)
1766 {
1767         if (rel) {
1768                 *cpx += args[0];
1769                 *cpy += args[1];
1770         } else {
1771                 *cpx = args[0];
1772                 *cpy = args[1];
1773         }
1774         nsvg__lineTo(p, *cpx, *cpy);
1775 }
1776
1777 static void nsvg__pathHLineTo(NSVGparser* p, float* cpx, float* cpy, float* args, int rel)
1778 {
1779         if (rel)
1780                 *cpx += args[0];
1781         else
1782                 *cpx = args[0];
1783         nsvg__lineTo(p, *cpx, *cpy);
1784 }
1785
1786 static void nsvg__pathVLineTo(NSVGparser* p, float* cpx, float* cpy, float* args, int rel)
1787 {
1788         if (rel)
1789                 *cpy += args[0];
1790         else
1791                 *cpy = args[0];
1792         nsvg__lineTo(p, *cpx, *cpy);
1793 }
1794
1795 static void nsvg__pathCubicBezTo(NSVGparser* p, float* cpx, float* cpy,
1796                                                                  float* cpx2, float* cpy2, float* args, int rel)
1797 {
1798         float x2, y2, cx1, cy1, cx2, cy2;
1799
1800         if (rel) {
1801                 cx1 = *cpx + args[0];
1802                 cy1 = *cpy + args[1];
1803                 cx2 = *cpx + args[2];
1804                 cy2 = *cpy + args[3];
1805                 x2 = *cpx + args[4];
1806                 y2 = *cpy + args[5];
1807         } else {
1808                 cx1 = args[0];
1809                 cy1 = args[1];
1810                 cx2 = args[2];
1811                 cy2 = args[3];
1812                 x2 = args[4];
1813                 y2 = args[5];
1814         }
1815
1816         nsvg__cubicBezTo(p, cx1,cy1, cx2,cy2, x2,y2);
1817
1818         *cpx2 = cx2;
1819         *cpy2 = cy2;
1820         *cpx = x2;
1821         *cpy = y2;
1822 }
1823
1824 static void nsvg__pathCubicBezShortTo(NSVGparser* p, float* cpx, float* cpy,
1825                                                                           float* cpx2, float* cpy2, float* args, int rel)
1826 {
1827         float x1, y1, x2, y2, cx1, cy1, cx2, cy2;
1828
1829         x1 = *cpx;
1830         y1 = *cpy;
1831         if (rel) {
1832                 cx2 = *cpx + args[0];
1833                 cy2 = *cpy + args[1];
1834                 x2 = *cpx + args[2];
1835                 y2 = *cpy + args[3];
1836         } else {
1837                 cx2 = args[0];
1838                 cy2 = args[1];
1839                 x2 = args[2];
1840                 y2 = args[3];
1841         }
1842
1843         cx1 = 2*x1 - *cpx2;
1844         cy1 = 2*y1 - *cpy2;
1845
1846         nsvg__cubicBezTo(p, cx1,cy1, cx2,cy2, x2,y2);
1847
1848         *cpx2 = cx2;
1849         *cpy2 = cy2;
1850         *cpx = x2;
1851         *cpy = y2;
1852 }
1853
1854 static void nsvg__pathQuadBezTo(NSVGparser* p, float* cpx, float* cpy,
1855                                                                 float* cpx2, float* cpy2, float* args, int rel)
1856 {
1857         float x1, y1, x2, y2, cx, cy;
1858         float cx1, cy1, cx2, cy2;
1859
1860         x1 = *cpx;
1861         y1 = *cpy;
1862         if (rel) {
1863                 cx = *cpx + args[0];
1864                 cy = *cpy + args[1];
1865                 x2 = *cpx + args[2];
1866                 y2 = *cpy + args[3];
1867         } else {
1868                 cx = args[0];
1869                 cy = args[1];
1870                 x2 = args[2];
1871                 y2 = args[3];
1872         }
1873
1874         // Convert to cubic bezier
1875         cx1 = x1 + 2.0f/3.0f*(cx - x1);
1876         cy1 = y1 + 2.0f/3.0f*(cy - y1);
1877         cx2 = x2 + 2.0f/3.0f*(cx - x2);
1878         cy2 = y2 + 2.0f/3.0f*(cy - y2);
1879
1880         nsvg__cubicBezTo(p, cx1,cy1, cx2,cy2, x2,y2);
1881
1882         *cpx2 = cx;
1883         *cpy2 = cy;
1884         *cpx = x2;
1885         *cpy = y2;
1886 }
1887
1888 static void nsvg__pathQuadBezShortTo(NSVGparser* p, float* cpx, float* cpy,
1889                                                                          float* cpx2, float* cpy2, float* args, int rel)
1890 {
1891         float x1, y1, x2, y2, cx, cy;
1892         float cx1, cy1, cx2, cy2;
1893
1894         x1 = *cpx;
1895         y1 = *cpy;
1896         if (rel) {
1897                 x2 = *cpx + args[0];
1898                 y2 = *cpy + args[1];
1899         } else {
1900                 x2 = args[0];
1901                 y2 = args[1];
1902         }
1903
1904         cx = 2*x1 - *cpx2;
1905         cy = 2*y1 - *cpy2;
1906
1907         // Convert to cubix bezier
1908         cx1 = x1 + 2.0f/3.0f*(cx - x1);
1909         cy1 = y1 + 2.0f/3.0f*(cy - y1);
1910         cx2 = x2 + 2.0f/3.0f*(cx - x2);
1911         cy2 = y2 + 2.0f/3.0f*(cy - y2);
1912
1913         nsvg__cubicBezTo(p, cx1,cy1, cx2,cy2, x2,y2);
1914
1915         *cpx2 = cx;
1916         *cpy2 = cy;
1917         *cpx = x2;
1918         *cpy = y2;
1919 }
1920
1921 static float nsvg__sqr(float x) { return x*x; }
1922 static float nsvg__vmag(float x, float y) { return sqrtf(x*x + y*y); }
1923
1924 static float nsvg__vecrat(float ux, float uy, float vx, float vy)
1925 {
1926         return (ux*vx + uy*vy) / (nsvg__vmag(ux,uy) * nsvg__vmag(vx,vy));
1927 }
1928
1929 static float nsvg__vecang(float ux, float uy, float vx, float vy)
1930 {
1931         float r = nsvg__vecrat(ux,uy, vx,vy);
1932         if (r < -1.0f) r = -1.0f;
1933         if (r > 1.0f) r = 1.0f;
1934         return ((ux*vy < uy*vx) ? -1.0f : 1.0f) * acosf(r);
1935 }
1936
1937 static void nsvg__pathArcTo(NSVGparser* p, float* cpx, float* cpy, float* args, int rel)
1938 {
1939         // Ported from canvg (https://code.google.com/p/canvg/)
1940         float rx, ry, rotx;
1941         float x1, y1, x2, y2, cx, cy, dx, dy, d;
1942         float x1p, y1p, cxp, cyp, s, sa, sb;
1943         float ux, uy, vx, vy, a1, da;
1944         float x, y, tanx, tany, a, px = 0, py = 0, ptanx = 0, ptany = 0, t[6];
1945         float sinrx, cosrx;
1946         int fa, fs;
1947         int i, ndivs;
1948         float hda, kappa;
1949
1950         rx = fabsf(args[0]);                            // y radius
1951         ry = fabsf(args[1]);                            // x radius
1952         rotx = args[2] / 180.0f * NSVG_PI;              // x rotation angle
1953         fa = fabsf(args[3]) > 1e-6 ? 1 : 0;     // Large arc
1954         fs = fabsf(args[4]) > 1e-6 ? 1 : 0;     // Sweep direction
1955         x1 = *cpx;                                                      // start point
1956         y1 = *cpy;
1957         if (rel) {                                                      // end point
1958                 x2 = *cpx + args[5];
1959                 y2 = *cpy + args[6];
1960         } else {
1961                 x2 = args[5];
1962                 y2 = args[6];
1963         }
1964
1965         dx = x1 - x2;
1966         dy = y1 - y2;
1967         d = sqrtf(dx*dx + dy*dy);
1968         if (d < 1e-6f || rx < 1e-6f || ry < 1e-6f) {
1969                 // The arc degenerates to a line
1970                 nsvg__lineTo(p, x2, y2);
1971                 *cpx = x2;
1972                 *cpy = y2;
1973                 return;
1974         }
1975
1976         sinrx = sinf(rotx);
1977         cosrx = cosf(rotx);
1978
1979         // Convert to center point parameterization.
1980         // http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes
1981         // 1) Compute x1', y1'
1982         x1p = cosrx * dx / 2.0f + sinrx * dy / 2.0f;
1983         y1p = -sinrx * dx / 2.0f + cosrx * dy / 2.0f;
1984         d = nsvg__sqr(x1p)/nsvg__sqr(rx) + nsvg__sqr(y1p)/nsvg__sqr(ry);
1985         if (d > 1) {
1986                 d = sqrtf(d);
1987                 rx *= d;
1988                 ry *= d;
1989         }
1990         // 2) Compute cx', cy'
1991         s = 0.0f;
1992         sa = nsvg__sqr(rx)*nsvg__sqr(ry) - nsvg__sqr(rx)*nsvg__sqr(y1p) - nsvg__sqr(ry)*nsvg__sqr(x1p);
1993         sb = nsvg__sqr(rx)*nsvg__sqr(y1p) + nsvg__sqr(ry)*nsvg__sqr(x1p);
1994         if (sa < 0.0f) sa = 0.0f;
1995         if (sb > 0.0f)
1996                 s = sqrtf(sa / sb);
1997         if (fa == fs)
1998                 s = -s;
1999         cxp = s * rx * y1p / ry;
2000         cyp = s * -ry * x1p / rx;
2001
2002         // 3) Compute cx,cy from cx',cy'
2003         cx = (x1 + x2)/2.0f + cosrx*cxp - sinrx*cyp;
2004         cy = (y1 + y2)/2.0f + sinrx*cxp + cosrx*cyp;
2005
2006         // 4) Calculate theta1, and delta theta.
2007         ux = (x1p - cxp) / rx;
2008         uy = (y1p - cyp) / ry;
2009         vx = (-x1p - cxp) / rx;
2010         vy = (-y1p - cyp) / ry;
2011         a1 = nsvg__vecang(1.0f,0.0f, ux,uy);    // Initial angle
2012         da = nsvg__vecang(ux,uy, vx,vy);                // Delta angle
2013
2014 //      if (vecrat(ux,uy,vx,vy) <= -1.0f) da = NSVG_PI;
2015 //      if (vecrat(ux,uy,vx,vy) >= 1.0f) da = 0;
2016
2017         if (fs == 0 && da > 0)
2018                 da -= 2 * NSVG_PI;
2019         else if (fs == 1 && da < 0)
2020                 da += 2 * NSVG_PI;
2021
2022         // Approximate the arc using cubic spline segments.
2023         t[0] = cosrx; t[1] = sinrx;
2024         t[2] = -sinrx; t[3] = cosrx;
2025         t[4] = cx; t[5] = cy;
2026
2027         // Split arc into max 90 degree segments.
2028         // The loop assumes an iteration per end point (including start and end), this +1.
2029         ndivs = (int)(fabsf(da) / (NSVG_PI*0.5f) + 1.0f);
2030         hda = (da / (float)ndivs) / 2.0f;
2031         kappa = fabsf(4.0f / 3.0f * (1.0f - cosf(hda)) / sinf(hda));
2032         if (da < 0.0f)
2033                 kappa = -kappa;
2034
2035         for (i = 0; i <= ndivs; i++) {
2036                 a = a1 + da * ((float)i/(float)ndivs);
2037                 dx = cosf(a);
2038                 dy = sinf(a);
2039                 nsvg__xformPoint(&x, &y, dx*rx, dy*ry, t); // position
2040                 nsvg__xformVec(&tanx, &tany, -dy*rx * kappa, dx*ry * kappa, t); // tangent
2041                 if (i > 0)
2042                         nsvg__cubicBezTo(p, px+ptanx,py+ptany, x-tanx, y-tany, x, y);
2043                 px = x;
2044                 py = y;
2045                 ptanx = tanx;
2046                 ptany = tany;
2047         }
2048
2049         *cpx = x2;
2050         *cpy = y2;
2051 }
2052
2053 static void nsvg__parsePath(NSVGparser* p, const char** attr)
2054 {
2055         const char* s = NULL;
2056         char cmd = '\0';
2057         float args[10];
2058         int nargs;
2059         int rargs = 0;
2060         float cpx, cpy, cpx2, cpy2;
2061         const char* tmp[4];
2062         char closedFlag;
2063         int i;
2064         char item[64];
2065
2066         for (i = 0; attr[i]; i += 2) {
2067                 if (strcmp(attr[i], "d") == 0) {
2068                         s = attr[i + 1];
2069                 } else {
2070                         tmp[0] = attr[i];
2071                         tmp[1] = attr[i + 1];
2072                         tmp[2] = 0;
2073                         tmp[3] = 0;
2074                         nsvg__parseAttribs(p, tmp);
2075                 }
2076         }
2077
2078         if (s) {
2079                 nsvg__resetPath(p);
2080                 cpx = 0; cpy = 0;
2081                 cpx2 = 0; cpy2 = 0;
2082                 closedFlag = 0;
2083                 nargs = 0;
2084
2085                 while (*s) {
2086                         s = nsvg__getNextPathItem(s, item);
2087                         if (!*item) break;
2088                         if (nsvg__isnum(item[0])) {
2089                                 if (nargs < 10)
2090                                         args[nargs++] = (float)nsvg__atof(item);
2091                                 if (nargs >= rargs) {
2092                                         switch (cmd) {
2093                                                 case 'm':
2094                                                 case 'M':
2095                                                         nsvg__pathMoveTo(p, &cpx, &cpy, args, cmd == 'm' ? 1 : 0);
2096                                                         // Moveto can be followed by multiple coordinate pairs,
2097                                                         // which should be treated as linetos.
2098                                                         cmd = (cmd == 'm') ? 'l' : 'L';
2099                                                         rargs = nsvg__getArgsPerElement(cmd);
2100                                                         cpx2 = cpx; cpy2 = cpy;
2101                                                         break;
2102                                                 case 'l':
2103                                                 case 'L':
2104                                                         nsvg__pathLineTo(p, &cpx, &cpy, args, cmd == 'l' ? 1 : 0);
2105                                                         cpx2 = cpx; cpy2 = cpy;
2106                                                         break;
2107                                                 case 'H':
2108                                                 case 'h':
2109                                                         nsvg__pathHLineTo(p, &cpx, &cpy, args, cmd == 'h' ? 1 : 0);
2110                                                         cpx2 = cpx; cpy2 = cpy;
2111                                                         break;
2112                                                 case 'V':
2113                                                 case 'v':
2114                                                         nsvg__pathVLineTo(p, &cpx, &cpy, args, cmd == 'v' ? 1 : 0);
2115                                                         cpx2 = cpx; cpy2 = cpy;
2116                                                         break;
2117                                                 case 'C':
2118                                                 case 'c':
2119                                                         nsvg__pathCubicBezTo(p, &cpx, &cpy, &cpx2, &cpy2, args, cmd == 'c' ? 1 : 0);
2120                                                         break;
2121                                                 case 'S':
2122                                                 case 's':
2123                                                         nsvg__pathCubicBezShortTo(p, &cpx, &cpy, &cpx2, &cpy2, args, cmd == 's' ? 1 : 0);
2124                                                         break;
2125                                                 case 'Q':
2126                                                 case 'q':
2127                                                         nsvg__pathQuadBezTo(p, &cpx, &cpy, &cpx2, &cpy2, args, cmd == 'q' ? 1 : 0);
2128                                                         break;
2129                                                 case 'T':
2130                                                 case 't':
2131                                                         nsvg__pathQuadBezShortTo(p, &cpx, &cpy, &cpx2, &cpy2, args, cmd == 't' ? 1 : 0);
2132                                                         break;
2133                                                 case 'A':
2134                                                 case 'a':
2135                                                         nsvg__pathArcTo(p, &cpx, &cpy, args, cmd == 'a' ? 1 : 0);
2136                                                         cpx2 = cpx; cpy2 = cpy;
2137                                                         break;
2138                                                 default:
2139                                                         if (nargs >= 2) {
2140                                                                 cpx = args[nargs-2];
2141                                                                 cpy = args[nargs-1];
2142                                                                 cpx2 = cpx; cpy2 = cpy;
2143                                                         }
2144                                                         break;
2145                                         }
2146                                         nargs = 0;
2147                                 }
2148                         } else {
2149                                 cmd = item[0];
2150                                 rargs = nsvg__getArgsPerElement(cmd);
2151                                 if (cmd == 'M' || cmd == 'm') {
2152                                         // Commit path.
2153                                         if (p->npts > 0)
2154                                                 nsvg__addPath(p, closedFlag);
2155                                         // Start new subpath.
2156                                         nsvg__resetPath(p);
2157                                         closedFlag = 0;
2158                                         nargs = 0;
2159                                 } else if (cmd == 'Z' || cmd == 'z') {
2160                                         closedFlag = 1;
2161                                         // Commit path.
2162                                         if (p->npts > 0) {
2163                                                 // Move current point to first point
2164                                                 cpx = p->pts[0];
2165                                                 cpy = p->pts[1];
2166                                                 cpx2 = cpx; cpy2 = cpy;
2167                                                 nsvg__addPath(p, closedFlag);
2168                                         }
2169                                         // Start new subpath.
2170                                         nsvg__resetPath(p);
2171                                         nsvg__moveTo(p, cpx, cpy);
2172                                         closedFlag = 0;
2173                                         nargs = 0;
2174                                 }
2175                         }
2176                 }
2177                 // Commit path.
2178                 if (p->npts)
2179                         nsvg__addPath(p, closedFlag);
2180         }
2181
2182         nsvg__addShape(p);
2183 }
2184
2185 static void nsvg__parseRect(NSVGparser* p, const char** attr)
2186 {
2187         float x = 0.0f;
2188         float y = 0.0f;
2189         float w = 0.0f;
2190         float h = 0.0f;
2191         float rx = -1.0f; // marks not set
2192         float ry = -1.0f;
2193         int i;
2194
2195         for (i = 0; attr[i]; i += 2) {
2196                 if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) {
2197                         if (strcmp(attr[i], "x") == 0) x = nsvg__parseCoordinate(p, attr[i+1], nsvg__actualOrigX(p), nsvg__actualWidth(p));
2198                         if (strcmp(attr[i], "y") == 0) y = nsvg__parseCoordinate(p, attr[i+1], nsvg__actualOrigY(p), nsvg__actualHeight(p));
2199                         if (strcmp(attr[i], "width") == 0) w = nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualWidth(p));
2200                         if (strcmp(attr[i], "height") == 0) h = nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualHeight(p));
2201                         if (strcmp(attr[i], "rx") == 0) rx = fabsf(nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualWidth(p)));
2202                         if (strcmp(attr[i], "ry") == 0) ry = fabsf(nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualHeight(p)));
2203                 }
2204         }
2205
2206         if (rx < 0.0f && ry > 0.0f) rx = ry;
2207         if (ry < 0.0f && rx > 0.0f) ry = rx;
2208         if (rx < 0.0f) rx = 0.0f;
2209         if (ry < 0.0f) ry = 0.0f;
2210         if (rx > w/2.0f) rx = w/2.0f;
2211         if (ry > h/2.0f) ry = h/2.0f;
2212
2213         if (w != 0.0f && h != 0.0f) {
2214                 nsvg__resetPath(p);
2215
2216                 if (rx < 0.00001f || ry < 0.0001f) {
2217                         nsvg__moveTo(p, x, y);
2218                         nsvg__lineTo(p, x+w, y);
2219                         nsvg__lineTo(p, x+w, y+h);
2220                         nsvg__lineTo(p, x, y+h);
2221                 } else {
2222                         // Rounded rectangle
2223                         nsvg__moveTo(p, x+rx, y);
2224                         nsvg__lineTo(p, x+w-rx, y);
2225                         nsvg__cubicBezTo(p, x+w-rx*(1-NSVG_KAPPA90), y, x+w, y+ry*(1-NSVG_KAPPA90), x+w, y+ry);
2226                         nsvg__lineTo(p, x+w, y+h-ry);
2227                         nsvg__cubicBezTo(p, x+w, y+h-ry*(1-NSVG_KAPPA90), x+w-rx*(1-NSVG_KAPPA90), y+h, x+w-rx, y+h);
2228                         nsvg__lineTo(p, x+rx, y+h);
2229                         nsvg__cubicBezTo(p, x+rx*(1-NSVG_KAPPA90), y+h, x, y+h-ry*(1-NSVG_KAPPA90), x, y+h-ry);
2230                         nsvg__lineTo(p, x, y+ry);
2231                         nsvg__cubicBezTo(p, x, y+ry*(1-NSVG_KAPPA90), x+rx*(1-NSVG_KAPPA90), y, x+rx, y);
2232                 }
2233
2234                 nsvg__addPath(p, 1);
2235
2236                 nsvg__addShape(p);
2237         }
2238 }
2239
2240 static void nsvg__parseCircle(NSVGparser* p, const char** attr)
2241 {
2242         float cx = 0.0f;
2243         float cy = 0.0f;
2244         float r = 0.0f;
2245         int i;
2246
2247         for (i = 0; attr[i]; i += 2) {
2248                 if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) {
2249                         if (strcmp(attr[i], "cx") == 0) cx = nsvg__parseCoordinate(p, attr[i+1], nsvg__actualOrigX(p), nsvg__actualWidth(p));
2250                         if (strcmp(attr[i], "cy") == 0) cy = nsvg__parseCoordinate(p, attr[i+1], nsvg__actualOrigY(p), nsvg__actualHeight(p));
2251                         if (strcmp(attr[i], "r") == 0) r = fabsf(nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualLength(p)));
2252                 }
2253         }
2254
2255         if (r > 0.0f) {
2256                 nsvg__resetPath(p);
2257
2258                 nsvg__moveTo(p, cx+r, cy);
2259                 nsvg__cubicBezTo(p, cx+r, cy+r*NSVG_KAPPA90, cx+r*NSVG_KAPPA90, cy+r, cx, cy+r);
2260                 nsvg__cubicBezTo(p, cx-r*NSVG_KAPPA90, cy+r, cx-r, cy+r*NSVG_KAPPA90, cx-r, cy);
2261                 nsvg__cubicBezTo(p, cx-r, cy-r*NSVG_KAPPA90, cx-r*NSVG_KAPPA90, cy-r, cx, cy-r);
2262                 nsvg__cubicBezTo(p, cx+r*NSVG_KAPPA90, cy-r, cx+r, cy-r*NSVG_KAPPA90, cx+r, cy);
2263
2264                 nsvg__addPath(p, 1);
2265
2266                 nsvg__addShape(p);
2267         }
2268 }
2269
2270 static void nsvg__parseEllipse(NSVGparser* p, const char** attr)
2271 {
2272         float cx = 0.0f;
2273         float cy = 0.0f;
2274         float rx = 0.0f;
2275         float ry = 0.0f;
2276         int i;
2277
2278         for (i = 0; attr[i]; i += 2) {
2279                 if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) {
2280                         if (strcmp(attr[i], "cx") == 0) cx = nsvg__parseCoordinate(p, attr[i+1], nsvg__actualOrigX(p), nsvg__actualWidth(p));
2281                         if (strcmp(attr[i], "cy") == 0) cy = nsvg__parseCoordinate(p, attr[i+1], nsvg__actualOrigY(p), nsvg__actualHeight(p));
2282                         if (strcmp(attr[i], "rx") == 0) rx = fabsf(nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualWidth(p)));
2283                         if (strcmp(attr[i], "ry") == 0) ry = fabsf(nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualHeight(p)));
2284                 }
2285         }
2286
2287         if (rx > 0.0f && ry > 0.0f) {
2288
2289                 nsvg__resetPath(p);
2290
2291                 nsvg__moveTo(p, cx+rx, cy);
2292                 nsvg__cubicBezTo(p, cx+rx, cy+ry*NSVG_KAPPA90, cx+rx*NSVG_KAPPA90, cy+ry, cx, cy+ry);
2293                 nsvg__cubicBezTo(p, cx-rx*NSVG_KAPPA90, cy+ry, cx-rx, cy+ry*NSVG_KAPPA90, cx-rx, cy);
2294                 nsvg__cubicBezTo(p, cx-rx, cy-ry*NSVG_KAPPA90, cx-rx*NSVG_KAPPA90, cy-ry, cx, cy-ry);
2295                 nsvg__cubicBezTo(p, cx+rx*NSVG_KAPPA90, cy-ry, cx+rx, cy-ry*NSVG_KAPPA90, cx+rx, cy);
2296
2297                 nsvg__addPath(p, 1);
2298
2299                 nsvg__addShape(p);
2300         }
2301 }
2302
2303 static void nsvg__parseLine(NSVGparser* p, const char** attr)
2304 {
2305         float x1 = 0.0;
2306         float y1 = 0.0;
2307         float x2 = 0.0;
2308         float y2 = 0.0;
2309         int i;
2310
2311         for (i = 0; attr[i]; i += 2) {
2312                 if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) {
2313                         if (strcmp(attr[i], "x1") == 0) x1 = nsvg__parseCoordinate(p, attr[i + 1], nsvg__actualOrigX(p), nsvg__actualWidth(p));
2314                         if (strcmp(attr[i], "y1") == 0) y1 = nsvg__parseCoordinate(p, attr[i + 1], nsvg__actualOrigY(p), nsvg__actualHeight(p));
2315                         if (strcmp(attr[i], "x2") == 0) x2 = nsvg__parseCoordinate(p, attr[i + 1], nsvg__actualOrigX(p), nsvg__actualWidth(p));
2316                         if (strcmp(attr[i], "y2") == 0) y2 = nsvg__parseCoordinate(p, attr[i + 1], nsvg__actualOrigY(p), nsvg__actualHeight(p));
2317                 }
2318         }
2319
2320         nsvg__resetPath(p);
2321
2322         nsvg__moveTo(p, x1, y1);
2323         nsvg__lineTo(p, x2, y2);
2324
2325         nsvg__addPath(p, 0);
2326
2327         nsvg__addShape(p);
2328 }
2329
2330 static void nsvg__parsePoly(NSVGparser* p, const char** attr, int closeFlag)
2331 {
2332         int i;
2333         const char* s;
2334         float args[2];
2335         int nargs, npts = 0;
2336         char item[64];
2337
2338         nsvg__resetPath(p);
2339
2340         for (i = 0; attr[i]; i += 2) {
2341                 if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) {
2342                         if (strcmp(attr[i], "points") == 0) {
2343                                 s = attr[i + 1];
2344                                 nargs = 0;
2345                                 while (*s) {
2346                                         s = nsvg__getNextPathItem(s, item);
2347                                         args[nargs++] = (float)nsvg__atof(item);
2348                                         if (nargs >= 2) {
2349                                                 if (npts == 0)
2350                                                         nsvg__moveTo(p, args[0], args[1]);
2351                                                 else
2352                                                         nsvg__lineTo(p, args[0], args[1]);
2353                                                 nargs = 0;
2354                                                 npts++;
2355                                         }
2356                                 }
2357                         }
2358                 }
2359         }
2360
2361         nsvg__addPath(p, (char)closeFlag);
2362
2363         nsvg__addShape(p);
2364 }
2365
2366 static void nsvg__parseSVG(NSVGparser* p, const char** attr)
2367 {
2368         int i;
2369         for (i = 0; attr[i]; i += 2) {
2370                 if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) {
2371                         if (strcmp(attr[i], "width") == 0) {
2372                                 p->image->width = nsvg__parseCoordinate(p, attr[i + 1], 0.0f, 0.0f);
2373                         } else if (strcmp(attr[i], "height") == 0) {
2374                                 p->image->height = nsvg__parseCoordinate(p, attr[i + 1], 0.0f, 0.0f);
2375                         } else if (strcmp(attr[i], "viewBox") == 0) {
2376                                 const char *s = attr[i + 1];
2377                                 char buf[64];
2378                                 s = nsvg__parseNumber(s, buf, 64);
2379                                 p->viewMinx = nsvg__atof(buf);
2380                                 while (*s && (nsvg__isspace(*s) || *s == '%' || *s == ',')) s++;
2381                                 if (!*s) return;
2382                                 s = nsvg__parseNumber(s, buf, 64);
2383                                 p->viewMiny = nsvg__atof(buf);
2384                                 while (*s && (nsvg__isspace(*s) || *s == '%' || *s == ',')) s++;
2385                                 if (!*s) return;
2386                                 s = nsvg__parseNumber(s, buf, 64);
2387                                 p->viewWidth = nsvg__atof(buf);
2388                                 while (*s && (nsvg__isspace(*s) || *s == '%' || *s == ',')) s++;
2389                                 if (!*s) return;
2390                                 s = nsvg__parseNumber(s, buf, 64);
2391                                 p->viewHeight = nsvg__atof(buf);
2392                         } else if (strcmp(attr[i], "preserveAspectRatio") == 0) {
2393                                 if (strstr(attr[i + 1], "none") != 0) {
2394                                         // No uniform scaling
2395                                         p->alignType = NSVG_ALIGN_NONE;
2396                                 } else {
2397                                         // Parse X align
2398                                         if (strstr(attr[i + 1], "xMin") != 0)
2399                                                 p->alignX = NSVG_ALIGN_MIN;
2400                                         else if (strstr(attr[i + 1], "xMid") != 0)
2401                                                 p->alignX = NSVG_ALIGN_MID;
2402                                         else if (strstr(attr[i + 1], "xMax") != 0)
2403                                                 p->alignX = NSVG_ALIGN_MAX;
2404                                         // Parse X align
2405                                         if (strstr(attr[i + 1], "yMin") != 0)
2406                                                 p->alignY = NSVG_ALIGN_MIN;
2407                                         else if (strstr(attr[i + 1], "yMid") != 0)
2408                                                 p->alignY = NSVG_ALIGN_MID;
2409                                         else if (strstr(attr[i + 1], "yMax") != 0)
2410                                                 p->alignY = NSVG_ALIGN_MAX;
2411                                         // Parse meet/slice
2412                                         p->alignType = NSVG_ALIGN_MEET;
2413                                         if (strstr(attr[i + 1], "slice") != 0)
2414                                                 p->alignType = NSVG_ALIGN_SLICE;
2415                                 }
2416                         }
2417                 }
2418         }
2419 }
2420
2421 static void nsvg__parseGradient(NSVGparser* p, const char** attr, char type)
2422 {
2423         int i;
2424         NSVGgradientData* grad = (NSVGgradientData*)malloc(sizeof(NSVGgradientData));
2425         if (grad == NULL) return;
2426         memset(grad, 0, sizeof(NSVGgradientData));
2427         grad->units = NSVG_OBJECT_SPACE;
2428         grad->type = type;
2429         if (grad->type == NSVG_PAINT_LINEAR_GRADIENT) {
2430                 grad->linear.x1 = nsvg__coord(0.0f, NSVG_UNITS_PERCENT);
2431                 grad->linear.y1 = nsvg__coord(0.0f, NSVG_UNITS_PERCENT);
2432                 grad->linear.x2 = nsvg__coord(100.0f, NSVG_UNITS_PERCENT);
2433                 grad->linear.y2 = nsvg__coord(0.0f, NSVG_UNITS_PERCENT);
2434         } else if (grad->type == NSVG_PAINT_RADIAL_GRADIENT) {
2435                 grad->radial.cx = nsvg__coord(50.0f, NSVG_UNITS_PERCENT);
2436                 grad->radial.cy = nsvg__coord(50.0f, NSVG_UNITS_PERCENT);
2437                 grad->radial.r = nsvg__coord(50.0f, NSVG_UNITS_PERCENT);
2438         }
2439
2440         nsvg__xformIdentity(grad->xform);
2441
2442         for (i = 0; attr[i]; i += 2) {
2443                 if (strcmp(attr[i], "id") == 0) {
2444                         strncpy(grad->id, attr[i+1], 63);
2445                         grad->id[63] = '\0';
2446                 } else if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) {
2447                         if (strcmp(attr[i], "gradientUnits") == 0) {
2448                                 if (strcmp(attr[i+1], "objectBoundingBox") == 0)
2449                                         grad->units = NSVG_OBJECT_SPACE;
2450                                 else
2451                                         grad->units = NSVG_USER_SPACE;
2452                         } else if (strcmp(attr[i], "gradientTransform") == 0) {
2453                                 nsvg__parseTransform(grad->xform, attr[i + 1]);
2454                         } else if (strcmp(attr[i], "cx") == 0) {
2455                                 grad->radial.cx = nsvg__parseCoordinateRaw(attr[i + 1]);
2456                         } else if (strcmp(attr[i], "cy") == 0) {
2457                                 grad->radial.cy = nsvg__parseCoordinateRaw(attr[i + 1]);
2458                         } else if (strcmp(attr[i], "r") == 0) {
2459                                 grad->radial.r = nsvg__parseCoordinateRaw(attr[i + 1]);
2460                         } else if (strcmp(attr[i], "fx") == 0) {
2461                                 grad->radial.fx = nsvg__parseCoordinateRaw(attr[i + 1]);
2462                         } else if (strcmp(attr[i], "fy") == 0) {
2463                                 grad->radial.fy = nsvg__parseCoordinateRaw(attr[i + 1]);
2464                         } else if (strcmp(attr[i], "x1") == 0) {
2465                                 grad->linear.x1 = nsvg__parseCoordinateRaw(attr[i + 1]);
2466                         } else if (strcmp(attr[i], "y1") == 0) {
2467                                 grad->linear.y1 = nsvg__parseCoordinateRaw(attr[i + 1]);
2468                         } else if (strcmp(attr[i], "x2") == 0) {
2469                                 grad->linear.x2 = nsvg__parseCoordinateRaw(attr[i + 1]);
2470                         } else if (strcmp(attr[i], "y2") == 0) {
2471                                 grad->linear.y2 = nsvg__parseCoordinateRaw(attr[i + 1]);
2472                         } else if (strcmp(attr[i], "spreadMethod") == 0) {
2473                                 if (strcmp(attr[i+1], "pad") == 0)
2474                                         grad->spread = NSVG_SPREAD_PAD;
2475                                 else if (strcmp(attr[i+1], "reflect") == 0)
2476                                         grad->spread = NSVG_SPREAD_REFLECT;
2477                                 else if (strcmp(attr[i+1], "repeat") == 0)
2478                                         grad->spread = NSVG_SPREAD_REPEAT;
2479                         } else if (strcmp(attr[i], "xlink:href") == 0) {
2480                                 const char *href = attr[i+1];
2481                                 strncpy(grad->ref, href+1, 62);
2482                                 grad->ref[62] = '\0';
2483                         }
2484                 }
2485         }
2486
2487         grad->next = p->gradients;
2488         p->gradients = grad;
2489 }
2490
2491 static void nsvg__parseGradientStop(NSVGparser* p, const char** attr)
2492 {
2493         NSVGattrib* curAttr = nsvg__getAttr(p);
2494         NSVGgradientData* grad;
2495         NSVGgradientStop* stop;
2496         int i, idx;
2497
2498         curAttr->stopOffset = 0;
2499         curAttr->stopColor = 0;
2500         curAttr->stopOpacity = 1.0f;
2501
2502         for (i = 0; attr[i]; i += 2) {
2503                 nsvg__parseAttr(p, attr[i], attr[i + 1]);
2504         }
2505
2506         // Add stop to the last gradient.
2507         grad = p->gradients;
2508         if (grad == NULL) return;
2509
2510         grad->nstops++;
2511         grad->stops = (NSVGgradientStop*)realloc(grad->stops, sizeof(NSVGgradientStop)*grad->nstops);
2512         if (grad->stops == NULL) return;
2513
2514         // Insert
2515         idx = grad->nstops-1;
2516         for (i = 0; i < grad->nstops-1; i++) {
2517                 if (curAttr->stopOffset < grad->stops[i].offset) {
2518                         idx = i;
2519                         break;
2520                 }
2521         }
2522         if (idx != grad->nstops-1) {
2523                 for (i = grad->nstops-1; i > idx; i--)
2524                         grad->stops[i] = grad->stops[i-1];
2525         }
2526
2527         stop = &grad->stops[idx];
2528         stop->color = curAttr->stopColor;
2529         stop->color |= (unsigned int)(curAttr->stopOpacity*255) << 24;
2530         stop->offset = curAttr->stopOffset;
2531 }
2532
2533 static void nsvg__startElement(void* ud, const char* el, const char** attr)
2534 {
2535         NSVGparser* p = (NSVGparser*)ud;
2536
2537         if (p->defsFlag) {
2538                 // Skip everything but gradients in defs
2539                 if (strcmp(el, "linearGradient") == 0) {
2540                         nsvg__parseGradient(p, attr, NSVG_PAINT_LINEAR_GRADIENT);
2541                 } else if (strcmp(el, "radialGradient") == 0) {
2542                         nsvg__parseGradient(p, attr, NSVG_PAINT_RADIAL_GRADIENT);
2543                 } else if (strcmp(el, "stop") == 0) {
2544                         nsvg__parseGradientStop(p, attr);
2545                 }
2546                 return;
2547         }
2548
2549         if (strcmp(el, "g") == 0) {
2550                 nsvg__pushAttr(p);
2551                 nsvg__parseAttribs(p, attr);
2552         } else if (strcmp(el, "path") == 0) {
2553                 if (p->pathFlag)        // Do not allow nested paths.
2554                         return;
2555                 nsvg__pushAttr(p);
2556                 nsvg__parsePath(p, attr);
2557                 nsvg__popAttr(p);
2558         } else if (strcmp(el, "rect") == 0) {
2559                 nsvg__pushAttr(p);
2560                 nsvg__parseRect(p, attr);
2561                 nsvg__popAttr(p);
2562         } else if (strcmp(el, "circle") == 0) {
2563                 nsvg__pushAttr(p);
2564                 nsvg__parseCircle(p, attr);
2565                 nsvg__popAttr(p);
2566         } else if (strcmp(el, "ellipse") == 0) {
2567                 nsvg__pushAttr(p);
2568                 nsvg__parseEllipse(p, attr);
2569                 nsvg__popAttr(p);
2570         } else if (strcmp(el, "line") == 0)  {
2571                 nsvg__pushAttr(p);
2572                 nsvg__parseLine(p, attr);
2573                 nsvg__popAttr(p);
2574         } else if (strcmp(el, "polyline") == 0)  {
2575                 nsvg__pushAttr(p);
2576                 nsvg__parsePoly(p, attr, 0);
2577                 nsvg__popAttr(p);
2578         } else if (strcmp(el, "polygon") == 0)  {
2579                 nsvg__pushAttr(p);
2580                 nsvg__parsePoly(p, attr, 1);
2581                 nsvg__popAttr(p);
2582         } else  if (strcmp(el, "linearGradient") == 0) {
2583                 nsvg__parseGradient(p, attr, NSVG_PAINT_LINEAR_GRADIENT);
2584         } else if (strcmp(el, "radialGradient") == 0) {
2585                 nsvg__parseGradient(p, attr, NSVG_PAINT_RADIAL_GRADIENT);
2586         } else if (strcmp(el, "stop") == 0) {
2587                 nsvg__parseGradientStop(p, attr);
2588         } else if (strcmp(el, "defs") == 0) {
2589                 p->defsFlag = 1;
2590         } else if (strcmp(el, "svg") == 0) {
2591                 nsvg__parseSVG(p, attr);
2592         }
2593 }
2594
2595 static void nsvg__endElement(void* ud, const char* el)
2596 {
2597         NSVGparser* p = (NSVGparser*)ud;
2598
2599         if (strcmp(el, "g") == 0) {
2600                 nsvg__popAttr(p);
2601         } else if (strcmp(el, "path") == 0) {
2602                 p->pathFlag = 0;
2603         } else if (strcmp(el, "defs") == 0) {
2604                 p->defsFlag = 0;
2605         }
2606 }
2607
2608 static void nsvg__content(void* ud, const char* s)
2609 {
2610         NSVG_NOTUSED(ud);
2611         NSVG_NOTUSED(s);
2612         // empty
2613 }
2614
2615 static void nsvg__imageBounds(NSVGparser* p, float* bounds)
2616 {
2617         NSVGshape* shape;
2618         shape = p->image->shapes;
2619         if (shape == NULL) {
2620                 bounds[0] = bounds[1] = bounds[2] = bounds[3] = 0.0;
2621                 return;
2622         }
2623         bounds[0] = shape->bounds[0];
2624         bounds[1] = shape->bounds[1];
2625         bounds[2] = shape->bounds[2];
2626         bounds[3] = shape->bounds[3];
2627         for (shape = shape->next; shape != NULL; shape = shape->next) {
2628                 bounds[0] = nsvg__minf(bounds[0], shape->bounds[0]);
2629                 bounds[1] = nsvg__minf(bounds[1], shape->bounds[1]);
2630                 bounds[2] = nsvg__maxf(bounds[2], shape->bounds[2]);
2631                 bounds[3] = nsvg__maxf(bounds[3], shape->bounds[3]);
2632         }
2633 }
2634
2635 static float nsvg__viewAlign(float content, float container, int type)
2636 {
2637         if (type == NSVG_ALIGN_MIN)
2638                 return 0;
2639         else if (type == NSVG_ALIGN_MAX)
2640                 return container - content;
2641         // mid
2642         return (container - content) * 0.5f;
2643 }
2644
2645 static void nsvg__scaleGradient(NSVGgradient* grad, float tx, float ty, float sx, float sy)
2646 {
2647         float t[6];
2648         nsvg__xformSetTranslation(t, tx, ty);
2649         nsvg__xformMultiply (grad->xform, t);
2650
2651         nsvg__xformSetScale(t, sx, sy);
2652         nsvg__xformMultiply (grad->xform, t);
2653 }
2654
2655 static void nsvg__scaleToViewbox(NSVGparser* p, const char* units)
2656 {
2657         NSVGshape* shape;
2658         NSVGpath* path;
2659         float tx, ty, sx, sy, us, bounds[4], t[6], avgs;
2660         int i;
2661         float* pt;
2662
2663         // Guess image size if not set completely.
2664         nsvg__imageBounds(p, bounds);
2665
2666         if (p->viewWidth == 0) {
2667                 if (p->image->width > 0) {
2668                         p->viewWidth = p->image->width;
2669                 } else {
2670                         p->viewMinx = bounds[0];
2671                         p->viewWidth = bounds[2] - bounds[0];
2672                 }
2673         }
2674         if (p->viewHeight == 0) {
2675                 if (p->image->height > 0) {
2676                         p->viewHeight = p->image->height;
2677                 } else {
2678                         p->viewMiny = bounds[1];
2679                         p->viewHeight = bounds[3] - bounds[1];
2680                 }
2681         }
2682
2683         /**
2684          * We have sample images with the width and height set to 1, whereas the viewbox aspect ratio 
2685          * is not square. Use the viewbox in this case.
2686          */
2687         if (p->image->width <= 1)
2688                 p->image->width = p->viewWidth;
2689         if (p->image->height <= 1)
2690                 p->image->height = p->viewHeight;
2691
2692         tx = -p->viewMinx;
2693         ty = -p->viewMiny;
2694         sx = p->viewWidth > 0 ? p->image->width / p->viewWidth : 0;
2695         sy = p->viewHeight > 0 ? p->image->height / p->viewHeight : 0;
2696         // Unit scaling
2697         us = 1.0f / nsvg__convertToPixels(p, nsvg__coord(1.0f, nsvg__parseUnits(units)), 0.0f, 1.0f);
2698
2699         // Fix aspect ratio
2700         if (p->alignType == NSVG_ALIGN_MEET) {
2701                 // fit whole image into viewbox
2702                 sx = sy = nsvg__minf(sx, sy);
2703                 tx += nsvg__viewAlign(p->viewWidth*sx, p->image->width, p->alignX) / sx;
2704                 ty += nsvg__viewAlign(p->viewHeight*sy, p->image->height, p->alignY) / sy;
2705         } else if (p->alignType == NSVG_ALIGN_SLICE) {
2706                 // fill whole viewbox with image
2707                 sx = sy = nsvg__maxf(sx, sy);
2708                 tx += nsvg__viewAlign(p->viewWidth*sx, p->image->width, p->alignX) / sx;
2709                 ty += nsvg__viewAlign(p->viewHeight*sy, p->image->height, p->alignY) / sy;
2710         }
2711
2712         // Transform
2713         sx *= us;
2714         sy *= us;
2715         avgs = (sx+sy) / 2.0f;
2716         for (shape = p->image->shapes; shape != NULL; shape = shape->next) {
2717                 shape->bounds[0] = (shape->bounds[0] + tx) * sx;
2718                 shape->bounds[1] = (shape->bounds[1] + ty) * sy;
2719                 shape->bounds[2] = (shape->bounds[2] + tx) * sx;
2720                 shape->bounds[3] = (shape->bounds[3] + ty) * sy;
2721                 for (path = shape->paths; path != NULL; path = path->next) {
2722                         path->bounds[0] = (path->bounds[0] + tx) * sx;
2723                         path->bounds[1] = (path->bounds[1] + ty) * sy;
2724                         path->bounds[2] = (path->bounds[2] + tx) * sx;
2725                         path->bounds[3] = (path->bounds[3] + ty) * sy;
2726                         for (i =0; i < path->npts; i++) {
2727                                 pt = &path->pts[i*2];
2728                                 pt[0] = (pt[0] + tx) * sx;
2729                                 pt[1] = (pt[1] + ty) * sy;
2730                         }
2731                 }
2732
2733                 if (shape->fill.type == NSVG_PAINT_LINEAR_GRADIENT || shape->fill.type == NSVG_PAINT_RADIAL_GRADIENT) {
2734                         nsvg__scaleGradient(shape->fill.gradient, tx,ty, sx,sy);
2735                         memcpy(t, shape->fill.gradient->xform, sizeof(float)*6);
2736                         nsvg__xformInverse(shape->fill.gradient->xform, t);
2737                 }
2738                 if (shape->stroke.type == NSVG_PAINT_LINEAR_GRADIENT || shape->stroke.type == NSVG_PAINT_RADIAL_GRADIENT) {
2739                         nsvg__scaleGradient(shape->stroke.gradient, tx,ty, sx,sy);
2740                         memcpy(t, shape->stroke.gradient->xform, sizeof(float)*6);
2741                         nsvg__xformInverse(shape->stroke.gradient->xform, t);
2742                 }
2743
2744                 shape->strokeWidth *= avgs;
2745                 shape->strokeDashOffset *= avgs;
2746                 for (i = 0; i < shape->strokeDashCount; i++)
2747                         shape->strokeDashArray[i] *= avgs;
2748         }
2749 }
2750
2751 NSVGimage* nsvgParse(char* input, const char* units, float dpi)
2752 {
2753         NSVGparser* p;
2754         NSVGimage* ret = 0;
2755
2756         p = nsvg__createParser();
2757         if (p == NULL) {
2758                 return NULL;
2759         }
2760         p->dpi = dpi;
2761
2762         nsvg__parseXML(input, nsvg__startElement, nsvg__endElement, nsvg__content, p);
2763
2764         // Scale to viewBox
2765         nsvg__scaleToViewbox(p, units);
2766
2767         ret = p->image;
2768         p->image = NULL;
2769
2770         nsvg__deleteParser(p);
2771
2772         return ret;
2773 }
2774
2775 NSVGimage* nsvgParseFromFile(const char* filename, const char* units, float dpi)
2776 {
2777         FILE* fp = NULL;
2778         size_t size = 0;
2779         long value = 0;
2780         char* data = NULL;
2781         NSVGimage* image = NULL;
2782
2783         fp = fopen(filename, "rb");
2784         if (!fp) goto error;
2785         fseek(fp, 0, SEEK_END);
2786         value = ftell(fp);
2787         /**
2788          * In the original file, unsigned long type 'size' gets a return value. But, the return value of 'ftell()' is
2789          * signed long type. To prevent interpreting an unexpected large value, we put the comparitive condition here.
2790          */
2791         if( value < 0 ) goto error;
2792         size = value;
2793         fseek(fp, 0, SEEK_SET);
2794         data = (char*)malloc(size+1);
2795         if (data == NULL) goto error;
2796         if (fread(data, 1, size, fp) != size) goto error;
2797         data[size] = '\0';      // Must be null terminated.
2798         fclose(fp);
2799         image = nsvgParse(data, units, dpi);
2800         free(data);
2801
2802         return image;
2803
2804 error:
2805         if (fp) fclose(fp);
2806         if (data) free(data);
2807         if (image) nsvgDelete(image);
2808         return NULL;
2809 }
2810
2811 NSVGpath* nsvgDuplicatePath(NSVGpath* p)
2812 {
2813     NSVGpath* res = NULL;
2814
2815     if (p == NULL)
2816         return NULL;
2817
2818     res = (NSVGpath*)malloc(sizeof(NSVGpath));
2819     if (res == NULL) goto error;
2820     memset(res, 0, sizeof(NSVGpath));
2821
2822     res->pts = (float*)malloc(p->npts*2*sizeof(float));
2823     if (res->pts == NULL) goto error;
2824     memcpy(res->pts, p->pts, p->npts * sizeof(float) * 2);
2825     res->npts = p->npts;
2826
2827     memcpy(res->bounds, p->bounds, sizeof(p->bounds));
2828
2829     res->closed = p->closed;
2830
2831     return res;
2832
2833 error:
2834     if (res != NULL) {
2835         free(res->pts);
2836         free(res);
2837     }
2838     return NULL;
2839 }
2840
2841 void nsvgDelete(NSVGimage* image)
2842 {
2843         NSVGshape *snext, *shape;
2844         if (image == NULL) return;
2845         shape = image->shapes;
2846         while (shape != NULL) {
2847                 snext = shape->next;
2848                 nsvg__deletePaths(shape->paths);
2849                 nsvg__deletePaint(&shape->fill);
2850                 nsvg__deletePaint(&shape->stroke);
2851                 free(shape);
2852                 shape = snext;
2853         }
2854         free(image);
2855 }