camlib.py 83 KB

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