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