import-svg.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. #define _USE_MATH_DEFINES
  2. #define _CRT_SECURE_NO_WARNINGS
  3. #include "import-svg.h"
  4. #include <cstdio>
  5. #include <tinyxml2.h>
  6. #include "../core/arithmetics.hpp"
  7. #define ARC_SEGMENTS_PER_PI 2
  8. #define ENDPOINT_SNAP_RANGE_PROPORTION (1/16384.)
  9. namespace msdfgen {
  10. #if defined(_DEBUG) || !NDEBUG
  11. #define REQUIRE(cond) { if (!(cond)) { fprintf(stderr, "SVG Parse Error (%s:%d): " #cond "\n", __FILE__, __LINE__); return false; } }
  12. #else
  13. #define REQUIRE(cond) { if (!(cond)) return false; }
  14. #endif
  15. static void skipExtraChars(const char *&pathDef) {
  16. while (*pathDef == ',' || *pathDef == ' ' || *pathDef == '\t' || *pathDef == '\r' || *pathDef == '\n')
  17. ++pathDef;
  18. }
  19. static bool readNodeType(char &output, const char *&pathDef) {
  20. skipExtraChars(pathDef);
  21. char nodeType = *pathDef;
  22. if (nodeType && nodeType != '+' && nodeType != '-' && nodeType != '.' && nodeType != ',' && (nodeType < '0' || nodeType > '9')) {
  23. ++pathDef;
  24. output = nodeType;
  25. return true;
  26. }
  27. return false;
  28. }
  29. static bool readCoord(Point2 &output, const char *&pathDef) {
  30. skipExtraChars(pathDef);
  31. int shift;
  32. double x, y;
  33. if (sscanf(pathDef, "%lf%lf%n", &x, &y, &shift) == 2 || sscanf(pathDef, "%lf , %lf%n", &x, &y, &shift) == 2) {
  34. output.x = x;
  35. output.y = y;
  36. pathDef += shift;
  37. return true;
  38. }
  39. return false;
  40. }
  41. static bool readDouble(double &output, const char *&pathDef) {
  42. skipExtraChars(pathDef);
  43. int shift;
  44. double v;
  45. if (sscanf(pathDef, "%lf%n", &v, &shift) == 1) {
  46. pathDef += shift;
  47. output = v;
  48. return true;
  49. }
  50. return false;
  51. }
  52. static bool readBool(bool &output, const char *&pathDef) {
  53. skipExtraChars(pathDef);
  54. int shift;
  55. int v;
  56. if (sscanf(pathDef, "%d%n", &v, &shift) == 1) {
  57. pathDef += shift;
  58. output = v != 0;
  59. return true;
  60. }
  61. return false;
  62. }
  63. static double arcAngle(Vector2 u, Vector2 v) {
  64. return nonZeroSign(crossProduct(u, v))*acos(clamp(dotProduct(u, v)/(u.length()*v.length()), -1., +1.));
  65. }
  66. static Vector2 rotateVector(Vector2 v, Vector2 direction) {
  67. return Vector2(direction.x*v.x-direction.y*v.y, direction.y*v.x+direction.x*v.y);
  68. }
  69. static void addArcApproximate(Contour &contour, Point2 startPoint, Point2 endPoint, Vector2 radius, double rotation, bool largeArc, bool sweep) {
  70. if (endPoint == startPoint)
  71. return;
  72. if (radius.x == 0 || radius.y == 0)
  73. return contour.addEdge(new LinearSegment(startPoint, endPoint));
  74. radius.x = fabs(radius.x);
  75. radius.y = fabs(radius.y);
  76. Vector2 axis(cos(rotation), sin(rotation));
  77. Vector2 rm = rotateVector(.5*(startPoint-endPoint), Vector2(axis.x, -axis.y));
  78. Vector2 rm2 = rm*rm;
  79. Vector2 radius2 = radius*radius;
  80. double radiusGap = rm2.x/radius2.x+rm2.y/radius2.y;
  81. if (radiusGap > 1) {
  82. radius *= sqrt(radiusGap);
  83. radius2 = radius*radius;
  84. }
  85. double dq = (radius2.x*rm2.y+radius2.y*rm2.x);
  86. double pq = radius2.x*radius2.y/dq-1;
  87. double q = (largeArc == sweep ? -1 : +1)*sqrt(max(pq, 0.));
  88. Vector2 rc(q*radius.x*rm.y/radius.y, -q*radius.y*rm.x/radius.x);
  89. Point2 center = .5*(startPoint+endPoint)+rotateVector(rc, axis);
  90. double angleStart = arcAngle(Vector2(1, 0), (rm-rc)/radius);
  91. double angleExtent = arcAngle((rm-rc)/radius, (-rm-rc)/radius);
  92. if (!sweep && angleExtent > 0)
  93. angleExtent -= 2*M_PI;
  94. else if (sweep && angleExtent < 0)
  95. angleExtent += 2*M_PI;
  96. int segments = (int) ceil(ARC_SEGMENTS_PER_PI/M_PI*fabs(angleExtent));
  97. double angleIncrement = angleExtent/segments;
  98. double cl = 4/3.*sin(.5*angleIncrement)/(1+cos(.5*angleIncrement));
  99. Point2 prevNode = startPoint;
  100. double angle = angleStart;
  101. for (int i = 0; i < segments; ++i) {
  102. Point2 controlPoint[2];
  103. Vector2 d(cos(angle), sin(angle));
  104. controlPoint[0] = center+rotateVector(Vector2(d.x-cl*d.y, d.y+cl*d.x)*radius, axis);
  105. angle += angleIncrement;
  106. d.set(cos(angle), sin(angle));
  107. controlPoint[1] = center+rotateVector(Vector2(d.x+cl*d.y, d.y-cl*d.x)*radius, axis);
  108. Point2 node = i == segments-1 ? endPoint : center+rotateVector(d*radius, axis);
  109. contour.addEdge(new CubicSegment(prevNode, controlPoint[0], controlPoint[1], node));
  110. prevNode = node;
  111. }
  112. }
  113. bool buildShapeFromSvgPath(Shape &shape, const char *pathDef, double endpointSnapRange) {
  114. char nodeType = '\0';
  115. char prevNodeType = '\0';
  116. Point2 prevNode(0, 0);
  117. bool nodeTypePreread = false;
  118. while (nodeTypePreread || readNodeType(nodeType, pathDef)) {
  119. nodeTypePreread = false;
  120. Contour &contour = shape.addContour();
  121. bool contourStart = true;
  122. Point2 startPoint;
  123. Point2 controlPoint[2];
  124. Point2 node;
  125. while (*pathDef) {
  126. switch (nodeType) {
  127. case 'M': case 'm':
  128. if (!contourStart) {
  129. nodeTypePreread = true;
  130. goto NEXT_CONTOUR;
  131. }
  132. REQUIRE(readCoord(node, pathDef));
  133. if (nodeType == 'm')
  134. node += prevNode;
  135. startPoint = node;
  136. --nodeType; // to 'L' or 'l'
  137. break;
  138. case 'Z': case 'z':
  139. REQUIRE(!contourStart);
  140. goto NEXT_CONTOUR;
  141. case 'L': case 'l':
  142. REQUIRE(readCoord(node, pathDef));
  143. if (nodeType == 'l')
  144. node += prevNode;
  145. contour.addEdge(new LinearSegment(prevNode, node));
  146. break;
  147. case 'H': case 'h':
  148. REQUIRE(readDouble(node.x, pathDef));
  149. if (nodeType == 'h')
  150. node.x += prevNode.x;
  151. contour.addEdge(new LinearSegment(prevNode, node));
  152. break;
  153. case 'V': case 'v':
  154. REQUIRE(readDouble(node.y, pathDef));
  155. if (nodeType == 'v')
  156. node.y += prevNode.y;
  157. contour.addEdge(new LinearSegment(prevNode, node));
  158. break;
  159. case 'Q': case 'q':
  160. REQUIRE(readCoord(controlPoint[0], pathDef));
  161. REQUIRE(readCoord(node, pathDef));
  162. if (nodeType == 'q') {
  163. controlPoint[0] += prevNode;
  164. node += prevNode;
  165. }
  166. contour.addEdge(new QuadraticSegment(prevNode, controlPoint[0], node));
  167. break;
  168. case 'T': case 't':
  169. if (prevNodeType == 'Q' || prevNodeType == 'q' || prevNodeType == 'T' || prevNodeType == 't')
  170. controlPoint[0] = node+node-controlPoint[0];
  171. else
  172. controlPoint[0] = node;
  173. REQUIRE(readCoord(node, pathDef));
  174. if (nodeType == 't')
  175. node += prevNode;
  176. contour.addEdge(new QuadraticSegment(prevNode, controlPoint[0], node));
  177. break;
  178. case 'C': case 'c':
  179. REQUIRE(readCoord(controlPoint[0], pathDef));
  180. REQUIRE(readCoord(controlPoint[1], pathDef));
  181. REQUIRE(readCoord(node, pathDef));
  182. if (nodeType == 'c') {
  183. controlPoint[0] += prevNode;
  184. controlPoint[1] += prevNode;
  185. node += prevNode;
  186. }
  187. contour.addEdge(new CubicSegment(prevNode, controlPoint[0], controlPoint[1], node));
  188. break;
  189. case 'S': case 's':
  190. if (prevNodeType == 'C' || prevNodeType == 'c' || prevNodeType == 'S' || prevNodeType == 's')
  191. controlPoint[0] = node+node-controlPoint[1];
  192. else
  193. controlPoint[0] = node;
  194. REQUIRE(readCoord(controlPoint[1], pathDef));
  195. REQUIRE(readCoord(node, pathDef));
  196. if (nodeType == 's') {
  197. controlPoint[1] += prevNode;
  198. node += prevNode;
  199. }
  200. contour.addEdge(new CubicSegment(prevNode, controlPoint[0], controlPoint[1], node));
  201. break;
  202. case 'A': case 'a':
  203. {
  204. Vector2 radius;
  205. double angle;
  206. bool largeArg;
  207. bool sweep;
  208. REQUIRE(readCoord(radius, pathDef));
  209. REQUIRE(readDouble(angle, pathDef));
  210. REQUIRE(readBool(largeArg, pathDef));
  211. REQUIRE(readBool(sweep, pathDef));
  212. REQUIRE(readCoord(node, pathDef));
  213. if (nodeType == 'a')
  214. node += prevNode;
  215. angle *= M_PI/180.0;
  216. addArcApproximate(contour, prevNode, node, radius, angle, largeArg, sweep);
  217. }
  218. break;
  219. default:
  220. REQUIRE(!"Unknown node type");
  221. }
  222. contourStart &= nodeType == 'M' || nodeType == 'm';
  223. prevNode = node;
  224. prevNodeType = nodeType;
  225. readNodeType(nodeType, pathDef);
  226. }
  227. NEXT_CONTOUR:
  228. // Fix contour if it isn't properly closed
  229. if (!contour.edges.empty() && prevNode != startPoint) {
  230. if ((contour.edges.back()->point(1)-contour.edges[0]->point(0)).length() < endpointSnapRange)
  231. contour.edges.back()->moveEndPoint(contour.edges[0]->point(0));
  232. else
  233. contour.addEdge(new LinearSegment(prevNode, startPoint));
  234. }
  235. prevNode = startPoint;
  236. prevNodeType = '\0';
  237. }
  238. return true;
  239. }
  240. bool loadSvgShape(Shape &output, const char *filename, int pathIndex, Vector2 *dimensions) {
  241. tinyxml2::XMLDocument doc;
  242. if (doc.LoadFile(filename))
  243. return false;
  244. tinyxml2::XMLElement *root = doc.FirstChildElement("svg");
  245. if (!root)
  246. return false;
  247. tinyxml2::XMLElement *path = NULL;
  248. if (pathIndex > 0) {
  249. path = root->FirstChildElement("path");
  250. if (!path) {
  251. tinyxml2::XMLElement *g = root->FirstChildElement("g");
  252. if (g)
  253. path = g->FirstChildElement("path");
  254. }
  255. while (path && --pathIndex > 0)
  256. path = path->NextSiblingElement("path");
  257. } else {
  258. path = root->LastChildElement("path");
  259. if (!path) {
  260. tinyxml2::XMLElement *g = root->LastChildElement("g");
  261. if (g)
  262. path = g->LastChildElement("path");
  263. }
  264. while (path && ++pathIndex < 0)
  265. path = path->PreviousSiblingElement("path");
  266. }
  267. if (!path)
  268. return false;
  269. const char *pd = path->Attribute("d");
  270. if (!pd)
  271. return false;
  272. output.contours.clear();
  273. output.inverseYAxis = true;
  274. Vector2 dims(root->DoubleAttribute("width"), root->DoubleAttribute("height"));
  275. if (!dims) {
  276. double left, top;
  277. const char *viewBox = root->Attribute("viewBox");
  278. if (viewBox)
  279. sscanf(viewBox, "%lf %lf %lf %lf", &left, &top, &dims.x, &dims.y);
  280. }
  281. if (dimensions)
  282. *dimensions = dims;
  283. return buildShapeFromSvgPath(output, pd, ENDPOINT_SNAP_RANGE_PROPORTION*dims.length());
  284. }
  285. }