camlib.py 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152
  1. from numpy import arctan2, Inf, array, sqrt, pi, ceil, sin, cos
  2. from matplotlib.figure import Figure
  3. import re
  4. # See: http://toblerity.org/shapely/manual.html
  5. from shapely.geometry import Polygon, LineString, Point, LinearRing
  6. from shapely.geometry import MultiPoint, MultiPolygon
  7. from shapely.geometry import box as shply_box
  8. from shapely.ops import cascaded_union
  9. import shapely.affinity as affinity
  10. from shapely.wkt import loads as sloads
  11. from shapely.wkt import dumps as sdumps
  12. from shapely.geometry.base import BaseGeometry
  13. # Used for solid polygons in Matplotlib
  14. from descartes.patch import PolygonPatch
  15. import simplejson as json
  16. class Geometry:
  17. def __init__(self):
  18. # Units (in or mm)
  19. self.units = 'in'
  20. # Final geometry: MultiPolygon
  21. self.solid_geometry = None
  22. # Attributes to be included in serialization
  23. self.ser_attrs = ['units', 'solid_geometry']
  24. def isolation_geometry(self, offset):
  25. """
  26. Creates contours around geometry at a given
  27. offset distance.
  28. """
  29. return self.solid_geometry.buffer(offset)
  30. def bounds(self):
  31. """
  32. Returns coordinates of rectangular bounds
  33. of geometry: (xmin, ymin, xmax, ymax).
  34. """
  35. if self.solid_geometry is None:
  36. print "Warning: solid_geometry not computed yet."
  37. return (0, 0, 0, 0)
  38. if type(self.solid_geometry) == list:
  39. return cascaded_union(self.solid_geometry).bounds
  40. else:
  41. return self.solid_geometry.bounds
  42. def size(self):
  43. """
  44. Returns (width, height) of rectangular
  45. bounds of geometry.
  46. """
  47. if self.solid_geometry is None:
  48. print "Warning: solid_geometry not computed yet."
  49. return 0
  50. bounds = self.bounds()
  51. return (bounds[2]-bounds[0], bounds[3]-bounds[1])
  52. def get_empty_area(self, boundary=None):
  53. """
  54. Returns the complement of self.solid_geometry within
  55. the given boundary polygon. If not specified, it defaults to
  56. the rectangular bounding box of self.solid_geometry.
  57. """
  58. if boundary is None:
  59. boundary = self.solid_geometry.envelope
  60. return boundary.difference(self.solid_geometry)
  61. def clear_polygon(self, polygon, tooldia, overlap=0.15):
  62. """
  63. Creates geometry inside a polygon for a tool to cover
  64. the whole area.
  65. """
  66. poly_cuts = [polygon.buffer(-tooldia/2.0)]
  67. while True:
  68. polygon = poly_cuts[-1].buffer(-tooldia*(1-overlap))
  69. if polygon.area > 0:
  70. poly_cuts.append(polygon)
  71. else:
  72. break
  73. return poly_cuts
  74. def scale(self, factor):
  75. """
  76. Scales all of the object's geometry by a given factor. Override
  77. this method.
  78. :param factor: Number by which to scale.
  79. :type factor: float
  80. :return: None
  81. :rtype: None
  82. """
  83. return
  84. def convert_units(self, units):
  85. """
  86. Converts the units of the object to ``units`` by scaling all
  87. the geometry appropriately.
  88. :param units: "IN" or "MM"
  89. :type units: str
  90. :return: Scaling factor resulting from unit change.
  91. :rtype: float
  92. """
  93. if units.upper() == self.units.upper():
  94. return 1.0
  95. if units.upper() == "MM":
  96. factor = 25.4
  97. elif units.upper() == "IN":
  98. factor = 1/25.4
  99. else:
  100. print "Unsupported units:", units
  101. return 1.0
  102. self.units = units
  103. self.scale(factor)
  104. return factor
  105. def to_dict(self):
  106. """
  107. Returns a respresentation of the object as a dictionary.
  108. ``self.solid_geometry`` has been converted using the ``to_dict``
  109. function. Attributes to include are listed in
  110. ``self.ser_attrs``.
  111. :return: A dictionary-encoded copy of the object.
  112. :rtype: dict
  113. """
  114. d = {}
  115. for attr in self.ser_attrs:
  116. d[attr] = getattr(self, attr)
  117. return d
  118. def from_dict(self, d):
  119. return
  120. class Gerber (Geometry):
  121. """
  122. **ATTRIBUTES**
  123. * ``apertures`` (dict): The keys are names/identifiers of each aperture.
  124. The values are dictionaries key/value pairs which describe the aperture. The
  125. type key is always present and the rest depend on the key:
  126. +-----------+-----------------------------------+
  127. | Key | Value |
  128. +===========+===================================+
  129. | type | (str) "C", "R", or "O" |
  130. +-----------+-----------------------------------+
  131. | others | Depend on ``type`` |
  132. +-----------+-----------------------------------+
  133. * ``paths`` (list): A path is described by a line an aperture that follows that
  134. line. Each paths[i] is a dictionary:
  135. +------------+------------------------------------------------+
  136. | Key | Value |
  137. +============+================================================+
  138. | linestring | (Shapely.LineString) The actual path. |
  139. +------------+------------------------------------------------+
  140. | aperture | (str) The key for an aperture in apertures. |
  141. +------------+------------------------------------------------+
  142. * ``flashes`` (list): Flashes are single-point strokes of an aperture. Each
  143. is a dictionary:
  144. +------------+------------------------------------------------+
  145. | Key | Value |
  146. +============+================================================+
  147. | loc | (list) [x (float), y (float)] coordinates. |
  148. +------------+------------------------------------------------+
  149. | aperture | (str) The key for an aperture in apertures. |
  150. +------------+------------------------------------------------+
  151. * ``regions`` (list): Are surfaces defined by a polygon (Shapely.Polygon),
  152. which have an exterior and zero or more interiors. An aperture is also
  153. associated with a region. Each is a dictionary:
  154. +------------+-----------------------------------------------------+
  155. | Key | Value |
  156. +============+=====================================================+
  157. | polygon | (Shapely.Polygon) The polygon defining the region. |
  158. +------------+-----------------------------------------------------+
  159. | aperture | (str) The key for an aperture in apertures. |
  160. +------------+-----------------------------------------------------+
  161. * ``flash_geometry`` (list): List of (Shapely) geometric object resulting
  162. from ``flashes``. These are generated from ``flashes`` in ``do_flashes()``.
  163. * ``buffered_paths`` (list): List of (Shapely) polygons resulting from
  164. *buffering* (or thickening) the ``paths`` with the aperture. These are
  165. generated from ``paths`` in ``buffer_paths()``.
  166. """
  167. def __init__(self):
  168. # Initialize parent
  169. Geometry.__init__(self)
  170. # Number format
  171. self.digits = 3
  172. """Number of integer digits in Gerber numbers. Used during parsing."""
  173. self.fraction = 4
  174. """Number of fraction digits in Gerber numbers. Used during parsing."""
  175. ## Gerber elements ##
  176. # Apertures {'id':{'type':chr,
  177. # ['size':float], ['width':float],
  178. # ['height':float]}, ...}
  179. self.apertures = {}
  180. # Paths [{'linestring':LineString, 'aperture':str}]
  181. self.paths = []
  182. # Buffered Paths [Polygon]
  183. # Paths transformed into Polygons by
  184. # offsetting the aperture size/2
  185. self.buffered_paths = []
  186. # Polygon regions [{'polygon':Polygon, 'aperture':str}]
  187. self.regions = []
  188. # Flashes [{'loc':[float,float], 'aperture':str}]
  189. self.flashes = []
  190. # Geometry from flashes
  191. self.flash_geometry = []
  192. # Attributes to be included in serialization
  193. # Always append to it because it carries contents
  194. # from Geometry.
  195. self.ser_attrs += ['digits', 'fraction', 'apertures', 'paths',
  196. 'buffered_paths', 'regions', 'flashes',
  197. 'flash_geometry']
  198. def scale(self, factor):
  199. """
  200. Scales the objects' geometry on the XY plane by a given factor.
  201. These are:
  202. * ``apertures``
  203. * ``paths``
  204. * ``regions``
  205. * ``flashes``
  206. Then ``buffered_paths``, ``flash_geometry`` and ``solid_geometry``
  207. are re-created with ``self.create_geometry()``.
  208. :param factor: Number by which to scale.
  209. :type factor: float
  210. :rtype : None
  211. """
  212. # Apertures
  213. print "Scaling apertures..."
  214. for apid in self.apertures:
  215. for param in self.apertures[apid]:
  216. if param != "type": # All others are dimensions.
  217. print "Tool:", apid, "Parameter:", param
  218. self.apertures[apid][param] *= factor
  219. # Paths
  220. print "Scaling paths..."
  221. for path in self.paths:
  222. path['linestring'] = affinity.scale(path['linestring'],
  223. factor, factor, origin=(0, 0))
  224. # Flashes
  225. print "Scaling flashes..."
  226. for fl in self.flashes:
  227. # TODO: Shouldn't 'loc' be a numpy.array()?
  228. fl['loc'][0] *= factor
  229. fl['loc'][1] *= factor
  230. # Regions
  231. print "Scaling regions..."
  232. for reg in self.regions:
  233. reg['polygon'] = affinity.scale(reg['polygon'], factor, factor,
  234. origin=(0, 0))
  235. # Now buffered_paths, flash_geometry and solid_geometry
  236. self.create_geometry()
  237. def fix_regions(self):
  238. """
  239. Overwrites the region polygons with fixed
  240. versions if found to be invalid (according to Shapely).
  241. """
  242. for region in self.regions:
  243. if not region['polygon'].is_valid:
  244. region['polygon'] = region['polygon'].buffer(0)
  245. def buffer_paths(self):
  246. self.buffered_paths = []
  247. for path in self.paths:
  248. width = self.apertures[path["aperture"]]["size"]
  249. self.buffered_paths.append(path["linestring"].buffer(width/2))
  250. def aperture_parse(self, gline):
  251. """
  252. Parse gerber aperture definition into dictionary of apertures.
  253. The following kinds and their attributes are supported:
  254. * *Circular (C)*: size (float)
  255. * *Rectangle (R)*: width (float), height (float)
  256. * *Obround (O)*: width (float), height (float). NOTE: This can
  257. be parsed, but it is not supported further yet.
  258. """
  259. indexstar = gline.find("*")
  260. indexc = gline.find("C,")
  261. if indexc != -1: # Circle, example: %ADD11C,0.1*%
  262. apid = gline[4:indexc]
  263. self.apertures[apid] = {"type": "C",
  264. "size": float(gline[indexc+2:indexstar])}
  265. return apid
  266. indexr = gline.find("R,")
  267. if indexr != -1: # Rectangle, example: %ADD15R,0.05X0.12*%
  268. apid = gline[4:indexr]
  269. indexx = gline.find("X")
  270. self.apertures[apid] = {"type": "R",
  271. "width": float(gline[indexr+2:indexx]),
  272. "height": float(gline[indexx+1:indexstar])}
  273. return apid
  274. indexo = gline.find("O,")
  275. if indexo != -1: # Obround
  276. apid = gline[4:indexo]
  277. indexx = gline.find("X")
  278. self.apertures[apid] = {"type": "O",
  279. "width": float(gline[indexo+2:indexx]),
  280. "height": float(gline[indexx+1:indexstar])}
  281. return apid
  282. print "WARNING: Aperture not implemented:", gline
  283. return None
  284. def parse_file(self, filename):
  285. """
  286. Calls Gerber.parse_lines() with array of lines
  287. read from the given file.
  288. """
  289. gfile = open(filename, 'r')
  290. gstr = gfile.readlines()
  291. gfile.close()
  292. self.parse_lines(gstr)
  293. def parse_lines(self, glines):
  294. """
  295. Main Gerber parser.
  296. """
  297. # Mode (IN/MM)
  298. mode_re = re.compile(r'^%MO(IN|MM)\*%$')
  299. path = [] # Coordinates of the current path
  300. last_path_aperture = None
  301. current_aperture = None
  302. for gline in glines:
  303. if gline.find("D01*") != -1: # pen down
  304. path.append(coord(gline, self.digits, self.fraction))
  305. last_path_aperture = current_aperture
  306. continue
  307. if gline.find("D02*") != -1: # pen up
  308. if len(path) > 1:
  309. # Path completed, create shapely LineString
  310. self.paths.append({"linestring": LineString(path),
  311. "aperture": last_path_aperture})
  312. path = [coord(gline, self.digits, self.fraction)]
  313. continue
  314. indexd3 = gline.find("D03*")
  315. if indexd3 > 0: # Flash
  316. self.flashes.append({"loc": coord(gline, self.digits, self.fraction),
  317. "aperture": current_aperture})
  318. continue
  319. if indexd3 == 0: # Flash?
  320. print "WARNING: Uninplemented flash style:", gline
  321. continue
  322. if gline.find("G37*") != -1: # end region
  323. # Only one path defines region?
  324. self.regions.append({"polygon": Polygon(path),
  325. "aperture": last_path_aperture})
  326. path = []
  327. continue
  328. if gline.find("%ADD") != -1: # aperture definition
  329. self.aperture_parse(gline) # adds element to apertures
  330. continue
  331. indexstar = gline.find("*")
  332. if gline.find("D") == 0: # Aperture change
  333. current_aperture = gline[1:indexstar]
  334. continue
  335. if gline.find("G54D") == 0: # Aperture change (deprecated)
  336. current_aperture = gline[4:indexstar]
  337. continue
  338. if gline.find("%FS") != -1: # Format statement
  339. indexx = gline.find("X")
  340. self.digits = int(gline[indexx + 1])
  341. self.fraction = int(gline[indexx + 2])
  342. continue
  343. # Mode (IN/MM)
  344. match = mode_re.search(gline)
  345. if match:
  346. self.units = match.group(1)
  347. continue
  348. print "WARNING: Line ignored:", gline
  349. if len(path) > 1:
  350. # EOF, create shapely LineString if something still in path
  351. self.paths.append({"linestring": LineString(path),
  352. "aperture": last_path_aperture})
  353. def do_flashes(self):
  354. """
  355. Creates geometry for Gerber flashes (aperture on a single point).
  356. """
  357. self.flash_geometry = []
  358. for flash in self.flashes:
  359. aperture = self.apertures[flash['aperture']]
  360. if aperture['type'] == 'C': # Circles
  361. circle = Point(flash['loc']).buffer(aperture['size']/2)
  362. self.flash_geometry.append(circle)
  363. continue
  364. if aperture['type'] == 'R': # Rectangles
  365. loc = flash['loc']
  366. width = aperture['width']
  367. height = aperture['height']
  368. minx = loc[0] - width/2
  369. maxx = loc[0] + width/2
  370. miny = loc[1] - height/2
  371. maxy = loc[1] + height/2
  372. rectangle = shply_box(minx, miny, maxx, maxy)
  373. self.flash_geometry.append(rectangle)
  374. continue
  375. #TODO: Add support for type='O'
  376. print "WARNING: Aperture type %s not implemented" % (aperture['type'])
  377. def create_geometry(self):
  378. """
  379. Geometry from a Gerber file is made up entirely of polygons.
  380. Every stroke (linear or circular) has an aperture which gives
  381. it thickness. Additionally, aperture strokes have non-zero area,
  382. and regions naturally do as well.
  383. :rtype : None
  384. @return: None
  385. """
  386. # if len(self.buffered_paths) == 0:
  387. # self.buffer_paths()
  388. self.buffer_paths()
  389. self.fix_regions()
  390. self.do_flashes()
  391. self.solid_geometry = cascaded_union(
  392. self.buffered_paths +
  393. [poly['polygon'] for poly in self.regions] +
  394. self.flash_geometry)
  395. class Excellon(Geometry):
  396. """
  397. *ATTRIBUTES*
  398. * ``tools`` (dict): The key is the tool name and the value is
  399. the size (diameter).
  400. * ``drills`` (list): Each is a dictionary:
  401. ================ ====================================
  402. Key Value
  403. ================ ====================================
  404. point (Shapely.Point) Where to drill
  405. tool (str) A key in ``tools``
  406. ================ ====================================
  407. """
  408. def __init__(self):
  409. Geometry.__init__(self)
  410. self.tools = {}
  411. self.drills = []
  412. # Trailing "T" or leading "L"
  413. self.zeros = ""
  414. # Attributes to be included in serialization
  415. # Always append to it because it carries contents
  416. # from Geometry.
  417. self.ser_attrs += ['tools', 'drills', 'zeros']
  418. def parse_file(self, filename):
  419. efile = open(filename, 'r')
  420. estr = efile.readlines()
  421. efile.close()
  422. self.parse_lines(estr)
  423. def parse_lines(self, elines):
  424. """
  425. Main Excellon parser.
  426. """
  427. units_re = re.compile(r'^(INCH|METRIC)(?:,([TL])Z)?$')
  428. current_tool = ""
  429. for eline in elines:
  430. ## Tool definitions ##
  431. # TODO: Verify all this
  432. indexT = eline.find("T")
  433. indexC = eline.find("C")
  434. indexF = eline.find("F")
  435. # Type 1
  436. if indexT != -1 and indexC > indexT and indexF > indexC:
  437. tool = eline[1:indexC]
  438. spec = eline[indexC+1:indexF]
  439. self.tools[tool] = float(spec)
  440. continue
  441. # Type 2
  442. # TODO: Is this inches?
  443. #indexsp = eline.find(" ")
  444. #indexin = eline.find("in")
  445. #if indexT != -1 and indexsp > indexT and indexin > indexsp:
  446. # tool = eline[1:indexsp]
  447. # spec = eline[indexsp+1:indexin]
  448. # self.tools[tool] = spec
  449. # continue
  450. # Type 3
  451. if indexT != -1 and indexC > indexT:
  452. tool = eline[1:indexC]
  453. spec = eline[indexC+1:-1]
  454. self.tools[tool] = float(spec)
  455. continue
  456. ## Tool change
  457. if indexT == 0:
  458. current_tool = eline[1:-1]
  459. continue
  460. ## Drill
  461. indexx = eline.find("X")
  462. indexy = eline.find("Y")
  463. if indexx != -1 and indexy != -1:
  464. x = float(int(eline[indexx+1:indexy])/10000.0)
  465. y = float(int(eline[indexy+1:-1])/10000.0)
  466. self.drills.append({'point': Point((x, y)), 'tool': current_tool})
  467. continue
  468. # Units and number format
  469. match = units_re.match(eline)
  470. if match:
  471. self.zeros = match.group(2) # "T" or "L"
  472. self.units = {"INCH": "IN", "METRIC": "MM"}[match.group(1)]
  473. print "WARNING: Line ignored:", eline
  474. def create_geometry(self):
  475. self.solid_geometry = []
  476. sizes = {}
  477. for tool in self.tools:
  478. sizes[tool] = float(self.tools[tool])
  479. for drill in self.drills:
  480. poly = Point(drill['point']).buffer(sizes[drill['tool']]/2.0)
  481. self.solid_geometry.append(poly)
  482. self.solid_geometry = cascaded_union(self.solid_geometry)
  483. def scale(self, factor):
  484. """
  485. Scales geometry on the XY plane in the object by a given factor.
  486. Tool sizes, feedrates an Z-plane dimensions are untouched.
  487. :param factor: Number by which to scale the object.
  488. :type factor: float
  489. :return: None
  490. :rtype: NOne
  491. """
  492. # Drills
  493. for drill in self.drills:
  494. drill.point = affinity.scale(drill.point, factor, factor, origin=(0, 0))
  495. def convert_units(self, units):
  496. factor = Geometry.convert_units(self, units)
  497. # Tools
  498. for tname in self.tools:
  499. self.tools[tname] *= factor
  500. return factor
  501. class CNCjob(Geometry):
  502. """
  503. Represents work to be done by a CNC machine.
  504. *ATTRIBUTES*
  505. * ``gcode_parsed`` (list): Each is a dictionary:
  506. ===================== =========================================
  507. Key Value
  508. ===================== =========================================
  509. geom (Shapely.LineString) Tool path (XY plane)
  510. kind (string) "AB", A is "T" (travel) or
  511. "C" (cut). B is "F" (fast) or "S" (slow).
  512. ===================== =========================================
  513. """
  514. def __init__(self, units="in", kind="generic", z_move=0.1,
  515. feedrate=3.0, z_cut=-0.002, tooldia=0.0):
  516. Geometry.__init__(self)
  517. self.kind = kind
  518. self.units = units
  519. self.z_cut = z_cut
  520. self.z_move = z_move
  521. self.feedrate = feedrate
  522. self.tooldia = tooldia
  523. self.unitcode = {"IN": "G20", "MM": "G21"}
  524. self.pausecode = "G04 P1"
  525. self.feedminutecode = "G94"
  526. self.absolutecode = "G90"
  527. self.gcode = ""
  528. self.input_geometry_bounds = None
  529. self.gcode_parsed = None
  530. self.steps_per_circ = 20 # Used when parsing G-code arcs
  531. # Attributes to be included in serialization
  532. # Always append to it because it carries contents
  533. # from Geometry.
  534. self.ser_attrs += ['kind', 'z_cut', 'z_move', 'feedrate', 'tooldia',
  535. 'gcode', 'input_geometry_bounds', 'gcode_parsed',
  536. 'steps_per_circ']
  537. def generate_from_excellon(self, exobj):
  538. """
  539. Generates G-code for drilling from Excellon object.
  540. self.gcode becomes a list, each element is a
  541. different job for each tool in the excellon code.
  542. """
  543. self.kind = "drill"
  544. self.gcode = []
  545. t = "G00 X%.4fY%.4f\n"
  546. down = "G01 Z%.4f\n" % self.z_cut
  547. up = "G01 Z%.4f\n" % self.z_move
  548. for tool in exobj.tools:
  549. points = []
  550. for drill in exobj.drill:
  551. if drill['tool'] == tool:
  552. points.append(drill['point'])
  553. gcode = self.unitcode[self.units.upper()] + "\n"
  554. gcode += self.absolutecode + "\n"
  555. gcode += self.feedminutecode + "\n"
  556. gcode += "F%.2f\n" % self.feedrate
  557. gcode += "G00 Z%.4f\n" % self.z_move # Move to travel height
  558. gcode += "M03\n" # Spindle start
  559. gcode += self.pausecode + "\n"
  560. for point in points:
  561. gcode += t % point
  562. gcode += down + up
  563. gcode += t % (0, 0)
  564. gcode += "M05\n" # Spindle stop
  565. self.gcode.append(gcode)
  566. def generate_from_excellon_by_tool(self, exobj, tools="all"):
  567. """
  568. Creates gcode for this object from an Excellon object
  569. for the specified tools.
  570. @param exobj: Excellon object to process
  571. @type exobj: Excellon
  572. @param tools: Comma separated tool names
  573. @type: tools: str
  574. @return: None
  575. """
  576. print "Creating CNC Job from Excellon..."
  577. if tools == "all":
  578. tools = [tool for tool in exobj.tools]
  579. else:
  580. tools = [x.strip() for x in tools.split(",")]
  581. tools = filter(lambda y: y in exobj.tools, tools)
  582. print "Tools are:", tools
  583. points = []
  584. for drill in exobj.drills:
  585. if drill['tool'] in tools:
  586. points.append(drill['point'])
  587. print "Found %d drills." % len(points)
  588. #self.kind = "drill"
  589. self.gcode = []
  590. t = "G00 X%.4fY%.4f\n"
  591. down = "G01 Z%.4f\n" % self.z_cut
  592. up = "G01 Z%.4f\n" % self.z_move
  593. gcode = self.unitcode[self.units.upper()] + "\n"
  594. gcode += self.absolutecode + "\n"
  595. gcode += self.feedminutecode + "\n"
  596. gcode += "F%.2f\n" % self.feedrate
  597. gcode += "G00 Z%.4f\n" % self.z_move # Move to travel height
  598. gcode += "M03\n" # Spindle start
  599. gcode += self.pausecode + "\n"
  600. for point in points:
  601. x, y = point.coords.xy
  602. gcode += t % (x[0], y[0])
  603. gcode += down + up
  604. gcode += t % (0, 0)
  605. gcode += "M05\n" # Spindle stop
  606. self.gcode = gcode
  607. def generate_from_geometry(self, geometry, append=True, tooldia=None):
  608. """
  609. Generates G-Code from a Geometry object.
  610. """
  611. if tooldia is not None:
  612. self.tooldia = tooldia
  613. self.input_geometry_bounds = geometry.bounds()
  614. if not append:
  615. self.gcode = ""
  616. self.gcode = self.unitcode[self.units.upper()] + "\n"
  617. self.gcode += self.absolutecode + "\n"
  618. self.gcode += self.feedminutecode + "\n"
  619. self.gcode += "F%.2f\n" % self.feedrate
  620. self.gcode += "G00 Z%.4f\n" % self.z_move # Move to travel height
  621. self.gcode += "M03\n" # Spindle start
  622. self.gcode += self.pausecode + "\n"
  623. for geo in geometry.solid_geometry:
  624. if type(geo) == Polygon:
  625. self.gcode += self.polygon2gcode(geo)
  626. continue
  627. if type(geo) == LineString or type(geo) == LinearRing:
  628. self.gcode += self.linear2gcode(geo)
  629. continue
  630. if type(geo) == Point:
  631. self.gcode += self.point2gcode(geo)
  632. continue
  633. if type(geo) == MultiPolygon:
  634. for poly in geo:
  635. self.gcode += self.polygon2gcode(poly)
  636. continue
  637. print "WARNING: G-code generation not implemented for %s" % (str(type(geo)))
  638. self.gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  639. self.gcode += "G00 X0Y0\n"
  640. self.gcode += "M05\n" # Spindle stop
  641. def pre_parse(self, gtext):
  642. """
  643. gtext is a single string with g-code
  644. """
  645. # Units: G20-inches, G21-mm
  646. units_re = re.compile(r'^G2([01])')
  647. # TODO: This has to be re-done
  648. gcmds = []
  649. lines = gtext.split("\n") # TODO: This is probably a lot of work!
  650. for line in lines:
  651. # Clean up
  652. line = line.strip()
  653. # Remove comments
  654. # NOTE: Limited to 1 bracket pair
  655. op = line.find("(")
  656. cl = line.find(")")
  657. if op > -1 and cl > op:
  658. #comment = line[op+1:cl]
  659. line = line[:op] + line[(cl+1):]
  660. # Units
  661. match = units_re.match(line)
  662. if match:
  663. self.units = {'0': "IN", '1': "MM"}[match.group(1)]
  664. # Parse GCode
  665. # 0 4 12
  666. # G01 X-0.007 Y-0.057
  667. # --> codes_idx = [0, 4, 12]
  668. codes = "NMGXYZIJFP"
  669. codes_idx = []
  670. i = 0
  671. for ch in line:
  672. if ch in codes:
  673. codes_idx.append(i)
  674. i += 1
  675. n_codes = len(codes_idx)
  676. if n_codes == 0:
  677. continue
  678. # Separate codes in line
  679. parts = []
  680. for p in range(n_codes-1):
  681. parts.append(line[codes_idx[p]:codes_idx[p+1]].strip())
  682. parts.append(line[codes_idx[-1]:].strip())
  683. # Separate codes from values
  684. cmds = {}
  685. for part in parts:
  686. cmds[part[0]] = float(part[1:])
  687. gcmds.append(cmds)
  688. return gcmds
  689. def gcode_parse(self):
  690. """
  691. G-Code parser (from self.gcode). Generates dictionary with
  692. single-segment LineString's and "kind" indicating cut or travel,
  693. fast or feedrate speed.
  694. """
  695. # Results go here
  696. geometry = []
  697. # TODO: Merge into single parser?
  698. gobjs = self.pre_parse(self.gcode)
  699. # Last known instruction
  700. current = {'X': 0.0, 'Y': 0.0, 'Z': 0.0, 'G': 0}
  701. # Process every instruction
  702. for gobj in gobjs:
  703. if 'Z' in gobj:
  704. if ('X' in gobj or 'Y' in gobj) and gobj['Z'] != current['Z']:
  705. print "WARNING: Non-orthogonal motion: From", current
  706. print " To:", gobj
  707. current['Z'] = gobj['Z']
  708. if 'G' in gobj:
  709. current['G'] = int(gobj['G'])
  710. if 'X' in gobj or 'Y' in gobj:
  711. x = 0
  712. y = 0
  713. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  714. if 'X' in gobj:
  715. x = gobj['X']
  716. else:
  717. x = current['X']
  718. if 'Y' in gobj:
  719. y = gobj['Y']
  720. else:
  721. y = current['Y']
  722. if current['Z'] > 0:
  723. kind[0] = 'T'
  724. if current['G'] > 0:
  725. kind[1] = 'S'
  726. arcdir = [None, None, "cw", "ccw"]
  727. if current['G'] in [0, 1]: # line
  728. geometry.append({'geom': LineString([(current['X'], current['Y']),
  729. (x, y)]), 'kind': kind})
  730. if current['G'] in [2, 3]: # arc
  731. center = [gobj['I'] + current['X'], gobj['J'] + current['Y']]
  732. radius = sqrt(gobj['I']**2 + gobj['J']**2)
  733. start = arctan2(-gobj['J'], -gobj['I'])
  734. stop = arctan2(-center[1]+y, -center[0]+x)
  735. geometry.append({'geom': arc(center, radius, start, stop,
  736. arcdir[current['G']],
  737. self.steps_per_circ),
  738. 'kind': kind})
  739. # Update current instruction
  740. for code in gobj:
  741. current[code] = gobj[code]
  742. #self.G_geometry = geometry
  743. self.gcode_parsed = geometry
  744. return geometry
  745. def plot(self, tooldia=None, dpi=75, margin=0.1,
  746. color={"T": ["#F0E24D", "#B5AB3A"], "C": ["#5E6CFF", "#4650BD"]},
  747. alpha={"T": 0.3, "C": 1.0}):
  748. """
  749. Creates a Matplotlib figure with a plot of the
  750. G-code job.
  751. """
  752. if tooldia is None:
  753. tooldia = self.tooldia
  754. fig = Figure(dpi=dpi)
  755. ax = fig.add_subplot(111)
  756. ax.set_aspect(1)
  757. xmin, ymin, xmax, ymax = self.input_geometry_bounds
  758. ax.set_xlim(xmin-margin, xmax+margin)
  759. ax.set_ylim(ymin-margin, ymax+margin)
  760. if tooldia == 0:
  761. for geo in self.gcode_parsed:
  762. linespec = '--'
  763. linecolor = color[geo['kind'][0]][1]
  764. if geo['kind'][0] == 'C':
  765. linespec = 'k-'
  766. x, y = geo['geom'].coords.xy
  767. ax.plot(x, y, linespec, color=linecolor)
  768. else:
  769. for geo in self.gcode_parsed:
  770. poly = geo['geom'].buffer(tooldia/2.0)
  771. patch = PolygonPatch(poly, facecolor=color[geo['kind'][0]][0],
  772. edgecolor=color[geo['kind'][0]][1],
  773. alpha=alpha[geo['kind'][0]], zorder=2)
  774. ax.add_patch(patch)
  775. return fig
  776. def plot2(self, axes, tooldia=None, dpi=75, margin=0.1,
  777. color={"T": ["#F0E24D", "#B5AB3A"], "C": ["#5E6CFF", "#4650BD"]},
  778. alpha={"T": 0.3, "C":1.0}):
  779. """
  780. Plots the G-code job onto the given axes.
  781. """
  782. if tooldia is None:
  783. tooldia = self.tooldia
  784. if tooldia == 0:
  785. for geo in self.gcode_parsed:
  786. linespec = '--'
  787. linecolor = color[geo['kind'][0]][1]
  788. if geo['kind'][0] == 'C':
  789. linespec = 'k-'
  790. x, y = geo['geom'].coords.xy
  791. axes.plot(x, y, linespec, color=linecolor)
  792. else:
  793. for geo in self.gcode_parsed:
  794. poly = geo['geom'].buffer(tooldia/2.0)
  795. patch = PolygonPatch(poly, facecolor=color[geo['kind'][0]][0],
  796. edgecolor=color[geo['kind'][0]][1],
  797. alpha=alpha[geo['kind'][0]], zorder=2)
  798. axes.add_patch(patch)
  799. def create_geometry(self):
  800. self.solid_geometry = cascaded_union([geo['geom'] for geo in self.gcode_parsed])
  801. def polygon2gcode(self, polygon):
  802. """
  803. Creates G-Code for the exterior and all interior paths
  804. of a polygon.
  805. @param polygon: A Shapely.Polygon
  806. @type polygon: Shapely.Polygon
  807. """
  808. gcode = ""
  809. t = "G0%d X%.4fY%.4f\n"
  810. path = list(polygon.exterior.coords) # Polygon exterior
  811. gcode += t % (0, path[0][0], path[0][1]) # Move to first point
  812. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  813. for pt in path[1:]:
  814. gcode += t % (1, pt[0], pt[1]) # Linear motion to point
  815. gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  816. for ints in polygon.interiors: # Polygon interiors
  817. path = list(ints.coords)
  818. gcode += t % (0, path[0][0], path[0][1]) # Move to first point
  819. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  820. for pt in path[1:]:
  821. gcode += t % (1, pt[0], pt[1]) # Linear motion to point
  822. gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  823. return gcode
  824. def linear2gcode(self, linear):
  825. gcode = ""
  826. t = "G0%d X%.4fY%.4f\n"
  827. path = list(linear.coords)
  828. gcode += t%(0, path[0][0], path[0][1]) # Move to first point
  829. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  830. for pt in path[1:]:
  831. gcode += t % (1, pt[0], pt[1]) # Linear motion to point
  832. gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  833. return gcode
  834. def point2gcode(self, point):
  835. # TODO: This is not doing anything.
  836. gcode = ""
  837. t = "G0%d X%.4fY%.4f\n"
  838. path = list(point.coords)
  839. gcode += t % (0, path[0][0], path[0][1]) # Move to first point
  840. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  841. gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  842. def scale(self, factor):
  843. """
  844. Scales all the geometry on the XY plane in the object by the
  845. given factor. Tool sizes, feedrates, or Z-axis dimensions are
  846. not altered.
  847. :param factor: Number by which to scale the object.
  848. :type factor: float
  849. :return: None
  850. :rtype: None
  851. """
  852. for g in self.gcode_parsed:
  853. g['geom'] = affinity.scale(g['geom'], factor, factor, origin=(0, 0))
  854. def convert_units(self, units):
  855. factor = Geometry.convert_units(self, units)
  856. self.z_move *= factor
  857. self.z_cut *= factor
  858. self.feedrate *= factor
  859. self.tooldia *= factor
  860. return factor
  861. def get_bounds(geometry_set):
  862. xmin = Inf
  863. ymin = Inf
  864. xmax = -Inf
  865. ymax = -Inf
  866. print "Getting bounds of:", str(geometry_set)
  867. for gs in geometry_set:
  868. gxmin, gymin, gxmax, gymax = geometry_set[gs].bounds()
  869. xmin = min([xmin, gxmin])
  870. ymin = min([ymin, gymin])
  871. xmax = max([xmax, gxmax])
  872. ymax = max([ymax, gymax])
  873. return [xmin, ymin, xmax, ymax]
  874. def arc(center, radius, start, stop, direction, steps_per_circ):
  875. """
  876. Creates a Shapely.LineString for the specified arc.
  877. @param center: Coordinates of the center [x, y]
  878. @type center: list
  879. @param radius: Radius of the arc.
  880. @type radius: float
  881. @param start: Starting angle in radians
  882. @type start: float
  883. @param stop: End angle in radians
  884. @type stop: float
  885. @param direction: Orientation of the arc, "CW" or "CCW"
  886. @type direction: string
  887. @param steps_per_circ: Number of straight line segments to
  888. represent a circle.
  889. @type steps_per_circ: int
  890. """
  891. da_sign = {"cw": -1.0, "ccw": 1.0}
  892. points = []
  893. if direction == "ccw" and stop <= start:
  894. stop += 2*pi
  895. if direction == "cw" and stop >= start:
  896. stop -= 2*pi
  897. angle = abs(stop - start)
  898. #angle = stop-start
  899. steps = max([int(ceil(angle/(2*pi)*steps_per_circ)), 2])
  900. delta_angle = da_sign[direction]*angle*1.0/steps
  901. for i in range(steps+1):
  902. theta = start + delta_angle*i
  903. points.append([center[0]+radius*cos(theta), center[1]+radius*sin(theta)])
  904. return LineString(points)
  905. def clear_poly(poly, tooldia, overlap=0.1):
  906. """
  907. Creates a list of Shapely geometry objects covering the inside
  908. of a Shapely.Polygon. Use for removing all the copper in a region
  909. or bed flattening.
  910. @param poly: Target polygon
  911. @type poly: Shapely.Polygon
  912. @param tooldia: Diameter of the tool
  913. @type tooldia: float
  914. @param overlap: Fraction of the tool diameter to overlap
  915. in each pass.
  916. @type overlap: float
  917. @return list of Shapely.Polygon
  918. """
  919. poly_cuts = [poly.buffer(-tooldia/2.0)]
  920. while True:
  921. poly = poly_cuts[-1].buffer(-tooldia*(1-overlap))
  922. if poly.area > 0:
  923. poly_cuts.append(poly)
  924. else:
  925. break
  926. return poly_cuts
  927. def find_polygon(poly_set, point):
  928. """
  929. Return the first polygon in the list of polygons poly_set
  930. that contains the given point.
  931. """
  932. p = Point(point)
  933. for poly in poly_set:
  934. if poly.contains(p):
  935. return poly
  936. return None
  937. def to_dict(geo):
  938. output = ''
  939. if isinstance(geo, BaseGeometry):
  940. return {
  941. "__class__": "Shply",
  942. "__inst__": sdumps(geo)
  943. }
  944. return geo
  945. def dict2obj(d):
  946. if '__class__' in d and '__inst__' in d:
  947. # For now assume all classes are Shapely geometry.
  948. return sloads(d['__inst__'])
  949. else:
  950. return d
  951. ############### cam.py ####################
  952. def coord(gstr, digits, fraction):
  953. """
  954. Parse Gerber coordinates
  955. """
  956. global gerbx, gerby
  957. xindex = gstr.find("X")
  958. yindex = gstr.find("Y")
  959. index = gstr.find("D")
  960. if xindex == -1:
  961. x = gerbx
  962. y = int(gstr[(yindex+1):index])*(10**(-fraction))
  963. elif yindex == -1:
  964. y = gerby
  965. x = int(gstr[(xindex+1):index])*(10**(-fraction))
  966. else:
  967. x = int(gstr[(xindex+1):yindex])*(10**(-fraction))
  968. y = int(gstr[(yindex+1):index])*(10**(-fraction))
  969. gerbx = x
  970. gerby = y
  971. return [x, y]
  972. ################ end of cam.py #############