camlib.py 84 KB

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