camlib.py 87 KB

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