camlib.py 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423
  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. import logging
  26. log = logging.getLogger('base2')
  27. #log.setLevel(logging.DEBUG)
  28. log.setLevel(logging.WARNING)
  29. formatter = logging.Formatter('[%(levelname)s] %(message)s')
  30. handler = logging.StreamHandler()
  31. handler.setFormatter(formatter)
  32. log.addHandler(handler)
  33. class Geometry(object):
  34. def __init__(self):
  35. # Units (in or mm)
  36. self.units = 'in'
  37. # Final geometry: MultiPolygon
  38. self.solid_geometry = None
  39. # Attributes to be included in serialization
  40. self.ser_attrs = ['units', 'solid_geometry']
  41. def isolation_geometry(self, offset):
  42. """
  43. Creates contours around geometry at a given
  44. offset distance.
  45. :param offset: Offset distance.
  46. :type offset: float
  47. :return: The buffered geometry.
  48. :rtype: Shapely.MultiPolygon or Shapely.Polygon
  49. """
  50. return self.solid_geometry.buffer(offset)
  51. def bounds(self):
  52. """
  53. Returns coordinates of rectangular bounds
  54. of geometry: (xmin, ymin, xmax, ymax).
  55. """
  56. if self.solid_geometry is None:
  57. log.warning("solid_geometry not computed yet.")
  58. return (0, 0, 0, 0)
  59. if type(self.solid_geometry) == list:
  60. # TODO: This can be done faster. See comment from Shapely mailing lists.
  61. return cascaded_union(self.solid_geometry).bounds
  62. else:
  63. return self.solid_geometry.bounds
  64. def size(self):
  65. """
  66. Returns (width, height) of rectangular
  67. bounds of geometry.
  68. """
  69. if self.solid_geometry is None:
  70. log.warning("Solid_geometry not computed yet.")
  71. return 0
  72. bounds = self.bounds()
  73. return (bounds[2]-bounds[0], bounds[3]-bounds[1])
  74. def get_empty_area(self, boundary=None):
  75. """
  76. Returns the complement of self.solid_geometry within
  77. the given boundary polygon. If not specified, it defaults to
  78. the rectangular bounding box of self.solid_geometry.
  79. """
  80. if boundary is None:
  81. boundary = self.solid_geometry.envelope
  82. return boundary.difference(self.solid_geometry)
  83. def clear_polygon(self, polygon, tooldia, overlap=0.15):
  84. """
  85. Creates geometry inside a polygon for a tool to cover
  86. the whole area.
  87. """
  88. poly_cuts = [polygon.buffer(-tooldia/2.0)]
  89. while True:
  90. polygon = poly_cuts[-1].buffer(-tooldia*(1-overlap))
  91. if polygon.area > 0:
  92. poly_cuts.append(polygon)
  93. else:
  94. break
  95. return poly_cuts
  96. def scale(self, factor):
  97. """
  98. Scales all of the object's geometry by a given factor. Override
  99. this method.
  100. :param factor: Number by which to scale.
  101. :type factor: float
  102. :return: None
  103. :rtype: None
  104. """
  105. return
  106. def offset(self, vect):
  107. """
  108. Offset the geometry by the given vector. Override this method.
  109. :param vect: (x, y) vector by which to offset the object.
  110. :type vect: tuple
  111. :return: None
  112. """
  113. return
  114. def convert_units(self, units):
  115. """
  116. Converts the units of the object to ``units`` by scaling all
  117. the geometry appropriately. This call ``scale()``. Don't call
  118. it again in descendents.
  119. :param units: "IN" or "MM"
  120. :type units: str
  121. :return: Scaling factor resulting from unit change.
  122. :rtype: float
  123. """
  124. log.debug("Geometry.convert_units()")
  125. if units.upper() == self.units.upper():
  126. return 1.0
  127. if units.upper() == "MM":
  128. factor = 25.4
  129. elif units.upper() == "IN":
  130. factor = 1/25.4
  131. else:
  132. log.error("Unsupported units: %s" % str(units))
  133. return 1.0
  134. self.units = units
  135. self.scale(factor)
  136. return factor
  137. def to_dict(self):
  138. """
  139. Returns a respresentation of the object as a dictionary.
  140. Attributes to include are listed in ``self.ser_attrs``.
  141. :return: A dictionary-encoded copy of the object.
  142. :rtype: dict
  143. """
  144. d = {}
  145. for attr in self.ser_attrs:
  146. d[attr] = getattr(self, attr)
  147. return d
  148. def from_dict(self, d):
  149. """
  150. Sets object's attributes from a dictionary.
  151. Attributes to include are listed in ``self.ser_attrs``.
  152. This method will look only for only and all the
  153. attributes in ``self.ser_attrs``. They must all
  154. be present. Use only for deserializing saved
  155. objects.
  156. :param d: Dictionary of attributes to set in the object.
  157. :type d: dict
  158. :return: None
  159. """
  160. for attr in self.ser_attrs:
  161. setattr(self, attr, d[attr])
  162. class ApertureMacro:
  163. ## Regular expressions
  164. am1_re = re.compile(r'^%AM([^\*]+)\*(.+)?(%)?$')
  165. am2_re = re.compile(r'(.*)%$')
  166. amcomm_re = re.compile(r'^0(.*)')
  167. amprim_re = re.compile(r'^[1-9].*')
  168. amvar_re = re.compile(r'^\$([0-9a-zA-z]+)=(.*)')
  169. def __init__(self, name=None):
  170. self.name = name
  171. self.raw = ""
  172. ## These below are recomputed for every aperture
  173. ## definition, in other words, are temporary variables.
  174. self.primitives = []
  175. self.locvars = {}
  176. self.geometry = None
  177. def to_dict(self):
  178. """
  179. Returns the object in a serializable form. Only the name and
  180. raw are required.
  181. :return: Dictionary representing the object. JSON ready.
  182. :rtype: dict
  183. """
  184. return {
  185. 'name': self.name,
  186. 'raw': self.raw
  187. }
  188. def from_dict(self, d):
  189. """
  190. Populates the object from a serial representation created
  191. with ``self.to_dict()``.
  192. :param d: Serial representation of an ApertureMacro object.
  193. :return: None
  194. """
  195. for attr in ['name', 'raw']:
  196. setattr(self, attr, d[attr])
  197. def parse_content(self):
  198. """
  199. Creates numerical lists for all primitives in the aperture
  200. macro (in ``self.raw``) by replacing all variables by their
  201. values iteratively and evaluating expressions. Results
  202. are stored in ``self.primitives``.
  203. :return: None
  204. """
  205. # Cleanup
  206. self.raw = self.raw.replace('\n', '').replace('\r', '').strip(" *")
  207. self.primitives = []
  208. # Separate parts
  209. parts = self.raw.split('*')
  210. #### Every part in the macro ####
  211. for part in parts:
  212. ### Comments. Ignored.
  213. match = ApertureMacro.amcomm_re.search(part)
  214. if match:
  215. continue
  216. ### Variables
  217. # These are variables defined locally inside the macro. They can be
  218. # numerical constant or defind in terms of previously define
  219. # variables, which can be defined locally or in an aperture
  220. # definition. All replacements ocurr here.
  221. match = ApertureMacro.amvar_re.search(part)
  222. if match:
  223. var = match.group(1)
  224. val = match.group(2)
  225. # Replace variables in value
  226. for v in self.locvars:
  227. val = re.sub(r'\$'+str(v)+r'(?![0-9a-zA-Z])', str(self.locvars[v]), val)
  228. # Make all others 0
  229. val = re.sub(r'\$[0-9a-zA-Z](?![0-9a-zA-Z])', "0", val)
  230. # Change x with *
  231. val = re.sub(r'[xX]', "*", val)
  232. # Eval() and store.
  233. self.locvars[var] = eval(val)
  234. continue
  235. ### Primitives
  236. # Each is an array. The first identifies the primitive, while the
  237. # rest depend on the primitive. All are strings representing a
  238. # number and may contain variable definition. The values of these
  239. # variables are defined in an aperture definition.
  240. match = ApertureMacro.amprim_re.search(part)
  241. if match:
  242. ## Replace all variables
  243. for v in self.locvars:
  244. part = re.sub(r'\$'+str(v)+r'(?![0-9a-zA-Z])', str(self.locvars[v]), part)
  245. # Make all others 0
  246. part = re.sub(r'\$[0-9a-zA-Z](?![0-9a-zA-Z])', "0", part)
  247. # Change x with *
  248. part = re.sub(r'[xX]', "*", part)
  249. ## Store
  250. elements = part.split(",")
  251. self.primitives.append([eval(x) for x in elements])
  252. continue
  253. log.warning("Unknown syntax of aperture macro part: %s" % str(part))
  254. def append(self, data):
  255. """
  256. Appends a string to the raw macro.
  257. :param data: Part of the macro.
  258. :type data: str
  259. :return: None
  260. """
  261. self.raw += data
  262. @staticmethod
  263. def default2zero(n, mods):
  264. """
  265. Pads the ``mods`` list with zeros resulting in an
  266. list of length n.
  267. :param n: Length of the resulting list.
  268. :type n: int
  269. :param mods: List to be padded.
  270. :type mods: list
  271. :return: Zero-padded list.
  272. :rtype: list
  273. """
  274. x = [0.0]*n
  275. na = len(mods)
  276. x[0:na] = mods
  277. return x
  278. @staticmethod
  279. def make_circle(mods):
  280. """
  281. :param mods: (Exposure 0/1, Diameter >=0, X-coord, Y-coord)
  282. :return:
  283. """
  284. pol, dia, x, y = ApertureMacro.default2zero(4, mods)
  285. return {"pol": int(pol), "geometry": Point(x, y).buffer(dia/2)}
  286. @staticmethod
  287. def make_vectorline(mods):
  288. """
  289. :param mods: (Exposure 0/1, Line width >= 0, X-start, Y-start, X-end, Y-end,
  290. rotation angle around origin in degrees)
  291. :return:
  292. """
  293. pol, width, xs, ys, xe, ye, angle = ApertureMacro.default2zero(7, mods)
  294. line = LineString([(xs, ys), (xe, ye)])
  295. box = line.buffer(width/2, cap_style=2)
  296. box_rotated = affinity.rotate(box, angle, origin=(0, 0))
  297. return {"pol": int(pol), "geometry": box_rotated}
  298. @staticmethod
  299. def make_centerline(mods):
  300. """
  301. :param mods: (Exposure 0/1, width >=0, height >=0, x-center, y-center,
  302. rotation angle around origin in degrees)
  303. :return:
  304. """
  305. pol, width, height, x, y, angle = ApertureMacro.default2zero(6, mods)
  306. box = shply_box(x-width/2, y-height/2, x+width/2, y+height/2)
  307. box_rotated = affinity.rotate(box, angle, origin=(0, 0))
  308. return {"pol": int(pol), "geometry": box_rotated}
  309. @staticmethod
  310. def make_lowerleftline(mods):
  311. """
  312. :param mods: (exposure 0/1, width >=0, height >=0, x-lowerleft, y-lowerleft,
  313. rotation angle around origin in degrees)
  314. :return:
  315. """
  316. pol, width, height, x, y, angle = ApertureMacro.default2zero(6, mods)
  317. box = shply_box(x, y, x+width, y+height)
  318. box_rotated = affinity.rotate(box, angle, origin=(0, 0))
  319. return {"pol": int(pol), "geometry": box_rotated}
  320. @staticmethod
  321. def make_outline(mods):
  322. """
  323. :param mods:
  324. :return:
  325. """
  326. pol = mods[0]
  327. n = mods[1]
  328. points = [(0, 0)]*(n+1)
  329. for i in range(n+1):
  330. points[i] = mods[2*i + 2:2*i + 4]
  331. angle = mods[2*n + 4]
  332. poly = Polygon(points)
  333. poly_rotated = affinity.rotate(poly, angle, origin=(0, 0))
  334. return {"pol": int(pol), "geometry": poly_rotated}
  335. @staticmethod
  336. def make_polygon(mods):
  337. """
  338. Note: Specs indicate that rotation is only allowed if the center
  339. (x, y) == (0, 0). I will tolerate breaking this rule.
  340. :param mods: (exposure 0/1, n_verts 3<=n<=12, x-center, y-center,
  341. diameter of circumscribed circle >=0, rotation angle around origin)
  342. :return:
  343. """
  344. pol, nverts, x, y, dia, angle = ApertureMacro.default2zero(6, mods)
  345. points = [(0, 0)]*nverts
  346. for i in range(nverts):
  347. points[i] = (x + 0.5 * dia * cos(2*pi * i/nverts),
  348. y + 0.5 * dia * sin(2*pi * i/nverts))
  349. poly = Polygon(points)
  350. poly_rotated = affinity.rotate(poly, angle, origin=(0, 0))
  351. return {"pol": int(pol), "geometry": poly_rotated}
  352. @staticmethod
  353. def make_moire(mods):
  354. """
  355. Note: Specs indicate that rotation is only allowed if the center
  356. (x, y) == (0, 0). I will tolerate breaking this rule.
  357. :param mods: (x-center, y-center, outer_dia_outer_ring, ring thickness,
  358. gap, max_rings, crosshair_thickness, crosshair_len, rotation
  359. angle around origin in degrees)
  360. :return:
  361. """
  362. x, y, dia, thickness, gap, nrings, cross_th, cross_len, angle = ApertureMacro.default2zero(9, mods)
  363. r = dia/2 - thickness/2
  364. result = Point((x, y)).buffer(r).exterior.buffer(thickness/2.0)
  365. ring = Point((x, y)).buffer(r).exterior.buffer(thickness/2.0) # Need a copy!
  366. i = 1 # Number of rings created so far
  367. ## If the ring does not have an interior it means that it is
  368. ## a disk. Then stop.
  369. while len(ring.interiors) > 0 and i < nrings:
  370. r -= thickness + gap
  371. if r <= 0:
  372. break
  373. ring = Point((x, y)).buffer(r).exterior.buffer(thickness/2.0)
  374. result = cascaded_union([result, ring])
  375. i += 1
  376. ## Crosshair
  377. hor = LineString([(x - cross_len, y), (x + cross_len, y)]).buffer(cross_th/2.0, cap_style=2)
  378. ver = LineString([(x, y-cross_len), (x, y + cross_len)]).buffer(cross_th/2.0, cap_style=2)
  379. result = cascaded_union([result, hor, ver])
  380. return {"pol": 1, "geometry": result}
  381. @staticmethod
  382. def make_thermal(mods):
  383. """
  384. Note: Specs indicate that rotation is only allowed if the center
  385. (x, y) == (0, 0). I will tolerate breaking this rule.
  386. :param mods: [x-center, y-center, diameter-outside, diameter-inside,
  387. gap-thickness, rotation angle around origin]
  388. :return:
  389. """
  390. x, y, dout, din, t, angle = ApertureMacro.default2zero(6, mods)
  391. ring = Point((x, y)).buffer(dout/2.0).difference(Point((x, y)).buffer(din/2.0))
  392. hline = LineString([(x - dout/2.0, y), (x + dout/2.0, y)]).buffer(t/2.0, cap_style=3)
  393. vline = LineString([(x, y - dout/2.0), (x, y + dout/2.0)]).buffer(t/2.0, cap_style=3)
  394. thermal = ring.difference(hline.union(vline))
  395. return {"pol": 1, "geometry": thermal}
  396. def make_geometry(self, modifiers):
  397. """
  398. Runs the macro for the given modifiers and generates
  399. the corresponding geometry.
  400. :param modifiers: Modifiers (parameters) for this macro
  401. :type modifiers: list
  402. """
  403. ## Primitive makers
  404. makers = {
  405. "1": ApertureMacro.make_circle,
  406. "2": ApertureMacro.make_vectorline,
  407. "20": ApertureMacro.make_vectorline,
  408. "21": ApertureMacro.make_centerline,
  409. "22": ApertureMacro.make_lowerleftline,
  410. "4": ApertureMacro.make_outline,
  411. "5": ApertureMacro.make_polygon,
  412. "6": ApertureMacro.make_moire,
  413. "7": ApertureMacro.make_thermal
  414. }
  415. ## Store modifiers as local variables
  416. modifiers = modifiers or []
  417. modifiers = [float(m) for m in modifiers]
  418. self.locvars = {}
  419. for i in range(0, len(modifiers)):
  420. self.locvars[str(i+1)] = modifiers[i]
  421. ## Parse
  422. self.primitives = [] # Cleanup
  423. self.geometry = None
  424. self.parse_content()
  425. ## Make the geometry
  426. for primitive in self.primitives:
  427. # Make the primitive
  428. prim_geo = makers[str(int(primitive[0]))](primitive[1:])
  429. # Add it (according to polarity)
  430. if self.geometry is None and prim_geo['pol'] == 1:
  431. self.geometry = prim_geo['geometry']
  432. continue
  433. if prim_geo['pol'] == 1:
  434. self.geometry = self.geometry.union(prim_geo['geometry'])
  435. continue
  436. if prim_geo['pol'] == 0:
  437. self.geometry = self.geometry.difference(prim_geo['geometry'])
  438. continue
  439. return self.geometry
  440. class Gerber (Geometry):
  441. """
  442. **ATTRIBUTES**
  443. * ``apertures`` (dict): The keys are names/identifiers of each aperture.
  444. The values are dictionaries key/value pairs which describe the aperture. The
  445. type key is always present and the rest depend on the key:
  446. +-----------+-----------------------------------+
  447. | Key | Value |
  448. +===========+===================================+
  449. | type | (str) "C", "R", "O", "P", or "AP" |
  450. +-----------+-----------------------------------+
  451. | others | Depend on ``type`` |
  452. +-----------+-----------------------------------+
  453. * ``aperture_macros`` (dictionary): Are predefined geometrical structures
  454. that can be instanciated with different parameters in an aperture
  455. definition. See ``apertures`` above. The key is the name of the macro,
  456. and the macro itself, the value, is a ``Aperture_Macro`` object.
  457. * ``flash_geometry`` (list): List of (Shapely) geometric object resulting
  458. from ``flashes``. These are generated from ``flashes`` in ``do_flashes()``.
  459. * ``buffered_paths`` (list): List of (Shapely) polygons resulting from
  460. *buffering* (or thickening) the ``paths`` with the aperture. These are
  461. generated from ``paths`` in ``buffer_paths()``.
  462. **USAGE**::
  463. g = Gerber()
  464. g.parse_file(filename)
  465. g.create_geometry()
  466. do_something(s.solid_geometry)
  467. """
  468. def __init__(self):
  469. """
  470. The constructor takes no parameters. Use ``gerber.parse_files()``
  471. or ``gerber.parse_lines()`` to populate the object from Gerber source.
  472. :return: Gerber object
  473. :rtype: Gerber
  474. """
  475. # Initialize parent
  476. Geometry.__init__(self)
  477. self.solid_geometry = Polygon()
  478. # Number format
  479. self.int_digits = 3
  480. """Number of integer digits in Gerber numbers. Used during parsing."""
  481. self.frac_digits = 4
  482. """Number of fraction digits in Gerber numbers. Used during parsing."""
  483. ## Gerber elements ##
  484. # Apertures {'id':{'type':chr,
  485. # ['size':float], ['width':float],
  486. # ['height':float]}, ...}
  487. self.apertures = {}
  488. # Aperture Macros
  489. self.aperture_macros = {}
  490. # Attributes to be included in serialization
  491. # Always append to it because it carries contents
  492. # from Geometry.
  493. self.ser_attrs += ['int_digits', 'frac_digits', 'apertures',
  494. 'aperture_macros', 'solid_geometry']
  495. #### Parser patterns ####
  496. # FS - Format Specification
  497. # The format of X and Y must be the same!
  498. # L-omit leading zeros, T-omit trailing zeros
  499. # A-absolute notation, I-incremental notation
  500. self.fmt_re = re.compile(r'%FS([LT])([AI])X(\d)(\d)Y\d\d\*%$')
  501. # Mode (IN/MM)
  502. self.mode_re = re.compile(r'^%MO(IN|MM)\*%$')
  503. # Comment G04|G4
  504. self.comm_re = re.compile(r'^G0?4(.*)$')
  505. # AD - Aperture definition
  506. self.ad_re = re.compile(r'^%ADD(\d\d+)([a-zA-Z0-9]*)(?:,(.*))?\*%$')
  507. # AM - Aperture Macro
  508. # Beginning of macro (Ends with *%):
  509. self.am_re = re.compile(r'^%AM([a-zA-Z0-9]*)\*')
  510. # Tool change
  511. # May begin with G54 but that is deprecated
  512. self.tool_re = re.compile(r'^(?:G54)?D(\d\d+)\*$')
  513. # G01... - Linear interpolation plus flashes with coordinates
  514. # Operation code (D0x) missing is deprecated... oh well I will support it.
  515. self.lin_re = re.compile(r'^(?:G0?(1))?(?=.*X(-?\d+))?(?=.*Y(-?\d+))?[XY][^DIJ]*(?:D0?([123]))?\*$')
  516. # Operation code alone, usually just D03 (Flash)
  517. self.opcode_re = re.compile(r'^D0?([123])\*$')
  518. # G02/3... - Circular interpolation with coordinates
  519. # 2-clockwise, 3-counterclockwise
  520. # Operation code (D0x) missing is deprecated... oh well I will support it.
  521. # Optional start with G02 or G03, optional end with D01 or D02 with
  522. # optional coordinates but at least one in any order.
  523. self.circ_re = re.compile(r'^(?:G0?([23]))?(?=.*X(-?\d+))?(?=.*Y(-?\d+))' +
  524. '?(?=.*I(-?\d+))?(?=.*J(-?\d+))?[XYIJ][^D]*(?:D0([12]))?\*$')
  525. # G01/2/3 Occurring without coordinates
  526. self.interp_re = re.compile(r'^(?:G0?([123]))\*')
  527. # Single D74 or multi D75 quadrant for circular interpolation
  528. self.quad_re = re.compile(r'^G7([45])\*$')
  529. # Region mode on
  530. # In region mode, D01 starts a region
  531. # and D02 ends it. A new region can be started again
  532. # with D01. All contours must be closed before
  533. # D02 or G37.
  534. self.regionon_re = re.compile(r'^G36\*$')
  535. # Region mode off
  536. # Will end a region and come off region mode.
  537. # All contours must be closed before D02 or G37.
  538. self.regionoff_re = re.compile(r'^G37\*$')
  539. # End of file
  540. self.eof_re = re.compile(r'^M02\*')
  541. # IP - Image polarity
  542. self.pol_re = re.compile(r'^%IP(POS|NEG)\*%$')
  543. # LP - Level polarity
  544. self.lpol_re = re.compile(r'^%LP([DC])\*%$')
  545. # Units (OBSOLETE)
  546. self.units_re = re.compile(r'^G7([01])\*$')
  547. # Absolute/Relative G90/1 (OBSOLETE)
  548. self.absrel_re = re.compile(r'^G9([01])\*$')
  549. # Aperture macros
  550. self.am1_re = re.compile(r'^%AM([^\*]+)\*(.+)?(%)?$')
  551. self.am2_re = re.compile(r'(.*)%$')
  552. # TODO: This is bad.
  553. self.steps_per_circ = 40
  554. def scale(self, factor):
  555. """
  556. Scales the objects' geometry on the XY plane by a given factor.
  557. These are:
  558. * ``buffered_paths``
  559. * ``flash_geometry``
  560. * ``solid_geometry``
  561. * ``regions``
  562. NOTE:
  563. Does not modify the data used to create these elements. If these
  564. are recreated, the scaling will be lost. This behavior was modified
  565. because of the complexity reached in this class.
  566. :param factor: Number by which to scale.
  567. :type factor: float
  568. :rtype : None
  569. """
  570. ## solid_geometry ???
  571. # It's a cascaded union of objects.
  572. self.solid_geometry = affinity.scale(self.solid_geometry, factor,
  573. factor, origin=(0, 0))
  574. # # Now buffered_paths, flash_geometry and solid_geometry
  575. # self.create_geometry()
  576. def offset(self, vect):
  577. """
  578. Offsets the objects' geometry on the XY plane by a given vector.
  579. These are:
  580. * ``buffered_paths``
  581. * ``flash_geometry``
  582. * ``solid_geometry``
  583. * ``regions``
  584. NOTE:
  585. Does not modify the data used to create these elements. If these
  586. are recreated, the scaling will be lost. This behavior was modified
  587. because of the complexity reached in this class.
  588. :param vect: (x, y) offset vector.
  589. :type vect: tuple
  590. :return: None
  591. """
  592. dx, dy = vect
  593. ## Solid geometry
  594. self.solid_geometry = affinity.translate(self.solid_geometry, xoff=dx, yoff=dy)
  595. def mirror(self, axis, point):
  596. """
  597. Mirrors the object around a specified axis passign through
  598. the given point. What is affected:
  599. * ``buffered_paths``
  600. * ``flash_geometry``
  601. * ``solid_geometry``
  602. * ``regions``
  603. NOTE:
  604. Does not modify the data used to create these elements. If these
  605. are recreated, the scaling will be lost. This behavior was modified
  606. because of the complexity reached in this class.
  607. :param axis: "X" or "Y" indicates around which axis to mirror.
  608. :type axis: str
  609. :param point: [x, y] point belonging to the mirror axis.
  610. :type point: list
  611. :return: None
  612. """
  613. px, py = point
  614. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  615. ## solid_geometry ???
  616. # It's a cascaded union of objects.
  617. self.solid_geometry = affinity.scale(self.solid_geometry,
  618. xscale, yscale, origin=(px, py))
  619. def aperture_parse(self, apertureId, apertureType, apParameters):
  620. """
  621. Parse gerber aperture definition into dictionary of apertures.
  622. The following kinds and their attributes are supported:
  623. * *Circular (C)*: size (float)
  624. * *Rectangle (R)*: width (float), height (float)
  625. * *Obround (O)*: width (float), height (float).
  626. * *Polygon (P)*: diameter(float), vertices(int), [rotation(float)]
  627. * *Aperture Macro (AM)*: macro (ApertureMacro), modifiers (list)
  628. :param apertureId: Id of the aperture being defined.
  629. :param apertureType: Type of the aperture.
  630. :param apParameters: Parameters of the aperture.
  631. :type apertureId: str
  632. :type apertureType: str
  633. :type apParameters: str
  634. :return: Identifier of the aperture.
  635. :rtype: str
  636. """
  637. # Found some Gerber with a leading zero in the aperture id and the
  638. # referenced it without the zero, so this is a hack to handle that.
  639. apid = str(int(apertureId))
  640. try: # Could be empty for aperture macros
  641. paramList = apParameters.split('X')
  642. except:
  643. paramList = None
  644. if apertureType == "C": # Circle, example: %ADD11C,0.1*%
  645. self.apertures[apid] = {"type": "C",
  646. "size": float(paramList[0])}
  647. return apid
  648. if apertureType == "R": # Rectangle, example: %ADD15R,0.05X0.12*%
  649. self.apertures[apid] = {"type": "R",
  650. "width": float(paramList[0]),
  651. "height": float(paramList[1])}
  652. return apid
  653. if apertureType == "O": # Obround
  654. self.apertures[apid] = {"type": "O",
  655. "width": float(paramList[0]),
  656. "height": float(paramList[1])}
  657. return apid
  658. if apertureType == "P": # Polygon (regular)
  659. self.apertures[apid] = {"type": "P",
  660. "diam": float(paramList[0]),
  661. "nVertices": int(paramList[1])}
  662. if len(paramList) >= 3:
  663. self.apertures[apid]["rotation"] = float(paramList[2])
  664. return apid
  665. if apertureType in self.aperture_macros:
  666. self.apertures[apid] = {"type": "AM",
  667. "macro": self.aperture_macros[apertureType],
  668. "modifiers": paramList}
  669. return apid
  670. log.warning("Aperture not implemented: %s" % str(apertureType))
  671. return None
  672. def parse_file(self, filename):
  673. """
  674. Calls Gerber.parse_lines() with array of lines
  675. read from the given file.
  676. :param filename: Gerber file to parse.
  677. :type filename: str
  678. :return: None
  679. """
  680. gfile = open(filename, 'r')
  681. gstr = gfile.readlines()
  682. gfile.close()
  683. self.parse_lines(gstr)
  684. def parse_lines(self, glines):
  685. """
  686. Main Gerber parser. Reads Gerber and populates ``self.paths``, ``self.apertures``,
  687. ``self.flashes``, ``self.regions`` and ``self.units``.
  688. :param glines: Gerber code as list of strings, each element being
  689. one line of the source file.
  690. :type glines: list
  691. :return: None
  692. :rtype: None
  693. """
  694. # Coordinates of the current path, each is [x, y]
  695. path = []
  696. # Polygons are stored here until there is a change in polarity.
  697. # Only then they are combined via cascaded_union and added or
  698. # subtracted from solid_geometry. This is ~100 times faster than
  699. # applyng a union for every new polygon.
  700. poly_buffer = []
  701. last_path_aperture = None
  702. current_aperture = None
  703. # 1,2 or 3 from "G01", "G02" or "G03"
  704. current_interpolation_mode = None
  705. # 1 or 2 from "D01" or "D02"
  706. # Note this is to support deprecated Gerber not putting
  707. # an operation code at the end of every coordinate line.
  708. current_operation_code = None
  709. # Current coordinates
  710. current_x = None
  711. current_y = None
  712. # Absolute or Relative/Incremental coordinates
  713. # Not implemented
  714. absolute = True
  715. # How to interpret circular interpolation: SINGLE or MULTI
  716. quadrant_mode = None
  717. # Indicates we are parsing an aperture macro
  718. current_macro = None
  719. # Indicates the current polarity: D-Dark, C-Clear
  720. current_polarity = 'D'
  721. # If a region is being defined
  722. making_region = False
  723. #### Parsing starts here ####
  724. line_num = 0
  725. for gline in glines:
  726. line_num += 1
  727. ### Cleanup
  728. gline = gline.strip(' \r\n')
  729. ### Aperture Macros
  730. # Having this at the beggining will slow things down
  731. # but macros can have complicated statements than could
  732. # be caught by other ptterns.
  733. if current_macro is None: # No macro started yet
  734. match = self.am1_re.search(gline)
  735. # Start macro if match, else not an AM, carry on.
  736. if match:
  737. current_macro = match.group(1)
  738. self.aperture_macros[current_macro] = ApertureMacro(name=current_macro)
  739. if match.group(2): # Append
  740. self.aperture_macros[current_macro].append(match.group(2))
  741. if match.group(3): # Finish macro
  742. #self.aperture_macros[current_macro].parse_content()
  743. current_macro = None
  744. continue
  745. else: # Continue macro
  746. match = self.am2_re.search(gline)
  747. if match: # Finish macro
  748. self.aperture_macros[current_macro].append(match.group(1))
  749. #self.aperture_macros[current_macro].parse_content()
  750. current_macro = None
  751. else: # Append
  752. self.aperture_macros[current_macro].append(gline)
  753. continue
  754. ### G01 - Linear interpolation plus flashes
  755. # Operation code (D0x) missing is deprecated... oh well I will support it.
  756. # REGEX: r'^(?:G0?(1))?(?:X(-?\d+))?(?:Y(-?\d+))?(?:D0([123]))?\*$'
  757. match = self.lin_re.search(gline)
  758. if match:
  759. # Dxx alone?
  760. # if match.group(1) is None and match.group(2) is None and match.group(3) is None:
  761. # try:
  762. # current_operation_code = int(match.group(4))
  763. # except:
  764. # pass # A line with just * will match too.
  765. # continue
  766. # NOTE: Letting it continue allows it to react to the
  767. # operation code.
  768. # Parse coordinates
  769. if match.group(2) is not None:
  770. current_x = parse_gerber_number(match.group(2), self.frac_digits)
  771. if match.group(3) is not None:
  772. current_y = parse_gerber_number(match.group(3), self.frac_digits)
  773. # Parse operation code
  774. if match.group(4) is not None:
  775. current_operation_code = int(match.group(4))
  776. # Pen down: add segment
  777. if current_operation_code == 1:
  778. path.append([current_x, current_y])
  779. last_path_aperture = current_aperture
  780. elif current_operation_code == 2:
  781. if len(path) > 1:
  782. ## --- BUFFERED ---
  783. if making_region:
  784. geo = Polygon(path)
  785. else:
  786. if last_path_aperture is None:
  787. log.warning("No aperture defined for curent path. (%d)" % line_num)
  788. width = self.apertures[last_path_aperture]["size"]
  789. geo = LineString(path).buffer(width/2)
  790. poly_buffer.append(geo)
  791. path = [[current_x, current_y]] # Start new path
  792. # Flash
  793. elif current_operation_code == 3:
  794. # --- BUFFERED ---
  795. flash = Gerber.create_flash_geometry(Point([current_x, current_y]),
  796. self.apertures[current_aperture])
  797. poly_buffer.append(flash)
  798. continue
  799. ### G02/3 - Circular interpolation
  800. # 2-clockwise, 3-counterclockwise
  801. match = self.circ_re.search(gline)
  802. if match:
  803. mode, x, y, i, j, d = match.groups()
  804. try:
  805. x = parse_gerber_number(x, self.frac_digits)
  806. except:
  807. x = current_x
  808. try:
  809. y = parse_gerber_number(y, self.frac_digits)
  810. except:
  811. y = current_y
  812. try:
  813. i = parse_gerber_number(i, self.frac_digits)
  814. except:
  815. i = 0
  816. try:
  817. j = parse_gerber_number(j, self.frac_digits)
  818. except:
  819. j = 0
  820. if quadrant_mode is None:
  821. log.error("Found arc without preceding quadrant specification G74 or G75. (%d)" % line_num)
  822. log.error(gline)
  823. continue
  824. if mode is None and current_interpolation_mode not in [2, 3]:
  825. log.error("Found arc without circular interpolation mode defined. (%d)" % line_num)
  826. log.error(gline)
  827. continue
  828. elif mode is not None:
  829. current_interpolation_mode = int(mode)
  830. # Set operation code if provided
  831. if d is not None:
  832. current_operation_code = int(d)
  833. # Nothing created! Pen Up.
  834. if current_operation_code == 2:
  835. log.warning("Arc with D2. (%d)" % line_num)
  836. if len(path) > 1:
  837. if last_path_aperture is None:
  838. log.warning("No aperture defined for curent path. (%d)" % line_num)
  839. # --- BUFFERED ---
  840. width = self.apertures[last_path_aperture]["size"]
  841. buffered = LineString(path).buffer(width/2)
  842. poly_buffer.append(buffered)
  843. current_x = x
  844. current_y = y
  845. path = [[current_x, current_y]] # Start new path
  846. continue
  847. # Flash should not happen here
  848. if current_operation_code == 3:
  849. log.error("Trying to flash within arc. (%d)" % line_num)
  850. continue
  851. if quadrant_mode == 'MULTI':
  852. center = [i + current_x, j + current_y]
  853. radius = sqrt(i**2 + j**2)
  854. start = arctan2(-j, -i)
  855. stop = arctan2(-center[1] + y, -center[0] + x)
  856. arcdir = [None, None, "cw", "ccw"]
  857. this_arc = arc(center, radius, start, stop,
  858. arcdir[current_interpolation_mode],
  859. self.steps_per_circ)
  860. # Last point in path is current point
  861. current_x = this_arc[-1][0]
  862. current_y = this_arc[-1][1]
  863. # Append
  864. path += this_arc
  865. last_path_aperture = current_aperture
  866. continue
  867. if quadrant_mode == 'SINGLE':
  868. log.warning("Single quadrant arc are not implemented yet. (%d)" % line_num)
  869. ### Operation code alone
  870. match = self.opcode_re.search(gline)
  871. if match:
  872. current_operation_code = int(match.group(1))
  873. if current_operation_code == 3:
  874. ## --- Buffered ---
  875. flash = Gerber.create_flash_geometry(Point(path[-1]),
  876. self.apertures[current_aperture])
  877. poly_buffer.append(flash)
  878. continue
  879. ### G74/75* - Single or multiple quadrant arcs
  880. match = self.quad_re.search(gline)
  881. if match:
  882. if match.group(1) == '4':
  883. quadrant_mode = 'SINGLE'
  884. else:
  885. quadrant_mode = 'MULTI'
  886. continue
  887. ### G36* - Begin region
  888. if self.regionon_re.search(gline):
  889. if len(path) > 1:
  890. # Take care of what is left in the path
  891. ## --- Buffered ---
  892. width = self.apertures[last_path_aperture]["size"]
  893. geo = LineString(path).buffer(width/2)
  894. poly_buffer.append(geo)
  895. path = [path[-1]]
  896. making_region = True
  897. continue
  898. ### G37* - End region
  899. if self.regionoff_re.search(gline):
  900. making_region = False
  901. # Only one path defines region?
  902. # This can happen if D02 happened before G37 and
  903. # is not and error.
  904. if len(path) < 3:
  905. # print "ERROR: Path contains less than 3 points:"
  906. # print path
  907. # print "Line (%d): " % line_num, gline
  908. # path = []
  909. #path = [[current_x, current_y]]
  910. continue
  911. # For regions we may ignore an aperture that is None
  912. # self.regions.append({"polygon": Polygon(path),
  913. # "aperture": last_path_aperture})
  914. # --- Buffered ---
  915. region = Polygon(path)
  916. if not region.is_valid:
  917. region = region.buffer(0)
  918. poly_buffer.append(region)
  919. path = [[current_x, current_y]] # Start new path
  920. continue
  921. ### Aperture definitions %ADD...
  922. match = self.ad_re.search(gline)
  923. if match:
  924. self.aperture_parse(match.group(1), match.group(2), match.group(3))
  925. continue
  926. ### G01/2/3* - Interpolation mode change
  927. # Can occur along with coordinates and operation code but
  928. # sometimes by itself (handled here).
  929. # Example: G01*
  930. match = self.interp_re.search(gline)
  931. if match:
  932. current_interpolation_mode = int(match.group(1))
  933. continue
  934. ### Tool/aperture change
  935. # Example: D12*
  936. match = self.tool_re.search(gline)
  937. if match:
  938. current_aperture = match.group(1)
  939. continue
  940. ### Polarity change
  941. # Example: %LPD*% or %LPC*%
  942. match = self.lpol_re.search(gline)
  943. if match:
  944. if len(path) > 1 and current_polarity != match.group(1):
  945. # --- Buffered ----
  946. width = self.apertures[last_path_aperture]["size"]
  947. geo = LineString(path).buffer(width/2)
  948. poly_buffer.append(geo)
  949. path = [path[-1]]
  950. # --- Apply buffer ---
  951. if current_polarity == 'D':
  952. self.solid_geometry = self.solid_geometry.union(cascaded_union(poly_buffer))
  953. else:
  954. self.solid_geometry = self.solid_geometry.difference(cascaded_union(poly_buffer))
  955. poly_buffer = []
  956. current_polarity = match.group(1)
  957. continue
  958. ### Number format
  959. # Example: %FSLAX24Y24*%
  960. # TODO: This is ignoring most of the format. Implement the rest.
  961. match = self.fmt_re.search(gline)
  962. if match:
  963. absolute = {'A': True, 'I': False}
  964. self.int_digits = int(match.group(3))
  965. self.frac_digits = int(match.group(4))
  966. continue
  967. ### Mode (IN/MM)
  968. # Example: %MOIN*%
  969. match = self.mode_re.search(gline)
  970. if match:
  971. self.units = match.group(1)
  972. continue
  973. ### Units (G70/1) OBSOLETE
  974. match = self.units_re.search(gline)
  975. if match:
  976. self.units = {'0': 'IN', '1': 'MM'}[match.group(1)]
  977. continue
  978. ### Absolute/relative coordinates G90/1 OBSOLETE
  979. match = self.absrel_re.search(gline)
  980. if match:
  981. absolute = {'0': True, '1': False}[match.group(1)]
  982. continue
  983. #### Ignored lines
  984. ## Comments
  985. match = self.comm_re.search(gline)
  986. if match:
  987. continue
  988. ## EOF
  989. match = self.eof_re.search(gline)
  990. if match:
  991. continue
  992. ### Line did not match any pattern. Warn user.
  993. log.warning("Line ignored (%d): %s" % (line_num, gline))
  994. if len(path) > 1:
  995. # EOF, create shapely LineString if something still in path
  996. ## --- Buffered ---
  997. width = self.apertures[last_path_aperture]["size"]
  998. geo = LineString(path).buffer(width/2)
  999. poly_buffer.append(geo)
  1000. # --- Apply buffer ---
  1001. if current_polarity == 'D':
  1002. self.solid_geometry = self.solid_geometry.union(cascaded_union(poly_buffer))
  1003. else:
  1004. self.solid_geometry = self.solid_geometry.difference(cascaded_union(poly_buffer))
  1005. @staticmethod
  1006. def create_flash_geometry(location, aperture):
  1007. if type(location) == list:
  1008. location = Point(location)
  1009. if aperture['type'] == 'C': # Circles
  1010. return location.buffer(aperture['size']/2)
  1011. if aperture['type'] == 'R': # Rectangles
  1012. loc = location.coords[0]
  1013. width = aperture['width']
  1014. height = aperture['height']
  1015. minx = loc[0] - width/2
  1016. maxx = loc[0] + width/2
  1017. miny = loc[1] - height/2
  1018. maxy = loc[1] + height/2
  1019. return shply_box(minx, miny, maxx, maxy)
  1020. if aperture['type'] == 'O': # Obround
  1021. loc = location.coords[0]
  1022. width = aperture['width']
  1023. height = aperture['height']
  1024. if width > height:
  1025. p1 = Point(loc[0] + 0.5*(width-height), loc[1])
  1026. p2 = Point(loc[0] - 0.5*(width-height), loc[1])
  1027. c1 = p1.buffer(height*0.5)
  1028. c2 = p2.buffer(height*0.5)
  1029. else:
  1030. p1 = Point(loc[0], loc[1] + 0.5*(height-width))
  1031. p2 = Point(loc[0], loc[1] - 0.5*(height-width))
  1032. c1 = p1.buffer(width*0.5)
  1033. c2 = p2.buffer(width*0.5)
  1034. return cascaded_union([c1, c2]).convex_hull
  1035. if aperture['type'] == 'P': # Regular polygon
  1036. loc = location.coords[0]
  1037. diam = aperture['diam']
  1038. n_vertices = aperture['nVertices']
  1039. points = []
  1040. for i in range(0, n_vertices):
  1041. x = loc[0] + diam * (cos(2 * pi * i / n_vertices))
  1042. y = loc[1] + diam * (sin(2 * pi * i / n_vertices))
  1043. points.append((x, y))
  1044. ply = Polygon(points)
  1045. if 'rotation' in aperture:
  1046. ply = affinity.rotate(ply, aperture['rotation'])
  1047. return ply
  1048. if aperture['type'] == 'AM': # Aperture Macro
  1049. loc = location.coords[0]
  1050. flash_geo = aperture['macro'].make_geometry(aperture['modifiers'])
  1051. return affinity.translate(flash_geo, xoff=loc[0], yoff=loc[1])
  1052. return None
  1053. def create_geometry(self):
  1054. """
  1055. Geometry from a Gerber file is made up entirely of polygons.
  1056. Every stroke (linear or circular) has an aperture which gives
  1057. it thickness. Additionally, aperture strokes have non-zero area,
  1058. and regions naturally do as well.
  1059. :rtype : None
  1060. :return: None
  1061. """
  1062. # self.buffer_paths()
  1063. #
  1064. # self.fix_regions()
  1065. #
  1066. # self.do_flashes()
  1067. #
  1068. # self.solid_geometry = cascaded_union(self.buffered_paths +
  1069. # [poly['polygon'] for poly in self.regions] +
  1070. # self.flash_geometry)
  1071. def get_bounding_box(self, margin=0.0, rounded=False):
  1072. """
  1073. Creates and returns a rectangular polygon bounding at a distance of
  1074. margin from the object's ``solid_geometry``. If margin > 0, the polygon
  1075. can optionally have rounded corners of radius equal to margin.
  1076. :param margin: Distance to enlarge the rectangular bounding
  1077. box in both positive and negative, x and y axes.
  1078. :type margin: float
  1079. :param rounded: Wether or not to have rounded corners.
  1080. :type rounded: bool
  1081. :return: The bounding box.
  1082. :rtype: Shapely.Polygon
  1083. """
  1084. bbox = self.solid_geometry.envelope.buffer(margin)
  1085. if not rounded:
  1086. bbox = bbox.envelope
  1087. return bbox
  1088. class Excellon(Geometry):
  1089. """
  1090. *ATTRIBUTES*
  1091. * ``tools`` (dict): The key is the tool name and the value is
  1092. a dictionary specifying the tool:
  1093. ================ ====================================
  1094. Key Value
  1095. ================ ====================================
  1096. C Diameter of the tool
  1097. Others Not supported (Ignored).
  1098. ================ ====================================
  1099. * ``drills`` (list): Each is a dictionary:
  1100. ================ ====================================
  1101. Key Value
  1102. ================ ====================================
  1103. point (Shapely.Point) Where to drill
  1104. tool (str) A key in ``tools``
  1105. ================ ====================================
  1106. """
  1107. def __init__(self):
  1108. """
  1109. The constructor takes no parameters.
  1110. :return: Excellon object.
  1111. :rtype: Excellon
  1112. """
  1113. Geometry.__init__(self)
  1114. self.tools = {}
  1115. self.drills = []
  1116. # Trailing "T" or leading "L" (default)
  1117. self.zeros = "L"
  1118. # Attributes to be included in serialization
  1119. # Always append to it because it carries contents
  1120. # from Geometry.
  1121. self.ser_attrs += ['tools', 'drills', 'zeros']
  1122. #### Patterns ####
  1123. # Regex basics:
  1124. # ^ - beginning
  1125. # $ - end
  1126. # *: 0 or more, +: 1 or more, ?: 0 or 1
  1127. # M48 - Beggining of Part Program Header
  1128. self.hbegin_re = re.compile(r'^M48$')
  1129. # M95 or % - End of Part Program Header
  1130. # NOTE: % has different meaning in the body
  1131. self.hend_re = re.compile(r'^(?:M95|%)$')
  1132. # FMAT Excellon format
  1133. self.fmat_re = re.compile(r'^FMAT,([12])$')
  1134. # Number format and units
  1135. # INCH uses 6 digits
  1136. # METRIC uses 5/6
  1137. self.units_re = re.compile(r'^(INCH|METRIC)(?:,([TL])Z)?$')
  1138. # Tool definition/parameters (?= is look-ahead
  1139. # NOTE: This might be an overkill!
  1140. # self.toolset_re = re.compile(r'^T(0?\d|\d\d)(?=.*C(\d*\.?\d*))?' +
  1141. # r'(?=.*F(\d*\.?\d*))?(?=.*S(\d*\.?\d*))?' +
  1142. # r'(?=.*B(\d*\.?\d*))?(?=.*H(\d*\.?\d*))?' +
  1143. # r'(?=.*Z([-\+]?\d*\.?\d*))?[CFSBHT]')
  1144. self.toolset_re = re.compile(r'^T(\d+)(?=.*C(\d*\.?\d*))?' +
  1145. r'(?=.*F(\d*\.?\d*))?(?=.*S(\d*\.?\d*))?' +
  1146. r'(?=.*B(\d*\.?\d*))?(?=.*H(\d*\.?\d*))?' +
  1147. r'(?=.*Z([-\+]?\d*\.?\d*))?[CFSBHT]')
  1148. # Tool select
  1149. # Can have additional data after tool number but
  1150. # is ignored if present in the header.
  1151. # Warning: This will match toolset_re too.
  1152. # self.toolsel_re = re.compile(r'^T((?:\d\d)|(?:\d))')
  1153. self.toolsel_re = re.compile(r'^T(\d+)')
  1154. # Comment
  1155. self.comm_re = re.compile(r'^;(.*)$')
  1156. # Absolute/Incremental G90/G91
  1157. self.absinc_re = re.compile(r'^G9([01])$')
  1158. # Modes of operation
  1159. # 1-linear, 2-circCW, 3-cirCCW, 4-vardwell, 5-Drill
  1160. self.modes_re = re.compile(r'^G0([012345])')
  1161. # Measuring mode
  1162. # 1-metric, 2-inch
  1163. self.meas_re = re.compile(r'^M7([12])$')
  1164. # Coordinates
  1165. #self.xcoord_re = re.compile(r'^X(\d*\.?\d*)(?:Y\d*\.?\d*)?$')
  1166. #self.ycoord_re = re.compile(r'^(?:X\d*\.?\d*)?Y(\d*\.?\d*)$')
  1167. self.coordsperiod_re = re.compile(r'(?=.*X([-\+]?\d*\.\d*))?(?=.*Y([-\+]?\d*\.\d*))?[XY]')
  1168. self.coordsnoperiod_re = re.compile(r'(?!.*\.)(?=.*X([-\+]?\d*))?(?=.*Y([-\+]?\d*))?[XY]')
  1169. # R - Repeat hole (# times, X offset, Y offset)
  1170. self.rep_re = re.compile(r'^R(\d+)(?=.*[XY])+(?:X([-\+]?\d*\.?\d*))?(?:Y([-\+]?\d*\.?\d*))?$')
  1171. # Various stop/pause commands
  1172. self.stop_re = re.compile(r'^((G04)|(M09)|(M06)|(M00)|(M30))')
  1173. # Parse coordinates
  1174. self.leadingzeros_re = re.compile(r'^(0*)(\d*)')
  1175. def parse_file(self, filename):
  1176. """
  1177. Reads the specified file as array of lines as
  1178. passes it to ``parse_lines()``.
  1179. :param filename: The file to be read and parsed.
  1180. :type filename: str
  1181. :return: None
  1182. """
  1183. efile = open(filename, 'r')
  1184. estr = efile.readlines()
  1185. efile.close()
  1186. self.parse_lines(estr)
  1187. def parse_lines(self, elines):
  1188. """
  1189. Main Excellon parser.
  1190. :param elines: List of strings, each being a line of Excellon code.
  1191. :type elines: list
  1192. :return: None
  1193. """
  1194. # State variables
  1195. current_tool = ""
  1196. in_header = False
  1197. current_x = None
  1198. current_y = None
  1199. line_num = 0 # Line number
  1200. for eline in elines:
  1201. line_num += 1
  1202. ### Cleanup lines
  1203. eline = eline.strip(' \r\n')
  1204. ## Header Begin/End ##
  1205. if self.hbegin_re.search(eline):
  1206. in_header = True
  1207. continue
  1208. if self.hend_re.search(eline):
  1209. in_header = False
  1210. continue
  1211. #### Body ####
  1212. if not in_header:
  1213. ## Tool change ##
  1214. match = self.toolsel_re.search(eline)
  1215. if match:
  1216. current_tool = str(int(match.group(1)))
  1217. continue
  1218. ## Coordinates without period ##
  1219. match = self.coordsnoperiod_re.search(eline)
  1220. if match:
  1221. try:
  1222. #x = float(match.group(1))/10000
  1223. x = self.parse_number(match.group(1))
  1224. current_x = x
  1225. except TypeError:
  1226. x = current_x
  1227. try:
  1228. #y = float(match.group(2))/10000
  1229. y = self.parse_number(match.group(2))
  1230. current_y = y
  1231. except TypeError:
  1232. y = current_y
  1233. if x is None or y is None:
  1234. log.error("Missing coordinates")
  1235. continue
  1236. self.drills.append({'point': Point((x, y)), 'tool': current_tool})
  1237. continue
  1238. ## Coordinates with period: Use literally. ##
  1239. match = self.coordsperiod_re.search(eline)
  1240. if match:
  1241. try:
  1242. x = float(match.group(1))
  1243. current_x = x
  1244. except TypeError:
  1245. x = current_x
  1246. try:
  1247. y = float(match.group(2))
  1248. current_y = y
  1249. except TypeError:
  1250. y = current_y
  1251. if x is None or y is None:
  1252. log.error("Missing coordinates")
  1253. continue
  1254. self.drills.append({'point': Point((x, y)), 'tool': current_tool})
  1255. continue
  1256. #### Header ####
  1257. if in_header:
  1258. ## Tool definitions ##
  1259. match = self.toolset_re.search(eline)
  1260. if match:
  1261. name = str(int(match.group(1)))
  1262. spec = {
  1263. "C": float(match.group(2)),
  1264. # "F": float(match.group(3)),
  1265. # "S": float(match.group(4)),
  1266. # "B": float(match.group(5)),
  1267. # "H": float(match.group(6)),
  1268. # "Z": float(match.group(7))
  1269. }
  1270. self.tools[name] = spec
  1271. continue
  1272. ## Units and number format ##
  1273. match = self.units_re.match(eline)
  1274. if match:
  1275. self.zeros = match.group(2) # "T" or "L"
  1276. self.units = {"INCH": "IN", "METRIC": "MM"}[match.group(1)]
  1277. continue
  1278. log.warning("Line ignored: %s" % eline)
  1279. def parse_number(self, number_str):
  1280. """
  1281. Parses coordinate numbers without period.
  1282. :param number_str: String representing the numerical value.
  1283. :type number_str: str
  1284. :return: Floating point representation of the number
  1285. :rtype: foat
  1286. """
  1287. if self.zeros == "L":
  1288. match = self.leadingzeros_re.search(number_str)
  1289. return float(number_str)/(10**(len(match.group(2))-2+len(match.group(1))))
  1290. else: # Trailing
  1291. return float(number_str)/10000
  1292. def create_geometry(self):
  1293. """
  1294. Creates circles of the tool diameter at every point
  1295. specified in ``self.drills``.
  1296. :return: None
  1297. """
  1298. self.solid_geometry = []
  1299. for drill in self.drills:
  1300. #poly = drill['point'].buffer(self.tools[drill['tool']]["C"]/2.0)
  1301. tooldia = self.tools[drill['tool']]['C']
  1302. poly = drill['point'].buffer(tooldia/2.0)
  1303. self.solid_geometry.append(poly)
  1304. def scale(self, factor):
  1305. """
  1306. Scales geometry on the XY plane in the object by a given factor.
  1307. Tool sizes, feedrates an Z-plane dimensions are untouched.
  1308. :param factor: Number by which to scale the object.
  1309. :type factor: float
  1310. :return: None
  1311. :rtype: NOne
  1312. """
  1313. # Drills
  1314. for drill in self.drills:
  1315. drill['point'] = affinity.scale(drill['point'], factor, factor, origin=(0, 0))
  1316. self.create_geometry()
  1317. def offset(self, vect):
  1318. """
  1319. Offsets geometry on the XY plane in the object by a given vector.
  1320. :param vect: (x, y) offset vector.
  1321. :type vect: tuple
  1322. :return: None
  1323. """
  1324. dx, dy = vect
  1325. # Drills
  1326. for drill in self.drills:
  1327. drill['point'] = affinity.translate(drill['point'], xoff=dx, yoff=dy)
  1328. # Recreate geometry
  1329. self.create_geometry()
  1330. def mirror(self, axis, point):
  1331. """
  1332. :param axis: "X" or "Y" indicates around which axis to mirror.
  1333. :type axis: str
  1334. :param point: [x, y] point belonging to the mirror axis.
  1335. :type point: list
  1336. :return: None
  1337. """
  1338. px, py = point
  1339. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  1340. # Modify data
  1341. for drill in self.drills:
  1342. drill['point'] = affinity.scale(drill['point'], xscale, yscale, origin=(px, py))
  1343. # Recreate geometry
  1344. self.create_geometry()
  1345. def convert_units(self, units):
  1346. factor = Geometry.convert_units(self, units)
  1347. # Tools
  1348. for tname in self.tools:
  1349. self.tools[tname]["C"] *= factor
  1350. self.create_geometry()
  1351. return factor
  1352. class CNCjob(Geometry):
  1353. """
  1354. Represents work to be done by a CNC machine.
  1355. *ATTRIBUTES*
  1356. * ``gcode_parsed`` (list): Each is a dictionary:
  1357. ===================== =========================================
  1358. Key Value
  1359. ===================== =========================================
  1360. geom (Shapely.LineString) Tool path (XY plane)
  1361. kind (string) "AB", A is "T" (travel) or
  1362. "C" (cut). B is "F" (fast) or "S" (slow).
  1363. ===================== =========================================
  1364. """
  1365. def __init__(self, units="in", kind="generic", z_move=0.1,
  1366. feedrate=3.0, z_cut=-0.002, tooldia=0.0):
  1367. Geometry.__init__(self)
  1368. self.kind = kind
  1369. self.units = units
  1370. self.z_cut = z_cut
  1371. self.z_move = z_move
  1372. self.feedrate = feedrate
  1373. self.tooldia = tooldia
  1374. self.unitcode = {"IN": "G20", "MM": "G21"}
  1375. self.pausecode = "G04 P1"
  1376. self.feedminutecode = "G94"
  1377. self.absolutecode = "G90"
  1378. self.gcode = ""
  1379. self.input_geometry_bounds = None
  1380. self.gcode_parsed = None
  1381. self.steps_per_circ = 20 # Used when parsing G-code arcs
  1382. # Attributes to be included in serialization
  1383. # Always append to it because it carries contents
  1384. # from Geometry.
  1385. self.ser_attrs += ['kind', 'z_cut', 'z_move', 'feedrate', 'tooldia',
  1386. 'gcode', 'input_geometry_bounds', 'gcode_parsed',
  1387. 'steps_per_circ']
  1388. def convert_units(self, units):
  1389. factor = Geometry.convert_units(self, units)
  1390. log.debug("CNCjob.convert_units()")
  1391. self.z_cut *= factor
  1392. self.z_move *= factor
  1393. self.feedrate *= factor
  1394. self.tooldia *= factor
  1395. return factor
  1396. def generate_from_excellon(self, exobj):
  1397. """
  1398. Generates G-code for drilling from Excellon object.
  1399. self.gcode becomes a list, each element is a
  1400. different job for each tool in the excellon code.
  1401. """
  1402. self.kind = "drill"
  1403. self.gcode = []
  1404. t = "G00 X%.4fY%.4f\n"
  1405. down = "G01 Z%.4f\n" % self.z_cut
  1406. up = "G01 Z%.4f\n" % self.z_move
  1407. for tool in exobj.tools:
  1408. points = []
  1409. for drill in exobj.drill:
  1410. if drill['tool'] == tool:
  1411. points.append(drill['point'])
  1412. gcode = self.unitcode[self.units.upper()] + "\n"
  1413. gcode += self.absolutecode + "\n"
  1414. gcode += self.feedminutecode + "\n"
  1415. gcode += "F%.2f\n" % self.feedrate
  1416. gcode += "G00 Z%.4f\n" % self.z_move # Move to travel height
  1417. gcode += "M03\n" # Spindle start
  1418. gcode += self.pausecode + "\n"
  1419. for point in points:
  1420. gcode += t % point
  1421. gcode += down + up
  1422. gcode += t % (0, 0)
  1423. gcode += "M05\n" # Spindle stop
  1424. self.gcode.append(gcode)
  1425. def generate_from_excellon_by_tool(self, exobj, tools="all"):
  1426. """
  1427. Creates gcode for this object from an Excellon object
  1428. for the specified tools.
  1429. :param exobj: Excellon object to process
  1430. :type exobj: Excellon
  1431. :param tools: Comma separated tool names
  1432. :type: tools: str
  1433. :return: None
  1434. :rtype: None
  1435. """
  1436. log.debug("Creating CNC Job from Excellon...")
  1437. if tools == "all":
  1438. tools = [tool for tool in exobj.tools]
  1439. else:
  1440. tools = [x.strip() for x in tools.split(",")]
  1441. tools = filter(lambda i: i in exobj.tools, tools)
  1442. log.debug("Tools are: %s" % str(tools))
  1443. points = []
  1444. for drill in exobj.drills:
  1445. if drill['tool'] in tools:
  1446. points.append(drill['point'])
  1447. log.debug("Found %d drills." % len(points))
  1448. #self.kind = "drill"
  1449. self.gcode = []
  1450. t = "G00 X%.4fY%.4f\n"
  1451. down = "G01 Z%.4f\n" % self.z_cut
  1452. up = "G01 Z%.4f\n" % self.z_move
  1453. gcode = self.unitcode[self.units.upper()] + "\n"
  1454. gcode += self.absolutecode + "\n"
  1455. gcode += self.feedminutecode + "\n"
  1456. gcode += "F%.2f\n" % self.feedrate
  1457. gcode += "G00 Z%.4f\n" % self.z_move # Move to travel height
  1458. gcode += "M03\n" # Spindle start
  1459. gcode += self.pausecode + "\n"
  1460. for point in points:
  1461. x, y = point.coords.xy
  1462. gcode += t % (x[0], y[0])
  1463. gcode += down + up
  1464. gcode += t % (0, 0)
  1465. gcode += "M05\n" # Spindle stop
  1466. self.gcode = gcode
  1467. def generate_from_geometry(self, geometry, append=True, tooldia=None, tolerance=0):
  1468. """
  1469. Generates G-Code from a Geometry object. Stores in ``self.gcode``.
  1470. :param geometry: Geometry defining the toolpath
  1471. :type geometry: Geometry
  1472. :param append: Wether to append to self.gcode or re-write it.
  1473. :type append: bool
  1474. :param tooldia: If given, sets the tooldia property but does
  1475. not affect the process in any other way.
  1476. :type tooldia: bool
  1477. :param tolerance: All points in the simplified object will be within the
  1478. tolerance distance of the original geometry.
  1479. :return: None
  1480. :rtype: None
  1481. """
  1482. if tooldia is not None:
  1483. self.tooldia = tooldia
  1484. self.input_geometry_bounds = geometry.bounds()
  1485. if not append:
  1486. self.gcode = ""
  1487. self.gcode = self.unitcode[self.units.upper()] + "\n"
  1488. self.gcode += self.absolutecode + "\n"
  1489. self.gcode += self.feedminutecode + "\n"
  1490. self.gcode += "F%.2f\n" % self.feedrate
  1491. self.gcode += "G00 Z%.4f\n" % self.z_move # Move to travel height
  1492. self.gcode += "M03\n" # Spindle start
  1493. self.gcode += self.pausecode + "\n"
  1494. for geo in geometry.solid_geometry:
  1495. if type(geo) == Polygon:
  1496. self.gcode += self.polygon2gcode(geo, tolerance=tolerance)
  1497. continue
  1498. if type(geo) == LineString or type(geo) == LinearRing:
  1499. self.gcode += self.linear2gcode(geo, tolerance=tolerance)
  1500. continue
  1501. if type(geo) == Point:
  1502. self.gcode += self.point2gcode(geo)
  1503. continue
  1504. if type(geo) == MultiPolygon:
  1505. for poly in geo:
  1506. self.gcode += self.polygon2gcode(poly, tolerance=tolerance)
  1507. continue
  1508. log.warning("G-code generation not implemented for %s" % (str(type(geo))))
  1509. self.gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  1510. self.gcode += "G00 X0Y0\n"
  1511. self.gcode += "M05\n" # Spindle stop
  1512. def pre_parse(self, gtext):
  1513. """
  1514. Separates parts of the G-Code text into a list of dictionaries.
  1515. Used by ``self.gcode_parse()``.
  1516. :param gtext: A single string with g-code
  1517. """
  1518. # Units: G20-inches, G21-mm
  1519. units_re = re.compile(r'^G2([01])')
  1520. # TODO: This has to be re-done
  1521. gcmds = []
  1522. lines = gtext.split("\n") # TODO: This is probably a lot of work!
  1523. for line in lines:
  1524. # Clean up
  1525. line = line.strip()
  1526. # Remove comments
  1527. # NOTE: Limited to 1 bracket pair
  1528. op = line.find("(")
  1529. cl = line.find(")")
  1530. #if op > -1 and cl > op:
  1531. if cl > op > -1:
  1532. #comment = line[op+1:cl]
  1533. line = line[:op] + line[(cl+1):]
  1534. # Units
  1535. match = units_re.match(line)
  1536. if match:
  1537. self.units = {'0': "IN", '1': "MM"}[match.group(1)]
  1538. # Parse GCode
  1539. # 0 4 12
  1540. # G01 X-0.007 Y-0.057
  1541. # --> codes_idx = [0, 4, 12]
  1542. codes = "NMGXYZIJFP"
  1543. codes_idx = []
  1544. i = 0
  1545. for ch in line:
  1546. if ch in codes:
  1547. codes_idx.append(i)
  1548. i += 1
  1549. n_codes = len(codes_idx)
  1550. if n_codes == 0:
  1551. continue
  1552. # Separate codes in line
  1553. parts = []
  1554. for p in range(n_codes-1):
  1555. parts.append(line[codes_idx[p]:codes_idx[p+1]].strip())
  1556. parts.append(line[codes_idx[-1]:].strip())
  1557. # Separate codes from values
  1558. cmds = {}
  1559. for part in parts:
  1560. cmds[part[0]] = float(part[1:])
  1561. gcmds.append(cmds)
  1562. return gcmds
  1563. def gcode_parse(self):
  1564. """
  1565. G-Code parser (from self.gcode). Generates dictionary with
  1566. single-segment LineString's and "kind" indicating cut or travel,
  1567. fast or feedrate speed.
  1568. """
  1569. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  1570. # Results go here
  1571. geometry = []
  1572. # TODO: Merge into single parser?
  1573. gobjs = self.pre_parse(self.gcode)
  1574. # Last known instruction
  1575. current = {'X': 0.0, 'Y': 0.0, 'Z': 0.0, 'G': 0}
  1576. # Current path: temporary storage until tool is
  1577. # lifted or lowered.
  1578. path = [(0, 0)]
  1579. # Process every instruction
  1580. for gobj in gobjs:
  1581. ## Changing height
  1582. if 'Z' in gobj:
  1583. if ('X' in gobj or 'Y' in gobj) and gobj['Z'] != current['Z']:
  1584. log.warning("Non-orthogonal motion: From %s" % str(current))
  1585. log.warning(" To: %s" % str(gobj))
  1586. current['Z'] = gobj['Z']
  1587. # Store the path into geometry and reset path
  1588. if len(path) > 1:
  1589. geometry.append({"geom": LineString(path),
  1590. "kind": kind})
  1591. path = [path[-1]] # Start with the last point of last path.
  1592. if 'G' in gobj:
  1593. current['G'] = int(gobj['G'])
  1594. if 'X' in gobj or 'Y' in gobj:
  1595. if 'X' in gobj:
  1596. x = gobj['X']
  1597. else:
  1598. x = current['X']
  1599. if 'Y' in gobj:
  1600. y = gobj['Y']
  1601. else:
  1602. y = current['Y']
  1603. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  1604. if current['Z'] > 0:
  1605. kind[0] = 'T'
  1606. if current['G'] > 0:
  1607. kind[1] = 'S'
  1608. arcdir = [None, None, "cw", "ccw"]
  1609. if current['G'] in [0, 1]: # line
  1610. path.append((x, y))
  1611. if current['G'] in [2, 3]: # arc
  1612. center = [gobj['I'] + current['X'], gobj['J'] + current['Y']]
  1613. radius = sqrt(gobj['I']**2 + gobj['J']**2)
  1614. start = arctan2(-gobj['J'], -gobj['I'])
  1615. stop = arctan2(-center[1]+y, -center[0]+x)
  1616. path += arc(center, radius, start, stop,
  1617. arcdir[current['G']],
  1618. self.steps_per_circ)
  1619. # Update current instruction
  1620. for code in gobj:
  1621. current[code] = gobj[code]
  1622. # There might not be a change in height at the
  1623. # end, therefore, see here too if there is
  1624. # a final path.
  1625. if len(path) > 1:
  1626. geometry.append({"geom": LineString(path),
  1627. "kind": kind})
  1628. self.gcode_parsed = geometry
  1629. return geometry
  1630. # def plot(self, tooldia=None, dpi=75, margin=0.1,
  1631. # color={"T": ["#F0E24D", "#B5AB3A"], "C": ["#5E6CFF", "#4650BD"]},
  1632. # alpha={"T": 0.3, "C": 1.0}):
  1633. # """
  1634. # Creates a Matplotlib figure with a plot of the
  1635. # G-code job.
  1636. # """
  1637. # if tooldia is None:
  1638. # tooldia = self.tooldia
  1639. #
  1640. # fig = Figure(dpi=dpi)
  1641. # ax = fig.add_subplot(111)
  1642. # ax.set_aspect(1)
  1643. # xmin, ymin, xmax, ymax = self.input_geometry_bounds
  1644. # ax.set_xlim(xmin-margin, xmax+margin)
  1645. # ax.set_ylim(ymin-margin, ymax+margin)
  1646. #
  1647. # if tooldia == 0:
  1648. # for geo in self.gcode_parsed:
  1649. # linespec = '--'
  1650. # linecolor = color[geo['kind'][0]][1]
  1651. # if geo['kind'][0] == 'C':
  1652. # linespec = 'k-'
  1653. # x, y = geo['geom'].coords.xy
  1654. # ax.plot(x, y, linespec, color=linecolor)
  1655. # else:
  1656. # for geo in self.gcode_parsed:
  1657. # poly = geo['geom'].buffer(tooldia/2.0)
  1658. # patch = PolygonPatch(poly, facecolor=color[geo['kind'][0]][0],
  1659. # edgecolor=color[geo['kind'][0]][1],
  1660. # alpha=alpha[geo['kind'][0]], zorder=2)
  1661. # ax.add_patch(patch)
  1662. #
  1663. # return fig
  1664. def plot2(self, axes, tooldia=None, dpi=75, margin=0.1,
  1665. color={"T": ["#F0E24D", "#B5AB3A"], "C": ["#5E6CFF", "#4650BD"]},
  1666. alpha={"T": 0.3, "C": 1.0}, tool_tolerance=0.0005):
  1667. """
  1668. Plots the G-code job onto the given axes.
  1669. :param axes: Matplotlib axes on which to plot.
  1670. :param tooldia: Tool diameter.
  1671. :param dpi: Not used!
  1672. :param margin: Not used!
  1673. :param color: Color specification.
  1674. :param alpha: Transparency specification.
  1675. :param tool_tolerance: Tolerance when drawing the toolshape.
  1676. :return: None
  1677. """
  1678. if tooldia is None:
  1679. tooldia = self.tooldia
  1680. if tooldia == 0:
  1681. for geo in self.gcode_parsed:
  1682. linespec = '--'
  1683. linecolor = color[geo['kind'][0]][1]
  1684. if geo['kind'][0] == 'C':
  1685. linespec = 'k-'
  1686. x, y = geo['geom'].coords.xy
  1687. axes.plot(x, y, linespec, color=linecolor)
  1688. else:
  1689. for geo in self.gcode_parsed:
  1690. poly = geo['geom'].buffer(tooldia/2.0).simplify(tool_tolerance)
  1691. patch = PolygonPatch(poly, facecolor=color[geo['kind'][0]][0],
  1692. edgecolor=color[geo['kind'][0]][1],
  1693. alpha=alpha[geo['kind'][0]], zorder=2)
  1694. axes.add_patch(patch)
  1695. def create_geometry(self):
  1696. # TODO: This takes forever. Too much data?
  1697. self.solid_geometry = cascaded_union([geo['geom'] for geo in self.gcode_parsed])
  1698. def polygon2gcode(self, polygon, tolerance=0):
  1699. """
  1700. Creates G-Code for the exterior and all interior paths
  1701. of a polygon.
  1702. :param polygon: A Shapely.Polygon
  1703. :type polygon: Shapely.Polygon
  1704. :param tolerance: All points in the simplified object will be within the
  1705. tolerance distance of the original geometry.
  1706. :type tolerance: float
  1707. :return: G-code to cut along polygon.
  1708. :rtype: str
  1709. """
  1710. if tolerance > 0:
  1711. target_polygon = polygon.simplify(tolerance)
  1712. else:
  1713. target_polygon = polygon
  1714. gcode = ""
  1715. t = "G0%d X%.4fY%.4f\n"
  1716. path = list(target_polygon.exterior.coords) # Polygon exterior
  1717. gcode += t % (0, path[0][0], path[0][1]) # Move to first point
  1718. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  1719. for pt in path[1:]:
  1720. gcode += t % (1, pt[0], pt[1]) # Linear motion to point
  1721. gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  1722. for ints in target_polygon.interiors: # Polygon interiors
  1723. path = list(ints.coords)
  1724. gcode += t % (0, path[0][0], path[0][1]) # Move to first point
  1725. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  1726. for pt in path[1:]:
  1727. gcode += t % (1, pt[0], pt[1]) # Linear motion to point
  1728. gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  1729. return gcode
  1730. def linear2gcode(self, linear, tolerance=0):
  1731. """
  1732. Generates G-code to cut along the linear feature.
  1733. :param linear: The path to cut along.
  1734. :type: Shapely.LinearRing or Shapely.Linear String
  1735. :param tolerance: All points in the simplified object will be within the
  1736. tolerance distance of the original geometry.
  1737. :type tolerance: float
  1738. :return: G-code to cut alon the linear feature.
  1739. :rtype: str
  1740. """
  1741. if tolerance > 0:
  1742. target_linear = linear.simplify(tolerance)
  1743. else:
  1744. target_linear = linear
  1745. gcode = ""
  1746. t = "G0%d X%.4fY%.4f\n"
  1747. path = list(target_linear.coords)
  1748. gcode += t % (0, path[0][0], path[0][1]) # Move to first point
  1749. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  1750. for pt in path[1:]:
  1751. gcode += t % (1, pt[0], pt[1]) # Linear motion to point
  1752. gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  1753. return gcode
  1754. def point2gcode(self, point):
  1755. # TODO: This is not doing anything.
  1756. gcode = ""
  1757. t = "G0%d X%.4fY%.4f\n"
  1758. path = list(point.coords)
  1759. gcode += t % (0, path[0][0], path[0][1]) # Move to first point
  1760. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  1761. gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  1762. def scale(self, factor):
  1763. """
  1764. Scales all the geometry on the XY plane in the object by the
  1765. given factor. Tool sizes, feedrates, or Z-axis dimensions are
  1766. not altered.
  1767. :param factor: Number by which to scale the object.
  1768. :type factor: float
  1769. :return: None
  1770. :rtype: None
  1771. """
  1772. for g in self.gcode_parsed:
  1773. g['geom'] = affinity.scale(g['geom'], factor, factor, origin=(0, 0))
  1774. self.create_geometry()
  1775. def offset(self, vect):
  1776. """
  1777. Offsets all the geometry on the XY plane in the object by the
  1778. given vector.
  1779. :param vect: (x, y) offset vector.
  1780. :type vect: tuple
  1781. :return: None
  1782. """
  1783. dx, dy = vect
  1784. for g in self.gcode_parsed:
  1785. g['geom'] = affinity.translate(g['geom'], xoff=dx, yoff=dy)
  1786. self.create_geometry()
  1787. # def get_bounds(geometry_set):
  1788. # xmin = Inf
  1789. # ymin = Inf
  1790. # xmax = -Inf
  1791. # ymax = -Inf
  1792. #
  1793. # #print "Getting bounds of:", str(geometry_set)
  1794. # for gs in geometry_set:
  1795. # try:
  1796. # gxmin, gymin, gxmax, gymax = geometry_set[gs].bounds()
  1797. # xmin = min([xmin, gxmin])
  1798. # ymin = min([ymin, gymin])
  1799. # xmax = max([xmax, gxmax])
  1800. # ymax = max([ymax, gymax])
  1801. # except:
  1802. # print "DEV WARNING: Tried to get bounds of empty geometry."
  1803. #
  1804. # return [xmin, ymin, xmax, ymax]
  1805. def get_bounds(geometry_list):
  1806. xmin = Inf
  1807. ymin = Inf
  1808. xmax = -Inf
  1809. ymax = -Inf
  1810. #print "Getting bounds of:", str(geometry_set)
  1811. for gs in geometry_list:
  1812. try:
  1813. gxmin, gymin, gxmax, gymax = gs.bounds()
  1814. xmin = min([xmin, gxmin])
  1815. ymin = min([ymin, gymin])
  1816. xmax = max([xmax, gxmax])
  1817. ymax = max([ymax, gymax])
  1818. except:
  1819. log.warning("DEVELOPMENT: Tried to get bounds of empty geometry.")
  1820. return [xmin, ymin, xmax, ymax]
  1821. def arc(center, radius, start, stop, direction, steps_per_circ):
  1822. """
  1823. Creates a list of point along the specified arc.
  1824. :param center: Coordinates of the center [x, y]
  1825. :type center: list
  1826. :param radius: Radius of the arc.
  1827. :type radius: float
  1828. :param start: Starting angle in radians
  1829. :type start: float
  1830. :param stop: End angle in radians
  1831. :type stop: float
  1832. :param direction: Orientation of the arc, "CW" or "CCW"
  1833. :type direction: string
  1834. :param steps_per_circ: Number of straight line segments to
  1835. represent a circle.
  1836. :type steps_per_circ: int
  1837. :return: The desired arc, as list of tuples
  1838. :rtype: list
  1839. """
  1840. # TODO: Resolution should be established by fraction of total length, not angle.
  1841. da_sign = {"cw": -1.0, "ccw": 1.0}
  1842. points = []
  1843. if direction == "ccw" and stop <= start:
  1844. stop += 2*pi
  1845. if direction == "cw" and stop >= start:
  1846. stop -= 2*pi
  1847. angle = abs(stop - start)
  1848. #angle = stop-start
  1849. steps = max([int(ceil(angle/(2*pi)*steps_per_circ)), 2])
  1850. delta_angle = da_sign[direction]*angle*1.0/steps
  1851. for i in range(steps+1):
  1852. theta = start + delta_angle*i
  1853. points.append((center[0]+radius*cos(theta), center[1]+radius*sin(theta)))
  1854. return points
  1855. def clear_poly(poly, tooldia, overlap=0.1):
  1856. """
  1857. Creates a list of Shapely geometry objects covering the inside
  1858. of a Shapely.Polygon. Use for removing all the copper in a region
  1859. or bed flattening.
  1860. :param poly: Target polygon
  1861. :type poly: Shapely.Polygon
  1862. :param tooldia: Diameter of the tool
  1863. :type tooldia: float
  1864. :param overlap: Fraction of the tool diameter to overlap
  1865. in each pass.
  1866. :type overlap: float
  1867. :return: list of Shapely.Polygon
  1868. :rtype: list
  1869. """
  1870. poly_cuts = [poly.buffer(-tooldia/2.0)]
  1871. while True:
  1872. poly = poly_cuts[-1].buffer(-tooldia*(1-overlap))
  1873. if poly.area > 0:
  1874. poly_cuts.append(poly)
  1875. else:
  1876. break
  1877. return poly_cuts
  1878. def find_polygon(poly_set, point):
  1879. """
  1880. Return the first polygon in the list of polygons poly_set
  1881. that contains the given point.
  1882. """
  1883. p = Point(point)
  1884. for poly in poly_set:
  1885. if poly.contains(p):
  1886. return poly
  1887. return None
  1888. def to_dict(obj):
  1889. """
  1890. Makes a Shapely geometry object into serializeable form.
  1891. :param obj: Shapely geometry.
  1892. :type obj: BaseGeometry
  1893. :return: Dictionary with serializable form if ``obj`` was
  1894. BaseGeometry or ApertureMacro, otherwise returns ``obj``.
  1895. """
  1896. if isinstance(obj, ApertureMacro):
  1897. return {
  1898. "__class__": "ApertureMacro",
  1899. "__inst__": obj.to_dict()
  1900. }
  1901. if isinstance(obj, BaseGeometry):
  1902. return {
  1903. "__class__": "Shply",
  1904. "__inst__": sdumps(obj)
  1905. }
  1906. return obj
  1907. def dict2obj(d):
  1908. """
  1909. Default deserializer.
  1910. :param d: Serializable dictionary representation of an object
  1911. to be reconstructed.
  1912. :return: Reconstructed object.
  1913. """
  1914. if '__class__' in d and '__inst__' in d:
  1915. if d['__class__'] == "Shply":
  1916. return sloads(d['__inst__'])
  1917. if d['__class__'] == "ApertureMacro":
  1918. am = ApertureMacro()
  1919. am.from_dict(d['__inst__'])
  1920. return am
  1921. return d
  1922. else:
  1923. return d
  1924. def plotg(geo):
  1925. try:
  1926. _ = iter(geo)
  1927. except:
  1928. geo = [geo]
  1929. for g in geo:
  1930. if type(g) == Polygon:
  1931. x, y = g.exterior.coords.xy
  1932. plot(x, y)
  1933. for ints in g.interiors:
  1934. x, y = ints.coords.xy
  1935. plot(x, y)
  1936. continue
  1937. if type(g) == LineString or type(g) == LinearRing:
  1938. x, y = g.coords.xy
  1939. plot(x, y)
  1940. continue
  1941. if type(g) == Point:
  1942. x, y = g.coords.xy
  1943. plot(x, y, 'o')
  1944. continue
  1945. try:
  1946. _ = iter(g)
  1947. plotg(g)
  1948. except:
  1949. log.error("Cannot plot: " + str(type(g)))
  1950. continue
  1951. def parse_gerber_number(strnumber, frac_digits):
  1952. """
  1953. Parse a single number of Gerber coordinates.
  1954. :param strnumber: String containing a number in decimal digits
  1955. from a coordinate data block, possibly with a leading sign.
  1956. :type strnumber: str
  1957. :param frac_digits: Number of digits used for the fractional
  1958. part of the number
  1959. :type frac_digits: int
  1960. :return: The number in floating point.
  1961. :rtype: float
  1962. """
  1963. return int(strnumber)*(10**(-frac_digits))