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