nanosvg.h 81 KB

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