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