svgparse.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  1. ############################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 12/18/2015 #
  6. # MIT Licence #
  7. # #
  8. # SVG Features supported: #
  9. # * Groups #
  10. # * Rectangles (w/ rounded corners) #
  11. # * Circles #
  12. # * Ellipses #
  13. # * Polygons #
  14. # * Polylines #
  15. # * Lines #
  16. # * Paths #
  17. # * All transformations #
  18. # #
  19. # Reference: www.w3.org/TR/SVG/Overview.html #
  20. ############################################################
  21. import xml.etree.ElementTree as ET
  22. import re
  23. import itertools
  24. from svg.path import Path, Line, Arc, CubicBezier, QuadraticBezier, parse_path
  25. from shapely.geometry import LinearRing, LineString, Point
  26. from shapely.affinity import translate, rotate, scale, skew, affine_transform
  27. import numpy as np
  28. import logging
  29. log = logging.getLogger('base2')
  30. def svgparselength(lengthstr):
  31. """
  32. Parse an SVG length string into a float and a units
  33. string, if any.
  34. :param lengthstr: SVG length string.
  35. :return: Number and units pair.
  36. :rtype: tuple(float, str|None)
  37. """
  38. integer_re_str = r'[+-]?[0-9]+'
  39. number_re_str = r'(?:[+-]?[0-9]*\.[0-9]+(?:[Ee]' + integer_re_str + ')?' + r')|' + \
  40. r'(?:' + integer_re_str + r'(?:[Ee]' + integer_re_str + r')?)'
  41. length_re_str = r'(' + number_re_str + r')(em|ex|px|in|cm|mm|pt|pc|%)?'
  42. match = re.search(length_re_str, lengthstr)
  43. if match:
  44. return float(match.group(1)), match.group(2)
  45. raise Exception('Cannot parse SVG length: %s' % lengthstr)
  46. def path2shapely(path, res=1.0):
  47. """
  48. Converts an svg.path.Path into a Shapely
  49. LinearRing or LinearString.
  50. :rtype : LinearRing
  51. :rtype : LineString
  52. :param path: svg.path.Path instance
  53. :param res: Resolution (minimum step along path)
  54. :return: Shapely geometry object
  55. """
  56. points = []
  57. for component in path:
  58. # Line
  59. if isinstance(component, Line):
  60. start = component.start
  61. x, y = start.real, start.imag
  62. if len(points) == 0 or points[-1] != (x, y):
  63. points.append((x, y))
  64. end = component.end
  65. points.append((end.real, end.imag))
  66. continue
  67. # Arc, CubicBezier or QuadraticBezier
  68. if isinstance(component, Arc) or \
  69. isinstance(component, CubicBezier) or \
  70. isinstance(component, QuadraticBezier):
  71. # How many points to use in the dicrete representation.
  72. length = component.length(res / 10.0)
  73. steps = int(length / res + 0.5)
  74. # solve error when step is below 1,
  75. # it may cause other problems, but LineString needs at least two points
  76. if steps == 0:
  77. steps = 1
  78. frac = 1.0 / steps
  79. # print length, steps, frac
  80. for i in range(steps):
  81. point = component.point(i * frac)
  82. x, y = point.real, point.imag
  83. if len(points) == 0 or points[-1] != (x, y):
  84. points.append((x, y))
  85. end = component.point(1.0)
  86. points.append((end.real, end.imag))
  87. continue
  88. log.warning("I don't know what this is:", component)
  89. continue
  90. if path.closed:
  91. return LinearRing(points)
  92. else:
  93. return LineString(points)
  94. def svgrect2shapely(rect, n_points=32):
  95. """
  96. Converts an SVG rect into Shapely geometry.
  97. :param rect: Rect Element
  98. :type rect: xml.etree.ElementTree.Element
  99. :return: shapely.geometry.polygon.LinearRing
  100. """
  101. w = svgparselength(rect.get('width'))[0]
  102. h = svgparselength(rect.get('height'))[0]
  103. x_obj = rect.get('x')
  104. if x_obj is not None:
  105. x = svgparselength(x_obj)[0]
  106. else:
  107. x = 0
  108. y_obj = rect.get('y')
  109. if y_obj is not None:
  110. y = svgparselength(y_obj)[0]
  111. else:
  112. y = 0
  113. rxstr = rect.get('rx')
  114. rystr = rect.get('ry')
  115. if rxstr is None and rystr is None: # Sharp corners
  116. pts = [
  117. (x, y), (x + w, y), (x + w, y + h), (x, y + h), (x, y)
  118. ]
  119. else: # Rounded corners
  120. rx = 0.0 if rxstr is None else svgparselength(rxstr)[0]
  121. ry = 0.0 if rystr is None else svgparselength(rystr)[0]
  122. n_points = int(n_points / 4 + 0.5)
  123. t = np.arange(n_points, dtype=float) / n_points / 4
  124. x_ = (x + w - rx) + rx * np.cos(2 * np.pi * (t + 0.75))
  125. y_ = (y + ry) + ry * np.sin(2 * np.pi * (t + 0.75))
  126. lower_right = [(x_[i], y_[i]) for i in range(n_points)]
  127. x_ = (x + w - rx) + rx * np.cos(2 * np.pi * t)
  128. y_ = (y + h - ry) + ry * np.sin(2 * np.pi * t)
  129. upper_right = [(x_[i], y_[i]) for i in range(n_points)]
  130. x_ = (x + rx) + rx * np.cos(2 * np.pi * (t + 0.25))
  131. y_ = (y + h - ry) + ry * np.sin(2 * np.pi * (t + 0.25))
  132. upper_left = [(x_[i], y_[i]) for i in range(n_points)]
  133. x_ = (x + rx) + rx * np.cos(2 * np.pi * (t + 0.5))
  134. y_ = (y + ry) + ry * np.sin(2 * np.pi * (t + 0.5))
  135. lower_left = [(x_[i], y_[i]) for i in range(n_points)]
  136. pts = [(x + rx, y), (x - rx + w, y)] + \
  137. lower_right + \
  138. [(x + w, y + ry), (x + w, y + h - ry)] + \
  139. upper_right + \
  140. [(x + w - rx, y + h), (x + rx, y + h)] + \
  141. upper_left + \
  142. [(x, y + h - ry), (x, y + ry)] + \
  143. lower_left
  144. return LinearRing(pts)
  145. def svgcircle2shapely(circle):
  146. """
  147. Converts an SVG circle into Shapely geometry.
  148. :param circle: Circle Element
  149. :type circle: xml.etree.ElementTree.Element
  150. :return: Shapely representation of the circle.
  151. :rtype: shapely.geometry.polygon.LinearRing
  152. """
  153. # cx = float(circle.get('cx'))
  154. # cy = float(circle.get('cy'))
  155. # r = float(circle.get('r'))
  156. cx = svgparselength(circle.get('cx'))[0] # TODO: No units support yet
  157. cy = svgparselength(circle.get('cy'))[0] # TODO: No units support yet
  158. r = svgparselength(circle.get('r'))[0] # TODO: No units support yet
  159. # TODO: No resolution specified.
  160. return Point(cx, cy).buffer(r)
  161. def svgellipse2shapely(ellipse, n_points=64):
  162. """
  163. Converts an SVG ellipse into Shapely geometry
  164. :param ellipse: Ellipse Element
  165. :type ellipse: xml.etree.ElementTree.Element
  166. :param n_points: Number of discrete points in output.
  167. :return: Shapely representation of the ellipse.
  168. :rtype: shapely.geometry.polygon.LinearRing
  169. """
  170. cx = svgparselength(ellipse.get('cx'))[0] # TODO: No units support yet
  171. cy = svgparselength(ellipse.get('cy'))[0] # TODO: No units support yet
  172. rx = svgparselength(ellipse.get('rx'))[0] # TODO: No units support yet
  173. ry = svgparselength(ellipse.get('ry'))[0] # TODO: No units support yet
  174. t = np.arange(n_points, dtype=float) / n_points
  175. x = cx + rx * np.cos(2 * np.pi * t)
  176. y = cy + ry * np.sin(2 * np.pi * t)
  177. pts = [(x[i], y[i]) for i in range(n_points)]
  178. return LinearRing(pts)
  179. def svgline2shapely(line):
  180. """
  181. :param line: Line element
  182. :type line: xml.etree.ElementTree.Element
  183. :return: Shapely representation on the line.
  184. :rtype: shapely.geometry.polygon.LinearRing
  185. """
  186. x1 = svgparselength(line.get('x1'))[0]
  187. y1 = svgparselength(line.get('y1'))[0]
  188. x2 = svgparselength(line.get('x2'))[0]
  189. y2 = svgparselength(line.get('y2'))[0]
  190. return LineString([(x1, y1), (x2, y2)])
  191. def svgpolyline2shapely(polyline):
  192. ptliststr = polyline.get('points')
  193. points = parse_svg_point_list(ptliststr)
  194. return LineString(points)
  195. def svgpolygon2shapely(polygon):
  196. ptliststr = polygon.get('points')
  197. points = parse_svg_point_list(ptliststr)
  198. return LinearRing(points)
  199. def getsvggeo(node):
  200. """
  201. Extracts and flattens all geometry from an SVG node
  202. into a list of Shapely geometry.
  203. :param node: xml.etree.ElementTree.Element
  204. :return: List of Shapely geometry
  205. :rtype: list
  206. """
  207. kind = re.search('(?:\{.*\})?(.*)$', node.tag).group(1)
  208. geo = []
  209. # Recurse
  210. if len(node) > 0:
  211. for child in node:
  212. subgeo = getsvggeo(child)
  213. if subgeo is not None:
  214. geo += subgeo
  215. # Parse
  216. elif kind == 'path':
  217. log.debug("***PATH***")
  218. P = parse_path(node.get('d'))
  219. P = path2shapely(P)
  220. geo = [P]
  221. elif kind == 'rect':
  222. log.debug("***RECT***")
  223. R = svgrect2shapely(node)
  224. geo = [R]
  225. elif kind == 'circle':
  226. log.debug("***CIRCLE***")
  227. C = svgcircle2shapely(node)
  228. geo = [C]
  229. elif kind == 'ellipse':
  230. log.debug("***ELLIPSE***")
  231. E = svgellipse2shapely(node)
  232. geo = [E]
  233. elif kind == 'polygon':
  234. log.debug("***POLYGON***")
  235. poly = svgpolygon2shapely(node)
  236. geo = [poly]
  237. elif kind == 'line':
  238. log.debug("***LINE***")
  239. line = svgline2shapely(node)
  240. geo = [line]
  241. elif kind == 'polyline':
  242. log.debug("***POLYLINE***")
  243. pline = svgpolyline2shapely(node)
  244. geo = [pline]
  245. else:
  246. log.warning("Unknown kind: " + kind)
  247. geo = None
  248. # ignore transformation for unknown kind
  249. if geo is not None:
  250. # Transformations
  251. if 'transform' in node.attrib:
  252. trstr = node.get('transform')
  253. trlist = parse_svg_transform(trstr)
  254. #log.debug(trlist)
  255. # Transformations are applied in reverse order
  256. for tr in trlist[::-1]:
  257. if tr[0] == 'translate':
  258. geo = [translate(geoi, tr[1], tr[2]) for geoi in geo]
  259. elif tr[0] == 'scale':
  260. geo = [scale(geoi, tr[0], tr[1], origin=(0, 0))
  261. for geoi in geo]
  262. elif tr[0] == 'rotate':
  263. geo = [rotate(geoi, tr[1], origin=(tr[2], tr[3]))
  264. for geoi in geo]
  265. elif tr[0] == 'skew':
  266. geo = [skew(geoi, tr[1], tr[2], origin=(0, 0))
  267. for geoi in geo]
  268. elif tr[0] == 'matrix':
  269. geo = [affine_transform(geoi, tr[1:]) for geoi in geo]
  270. else:
  271. raise Exception('Unknown transformation: %s', tr)
  272. return geo
  273. def parse_svg_point_list(ptliststr):
  274. """
  275. Returns a list of coordinate pairs extracted from the "points"
  276. attribute in SVG polygons and polylines.
  277. :param ptliststr: "points" attribute string in polygon or polyline.
  278. :return: List of tuples with coordinates.
  279. """
  280. pairs = []
  281. last = None
  282. pos = 0
  283. i = 0
  284. for match in re.finditer(r'(\s*,\s*)|(\s+)', ptliststr.strip(' ')):
  285. val = float(ptliststr[pos:match.start()])
  286. if i % 2 == 1:
  287. pairs.append((last, val))
  288. else:
  289. last = val
  290. pos = match.end()
  291. i += 1
  292. # Check for last element
  293. val = float(ptliststr[pos:])
  294. if i % 2 == 1:
  295. pairs.append((last, val))
  296. else:
  297. log.warning("Incomplete coordinates.")
  298. return pairs
  299. def parse_svg_transform(trstr):
  300. """
  301. Parses an SVG transform string into a list
  302. of transform names and their parameters.
  303. Possible transformations are:
  304. * Translate: translate(<tx> [<ty>]), which specifies
  305. a translation by tx and ty. If <ty> is not provided,
  306. it is assumed to be zero. Result is
  307. ['translate', tx, ty]
  308. * Scale: scale(<sx> [<sy>]), which specifies a scale operation
  309. by sx and sy. If <sy> is not provided, it is assumed to be
  310. equal to <sx>. Result is: ['scale', sx, sy]
  311. * Rotate: rotate(<rotate-angle> [<cx> <cy>]), which specifies
  312. a rotation by <rotate-angle> degrees about a given point.
  313. If optional parameters <cx> and <cy> are not supplied,
  314. the rotate is about the origin of the current user coordinate
  315. system. Result is: ['rotate', rotate-angle, cx, cy]
  316. * Skew: skewX(<skew-angle>), which specifies a skew
  317. transformation along the x-axis. skewY(<skew-angle>), which
  318. specifies a skew transformation along the y-axis.
  319. Result is ['skew', angle-x, angle-y]
  320. * Matrix: matrix(<a> <b> <c> <d> <e> <f>), which specifies a
  321. transformation in the form of a transformation matrix of six
  322. values. matrix(a,b,c,d,e,f) is equivalent to applying the
  323. transformation matrix [a b c d e f]. Result is
  324. ['matrix', a, b, c, d, e, f]
  325. Note: All parameters to the transformations are "numbers",
  326. i.e. no units present.
  327. :param trstr: SVG transform string.
  328. :type trstr: str
  329. :return: List of transforms.
  330. :rtype: list
  331. """
  332. trlist = []
  333. assert isinstance(trstr, str)
  334. trstr = trstr.strip(' ')
  335. integer_re_str = r'[+-]?[0-9]+'
  336. number_re_str = r'(?:[+-]?[0-9]*\.[0-9]+(?:[Ee]' + integer_re_str + ')?' + r')|' + \
  337. r'(?:' + integer_re_str + r'(?:[Ee]' + integer_re_str + r')?)'
  338. # num_re_str = r'[\+\-]?[0-9\.e]+' # TODO: Negative exponents missing
  339. comma_or_space_re_str = r'(?:(?:\s+)|(?:\s*,\s*))'
  340. translate_re_str = r'translate\s*\(\s*(' + \
  341. number_re_str + r')(?:' + \
  342. comma_or_space_re_str + \
  343. r'(' + number_re_str + r'))?\s*\)'
  344. scale_re_str = r'scale\s*\(\s*(' + \
  345. number_re_str + r')' + \
  346. r'(?:' + comma_or_space_re_str + \
  347. r'(' + number_re_str + r'))?\s*\)'
  348. skew_re_str = r'skew([XY])\s*\(\s*(' + \
  349. number_re_str + r')\s*\)'
  350. rotate_re_str = r'rotate\s*\(\s*(' + \
  351. number_re_str + r')' + \
  352. r'(?:' + comma_or_space_re_str + \
  353. r'(' + number_re_str + r')' + \
  354. comma_or_space_re_str + \
  355. r'(' + number_re_str + r'))?\s*\)'
  356. matrix_re_str = r'matrix\s*\(\s*' + \
  357. r'(' + number_re_str + r')' + comma_or_space_re_str + \
  358. r'(' + number_re_str + r')' + comma_or_space_re_str + \
  359. r'(' + number_re_str + r')' + comma_or_space_re_str + \
  360. r'(' + number_re_str + r')' + comma_or_space_re_str + \
  361. r'(' + number_re_str + r')' + comma_or_space_re_str + \
  362. r'(' + number_re_str + r')\s*\)'
  363. while len(trstr) > 0:
  364. match = re.search(r'^' + translate_re_str, trstr)
  365. if match:
  366. trlist.append([
  367. 'translate',
  368. float(match.group(1)),
  369. float(match.group(2)) if match.group else 0.0
  370. ])
  371. trstr = trstr[len(match.group(0)):].strip(' ')
  372. continue
  373. match = re.search(r'^' + scale_re_str, trstr)
  374. if match:
  375. trlist.append([
  376. 'translate',
  377. float(match.group(1)),
  378. float(match.group(2)) if match.group else float(match.group(1))
  379. ])
  380. trstr = trstr[len(match.group(0)):].strip(' ')
  381. continue
  382. match = re.search(r'^' + skew_re_str, trstr)
  383. if match:
  384. trlist.append([
  385. 'skew',
  386. float(match.group(2)) if match.group(1) == 'X' else 0.0,
  387. float(match.group(2)) if match.group(1) == 'Y' else 0.0
  388. ])
  389. trstr = trstr[len(match.group(0)):].strip(' ')
  390. continue
  391. match = re.search(r'^' + rotate_re_str, trstr)
  392. if match:
  393. trlist.append([
  394. 'rotate',
  395. float(match.group(1)),
  396. float(match.group(2)) if match.group(2) else 0.0,
  397. float(match.group(3)) if match.group(3) else 0.0
  398. ])
  399. trstr = trstr[len(match.group(0)):].strip(' ')
  400. continue
  401. match = re.search(r'^' + matrix_re_str, trstr)
  402. if match:
  403. trlist.append(['matrix'] + [float(x) for x in match.groups()])
  404. trstr = trstr[len(match.group(0)):].strip(' ')
  405. continue
  406. raise Exception("Don't know how to parse: %s" % trstr)
  407. return trlist
  408. if __name__ == "__main__":
  409. tree = ET.parse('tests/svg/drawing.svg')
  410. root = tree.getroot()
  411. ns = re.search(r'\{(.*)\}', root.tag).group(1)
  412. print ns
  413. for geo in getsvggeo(root):
  414. print geo