camlib.py 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458
  1. ############################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://caram.cl/software/flatcam #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. ############################################################
  8. from numpy import arctan2, Inf, array, sqrt, pi, ceil, sin, cos
  9. from matplotlib.figure import Figure
  10. import re
  11. # See: http://toblerity.org/shapely/manual.html
  12. from shapely.geometry import Polygon, LineString, Point, LinearRing
  13. from shapely.geometry import MultiPoint, MultiPolygon
  14. from shapely.geometry import box as shply_box
  15. from shapely.ops import cascaded_union
  16. import shapely.affinity as affinity
  17. from shapely.wkt import loads as sloads
  18. from shapely.wkt import dumps as sdumps
  19. from shapely.geometry.base import BaseGeometry
  20. # Used for solid polygons in Matplotlib
  21. from descartes.patch import PolygonPatch
  22. import simplejson as json
  23. # TODO: Commented for FlatCAM packaging with cx_freeze
  24. #from matplotlib.pyplot import plot
  25. class Geometry:
  26. def __init__(self):
  27. # Units (in or mm)
  28. self.units = 'in'
  29. # Final geometry: MultiPolygon
  30. self.solid_geometry = None
  31. # Attributes to be included in serialization
  32. self.ser_attrs = ['units', 'solid_geometry']
  33. def isolation_geometry(self, offset):
  34. """
  35. Creates contours around geometry at a given
  36. offset distance.
  37. """
  38. return self.solid_geometry.buffer(offset)
  39. def bounds(self):
  40. """
  41. Returns coordinates of rectangular bounds
  42. of geometry: (xmin, ymin, xmax, ymax).
  43. """
  44. if self.solid_geometry is None:
  45. print "Warning: solid_geometry not computed yet."
  46. return (0, 0, 0, 0)
  47. if type(self.solid_geometry) == list:
  48. # TODO: This can be done faster. See comment from Shapely mailing lists.
  49. return cascaded_union(self.solid_geometry).bounds
  50. else:
  51. return self.solid_geometry.bounds
  52. def size(self):
  53. """
  54. Returns (width, height) of rectangular
  55. bounds of geometry.
  56. """
  57. if self.solid_geometry is None:
  58. print "Warning: solid_geometry not computed yet."
  59. return 0
  60. bounds = self.bounds()
  61. return (bounds[2]-bounds[0], bounds[3]-bounds[1])
  62. def get_empty_area(self, boundary=None):
  63. """
  64. Returns the complement of self.solid_geometry within
  65. the given boundary polygon. If not specified, it defaults to
  66. the rectangular bounding box of self.solid_geometry.
  67. """
  68. if boundary is None:
  69. boundary = self.solid_geometry.envelope
  70. return boundary.difference(self.solid_geometry)
  71. def clear_polygon(self, polygon, tooldia, overlap=0.15):
  72. """
  73. Creates geometry inside a polygon for a tool to cover
  74. the whole area.
  75. """
  76. poly_cuts = [polygon.buffer(-tooldia/2.0)]
  77. while True:
  78. polygon = poly_cuts[-1].buffer(-tooldia*(1-overlap))
  79. if polygon.area > 0:
  80. poly_cuts.append(polygon)
  81. else:
  82. break
  83. return poly_cuts
  84. def scale(self, factor):
  85. """
  86. Scales all of the object's geometry by a given factor. Override
  87. this method.
  88. :param factor: Number by which to scale.
  89. :type factor: float
  90. :return: None
  91. :rtype: None
  92. """
  93. return
  94. def convert_units(self, units):
  95. """
  96. Converts the units of the object to ``units`` by scaling all
  97. the geometry appropriately. This call ``scale()``. Don't call
  98. it again in descendents.
  99. :param units: "IN" or "MM"
  100. :type units: str
  101. :return: Scaling factor resulting from unit change.
  102. :rtype: float
  103. """
  104. print "Geometry.convert_units()"
  105. if units.upper() == self.units.upper():
  106. return 1.0
  107. if units.upper() == "MM":
  108. factor = 25.4
  109. elif units.upper() == "IN":
  110. factor = 1/25.4
  111. else:
  112. print "Unsupported units:", units
  113. return 1.0
  114. self.units = units
  115. self.scale(factor)
  116. return factor
  117. def to_dict(self):
  118. """
  119. Returns a respresentation of the object as a dictionary.
  120. Attributes to include are listed in ``self.ser_attrs``.
  121. :return: A dictionary-encoded copy of the object.
  122. :rtype: dict
  123. """
  124. d = {}
  125. for attr in self.ser_attrs:
  126. d[attr] = getattr(self, attr)
  127. return d
  128. def from_dict(self, d):
  129. """
  130. Sets object's attributes from a dictionary.
  131. Attributes to include are listed in ``self.ser_attrs``.
  132. """
  133. for attr in self.ser_attrs:
  134. setattr(self, attr, d[attr])
  135. class Gerber (Geometry):
  136. """
  137. **ATTRIBUTES**
  138. * ``apertures`` (dict): The keys are names/identifiers of each aperture.
  139. The values are dictionaries key/value pairs which describe the aperture. The
  140. type key is always present and the rest depend on the key:
  141. +-----------+-----------------------------------+
  142. | Key | Value |
  143. +===========+===================================+
  144. | type | (str) "C", "R", or "O" |
  145. +-----------+-----------------------------------+
  146. | others | Depend on ``type`` |
  147. +-----------+-----------------------------------+
  148. * ``paths`` (list): A path is described by a line an aperture that follows that
  149. line. Each paths[i] is a dictionary:
  150. +------------+------------------------------------------------+
  151. | Key | Value |
  152. +============+================================================+
  153. | linestring | (Shapely.LineString) The actual path. |
  154. +------------+------------------------------------------------+
  155. | aperture | (str) The key for an aperture in apertures. |
  156. +------------+------------------------------------------------+
  157. * ``flashes`` (list): Flashes are single-point strokes of an aperture. Each
  158. is a dictionary:
  159. +------------+------------------------------------------------+
  160. | Key | Value |
  161. +============+================================================+
  162. | loc | (list) [x (float), y (float)] coordinates. |
  163. +------------+------------------------------------------------+
  164. | aperture | (str) The key for an aperture in apertures. |
  165. +------------+------------------------------------------------+
  166. * ``regions`` (list): Are surfaces defined by a polygon (Shapely.Polygon),
  167. which have an exterior and zero or more interiors. An aperture is also
  168. associated with a region. Each is a dictionary:
  169. +------------+-----------------------------------------------------+
  170. | Key | Value |
  171. +============+=====================================================+
  172. | polygon | (Shapely.Polygon) The polygon defining the region. |
  173. +------------+-----------------------------------------------------+
  174. | aperture | (str) The key for an aperture in apertures. |
  175. +------------+-----------------------------------------------------+
  176. * ``flash_geometry`` (list): List of (Shapely) geometric object resulting
  177. from ``flashes``. These are generated from ``flashes`` in ``do_flashes()``.
  178. * ``buffered_paths`` (list): List of (Shapely) polygons resulting from
  179. *buffering* (or thickening) the ``paths`` with the aperture. These are
  180. generated from ``paths`` in ``buffer_paths()``.
  181. **USAGE**::
  182. g = Gerber()
  183. g.parse_file(filename)
  184. g.create_geometry()
  185. do_something(s.solid_geometry)
  186. """
  187. def __init__(self):
  188. """
  189. The constructor takes no parameters. Use ``gerber.parse_files()``
  190. or ``gerber.parse_lines()`` to populate the object from Gerber source.
  191. :return: Gerber object
  192. :rtype: Gerber
  193. """
  194. # Initialize parent
  195. Geometry.__init__(self)
  196. # Number format
  197. self.int_digits = 3
  198. """Number of integer digits in Gerber numbers. Used during parsing."""
  199. self.frac_digits = 4
  200. """Number of fraction digits in Gerber numbers. Used during parsing."""
  201. ## Gerber elements ##
  202. # Apertures {'id':{'type':chr,
  203. # ['size':float], ['width':float],
  204. # ['height':float]}, ...}
  205. self.apertures = {}
  206. # Paths [{'linestring':LineString, 'aperture':str}]
  207. self.paths = []
  208. # Buffered Paths [Polygon]
  209. # Paths transformed into Polygons by
  210. # offsetting the aperture size/2
  211. self.buffered_paths = []
  212. # Polygon regions [{'polygon':Polygon, 'aperture':str}]
  213. self.regions = []
  214. # Flashes [{'loc':[float,float], 'aperture':str}]
  215. self.flashes = []
  216. # Geometry from flashes
  217. self.flash_geometry = []
  218. # Attributes to be included in serialization
  219. # Always append to it because it carries contents
  220. # from Geometry.
  221. self.ser_attrs += ['int_digits', 'frac_digits', 'apertures', 'paths',
  222. 'buffered_paths', 'regions', 'flashes',
  223. 'flash_geometry']
  224. #### Parser patterns ####
  225. # FS - Format Specification
  226. # The format of X and Y must be the same!
  227. # L-omit leading zeros, T-omit trailing zeros
  228. # A-absolute notation, I-incremental notation
  229. self.fmt_re = re.compile(r'%FS([LT])([AI])X(\d)(\d)Y\d\d\*%$')
  230. # Mode (IN/MM)
  231. self.mode_re = re.compile(r'^%MO(IN|MM)\*%$')
  232. # Comment G04|G4
  233. self.comm_re = re.compile(r'^G0?4(.*)$')
  234. # AD - Aperture definition
  235. self.ad_re = re.compile(r'^%ADD(\d\d+)([a-zA-Z0-9]*),(.*)\*%$')
  236. # AM - Aperture Macro
  237. # Beginning of macro (Ends with *%):
  238. self.am_re = re.compile(r'^%AM([a-zA-Z0-9]*)\*')
  239. # Tool change
  240. # May begin with G54 but that is deprecated
  241. self.tool_re = re.compile(r'^(?:G54)?D(\d\d+)\*$')
  242. # G01 - Linear interpolation plus flashes
  243. # Operation code (D0x) missing is deprecated... oh well I will support it.
  244. self.lin_re = re.compile(r'^(?:G0?(1))?(?:X(-?\d+))?(?:Y(-?\d+))?(?:D0([123]))?\*$')
  245. self.setlin_re = re.compile(r'^(?:G0?1)\*')
  246. # G02/3 - Circular interpolation
  247. # 2-clockwise, 3-counterclockwise
  248. self.circ_re = re.compile(r'^(?:G0?([23]))?(?:X(-?\d+))?(?:Y(-?\d+))' +
  249. '?(?:I(-?\d+))?(?:J(-?\d+))?D0([12])\*$')
  250. # G01/2/3 Occurring without coordinates
  251. self.interp_re = re.compile(r'^(?:G0?([123]))\*')
  252. # Single D74 or multi D75 quadrant for circular interpolation
  253. self.quad_re = re.compile(r'^G7([45])\*$')
  254. # Region mode on
  255. # In region mode, D01 starts a region
  256. # and D02 ends it. A new region can be started again
  257. # with D01. All contours must be closed before
  258. # D02 or G37.
  259. self.regionon_re = re.compile(r'^G36\*$')
  260. # Region mode off
  261. # Will end a region and come off region mode.
  262. # All contours must be closed before D02 or G37.
  263. self.regionoff_re = re.compile(r'^G37\*$')
  264. # End of file
  265. self.eof_re = re.compile(r'^M02\*')
  266. # IP - Image polarity
  267. self.pol_re = re.compile(r'^%IP(POS|NEG)\*%$')
  268. # LP - Level polarity
  269. self.lpol_re = re.compile(r'^%LP([DC])\*%$')
  270. def scale(self, factor):
  271. """
  272. Scales the objects' geometry on the XY plane by a given factor.
  273. These are:
  274. * ``apertures``
  275. * ``paths``
  276. * ``regions``
  277. * ``flashes``
  278. Then ``buffered_paths``, ``flash_geometry`` and ``solid_geometry``
  279. are re-created with ``self.create_geometry()``.
  280. :param factor: Number by which to scale.
  281. :type factor: float
  282. :rtype : None
  283. """
  284. # Apertures
  285. print "Scaling apertures..."
  286. for apid in self.apertures:
  287. for param in self.apertures[apid]:
  288. if param != "type": # All others are dimensions.
  289. print "Tool:", apid, "Parameter:", param
  290. self.apertures[apid][param] *= factor
  291. # Paths
  292. print "Scaling paths..."
  293. for path in self.paths:
  294. path['linestring'] = affinity.scale(path['linestring'],
  295. factor, factor, origin=(0, 0))
  296. # Flashes
  297. print "Scaling flashes..."
  298. for fl in self.flashes:
  299. # TODO: Shouldn't 'loc' be a numpy.array()?
  300. fl['loc'][0] *= factor
  301. fl['loc'][1] *= factor
  302. # Regions
  303. print "Scaling regions..."
  304. for reg in self.regions:
  305. reg['polygon'] = affinity.scale(reg['polygon'], factor, factor,
  306. origin=(0, 0))
  307. # Now buffered_paths, flash_geometry and solid_geometry
  308. self.create_geometry()
  309. def fix_regions(self):
  310. """
  311. Overwrites the region polygons with fixed
  312. versions if found to be invalid (according to Shapely).
  313. """
  314. for region in self.regions:
  315. if not region['polygon'].is_valid:
  316. region['polygon'] = region['polygon'].buffer(0)
  317. def buffer_paths(self):
  318. self.buffered_paths = []
  319. for path in self.paths:
  320. width = self.apertures[path["aperture"]]["size"]
  321. self.buffered_paths.append(path["linestring"].buffer(width/2))
  322. def aperture_parse(self, gline):
  323. """
  324. Parse gerber aperture definition into dictionary of apertures.
  325. The following kinds and their attributes are supported:
  326. * *Circular (C)*: size (float)
  327. * *Rectangle (R)*: width (float), height (float)
  328. * *Obround (O)*: width (float), height (float).
  329. :param gline: Line of Gerber code known to have an aperture definition.
  330. :type gline: str
  331. :return: Identifier of the aperture.
  332. :rtype: str
  333. """
  334. indexstar = gline.find("*")
  335. indexc = gline.find("C,")
  336. if indexc != -1: # Circle, example: %ADD11C,0.1*%
  337. # Found some Gerber with a leading zero in the aperture id and the
  338. # referenced it without the zero, so this is a hack to handle that.
  339. apid = str(int(gline[4:indexc]))
  340. self.apertures[apid] = {"type": "C",
  341. "size": float(gline[indexc+2:indexstar])}
  342. return apid
  343. indexr = gline.find("R,")
  344. if indexr != -1: # Rectangle, example: %ADD15R,0.05X0.12*%
  345. # Hack explained above
  346. apid = str(int(gline[4:indexr]))
  347. indexx = gline.find("X")
  348. self.apertures[apid] = {"type": "R",
  349. "width": float(gline[indexr+2:indexx]),
  350. "height": float(gline[indexx+1:indexstar])}
  351. return apid
  352. indexo = gline.find("O,")
  353. if indexo != -1: # Obround
  354. # Hack explained above
  355. apid = str(int(gline[4:indexo]))
  356. indexx = gline.find("X")
  357. self.apertures[apid] = {"type": "O",
  358. "width": float(gline[indexo+2:indexx]),
  359. "height": float(gline[indexx+1:indexstar])}
  360. return apid
  361. print "WARNING: Aperture not implemented:", gline
  362. return None
  363. def parse_file(self, filename):
  364. """
  365. Calls Gerber.parse_lines() with array of lines
  366. read from the given file.
  367. """
  368. gfile = open(filename, 'r')
  369. gstr = gfile.readlines()
  370. gfile.close()
  371. self.parse_lines(gstr)
  372. def parse_lines(self, glines):
  373. """
  374. Main Gerber parser. Reads Gerber and populates ``self.paths``, ``self.apertures``,
  375. ``self.flashes``, ``self.regions`` and ``self.units``.
  376. :param glines: Gerber code as list of strings, each
  377. element being one line of the source file.
  378. :type glines: list
  379. :return: None
  380. :rtype: None
  381. """
  382. path = [] # Coordinates of the current path
  383. last_path_aperture = None
  384. current_aperture = None
  385. # 1,2 or 3 from "G01", "G02" or "G03"
  386. current_interpolation_mode = None
  387. # 1 or 2 from "D01" or "D02"
  388. # Note this is to support deprecated Gerber not putting
  389. # an operation code at the end of every coordinate line.
  390. current_operation_code = None
  391. # Current coordinates
  392. current_x = None
  393. current_y = None
  394. for gline in glines:
  395. # Linear interpolation plus flashes
  396. match = self.lin_re.search(gline)
  397. if match:
  398. # Parse coordinates
  399. if match.group(2) is not None:
  400. current_x = parse_gerber_number(match.group(2), self.frac_digits)
  401. if match.group(3) is not None:
  402. current_y = parse_gerber_number(match.group(3), self.frac_digits)
  403. # Parse operation code
  404. if match.group(4) is not None:
  405. current_operation_code = match.group(4)
  406. # Pen down: add segment
  407. if current_operation_code == '1':
  408. path.append([current_x, current_y])
  409. last_path_aperture = current_aperture
  410. # Pen up: finish path
  411. elif current_operation_code == '2':
  412. if len(path) > 1:
  413. self.paths.append({"linestring": LineString(path),
  414. "aperture": last_path_aperture})
  415. path = [[current_x, current_y]]
  416. # Flash
  417. elif current_operation_code == '3':
  418. self.flashes.append({"loc": [current_x, current_y],
  419. "aperture": current_aperture})
  420. continue
  421. # if gline.find("D01*") != -1: # pen down
  422. # path.append(parse_gerber_coords(gline, self.int_digits, self.frac_digits))
  423. # last_path_aperture = current_aperture
  424. # continue
  425. #
  426. # if gline.find("D02*") != -1: # pen up
  427. # if len(path) > 1:
  428. # # Path completed, create shapely LineString
  429. # self.paths.append({"linestring": LineString(path),
  430. # "aperture": last_path_aperture})
  431. # path = [parse_gerber_coords(gline, self.int_digits, self.frac_digits)]
  432. # continue
  433. #
  434. # indexd3 = gline.find("D03*")
  435. # if indexd3 > 0: # Flash
  436. # self.flashes.append({"loc": parse_gerber_coords(gline, self.int_digits, self.frac_digits),
  437. # "aperture": current_aperture})
  438. # continue
  439. # if indexd3 == 0: # Flash?
  440. # print "WARNING: Uninplemented flash style:", gline
  441. # continue
  442. # End region
  443. if self.regionoff_re.search(gline):
  444. # Only one path defines region?
  445. self.regions.append({"polygon": Polygon(path),
  446. "aperture": last_path_aperture})
  447. path = []
  448. continue
  449. # if gline.find("G37*") != -1: # end region
  450. # # Only one path defines region?
  451. # self.regions.append({"polygon": Polygon(path),
  452. # "aperture": last_path_aperture})
  453. # path = []
  454. # continue
  455. if gline.find("%ADD") != -1: # aperture definition
  456. self.aperture_parse(gline) # adds element to apertures
  457. continue
  458. # Interpolation mode change
  459. # Can occur along with coordinates and operation code but
  460. # sometimes by itself (handled here).
  461. # Example: G01*
  462. match = self.interp_re.search(gline)
  463. if match:
  464. current_interpolation_mode = int(match.group(1))
  465. continue
  466. # Tool/aperture change
  467. # Example: D12*
  468. match = self.tool_re.search(gline)
  469. if match:
  470. current_aperture = match.group(1)
  471. continue
  472. # indexstar = gline.find("*")
  473. # if gline.find("D") == 0: # Aperture change
  474. # current_aperture = gline[1:indexstar]
  475. # continue
  476. # if gline.find("G54D") == 0: # Aperture change (deprecated)
  477. # current_aperture = gline[4:indexstar]
  478. # continue
  479. # Number format
  480. # TODO: This is ignoring most of the format. Implement the rest.
  481. match = self.fmt_re.search(gline)
  482. if match:
  483. self.int_digits = int(match.group(3))
  484. self.frac_digits = int(match.group(4))
  485. continue
  486. # if gline.find("%FS") != -1: # Format statement
  487. # indexx = gline.find("X")
  488. # self.int_digits = int(gline[indexx + 1])
  489. # self.frac_digits = int(gline[indexx + 2])
  490. # continue
  491. # Mode (IN/MM)
  492. match = self.mode_re.search(gline)
  493. if match:
  494. self.units = match.group(1)
  495. continue
  496. print "WARNING: Line ignored:", gline
  497. if len(path) > 1:
  498. # EOF, create shapely LineString if something still in path
  499. self.paths.append({"linestring": LineString(path),
  500. "aperture": last_path_aperture})
  501. # if len(path) > 1:
  502. # # EOF, create shapely LineString if something still in path
  503. # self.paths.append({"linestring": LineString(path),
  504. # "aperture": current_aperture})
  505. def do_flashes(self):
  506. """
  507. Creates geometry for Gerber flashes (aperture on a single point).
  508. """
  509. self.flash_geometry = []
  510. for flash in self.flashes:
  511. aperture = self.apertures[flash['aperture']]
  512. if aperture['type'] == 'C': # Circles
  513. circle = Point(flash['loc']).buffer(aperture['size']/2)
  514. self.flash_geometry.append(circle)
  515. continue
  516. if aperture['type'] == 'R': # Rectangles
  517. loc = flash['loc']
  518. width = aperture['width']
  519. height = aperture['height']
  520. minx = loc[0] - width/2
  521. maxx = loc[0] + width/2
  522. miny = loc[1] - height/2
  523. maxy = loc[1] + height/2
  524. rectangle = shply_box(minx, miny, maxx, maxy)
  525. self.flash_geometry.append(rectangle)
  526. continue
  527. if aperture['type'] == 'O': # Obround
  528. loc = flash['loc']
  529. width = aperture['width']
  530. height = aperture['height']
  531. if width > height:
  532. p1 = Point(loc[0] + 0.5*(width-height), loc[1])
  533. p2 = Point(loc[0] - 0.5*(width-height), loc[1])
  534. c1 = p1.buffer(height*0.5)
  535. c2 = p2.buffer(height*0.5)
  536. else:
  537. p1 = Point(loc[0], loc[1] + 0.5*(height-width))
  538. p2 = Point(loc[0], loc[1] - 0.5*(height-width))
  539. c1 = p1.buffer(width*0.5)
  540. c2 = p2.buffer(width*0.5)
  541. obround = cascaded_union([c1, c2]).convex_hull
  542. self.flash_geometry.append(obround)
  543. continue
  544. print "WARNING: Aperture type %s not implemented" % (aperture['type'])
  545. def create_geometry(self):
  546. """
  547. Geometry from a Gerber file is made up entirely of polygons.
  548. Every stroke (linear or circular) has an aperture which gives
  549. it thickness. Additionally, aperture strokes have non-zero area,
  550. and regions naturally do as well.
  551. :rtype : None
  552. :return: None
  553. """
  554. # if len(self.buffered_paths) == 0:
  555. # self.buffer_paths()
  556. print "... buffer_paths()"
  557. self.buffer_paths()
  558. print "... fix_regions()"
  559. self.fix_regions()
  560. print "... do_flashes()"
  561. self.do_flashes()
  562. print "... cascaded_union()"
  563. self.solid_geometry = cascaded_union(
  564. self.buffered_paths +
  565. [poly['polygon'] for poly in self.regions] +
  566. self.flash_geometry)
  567. def get_bounding_box(self, margin=0.0, rounded=False):
  568. """
  569. Creates and returns a rectangular polygon bounding at a distance of
  570. margin from the object's ``solid_geometry``. If margin > 0, the polygon
  571. can optionally have rounded corners of radius equal to margin.
  572. :param margin: Distance to enlarge the rectangular bounding
  573. box in both positive and negative, x and y axes.
  574. :type margin: float
  575. :param rounded: Wether or not to have rounded corners.
  576. :type rounded: bool
  577. :return: The bounding box.
  578. :rtype: Shapely.Polygon
  579. """
  580. bbox = self.solid_geometry.envelope.buffer(margin)
  581. if not rounded:
  582. bbox = bbox.envelope
  583. return bbox
  584. class Excellon(Geometry):
  585. """
  586. *ATTRIBUTES*
  587. * ``tools`` (dict): The key is the tool name and the value is
  588. the size (diameter).
  589. * ``drills`` (list): Each is a dictionary:
  590. ================ ====================================
  591. Key Value
  592. ================ ====================================
  593. point (Shapely.Point) Where to drill
  594. tool (str) A key in ``tools``
  595. ================ ====================================
  596. """
  597. def __init__(self):
  598. """
  599. The constructor takes no parameters.
  600. :return: Excellon object.
  601. :rtype: Excellon
  602. """
  603. Geometry.__init__(self)
  604. self.tools = {}
  605. self.drills = []
  606. # Trailing "T" or leading "L"
  607. self.zeros = ""
  608. # Attributes to be included in serialization
  609. # Always append to it because it carries contents
  610. # from Geometry.
  611. self.ser_attrs += ['tools', 'drills', 'zeros']
  612. def parse_file(self, filename):
  613. efile = open(filename, 'r')
  614. estr = efile.readlines()
  615. efile.close()
  616. self.parse_lines(estr)
  617. def parse_lines(self, elines):
  618. """
  619. Main Excellon parser.
  620. """
  621. units_re = re.compile(r'^(INCH|METRIC)(?:,([TL])Z)?$')
  622. current_tool = ""
  623. for eline in elines:
  624. ## Tool definitions ##
  625. # TODO: Verify all this
  626. indexT = eline.find("T")
  627. indexC = eline.find("C")
  628. indexF = eline.find("F")
  629. # Type 1
  630. if indexT != -1 and indexC > indexT and indexF > indexC:
  631. tool = eline[1:indexC]
  632. spec = eline[indexC+1:indexF]
  633. self.tools[tool] = float(spec)
  634. continue
  635. # Type 2
  636. # TODO: Is this inches?
  637. #indexsp = eline.find(" ")
  638. #indexin = eline.find("in")
  639. #if indexT != -1 and indexsp > indexT and indexin > indexsp:
  640. # tool = eline[1:indexsp]
  641. # spec = eline[indexsp+1:indexin]
  642. # self.tools[tool] = spec
  643. # continue
  644. # Type 3
  645. if indexT != -1 and indexC > indexT:
  646. tool = eline[1:indexC]
  647. spec = eline[indexC+1:-1]
  648. self.tools[tool] = float(spec)
  649. continue
  650. ## Tool change
  651. if indexT == 0:
  652. current_tool = eline[1:-1]
  653. continue
  654. ## Drill
  655. indexx = eline.find("X")
  656. indexy = eline.find("Y")
  657. if indexx != -1 and indexy != -1:
  658. x = float(int(eline[indexx+1:indexy])/10000.0)
  659. y = float(int(eline[indexy+1:-1])/10000.0)
  660. self.drills.append({'point': Point((x, y)), 'tool': current_tool})
  661. continue
  662. # Units and number format
  663. match = units_re.match(eline)
  664. if match:
  665. self.zeros = match.group(2) # "T" or "L"
  666. self.units = {"INCH": "IN", "METRIC": "MM"}[match.group(1)]
  667. print "WARNING: Line ignored:", eline
  668. def create_geometry(self):
  669. self.solid_geometry = []
  670. sizes = {}
  671. for tool in self.tools:
  672. sizes[tool] = float(self.tools[tool])
  673. for drill in self.drills:
  674. poly = Point(drill['point']).buffer(sizes[drill['tool']]/2.0)
  675. self.solid_geometry.append(poly)
  676. self.solid_geometry = cascaded_union(self.solid_geometry)
  677. def scale(self, factor):
  678. """
  679. Scales geometry on the XY plane in the object by a given factor.
  680. Tool sizes, feedrates an Z-plane dimensions are untouched.
  681. :param factor: Number by which to scale the object.
  682. :type factor: float
  683. :return: None
  684. :rtype: NOne
  685. """
  686. # Drills
  687. for drill in self.drills:
  688. drill['point'] = affinity.scale(drill['point'], factor, factor, origin=(0, 0))
  689. def convert_units(self, units):
  690. factor = Geometry.convert_units(self, units)
  691. # Tools
  692. for tname in self.tools:
  693. self.tools[tname] *= factor
  694. return factor
  695. class CNCjob(Geometry):
  696. """
  697. Represents work to be done by a CNC machine.
  698. *ATTRIBUTES*
  699. * ``gcode_parsed`` (list): Each is a dictionary:
  700. ===================== =========================================
  701. Key Value
  702. ===================== =========================================
  703. geom (Shapely.LineString) Tool path (XY plane)
  704. kind (string) "AB", A is "T" (travel) or
  705. "C" (cut). B is "F" (fast) or "S" (slow).
  706. ===================== =========================================
  707. """
  708. def __init__(self, units="in", kind="generic", z_move=0.1,
  709. feedrate=3.0, z_cut=-0.002, tooldia=0.0):
  710. Geometry.__init__(self)
  711. self.kind = kind
  712. self.units = units
  713. self.z_cut = z_cut
  714. self.z_move = z_move
  715. self.feedrate = feedrate
  716. self.tooldia = tooldia
  717. self.unitcode = {"IN": "G20", "MM": "G21"}
  718. self.pausecode = "G04 P1"
  719. self.feedminutecode = "G94"
  720. self.absolutecode = "G90"
  721. self.gcode = ""
  722. self.input_geometry_bounds = None
  723. self.gcode_parsed = None
  724. self.steps_per_circ = 20 # Used when parsing G-code arcs
  725. # Attributes to be included in serialization
  726. # Always append to it because it carries contents
  727. # from Geometry.
  728. self.ser_attrs += ['kind', 'z_cut', 'z_move', 'feedrate', 'tooldia',
  729. 'gcode', 'input_geometry_bounds', 'gcode_parsed',
  730. 'steps_per_circ']
  731. def convert_units(self, units):
  732. factor = Geometry.convert_units(self, units)
  733. print "CNCjob.convert_units()"
  734. self.z_cut *= factor
  735. self.z_move *= factor
  736. self.feedrate *= factor
  737. self.tooldia *= factor
  738. return factor
  739. def generate_from_excellon(self, exobj):
  740. """
  741. Generates G-code for drilling from Excellon object.
  742. self.gcode becomes a list, each element is a
  743. different job for each tool in the excellon code.
  744. """
  745. self.kind = "drill"
  746. self.gcode = []
  747. t = "G00 X%.4fY%.4f\n"
  748. down = "G01 Z%.4f\n" % self.z_cut
  749. up = "G01 Z%.4f\n" % self.z_move
  750. for tool in exobj.tools:
  751. points = []
  752. for drill in exobj.drill:
  753. if drill['tool'] == tool:
  754. points.append(drill['point'])
  755. gcode = self.unitcode[self.units.upper()] + "\n"
  756. gcode += self.absolutecode + "\n"
  757. gcode += self.feedminutecode + "\n"
  758. gcode += "F%.2f\n" % self.feedrate
  759. gcode += "G00 Z%.4f\n" % self.z_move # Move to travel height
  760. gcode += "M03\n" # Spindle start
  761. gcode += self.pausecode + "\n"
  762. for point in points:
  763. gcode += t % point
  764. gcode += down + up
  765. gcode += t % (0, 0)
  766. gcode += "M05\n" # Spindle stop
  767. self.gcode.append(gcode)
  768. def generate_from_excellon_by_tool(self, exobj, tools="all"):
  769. """
  770. Creates gcode for this object from an Excellon object
  771. for the specified tools.
  772. @param exobj: Excellon object to process
  773. @type exobj: Excellon
  774. @param tools: Comma separated tool names
  775. @type: tools: str
  776. @return: None
  777. """
  778. print "Creating CNC Job from Excellon..."
  779. if tools == "all":
  780. tools = [tool for tool in exobj.tools]
  781. else:
  782. tools = [x.strip() for x in tools.split(",")]
  783. tools = filter(lambda y: y in exobj.tools, tools)
  784. print "Tools are:", tools
  785. points = []
  786. for drill in exobj.drills:
  787. if drill['tool'] in tools:
  788. points.append(drill['point'])
  789. print "Found %d drills." % len(points)
  790. #self.kind = "drill"
  791. self.gcode = []
  792. t = "G00 X%.4fY%.4f\n"
  793. down = "G01 Z%.4f\n" % self.z_cut
  794. up = "G01 Z%.4f\n" % self.z_move
  795. gcode = self.unitcode[self.units.upper()] + "\n"
  796. gcode += self.absolutecode + "\n"
  797. gcode += self.feedminutecode + "\n"
  798. gcode += "F%.2f\n" % self.feedrate
  799. gcode += "G00 Z%.4f\n" % self.z_move # Move to travel height
  800. gcode += "M03\n" # Spindle start
  801. gcode += self.pausecode + "\n"
  802. for point in points:
  803. x, y = point.coords.xy
  804. gcode += t % (x[0], y[0])
  805. gcode += down + up
  806. gcode += t % (0, 0)
  807. gcode += "M05\n" # Spindle stop
  808. self.gcode = gcode
  809. def generate_from_geometry(self, geometry, append=True, tooldia=None):
  810. """
  811. Generates G-Code from a Geometry object.
  812. """
  813. if tooldia is not None:
  814. self.tooldia = tooldia
  815. self.input_geometry_bounds = geometry.bounds()
  816. if not append:
  817. self.gcode = ""
  818. self.gcode = self.unitcode[self.units.upper()] + "\n"
  819. self.gcode += self.absolutecode + "\n"
  820. self.gcode += self.feedminutecode + "\n"
  821. self.gcode += "F%.2f\n" % self.feedrate
  822. self.gcode += "G00 Z%.4f\n" % self.z_move # Move to travel height
  823. self.gcode += "M03\n" # Spindle start
  824. self.gcode += self.pausecode + "\n"
  825. for geo in geometry.solid_geometry:
  826. if type(geo) == Polygon:
  827. self.gcode += self.polygon2gcode(geo)
  828. continue
  829. if type(geo) == LineString or type(geo) == LinearRing:
  830. self.gcode += self.linear2gcode(geo)
  831. continue
  832. if type(geo) == Point:
  833. self.gcode += self.point2gcode(geo)
  834. continue
  835. if type(geo) == MultiPolygon:
  836. for poly in geo:
  837. self.gcode += self.polygon2gcode(poly)
  838. continue
  839. print "WARNING: G-code generation not implemented for %s" % (str(type(geo)))
  840. self.gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  841. self.gcode += "G00 X0Y0\n"
  842. self.gcode += "M05\n" # Spindle stop
  843. def pre_parse(self, gtext):
  844. """
  845. gtext is a single string with g-code
  846. """
  847. # Units: G20-inches, G21-mm
  848. units_re = re.compile(r'^G2([01])')
  849. # TODO: This has to be re-done
  850. gcmds = []
  851. lines = gtext.split("\n") # TODO: This is probably a lot of work!
  852. for line in lines:
  853. # Clean up
  854. line = line.strip()
  855. # Remove comments
  856. # NOTE: Limited to 1 bracket pair
  857. op = line.find("(")
  858. cl = line.find(")")
  859. if op > -1 and cl > op:
  860. #comment = line[op+1:cl]
  861. line = line[:op] + line[(cl+1):]
  862. # Units
  863. match = units_re.match(line)
  864. if match:
  865. self.units = {'0': "IN", '1': "MM"}[match.group(1)]
  866. # Parse GCode
  867. # 0 4 12
  868. # G01 X-0.007 Y-0.057
  869. # --> codes_idx = [0, 4, 12]
  870. codes = "NMGXYZIJFP"
  871. codes_idx = []
  872. i = 0
  873. for ch in line:
  874. if ch in codes:
  875. codes_idx.append(i)
  876. i += 1
  877. n_codes = len(codes_idx)
  878. if n_codes == 0:
  879. continue
  880. # Separate codes in line
  881. parts = []
  882. for p in range(n_codes-1):
  883. parts.append(line[codes_idx[p]:codes_idx[p+1]].strip())
  884. parts.append(line[codes_idx[-1]:].strip())
  885. # Separate codes from values
  886. cmds = {}
  887. for part in parts:
  888. cmds[part[0]] = float(part[1:])
  889. gcmds.append(cmds)
  890. return gcmds
  891. def gcode_parse(self):
  892. """
  893. G-Code parser (from self.gcode). Generates dictionary with
  894. single-segment LineString's and "kind" indicating cut or travel,
  895. fast or feedrate speed.
  896. """
  897. # Results go here
  898. geometry = []
  899. # TODO: Merge into single parser?
  900. gobjs = self.pre_parse(self.gcode)
  901. # Last known instruction
  902. current = {'X': 0.0, 'Y': 0.0, 'Z': 0.0, 'G': 0}
  903. # Process every instruction
  904. for gobj in gobjs:
  905. if 'Z' in gobj:
  906. if ('X' in gobj or 'Y' in gobj) and gobj['Z'] != current['Z']:
  907. print "WARNING: Non-orthogonal motion: From", current
  908. print " To:", gobj
  909. current['Z'] = gobj['Z']
  910. if 'G' in gobj:
  911. current['G'] = int(gobj['G'])
  912. if 'X' in gobj or 'Y' in gobj:
  913. x = 0
  914. y = 0
  915. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  916. if 'X' in gobj:
  917. x = gobj['X']
  918. else:
  919. x = current['X']
  920. if 'Y' in gobj:
  921. y = gobj['Y']
  922. else:
  923. y = current['Y']
  924. if current['Z'] > 0:
  925. kind[0] = 'T'
  926. if current['G'] > 0:
  927. kind[1] = 'S'
  928. arcdir = [None, None, "cw", "ccw"]
  929. if current['G'] in [0, 1]: # line
  930. geometry.append({'geom': LineString([(current['X'], current['Y']),
  931. (x, y)]), 'kind': kind})
  932. if current['G'] in [2, 3]: # arc
  933. center = [gobj['I'] + current['X'], gobj['J'] + current['Y']]
  934. radius = sqrt(gobj['I']**2 + gobj['J']**2)
  935. start = arctan2(-gobj['J'], -gobj['I'])
  936. stop = arctan2(-center[1]+y, -center[0]+x)
  937. geometry.append({'geom': arc(center, radius, start, stop,
  938. arcdir[current['G']],
  939. self.steps_per_circ),
  940. 'kind': kind})
  941. # Update current instruction
  942. for code in gobj:
  943. current[code] = gobj[code]
  944. #self.G_geometry = geometry
  945. self.gcode_parsed = geometry
  946. return geometry
  947. # def plot(self, tooldia=None, dpi=75, margin=0.1,
  948. # color={"T": ["#F0E24D", "#B5AB3A"], "C": ["#5E6CFF", "#4650BD"]},
  949. # alpha={"T": 0.3, "C": 1.0}):
  950. # """
  951. # Creates a Matplotlib figure with a plot of the
  952. # G-code job.
  953. # """
  954. # if tooldia is None:
  955. # tooldia = self.tooldia
  956. #
  957. # fig = Figure(dpi=dpi)
  958. # ax = fig.add_subplot(111)
  959. # ax.set_aspect(1)
  960. # xmin, ymin, xmax, ymax = self.input_geometry_bounds
  961. # ax.set_xlim(xmin-margin, xmax+margin)
  962. # ax.set_ylim(ymin-margin, ymax+margin)
  963. #
  964. # if tooldia == 0:
  965. # for geo in self.gcode_parsed:
  966. # linespec = '--'
  967. # linecolor = color[geo['kind'][0]][1]
  968. # if geo['kind'][0] == 'C':
  969. # linespec = 'k-'
  970. # x, y = geo['geom'].coords.xy
  971. # ax.plot(x, y, linespec, color=linecolor)
  972. # else:
  973. # for geo in self.gcode_parsed:
  974. # poly = geo['geom'].buffer(tooldia/2.0)
  975. # patch = PolygonPatch(poly, facecolor=color[geo['kind'][0]][0],
  976. # edgecolor=color[geo['kind'][0]][1],
  977. # alpha=alpha[geo['kind'][0]], zorder=2)
  978. # ax.add_patch(patch)
  979. #
  980. # return fig
  981. def plot2(self, axes, tooldia=None, dpi=75, margin=0.1,
  982. color={"T": ["#F0E24D", "#B5AB3A"], "C": ["#5E6CFF", "#4650BD"]},
  983. alpha={"T": 0.3, "C": 1.0}):
  984. """
  985. Plots the G-code job onto the given axes.
  986. """
  987. if tooldia is None:
  988. tooldia = self.tooldia
  989. if tooldia == 0:
  990. for geo in self.gcode_parsed:
  991. linespec = '--'
  992. linecolor = color[geo['kind'][0]][1]
  993. if geo['kind'][0] == 'C':
  994. linespec = 'k-'
  995. x, y = geo['geom'].coords.xy
  996. axes.plot(x, y, linespec, color=linecolor)
  997. else:
  998. for geo in self.gcode_parsed:
  999. poly = geo['geom'].buffer(tooldia/2.0)
  1000. patch = PolygonPatch(poly, facecolor=color[geo['kind'][0]][0],
  1001. edgecolor=color[geo['kind'][0]][1],
  1002. alpha=alpha[geo['kind'][0]], zorder=2)
  1003. axes.add_patch(patch)
  1004. def create_geometry(self):
  1005. self.solid_geometry = cascaded_union([geo['geom'] for geo in self.gcode_parsed])
  1006. def polygon2gcode(self, polygon):
  1007. """
  1008. Creates G-Code for the exterior and all interior paths
  1009. of a polygon.
  1010. :param polygon: A Shapely.Polygon
  1011. :type polygon: Shapely.Polygon
  1012. """
  1013. gcode = ""
  1014. t = "G0%d X%.4fY%.4f\n"
  1015. path = list(polygon.exterior.coords) # Polygon exterior
  1016. gcode += t % (0, path[0][0], path[0][1]) # Move to first point
  1017. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  1018. for pt in path[1:]:
  1019. gcode += t % (1, pt[0], pt[1]) # Linear motion to point
  1020. gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  1021. for ints in polygon.interiors: # Polygon interiors
  1022. path = list(ints.coords)
  1023. gcode += t % (0, path[0][0], path[0][1]) # Move to first point
  1024. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  1025. for pt in path[1:]:
  1026. gcode += t % (1, pt[0], pt[1]) # Linear motion to point
  1027. gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  1028. return gcode
  1029. def linear2gcode(self, linear):
  1030. gcode = ""
  1031. t = "G0%d X%.4fY%.4f\n"
  1032. path = list(linear.coords)
  1033. gcode += t%(0, path[0][0], path[0][1]) # Move to first point
  1034. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  1035. for pt in path[1:]:
  1036. gcode += t % (1, pt[0], pt[1]) # Linear motion to point
  1037. gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  1038. return gcode
  1039. def point2gcode(self, point):
  1040. # TODO: This is not doing anything.
  1041. gcode = ""
  1042. t = "G0%d X%.4fY%.4f\n"
  1043. path = list(point.coords)
  1044. gcode += t % (0, path[0][0], path[0][1]) # Move to first point
  1045. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  1046. gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  1047. def scale(self, factor):
  1048. """
  1049. Scales all the geometry on the XY plane in the object by the
  1050. given factor. Tool sizes, feedrates, or Z-axis dimensions are
  1051. not altered.
  1052. :param factor: Number by which to scale the object.
  1053. :type factor: float
  1054. :return: None
  1055. :rtype: None
  1056. """
  1057. for g in self.gcode_parsed:
  1058. g['geom'] = affinity.scale(g['geom'], factor, factor, origin=(0, 0))
  1059. self.create_geometry()
  1060. def get_bounds(geometry_set):
  1061. xmin = Inf
  1062. ymin = Inf
  1063. xmax = -Inf
  1064. ymax = -Inf
  1065. print "Getting bounds of:", str(geometry_set)
  1066. for gs in geometry_set:
  1067. try:
  1068. gxmin, gymin, gxmax, gymax = geometry_set[gs].bounds()
  1069. xmin = min([xmin, gxmin])
  1070. ymin = min([ymin, gymin])
  1071. xmax = max([xmax, gxmax])
  1072. ymax = max([ymax, gymax])
  1073. except:
  1074. print "DEV WARNING: Tried to get bounds of empty geometry."
  1075. return [xmin, ymin, xmax, ymax]
  1076. def arc(center, radius, start, stop, direction, steps_per_circ):
  1077. """
  1078. Creates a Shapely.LineString for the specified arc.
  1079. :param center: Coordinates of the center [x, y]
  1080. :type center: list
  1081. :param radius: Radius of the arc.
  1082. :type radius: float
  1083. :param start: Starting angle in radians
  1084. :type start: float
  1085. :param stop: End angle in radians
  1086. :type stop: float
  1087. :param direction: Orientation of the arc, "CW" or "CCW"
  1088. :type direction: string
  1089. :param steps_per_circ: Number of straight line segments to
  1090. represent a circle.
  1091. :type steps_per_circ: int
  1092. :return: The desired arc.
  1093. :rtype: Shapely.LineString
  1094. """
  1095. da_sign = {"cw": -1.0, "ccw": 1.0}
  1096. points = []
  1097. if direction == "ccw" and stop <= start:
  1098. stop += 2*pi
  1099. if direction == "cw" and stop >= start:
  1100. stop -= 2*pi
  1101. angle = abs(stop - start)
  1102. #angle = stop-start
  1103. steps = max([int(ceil(angle/(2*pi)*steps_per_circ)), 2])
  1104. delta_angle = da_sign[direction]*angle*1.0/steps
  1105. for i in range(steps+1):
  1106. theta = start + delta_angle*i
  1107. points.append([center[0]+radius*cos(theta), center[1]+radius*sin(theta)])
  1108. return LineString(points)
  1109. def clear_poly(poly, tooldia, overlap=0.1):
  1110. """
  1111. Creates a list of Shapely geometry objects covering the inside
  1112. of a Shapely.Polygon. Use for removing all the copper in a region
  1113. or bed flattening.
  1114. :param poly: Target polygon
  1115. :type poly: Shapely.Polygon
  1116. :param tooldia: Diameter of the tool
  1117. :type tooldia: float
  1118. :param overlap: Fraction of the tool diameter to overlap
  1119. in each pass.
  1120. :type overlap: float
  1121. :return: list of Shapely.Polygon
  1122. :rtype: list
  1123. """
  1124. poly_cuts = [poly.buffer(-tooldia/2.0)]
  1125. while True:
  1126. poly = poly_cuts[-1].buffer(-tooldia*(1-overlap))
  1127. if poly.area > 0:
  1128. poly_cuts.append(poly)
  1129. else:
  1130. break
  1131. return poly_cuts
  1132. def find_polygon(poly_set, point):
  1133. """
  1134. Return the first polygon in the list of polygons poly_set
  1135. that contains the given point.
  1136. """
  1137. p = Point(point)
  1138. for poly in poly_set:
  1139. if poly.contains(p):
  1140. return poly
  1141. return None
  1142. def to_dict(geo):
  1143. output = ''
  1144. if isinstance(geo, BaseGeometry):
  1145. return {
  1146. "__class__": "Shply",
  1147. "__inst__": sdumps(geo)
  1148. }
  1149. return geo
  1150. def dict2obj(d):
  1151. if '__class__' in d and '__inst__' in d:
  1152. # For now assume all classes are Shapely geometry.
  1153. return sloads(d['__inst__'])
  1154. else:
  1155. return d
  1156. def plotg(geo):
  1157. try:
  1158. _ = iter(geo)
  1159. except:
  1160. geo = [geo]
  1161. for g in geo:
  1162. if type(g) == Polygon:
  1163. x, y = g.exterior.coords.xy
  1164. plot(x, y)
  1165. for ints in g.interiors:
  1166. x, y = ints.coords.xy
  1167. plot(x, y)
  1168. continue
  1169. if type(g) == LineString or type(g) == LinearRing:
  1170. x, y = g.coords.xy
  1171. plot(x, y)
  1172. continue
  1173. if type(g) == Point:
  1174. x, y = g.coords.xy
  1175. plot(x, y, 'o')
  1176. continue
  1177. try:
  1178. _ = iter(g)
  1179. plotg(g)
  1180. except:
  1181. print "Cannot plot:", str(type(g))
  1182. continue
  1183. def parse_gerber_number(strnumber, frac_digits):
  1184. """
  1185. Parse a single number of Gerber coordinates.
  1186. :param strnumber: String containing a number in decimal digits
  1187. from a coordinate data block, possibly with a leading sign.
  1188. :type strnumber: str
  1189. :param frac_digits: Number of digits used for the fractional
  1190. part of the number
  1191. :type frac_digits: int
  1192. :return: The number in floating point.
  1193. :rtype: float
  1194. """
  1195. return int(strnumber)*(10**(-frac_digits))
  1196. def parse_gerber_coords(gstr, int_digits, frac_digits):
  1197. """
  1198. Parse Gerber coordinates
  1199. :param gstr: Line of G-Code containing coordinates.
  1200. :type gstr: str
  1201. :param int_digits: Number of digits in integer part of a number.
  1202. :type int_digits: int
  1203. :param frac_digits: Number of digits in frac_digits part of a number.
  1204. :type frac_digits: int
  1205. :return: [x, y] coordinates.
  1206. :rtype: list
  1207. """
  1208. global gerbx, gerby
  1209. xindex = gstr.find("X")
  1210. yindex = gstr.find("Y")
  1211. index = gstr.find("D")
  1212. if xindex == -1:
  1213. x = gerbx
  1214. y = int(gstr[(yindex+1):index])*(10**(-frac_digits))
  1215. elif yindex == -1:
  1216. y = gerby
  1217. x = int(gstr[(xindex+1):index])*(10**(-frac_digits))
  1218. else:
  1219. x = int(gstr[(xindex+1):yindex])*(10**(-frac_digits))
  1220. y = int(gstr[(yindex+1):index])*(10**(-frac_digits))
  1221. gerbx = x
  1222. gerby = y
  1223. return [x, y]