camlib.py 25 KB

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