camlib.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  1. from numpy import arctan2, Inf, array, sqrt, pi, ceil, sin, cos
  2. from matplotlib.figure import Figure
  3. # See: http://toblerity.org/shapely/manual.html
  4. from shapely.geometry import Polygon, LineString, Point, LinearRing
  5. from shapely.geometry import MultiPoint, MultiPolygon
  6. from shapely.geometry import box as shply_box
  7. from shapely.ops import cascaded_union
  8. from descartes.patch import PolygonPatch
  9. class Geometry:
  10. def __init__(self):
  11. # Units (in or mm)
  12. self.units = 'in'
  13. # Final geometry: MultiPolygon
  14. self.solid_geometry = None
  15. def isolation_geometry(self, offset):
  16. '''
  17. Creates contours around geometry at a given
  18. offset distance.
  19. '''
  20. return self.solid_geometry.buffer(offset)
  21. def bounds(self):
  22. '''
  23. Returns coordinates of rectangular bounds
  24. of geometry: (xmin, ymin, xmax, ymax).
  25. '''
  26. if self.solid_geometry == None:
  27. print "Warning: solid_geometry not computed yet."
  28. return (0,0,0,0)
  29. if type(self.solid_geometry) == list:
  30. return cascaded_union(self.solid_geometry).bounds
  31. else:
  32. return self.solid_geometry.bounds
  33. def size(self):
  34. '''
  35. Returns (width, height) of rectangular
  36. bounds of geometry.
  37. '''
  38. if self.solid_geometry == None:
  39. print "Warning: solid_geometry not computed yet."
  40. return 0
  41. bounds = self.bounds()
  42. return (bounds[2]-bounds[0], bounds[3]-bounds[1])
  43. def get_empty_area(self, boundary=None):
  44. '''
  45. Returns the complement of self.solid_geometry within
  46. the given boundary polygon. If not specified, it defaults to
  47. the rectangular bounding box of self.solid_geometry.
  48. '''
  49. if boundary == None:
  50. boundary = self.solid_geometry.envelope
  51. return boundary.difference(self.solid_geometry)
  52. def clear_polygon(self, polygon, tooldia, overlap = 0.15):
  53. '''
  54. Creates geometry inside a polygon for a tool to cover
  55. the whole area.
  56. '''
  57. poly_cuts = [polygon.buffer(-tooldia/2.0)]
  58. while(1):
  59. polygon = poly_cuts[-1].buffer(-tooldia*(1-overlap))
  60. if polygon.area > 0:
  61. poly_cuts.append(polygon)
  62. else:
  63. break
  64. return poly_cuts
  65. class Gerber (Geometry):
  66. def __init__(self):
  67. # Initialize parent
  68. Geometry.__init__(self)
  69. # Number format
  70. self.digits = 3
  71. self.fraction = 4
  72. ## Gerber elements ##
  73. # Apertures {'id':{'type':chr,
  74. # ['size':float], ['width':float],
  75. # ['height':float]}, ...}
  76. self.apertures = {}
  77. # Paths [{'linestring':LineString, 'aperture':dict}]
  78. self.paths = []
  79. # Buffered Paths [Polygon]
  80. # Paths transformed into Polygons by
  81. # offsetting the aperture size/2
  82. self.buffered_paths = []
  83. # Polygon regions [{'polygon':Polygon, 'aperture':dict}]
  84. self.regions = []
  85. # Flashes [{'loc':[float,float], 'aperture':dict}]
  86. self.flashes = []
  87. # Geometry from flashes
  88. self.flash_geometry = []
  89. def fix_regions(self):
  90. '''
  91. Overwrites the region polygons with fixed
  92. versions if found to be invalid (according to Shapely).
  93. '''
  94. for region in self.regions:
  95. if region['polygon'].is_valid == False:
  96. region['polygon'] = region['polygon'].buffer(0)
  97. def buffer_paths(self):
  98. self.buffered_paths = []
  99. for path in self.paths:
  100. width = self.apertures[path["aperture"]]["size"]
  101. self.buffered_paths.append(path["linestring"].buffer(width/2))
  102. def aperture_parse(self, gline):
  103. '''
  104. Parse gerber aperture definition
  105. into dictionary of apertures.
  106. '''
  107. indexstar = gline.find("*")
  108. indexC = gline.find("C,")
  109. if indexC != -1: # Circle, example: %ADD11C,0.1*%
  110. apid = gline[4:indexC]
  111. self.apertures[apid] = {"type":"C",
  112. "size":float(gline[indexC+2:indexstar])}
  113. return apid
  114. indexR = gline.find("R,")
  115. if indexR != -1: # Rectangle, example: %ADD15R,0.05X0.12*%
  116. apid = gline[4:indexR]
  117. indexX = gline.find("X")
  118. self.apertures[apid] = {"type":"R",
  119. "width":float(gline[indexR+2:indexX]),
  120. "height":float(gline[indexX+1:indexstar])}
  121. return apid
  122. indexO = gline.find("O,")
  123. if indexO != -1: # Obround
  124. apid = gline[4:indexO]
  125. indexX = gline.find("X")
  126. self.apertures[apid] = {"type":"O",
  127. "width":float(gline[indexO+2:indexX]),
  128. "height":float(gline[indexX+1:indexstar])}
  129. return apid
  130. print "WARNING: Aperture not implemented:", gline
  131. return None
  132. def parse_file(self, filename):
  133. '''
  134. Calls Gerber.parse_lines() with array of lines
  135. read from the given file.
  136. '''
  137. gfile = open(filename, 'r')
  138. gstr = gfile.readlines()
  139. gfile.close()
  140. self.parse_lines(gstr)
  141. def parse_lines(self, glines):
  142. '''
  143. Main Gerber parser.
  144. '''
  145. path = [] # Coordinates of the current path
  146. last_path_aperture = None
  147. current_aperture = None
  148. for gline in glines:
  149. if gline.find("D01*") != -1: # pen down
  150. path.append(coord(gline, self.digits, self.fraction))
  151. last_path_aperture = current_aperture
  152. continue
  153. if gline.find("D02*") != -1: # pen up
  154. if len(path) > 1:
  155. # Path completed, create shapely LineString
  156. self.paths.append({"linestring":LineString(path),
  157. "aperture":last_path_aperture})
  158. path = [coord(gline, self.digits, self.fraction)]
  159. continue
  160. indexD3 = gline.find("D03*")
  161. if indexD3 > 0: # Flash
  162. self.flashes.append({"loc":coord(gline, self.digits, self.fraction),
  163. "aperture":current_aperture})
  164. continue
  165. if indexD3 == 0: # Flash?
  166. print "WARNING: Uninplemented flash style:", gline
  167. continue
  168. if gline.find("G37*") != -1: # end region
  169. # Only one path defines region?
  170. self.regions.append({"polygon":Polygon(path),
  171. "aperture":last_path_aperture})
  172. path = []
  173. continue
  174. if gline.find("%ADD") != -1: # aperture definition
  175. self.aperture_parse(gline) # adds element to apertures
  176. continue
  177. indexstar = gline.find("*")
  178. if gline.find("D") == 0: # Aperture change
  179. current_aperture = gline[1:indexstar]
  180. continue
  181. if gline.find("G54D") == 0: # Aperture change (deprecated)
  182. current_aperture = gline[4:indexstar]
  183. continue
  184. if gline.find("%FS") != -1: # Format statement
  185. indexX = gline.find("X")
  186. self.digits = int(gline[indexX + 1])
  187. self.fraction = int(gline[indexX + 2])
  188. continue
  189. print "WARNING: Line ignored:", gline
  190. if len(path) > 1:
  191. # EOF, create shapely LineString if something in path
  192. self.paths.append({"linestring":LineString(path),
  193. "aperture":last_path_aperture})
  194. def do_flashes(self):
  195. '''
  196. Creates geometry for Gerber flashes (aperture on a single point).
  197. '''
  198. self.flash_geometry = []
  199. for flash in self.flashes:
  200. aperture = self.apertures[flash['aperture']]
  201. if aperture['type'] == 'C': # Circles
  202. circle = Point(flash['loc']).buffer(aperture['size']/2)
  203. self.flash_geometry.append(circle)
  204. continue
  205. if aperture['type'] == 'R': # Rectangles
  206. loc = flash['loc']
  207. width = aperture['width']
  208. height = aperture['height']
  209. minx = loc[0] - width/2
  210. maxx = loc[0] + width/2
  211. miny = loc[1] - height/2
  212. maxy = loc[1] + height/2
  213. rectangle = shply_box(minx, miny, maxx, maxy)
  214. self.flash_geometry.append(rectangle)
  215. continue
  216. #TODO: Add support for type='O'
  217. print "WARNING: Aperture type %s not implemented"%(aperture['type'])
  218. def create_geometry(self):
  219. if len(self.buffered_paths) == 0:
  220. self.buffer_paths()
  221. self.fix_regions()
  222. self.do_flashes()
  223. self.solid_geometry = cascaded_union(
  224. self.buffered_paths +
  225. [poly['polygon'] for poly in self.regions] +
  226. self.flash_geometry)
  227. class Excellon(Geometry):
  228. def __init__(self):
  229. Geometry.__init__(self)
  230. self.tools = {}
  231. self.drills = []
  232. def parse_file(self, filename):
  233. efile = open(filename, 'r')
  234. estr = efile.readlines()
  235. efile.close()
  236. self.parse_lines(estr)
  237. def parse_lines(self, elines):
  238. '''
  239. Main Excellon parser.
  240. '''
  241. current_tool = ""
  242. for eline in elines:
  243. ## Tool definitions ##
  244. # TODO: Verify all this
  245. indexT = eline.find("T")
  246. indexC = eline.find("C")
  247. indexF = eline.find("F")
  248. # Type 1
  249. if indexT != -1 and indexC > indexT and indexF > indexF:
  250. tool = eline[1:indexC]
  251. spec = eline[indexC+1:indexF]
  252. self.tools[tool] = spec
  253. continue
  254. # Type 2
  255. # TODO: Is this inches?
  256. #indexsp = eline.find(" ")
  257. #indexin = eline.find("in")
  258. #if indexT != -1 and indexsp > indexT and indexin > indexsp:
  259. # tool = eline[1:indexsp]
  260. # spec = eline[indexsp+1:indexin]
  261. # self.tools[tool] = spec
  262. # continue
  263. # Type 3
  264. if indexT != -1 and indexC > indexT:
  265. tool = eline[1:indexC]
  266. spec = eline[indexC+1:-1]
  267. self.tools[tool] = spec
  268. continue
  269. ## Tool change
  270. if indexT == 0:
  271. current_tool = eline[1:-1]
  272. continue
  273. ## Drill
  274. indexX = eline.find("X")
  275. indexY = eline.find("Y")
  276. if indexX != -1 and indexY != -1:
  277. x = float(int(eline[indexX+1:indexY])/10000.0)
  278. y = float(int(eline[indexY+1:-1])/10000.0)
  279. self.drills.append({'point':Point((x,y)), 'tool':current_tool})
  280. continue
  281. print "WARNING: Line ignored:", eline
  282. def create_geometry(self):
  283. self.solid_geometry = []
  284. sizes = {}
  285. for tool in self.tools:
  286. sizes[tool] = float(self.tools[tool])
  287. for drill in self.drills:
  288. poly = Point(drill['point']).buffer(sizes[drill['tool']]/2.0)
  289. self.solid_geometry.append(poly)
  290. self.solid_geometry = cascaded_union(self.solid_geometry)
  291. class CNCjob(Geometry):
  292. def __init__(self, units="in", kind="generic", z_move = 0.1,
  293. feedrate = 3.0, z_cut = -0.002, tooldia = 0.0):
  294. # Options
  295. self.kind = kind
  296. self.units = units
  297. self.z_cut = z_cut
  298. self.z_move = z_move
  299. self.feedrate = feedrate
  300. self.tooldia = tooldia
  301. # Constants
  302. self.unitcode = {"in": "G20", "mm": "G21"}
  303. self.pausecode = "G04 P1"
  304. self.feedminutecode = "G94"
  305. self.absolutecode = "G90"
  306. # Input/Output G-Code
  307. self.gcode = ""
  308. # Bounds of geometry given to CNCjob.generate_from_geometry()
  309. self.input_geometry_bounds = None
  310. # Output generated by CNCjob.create_gcode_geometry()
  311. #self.G_geometry = None
  312. self.gcode_parsed = None
  313. def generate_from_excellon(self, exobj):
  314. '''
  315. Generates G-code for drilling from excellon text.
  316. self.gcode becomes a list, each element is a
  317. different job for each tool in the excellon code.
  318. '''
  319. self.kind = "drill"
  320. self.gcode = []
  321. t = "G00 X%.4fY%.4f\n"
  322. down = "G01 Z%.4f\n"%self.z_cut
  323. up = "G01 Z%.4f\n"%self.z_move
  324. for tool in exobj.tools:
  325. points = []
  326. gcode = ""
  327. for drill in exobj.drill:
  328. if drill['tool'] == tool:
  329. points.append(drill['point'])
  330. gcode = self.unitcode[self.units] + "\n"
  331. gcode += self.absolutecode + "\n"
  332. gcode += self.feedminutecode + "\n"
  333. gcode += "F%.2f\n"%self.feedrate
  334. gcode += "G00 Z%.4f\n"%self.z_move # Move to travel height
  335. gcode += "M03\n" # Spindle start
  336. gcode += self.pausecode + "\n"
  337. for point in points:
  338. gcode += t%point
  339. gcode += down + up
  340. gcode += t%(0,0)
  341. gcode += "M05\n" # Spindle stop
  342. self.gcode.append(gcode)
  343. def generate_from_geometry(self, geometry, append=True, tooldia=None):
  344. '''
  345. Generates G-Code for geometry (Shapely collection).
  346. '''
  347. if tooldia == None:
  348. tooldia = self.tooldia
  349. else:
  350. self.tooldia = tooldia
  351. self.input_geometry_bounds = geometry.bounds
  352. if append == False:
  353. self.gcode = ""
  354. t = "G0%d X%.4fY%.4f\n"
  355. self.gcode = self.unitcode[self.units] + "\n"
  356. self.gcode += self.absolutecode + "\n"
  357. self.gcode += self.feedminutecode + "\n"
  358. self.gcode += "F%.2f\n"%self.feedrate
  359. self.gcode += "G00 Z%.4f\n"%self.z_move # Move to travel height
  360. self.gcode += "M03\n" # Spindle start
  361. self.gcode += self.pausecode + "\n"
  362. for geo in geometry:
  363. if type(geo) == Polygon:
  364. path = list(geo.exterior.coords) # Polygon exterior
  365. self.gcode += t%(0, path[0][0], path[0][1]) # Move to first point
  366. self.gcode += "G01 Z%.4f\n"%self.z_cut # Start cutting
  367. for pt in path[1:]:
  368. self.gcode += t%(1, pt[0], pt[1]) # Linear motion to point
  369. self.gcode += "G00 Z%.4f\n"%self.z_move # Stop cutting
  370. for ints in geo.interiors: # Polygon interiors
  371. path = list(ints.coords)
  372. self.gcode += t%(0, path[0][0], path[0][1]) # Move to first point
  373. self.gcode += "G01 Z%.4f\n"%self.z_cut # Start cutting
  374. for pt in path[1:]:
  375. self.gcode += t%(1, pt[0], pt[1]) # Linear motion to point
  376. self.gcode += "G00 Z%.4f\n"%self.z_move # Stop cutting
  377. continue
  378. if type(geo) == LineString or type(geo) == LinearRing:
  379. path = list(geo.coords)
  380. self.gcode += t%(0, path[0][0], path[0][1]) # Move to first point
  381. self.gcode += "G01 Z%.4f\n"%self.z_cut # Start cutting
  382. for pt in path[1:]:
  383. self.gcode += t%(1, pt[0], pt[1]) # Linear motion to point
  384. self.gcode += "G00 Z%.4f\n"%self.z_move # Stop cutting
  385. continue
  386. if type(geo) == Point:
  387. path = list(geo.coords)
  388. self.gcode += t%(0, path[0][0], path[0][1]) # Move to first point
  389. self.gcode += "G01 Z%.4f\n"%self.z_cut # Start cutting
  390. self.gcode += "G00 Z%.4f\n"%self.z_move # Stop cutting
  391. continue
  392. print "WARNING: G-code generation not implemented for %s"%(str(type(geo)))
  393. self.gcode += "G00 Z%.4f\n"%self.z_move # Stop cutting
  394. self.gcode += "G00 X0Y0\n"
  395. self.gcode += "M05\n" # Spindle stop
  396. def gcode_parse(self):
  397. steps_per_circ = 20
  398. '''
  399. G-Code parser (from self.gcode). Generates dictionary with
  400. single-segment LineString's and "kind" indicating cut or travel,
  401. fast or feedrate speed.
  402. '''
  403. geometry = []
  404. # TODO: ???? bring this into the class??
  405. gobjs = gparse1b(self.gcode)
  406. # Last known instruction
  407. current = {'X': 0.0, 'Y': 0.0, 'Z': 0.0, 'G': 0}
  408. # Process every instruction
  409. for gobj in gobjs:
  410. if 'Z' in gobj:
  411. if ('X' in gobj or 'Y' in gobj) and gobj['Z'] != current['Z']:
  412. print "WARNING: Non-orthogonal motion: From", current
  413. print " To:", gobj
  414. current['Z'] = gobj['Z']
  415. if 'G' in gobj:
  416. current['G'] = int(gobj['G'])
  417. if 'X' in gobj or 'Y' in gobj:
  418. x = 0
  419. y = 0
  420. kind = ["C","F"] # T=travel, C=cut, F=fast, S=slow
  421. if 'X' in gobj:
  422. x = gobj['X']
  423. else:
  424. x = current['X']
  425. if 'Y' in gobj:
  426. y = gobj['Y']
  427. else:
  428. y = current['Y']
  429. if current['Z'] > 0:
  430. kind[0] = 'T'
  431. if current['G'] > 0:
  432. kind[1] = 'S'
  433. arcdir = [None, None, "cw", "ccw"]
  434. if current['G'] in [0,1]: # line
  435. geometry.append({'geom':LineString([(current['X'],current['Y']),
  436. (x,y)]), 'kind':kind})
  437. if current['G'] in [2,3]: # arc
  438. center = [gobj['I'] + current['X'], gobj['J'] + current['Y']]
  439. radius = sqrt(gobj['I']**2 + gobj['J']**2)
  440. start = arctan2( -gobj['J'], -gobj['I'])
  441. stop = arctan2(-center[1]+y, -center[0]+x)
  442. geometry.append({'geom':arc(center, radius, start, stop,
  443. arcdir[current['G']],
  444. steps_per_circ),
  445. 'kind':kind})
  446. # Update current instruction
  447. for code in gobj:
  448. current[code] = gobj[code]
  449. #self.G_geometry = geometry
  450. self.gcode_parsed = geometry
  451. return geometry
  452. def plot(self, tooldia=None, dpi=75, margin=0.1,
  453. color={"T":["#F0E24D", "#B5AB3A"], "C":["#5E6CFF", "#4650BD"]},
  454. alpha={"T":0.3, "C":1.0}):
  455. '''
  456. Creates a Matplotlib figure with a plot of the
  457. G-code job.
  458. '''
  459. if tooldia == None:
  460. tooldia = self.tooldia
  461. fig = Figure(dpi=dpi)
  462. ax = fig.add_subplot(111)
  463. ax.set_aspect(1)
  464. xmin, ymin, xmax, ymax = self.input_geometry_bounds
  465. ax.set_xlim(xmin-margin, xmax+margin)
  466. ax.set_ylim(ymin-margin, ymax+margin)
  467. if tooldia == 0:
  468. for geo in self.gcode_parsed:
  469. linespec = '--'
  470. linecolor = color[geo['kind'][0]][1]
  471. if geo['kind'][0] == 'C':
  472. linespec = 'k-'
  473. x, y = geo['geom'].coords.xy
  474. ax.plot(x, y, linespec, color=linecolor)
  475. else:
  476. for geo in self.gcode_parsed:
  477. poly = geo['geom'].buffer(tooldia/2.0)
  478. patch = PolygonPatch(poly, facecolor=color[geo['kind'][0]][0],
  479. edgecolor=color[geo['kind'][0]][1],
  480. alpha=alpha[geo['kind'][0]], zorder=2)
  481. ax.add_patch(patch)
  482. return fig
  483. def plot2(self, axes, tooldia=None, dpi=75, margin=0.1,
  484. color={"T":["#F0E24D", "#B5AB3A"], "C":["#5E6CFF", "#4650BD"]},
  485. alpha={"T":0.3, "C":1.0}):
  486. '''
  487. Plots the G-code job onto the given axes.
  488. '''
  489. if tooldia == None:
  490. tooldia = self.tooldia
  491. if tooldia == 0:
  492. for geo in self.gcode_parsed:
  493. linespec = '--'
  494. linecolor = color[geo['kind'][0]][1]
  495. if geo['kind'][0] == 'C':
  496. linespec = 'k-'
  497. x, y = geo['geom'].coords.xy
  498. axes.plot(x, y, linespec, color=linecolor)
  499. else:
  500. for geo in self.gcode_parsed:
  501. poly = geo['geom'].buffer(tooldia/2.0)
  502. patch = PolygonPatch(poly, facecolor=color[geo['kind'][0]][0],
  503. edgecolor=color[geo['kind'][0]][1],
  504. alpha=alpha[geo['kind'][0]], zorder=2)
  505. axes.add_patch(patch)
  506. def create_geometry(self):
  507. self.solid_geometry = cascaded_union([geo['geom'] for geo in self.gcode_parsed])
  508. def gparse1b(gtext):
  509. '''
  510. gtext is a single string with g-code
  511. '''
  512. gcmds = []
  513. lines = gtext.split("\n") # TODO: This is probably a lot of work!
  514. for line in lines:
  515. line = line.strip()
  516. # Remove comments
  517. # NOTE: Limited to 1 bracket pair
  518. op = line.find("(")
  519. cl = line.find(")")
  520. if op > -1 and cl > op:
  521. #comment = line[op+1:cl]
  522. line = line[:op] + line[(cl+1):]
  523. # Parse GCode
  524. # 0 4 12
  525. # G01 X-0.007 Y-0.057
  526. # --> codes_idx = [0, 4, 12]
  527. codes = "NMGXYZIJFP"
  528. codes_idx = []
  529. i = 0
  530. for ch in line:
  531. if ch in codes:
  532. codes_idx.append(i)
  533. i += 1
  534. n_codes = len(codes_idx)
  535. if n_codes == 0:
  536. continue
  537. # Separate codes in line
  538. parts = []
  539. for p in range(n_codes-1):
  540. parts.append( line[ codes_idx[p]:codes_idx[p+1] ].strip() )
  541. parts.append( line[codes_idx[-1]:].strip() )
  542. # Separate codes from values
  543. cmds = {}
  544. for part in parts:
  545. cmds[part[0]] = float(part[1:])
  546. gcmds.append(cmds)
  547. return gcmds
  548. def get_bounds(geometry_set):
  549. xmin = Inf
  550. ymin = Inf
  551. xmax = -Inf
  552. ymax = -Inf
  553. for gs in geometry_set:
  554. gxmin, gymin, gxmax, gymax = geometry_set[gs].bounds()
  555. xmin = min([xmin, gxmin])
  556. ymin = min([ymin, gymin])
  557. xmax = max([xmax, gxmax])
  558. ymax = max([ymax, gymax])
  559. return [xmin, ymin, xmax, ymax]
  560. def arc(center, radius, start, stop, direction, steps_per_circ):
  561. da_sign = {"cw":-1.0, "ccw":1.0}
  562. points = []
  563. if direction=="ccw" and stop <= start:
  564. stop += 2*pi
  565. if direction=="cw" and stop >= start:
  566. stop -= 2*pi
  567. angle = abs(stop - start)
  568. #angle = stop-start
  569. steps = max([int(ceil(angle/(2*pi)*steps_per_circ)), 2])
  570. delta_angle = da_sign[direction]*angle*1.0/steps
  571. for i in range(steps+1):
  572. theta = start + delta_angle*i
  573. points.append([center[0]+radius*cos(theta), center[1]+radius*sin(theta)])
  574. return LineString(points)
  575. ############### cam.py ####################
  576. def coord(gstr,digits,fraction):
  577. '''
  578. Parse Gerber coordinates
  579. '''
  580. global gerbx, gerby
  581. xindex = gstr.find("X")
  582. yindex = gstr.find("Y")
  583. index = gstr.find("D")
  584. if (xindex == -1):
  585. x = gerbx
  586. y = int(gstr[(yindex+1):index])*(10**(-fraction))
  587. elif (yindex == -1):
  588. y = gerby
  589. x = int(gstr[(xindex+1):index])*(10**(-fraction))
  590. else:
  591. x = int(gstr[(xindex+1):yindex])*(10**(-fraction))
  592. y = int(gstr[(yindex+1):index])*(10**(-fraction))
  593. gerbx = x
  594. gerby = y
  595. return [x,y]
  596. ################ end of cam.py #############