import-svg.cpp 12 KB

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