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