camlib.py 134 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917
  1. ############################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. ############################################################
  8. #from __future__ import division
  9. #from scipy import optimize
  10. #import traceback
  11. from numpy import arctan2, Inf, array, sqrt, pi, ceil, sin, cos, dot, float32, \
  12. transpose
  13. from numpy.linalg import solve, norm
  14. from matplotlib.figure import Figure
  15. import re
  16. import sys
  17. import traceback
  18. from decimal import Decimal
  19. import collections
  20. import numpy as np
  21. import matplotlib
  22. #import matplotlib.pyplot as plt
  23. #from scipy.spatial import Delaunay, KDTree
  24. from rtree import index as rtindex
  25. # See: http://toblerity.org/shapely/manual.html
  26. from shapely.geometry import Polygon, LineString, Point, LinearRing
  27. from shapely.geometry import MultiPoint, MultiPolygon
  28. from shapely.geometry import box as shply_box
  29. from shapely.ops import cascaded_union
  30. import shapely.affinity as affinity
  31. from shapely.wkt import loads as sloads
  32. from shapely.wkt import dumps as sdumps
  33. from shapely.geometry.base import BaseGeometry
  34. # Used for solid polygons in Matplotlib
  35. from descartes.patch import PolygonPatch
  36. import simplejson as json
  37. # TODO: Commented for FlatCAM packaging with cx_freeze
  38. #from matplotlib.pyplot import plot, subplot
  39. import xml.etree.ElementTree as ET
  40. from svg.path import Path, Line, Arc, CubicBezier, QuadraticBezier, parse_path
  41. import itertools
  42. import xml.etree.ElementTree as ET
  43. from svg.path import Path, Line, Arc, CubicBezier, QuadraticBezier, parse_path
  44. from svgparse import *
  45. import logging
  46. log = logging.getLogger('base2')
  47. log.setLevel(logging.DEBUG)
  48. # log.setLevel(logging.WARNING)
  49. # log.setLevel(logging.INFO)
  50. formatter = logging.Formatter('[%(levelname)s] %(message)s')
  51. handler = logging.StreamHandler()
  52. handler.setFormatter(formatter)
  53. log.addHandler(handler)
  54. class ParseError(Exception):
  55. pass
  56. class Geometry(object):
  57. """
  58. Base geometry class.
  59. """
  60. defaults = {
  61. "init_units": 'in'
  62. }
  63. def __init__(self):
  64. # Units (in or mm)
  65. self.units = Geometry.defaults["init_units"]
  66. # Final geometry: MultiPolygon or list (of geometry constructs)
  67. self.solid_geometry = None
  68. # Attributes to be included in serialization
  69. self.ser_attrs = ['units', 'solid_geometry']
  70. # Flattened geometry (list of paths only)
  71. self.flat_geometry = []
  72. def add_circle(self, origin, radius):
  73. """
  74. Adds a circle to the object.
  75. :param origin: Center of the circle.
  76. :param radius: Radius of the circle.
  77. :return: None
  78. """
  79. # TODO: Decide what solid_geometry is supposed to be and how we append to it.
  80. if self.solid_geometry is None:
  81. self.solid_geometry = []
  82. if type(self.solid_geometry) is list:
  83. self.solid_geometry.append(Point(origin).buffer(radius))
  84. return
  85. try:
  86. self.solid_geometry = self.solid_geometry.union(Point(origin).buffer(radius))
  87. except:
  88. #print "Failed to run union on polygons."
  89. log.error("Failed to run union on polygons.")
  90. raise
  91. def add_polygon(self, points):
  92. """
  93. Adds a polygon to the object (by union)
  94. :param points: The vertices of the polygon.
  95. :return: None
  96. """
  97. if self.solid_geometry is None:
  98. self.solid_geometry = []
  99. if type(self.solid_geometry) is list:
  100. self.solid_geometry.append(Polygon(points))
  101. return
  102. try:
  103. self.solid_geometry = self.solid_geometry.union(Polygon(points))
  104. except:
  105. #print "Failed to run union on polygons."
  106. log.error("Failed to run union on polygons.")
  107. raise
  108. def bounds(self):
  109. """
  110. Returns coordinates of rectangular bounds
  111. of geometry: (xmin, ymin, xmax, ymax).
  112. """
  113. log.debug("Geometry->bounds()")
  114. if self.solid_geometry is None:
  115. log.debug("solid_geometry is None")
  116. return 0, 0, 0, 0
  117. if type(self.solid_geometry) is list:
  118. # TODO: This can be done faster. See comment from Shapely mailing lists.
  119. if len(self.solid_geometry) == 0:
  120. log.debug('solid_geometry is empty []')
  121. return 0, 0, 0, 0
  122. return cascaded_union(self.solid_geometry).bounds
  123. else:
  124. return self.solid_geometry.bounds
  125. def find_polygon(self, point, geoset=None):
  126. """
  127. Find an object that object.contains(Point(point)) in
  128. poly, which can can be iterable, contain iterable of, or
  129. be itself an implementer of .contains().
  130. :param poly: See description
  131. :return: Polygon containing point or None.
  132. """
  133. if geoset is None:
  134. geoset = self.solid_geometry
  135. try: # Iterable
  136. for sub_geo in geoset:
  137. p = self.find_polygon(point, geoset=sub_geo)
  138. if p is not None:
  139. return p
  140. except TypeError: # Non-iterable
  141. try: # Implements .contains()
  142. if geoset.contains(Point(point)):
  143. return geoset
  144. except AttributeError: # Does not implement .contains()
  145. return None
  146. return None
  147. def get_interiors(self, geometry=None):
  148. interiors = []
  149. if geometry is None:
  150. geometry = self.solid_geometry
  151. ## If iterable, expand recursively.
  152. try:
  153. for geo in geometry:
  154. interiors.extend(self.get_interiors(geometry=geo))
  155. ## Not iterable, get the exterior if polygon.
  156. except TypeError:
  157. if type(geometry) == Polygon:
  158. interiors.extend(geometry.interiors)
  159. return interiors
  160. def get_exteriors(self, geometry=None):
  161. """
  162. Returns all exteriors of polygons in geometry. Uses
  163. ``self.solid_geometry`` if geometry is not provided.
  164. :param geometry: Shapely type or list or list of list of such.
  165. :return: List of paths constituting the exteriors
  166. of polygons in geometry.
  167. """
  168. exteriors = []
  169. if geometry is None:
  170. geometry = self.solid_geometry
  171. ## If iterable, expand recursively.
  172. try:
  173. for geo in geometry:
  174. exteriors.extend(self.get_exteriors(geometry=geo))
  175. ## Not iterable, get the exterior if polygon.
  176. except TypeError:
  177. if type(geometry) == Polygon:
  178. exteriors.append(geometry.exterior)
  179. return exteriors
  180. def flatten(self, geometry=None, reset=True, pathonly=False):
  181. """
  182. Creates a list of non-iterable linear geometry objects.
  183. Polygons are expanded into its exterior and interiors if specified.
  184. Results are placed in self.flat_geoemtry
  185. :param geometry: Shapely type or list or list of list of such.
  186. :param reset: Clears the contents of self.flat_geometry.
  187. :param pathonly: Expands polygons into linear elements.
  188. """
  189. if geometry is None:
  190. geometry = self.solid_geometry
  191. if reset:
  192. self.flat_geometry = []
  193. ## If iterable, expand recursively.
  194. try:
  195. for geo in geometry:
  196. self.flatten(geometry=geo,
  197. reset=False,
  198. pathonly=pathonly)
  199. ## Not iterable, do the actual indexing and add.
  200. except TypeError:
  201. if pathonly and type(geometry) == Polygon:
  202. self.flat_geometry.append(geometry.exterior)
  203. self.flatten(geometry=geometry.interiors,
  204. reset=False,
  205. pathonly=True)
  206. else:
  207. self.flat_geometry.append(geometry)
  208. return self.flat_geometry
  209. # def make2Dstorage(self):
  210. #
  211. # self.flatten()
  212. #
  213. # def get_pts(o):
  214. # pts = []
  215. # if type(o) == Polygon:
  216. # g = o.exterior
  217. # pts += list(g.coords)
  218. # for i in o.interiors:
  219. # pts += list(i.coords)
  220. # else:
  221. # pts += list(o.coords)
  222. # return pts
  223. #
  224. # storage = FlatCAMRTreeStorage()
  225. # storage.get_points = get_pts
  226. # for shape in self.flat_geometry:
  227. # storage.insert(shape)
  228. # return storage
  229. # def flatten_to_paths(self, geometry=None, reset=True):
  230. # """
  231. # Creates a list of non-iterable linear geometry elements and
  232. # indexes them in rtree.
  233. #
  234. # :param geometry: Iterable geometry
  235. # :param reset: Wether to clear (True) or append (False) to self.flat_geometry
  236. # :return: self.flat_geometry, self.flat_geometry_rtree
  237. # """
  238. #
  239. # if geometry is None:
  240. # geometry = self.solid_geometry
  241. #
  242. # if reset:
  243. # self.flat_geometry = []
  244. #
  245. # ## If iterable, expand recursively.
  246. # try:
  247. # for geo in geometry:
  248. # self.flatten_to_paths(geometry=geo, reset=False)
  249. #
  250. # ## Not iterable, do the actual indexing and add.
  251. # except TypeError:
  252. # if type(geometry) == Polygon:
  253. # g = geometry.exterior
  254. # self.flat_geometry.append(g)
  255. #
  256. # ## Add first and last points of the path to the index.
  257. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[0])
  258. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[-1])
  259. #
  260. # for interior in geometry.interiors:
  261. # g = interior
  262. # self.flat_geometry.append(g)
  263. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[0])
  264. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[-1])
  265. # else:
  266. # g = geometry
  267. # self.flat_geometry.append(g)
  268. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[0])
  269. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[-1])
  270. #
  271. # return self.flat_geometry, self.flat_geometry_rtree
  272. def isolation_geometry(self, offset):
  273. """
  274. Creates contours around geometry at a given
  275. offset distance.
  276. :param offset: Offset distance.
  277. :type offset: float
  278. :return: The buffered geometry.
  279. :rtype: Shapely.MultiPolygon or Shapely.Polygon
  280. """
  281. return self.solid_geometry.buffer(offset)
  282. def is_empty(self):
  283. if self.solid_geometry is None:
  284. return True
  285. if type(self.solid_geometry) is list and len(self.solid_geometry) == 0:
  286. return True
  287. return False
  288. def import_svg(self, filename, flip=True):
  289. """
  290. Imports shapes from an SVG file into the object's geometry.
  291. :param filename: Path to the SVG file.
  292. :type filename: str
  293. :return: None
  294. """
  295. # Parse into list of shapely objects
  296. svg_tree = ET.parse(filename)
  297. svg_root = svg_tree.getroot()
  298. # Change origin to bottom left
  299. # h = float(svg_root.get('height'))
  300. # w = float(svg_root.get('width'))
  301. h = svgparselength(svg_root.get('height'))[0] # TODO: No units support yet
  302. geos = getsvggeo(svg_root)
  303. if flip:
  304. geos = [translate(scale(g, 1.0, -1.0, origin=(0, 0)), yoff=h) for g in geos]
  305. # Add to object
  306. if self.solid_geometry is None:
  307. self.solid_geometry = []
  308. if type(self.solid_geometry) is list:
  309. self.solid_geometry.append(cascaded_union(geos))
  310. else: # It's shapely geometry
  311. self.solid_geometry = cascaded_union([self.solid_geometry,
  312. cascaded_union(geos)])
  313. return
  314. def size(self):
  315. """
  316. Returns (width, height) of rectangular
  317. bounds of geometry.
  318. """
  319. if self.solid_geometry is None:
  320. log.warning("Solid_geometry not computed yet.")
  321. return 0
  322. bounds = self.bounds()
  323. return bounds[2] - bounds[0], bounds[3] - bounds[1]
  324. def get_empty_area(self, boundary=None):
  325. """
  326. Returns the complement of self.solid_geometry within
  327. the given boundary polygon. If not specified, it defaults to
  328. the rectangular bounding box of self.solid_geometry.
  329. """
  330. if boundary is None:
  331. boundary = self.solid_geometry.envelope
  332. return boundary.difference(self.solid_geometry)
  333. @staticmethod
  334. def clear_polygon(polygon, tooldia, overlap=0.15):
  335. """
  336. Creates geometry inside a polygon for a tool to cover
  337. the whole area.
  338. This algorithm shrinks the edges of the polygon and takes
  339. the resulting edges as toolpaths.
  340. :param polygon: Polygon to clear.
  341. :param tooldia: Diameter of the tool.
  342. :param overlap: Overlap of toolpasses.
  343. :return:
  344. """
  345. log.debug("camlib.clear_polygon()")
  346. assert type(polygon) == Polygon or type(polygon) == MultiPolygon, \
  347. "Expected a Polygon or MultiPolygon, got %s" % type(polygon)
  348. ## The toolpaths
  349. # Index first and last points in paths
  350. def get_pts(o):
  351. return [o.coords[0], o.coords[-1]]
  352. geoms = FlatCAMRTreeStorage()
  353. geoms.get_points = get_pts
  354. # Can only result in a Polygon or MultiPolygon
  355. current = polygon.buffer(-tooldia / 2.0)
  356. # current can be a MultiPolygon
  357. try:
  358. for p in current:
  359. geoms.insert(p.exterior)
  360. for i in p.interiors:
  361. geoms.insert(i)
  362. # Not a Multipolygon. Must be a Polygon
  363. except TypeError:
  364. geoms.insert(current.exterior)
  365. for i in current.interiors:
  366. geoms.insert(i)
  367. while True:
  368. # Can only result in a Polygon or MultiPolygon
  369. current = current.buffer(-tooldia * (1 - overlap))
  370. if current.area > 0:
  371. # current can be a MultiPolygon
  372. try:
  373. for p in current:
  374. geoms.insert(p.exterior)
  375. for i in p.interiors:
  376. geoms.insert(i)
  377. # Not a Multipolygon. Must be a Polygon
  378. except TypeError:
  379. geoms.insert(current.exterior)
  380. for i in current.interiors:
  381. geoms.insert(i)
  382. else:
  383. break
  384. # Optimization: Reduce lifts
  385. log.debug("Reducing tool lifts...")
  386. geoms = Geometry.paint_connect(geoms, polygon, tooldia)
  387. return geoms
  388. @staticmethod
  389. def clear_polygon2(polygon, tooldia, seedpoint=None, overlap=0.15):
  390. """
  391. Creates geometry inside a polygon for a tool to cover
  392. the whole area.
  393. This algorithm starts with a seed point inside the polygon
  394. and draws circles around it. Arcs inside the polygons are
  395. valid cuts. Finalizes by cutting around the inside edge of
  396. the polygon.
  397. :param polygon: Shapely.geometry.Polygon
  398. :param tooldia: Diameter of the tool
  399. :param seedpoint: Shapely.geometry.Point or None
  400. :param overlap: Tool fraction overlap bewteen passes
  401. :return: List of toolpaths covering polygon.
  402. """
  403. log.debug("camlib.clear_polygon2()")
  404. # Current buffer radius
  405. radius = tooldia / 2 * (1 - overlap)
  406. ## The toolpaths
  407. # Index first and last points in paths
  408. def get_pts(o):
  409. return [o.coords[0], o.coords[-1]]
  410. geoms = FlatCAMRTreeStorage()
  411. geoms.get_points = get_pts
  412. # Path margin
  413. path_margin = polygon.buffer(-tooldia / 2)
  414. # Estimate good seedpoint if not provided.
  415. if seedpoint is None:
  416. seedpoint = path_margin.representative_point()
  417. # Grow from seed until outside the box. The polygons will
  418. # never have an interior, so take the exterior LinearRing.
  419. while 1:
  420. path = Point(seedpoint).buffer(radius).exterior
  421. path = path.intersection(path_margin)
  422. # Touches polygon?
  423. if path.is_empty:
  424. break
  425. else:
  426. #geoms.append(path)
  427. #geoms.insert(path)
  428. # path can be a collection of paths.
  429. try:
  430. for p in path:
  431. geoms.insert(p)
  432. except TypeError:
  433. geoms.insert(path)
  434. radius += tooldia * (1 - overlap)
  435. # Clean inside edges of the original polygon
  436. outer_edges = [x.exterior for x in autolist(polygon.buffer(-tooldia / 2))]
  437. inner_edges = []
  438. for x in autolist(polygon.buffer(-tooldia / 2)): # Over resulting polygons
  439. for y in x.interiors: # Over interiors of each polygon
  440. inner_edges.append(y)
  441. #geoms += outer_edges + inner_edges
  442. for g in outer_edges + inner_edges:
  443. geoms.insert(g)
  444. # Optimization connect touching paths
  445. # log.debug("Connecting paths...")
  446. # geoms = Geometry.path_connect(geoms)
  447. # Optimization: Reduce lifts
  448. log.debug("Reducing tool lifts...")
  449. geoms = Geometry.paint_connect(geoms, polygon, tooldia)
  450. return geoms
  451. def scale(self, factor):
  452. """
  453. Scales all of the object's geometry by a given factor. Override
  454. this method.
  455. :param factor: Number by which to scale.
  456. :type factor: float
  457. :return: None
  458. :rtype: None
  459. """
  460. return
  461. def offset(self, vect):
  462. """
  463. Offset the geometry by the given vector. Override this method.
  464. :param vect: (x, y) vector by which to offset the object.
  465. :type vect: tuple
  466. :return: None
  467. """
  468. return
  469. @staticmethod
  470. def paint_connect(storage, boundary, tooldia, max_walk=None):
  471. """
  472. Connects paths that results in a connection segment that is
  473. within the paint area. This avoids unnecessary tool lifting.
  474. :param storage: Geometry to be optimized.
  475. :type storage: FlatCAMRTreeStorage
  476. :param boundary: Polygon defining the limits of the paintable area.
  477. :type boundary: Polygon
  478. :param max_walk: Maximum allowable distance without lifting tool.
  479. :type max_walk: float or None
  480. :return: Optimized geometry.
  481. :rtype: FlatCAMRTreeStorage
  482. """
  483. # If max_walk is not specified, the maximum allowed is
  484. # 10 times the tool diameter
  485. max_walk = max_walk or 10 * tooldia
  486. # Assuming geolist is a flat list of flat elements
  487. ## Index first and last points in paths
  488. def get_pts(o):
  489. return [o.coords[0], o.coords[-1]]
  490. # storage = FlatCAMRTreeStorage()
  491. # storage.get_points = get_pts
  492. #
  493. # for shape in geolist:
  494. # if shape is not None: # TODO: This shouldn't have happened.
  495. # # Make LlinearRings into linestrings otherwise
  496. # # When chaining the coordinates path is messed up.
  497. # storage.insert(LineString(shape))
  498. # #storage.insert(shape)
  499. ## Iterate over geometry paths getting the nearest each time.
  500. #optimized_paths = []
  501. optimized_paths = FlatCAMRTreeStorage()
  502. optimized_paths.get_points = get_pts
  503. path_count = 0
  504. current_pt = (0, 0)
  505. pt, geo = storage.nearest(current_pt)
  506. storage.remove(geo)
  507. geo = LineString(geo)
  508. current_pt = geo.coords[-1]
  509. try:
  510. while True:
  511. path_count += 1
  512. #log.debug("Path %d" % path_count)
  513. pt, candidate = storage.nearest(current_pt)
  514. storage.remove(candidate)
  515. candidate = LineString(candidate)
  516. # If last point in geometry is the nearest
  517. # then reverse coordinates.
  518. # but prefer the first one if last == first
  519. if pt != candidate.coords[0] and pt == candidate.coords[-1]:
  520. candidate.coords = list(candidate.coords)[::-1]
  521. # Straight line from current_pt to pt.
  522. # Is the toolpath inside the geometry?
  523. walk_path = LineString([current_pt, pt])
  524. walk_cut = walk_path.buffer(tooldia / 2)
  525. if walk_cut.within(boundary) and walk_path.length < max_walk:
  526. #log.debug("Walk to path #%d is inside. Joining." % path_count)
  527. # Completely inside. Append...
  528. geo.coords = list(geo.coords) + list(candidate.coords)
  529. # try:
  530. # last = optimized_paths[-1]
  531. # last.coords = list(last.coords) + list(geo.coords)
  532. # except IndexError:
  533. # optimized_paths.append(geo)
  534. else:
  535. # Have to lift tool. End path.
  536. #log.debug("Path #%d not within boundary. Next." % path_count)
  537. #optimized_paths.append(geo)
  538. optimized_paths.insert(geo)
  539. geo = candidate
  540. current_pt = geo.coords[-1]
  541. # Next
  542. #pt, geo = storage.nearest(current_pt)
  543. except StopIteration: # Nothing left in storage.
  544. #pass
  545. optimized_paths.insert(geo)
  546. return optimized_paths
  547. @staticmethod
  548. def path_connect(storage, origin=(0, 0)):
  549. """
  550. :return: None
  551. """
  552. log.debug("path_connect()")
  553. ## Index first and last points in paths
  554. def get_pts(o):
  555. return [o.coords[0], o.coords[-1]]
  556. #
  557. # storage = FlatCAMRTreeStorage()
  558. # storage.get_points = get_pts
  559. #
  560. # for shape in pathlist:
  561. # if shape is not None: # TODO: This shouldn't have happened.
  562. # storage.insert(shape)
  563. path_count = 0
  564. pt, geo = storage.nearest(origin)
  565. storage.remove(geo)
  566. #optimized_geometry = [geo]
  567. optimized_geometry = FlatCAMRTreeStorage()
  568. optimized_geometry.get_points = get_pts
  569. #optimized_geometry.insert(geo)
  570. try:
  571. while True:
  572. path_count += 1
  573. #print "geo is", geo
  574. _, left = storage.nearest(geo.coords[0])
  575. #print "left is", left
  576. # If left touches geo, remove left from original
  577. # storage and append to geo.
  578. if type(left) == LineString:
  579. if left.coords[0] == geo.coords[0]:
  580. storage.remove(left)
  581. geo.coords = list(geo.coords)[::-1] + list(left.coords)
  582. continue
  583. if left.coords[-1] == geo.coords[0]:
  584. storage.remove(left)
  585. geo.coords = list(left.coords) + list(geo.coords)
  586. continue
  587. if left.coords[0] == geo.coords[-1]:
  588. storage.remove(left)
  589. geo.coords = list(geo.coords) + list(left.coords)
  590. continue
  591. if left.coords[-1] == geo.coords[-1]:
  592. storage.remove(left)
  593. geo.coords = list(geo.coords) + list(left.coords)[::-1]
  594. continue
  595. _, right = storage.nearest(geo.coords[-1])
  596. #print "right is", right
  597. # If right touches geo, remove left from original
  598. # storage and append to geo.
  599. if type(right) == LineString:
  600. if right.coords[0] == geo.coords[-1]:
  601. storage.remove(right)
  602. geo.coords = list(geo.coords) + list(right.coords)
  603. continue
  604. if right.coords[-1] == geo.coords[-1]:
  605. storage.remove(right)
  606. geo.coords = list(geo.coords) + list(right.coords)[::-1]
  607. continue
  608. if right.coords[0] == geo.coords[0]:
  609. storage.remove(right)
  610. geo.coords = list(geo.coords)[::-1] + list(right.coords)
  611. continue
  612. if right.coords[-1] == geo.coords[0]:
  613. storage.remove(right)
  614. geo.coords = list(left.coords) + list(geo.coords)
  615. continue
  616. # right is either a LinearRing or it does not connect
  617. # to geo (nothing left to connect to geo), so we continue
  618. # with right as geo.
  619. storage.remove(right)
  620. if type(right) == LinearRing:
  621. optimized_geometry.insert(right)
  622. else:
  623. # Cannot exteng geo any further. Put it away.
  624. optimized_geometry.insert(geo)
  625. # Continue with right.
  626. geo = right
  627. except StopIteration: # Nothing found in storage.
  628. optimized_geometry.insert(geo)
  629. #print path_count
  630. log.debug("path_count = %d" % path_count)
  631. return optimized_geometry
  632. def convert_units(self, units):
  633. """
  634. Converts the units of the object to ``units`` by scaling all
  635. the geometry appropriately. This call ``scale()``. Don't call
  636. it again in descendents.
  637. :param units: "IN" or "MM"
  638. :type units: str
  639. :return: Scaling factor resulting from unit change.
  640. :rtype: float
  641. """
  642. log.debug("Geometry.convert_units()")
  643. if units.upper() == self.units.upper():
  644. return 1.0
  645. if units.upper() == "MM":
  646. factor = 25.4
  647. elif units.upper() == "IN":
  648. factor = 1 / 25.4
  649. else:
  650. log.error("Unsupported units: %s" % str(units))
  651. return 1.0
  652. self.units = units
  653. self.scale(factor)
  654. return factor
  655. def to_dict(self):
  656. """
  657. Returns a respresentation of the object as a dictionary.
  658. Attributes to include are listed in ``self.ser_attrs``.
  659. :return: A dictionary-encoded copy of the object.
  660. :rtype: dict
  661. """
  662. d = {}
  663. for attr in self.ser_attrs:
  664. d[attr] = getattr(self, attr)
  665. return d
  666. def from_dict(self, d):
  667. """
  668. Sets object's attributes from a dictionary.
  669. Attributes to include are listed in ``self.ser_attrs``.
  670. This method will look only for only and all the
  671. attributes in ``self.ser_attrs``. They must all
  672. be present. Use only for deserializing saved
  673. objects.
  674. :param d: Dictionary of attributes to set in the object.
  675. :type d: dict
  676. :return: None
  677. """
  678. for attr in self.ser_attrs:
  679. setattr(self, attr, d[attr])
  680. def union(self):
  681. """
  682. Runs a cascaded union on the list of objects in
  683. solid_geometry.
  684. :return: None
  685. """
  686. self.solid_geometry = [cascaded_union(self.solid_geometry)]
  687. class ApertureMacro:
  688. """
  689. Syntax of aperture macros.
  690. <AM command>: AM<Aperture macro name>*<Macro content>
  691. <Macro content>: {{<Variable definition>*}{<Primitive>*}}
  692. <Variable definition>: $K=<Arithmetic expression>
  693. <Primitive>: <Primitive code>,<Modifier>{,<Modifier>}|<Comment>
  694. <Modifier>: $M|< Arithmetic expression>
  695. <Comment>: 0 <Text>
  696. """
  697. ## Regular expressions
  698. am1_re = re.compile(r'^%AM([^\*]+)\*(.+)?(%)?$')
  699. am2_re = re.compile(r'(.*)%$')
  700. amcomm_re = re.compile(r'^0(.*)')
  701. amprim_re = re.compile(r'^[1-9].*')
  702. amvar_re = re.compile(r'^\$([0-9a-zA-z]+)=(.*)')
  703. def __init__(self, name=None):
  704. self.name = name
  705. self.raw = ""
  706. ## These below are recomputed for every aperture
  707. ## definition, in other words, are temporary variables.
  708. self.primitives = []
  709. self.locvars = {}
  710. self.geometry = None
  711. def to_dict(self):
  712. """
  713. Returns the object in a serializable form. Only the name and
  714. raw are required.
  715. :return: Dictionary representing the object. JSON ready.
  716. :rtype: dict
  717. """
  718. return {
  719. 'name': self.name,
  720. 'raw': self.raw
  721. }
  722. def from_dict(self, d):
  723. """
  724. Populates the object from a serial representation created
  725. with ``self.to_dict()``.
  726. :param d: Serial representation of an ApertureMacro object.
  727. :return: None
  728. """
  729. for attr in ['name', 'raw']:
  730. setattr(self, attr, d[attr])
  731. def parse_content(self):
  732. """
  733. Creates numerical lists for all primitives in the aperture
  734. macro (in ``self.raw``) by replacing all variables by their
  735. values iteratively and evaluating expressions. Results
  736. are stored in ``self.primitives``.
  737. :return: None
  738. """
  739. # Cleanup
  740. self.raw = self.raw.replace('\n', '').replace('\r', '').strip(" *")
  741. self.primitives = []
  742. # Separate parts
  743. parts = self.raw.split('*')
  744. #### Every part in the macro ####
  745. for part in parts:
  746. ### Comments. Ignored.
  747. match = ApertureMacro.amcomm_re.search(part)
  748. if match:
  749. continue
  750. ### Variables
  751. # These are variables defined locally inside the macro. They can be
  752. # numerical constant or defind in terms of previously define
  753. # variables, which can be defined locally or in an aperture
  754. # definition. All replacements ocurr here.
  755. match = ApertureMacro.amvar_re.search(part)
  756. if match:
  757. var = match.group(1)
  758. val = match.group(2)
  759. # Replace variables in value
  760. for v in self.locvars:
  761. val = re.sub(r'\$'+str(v)+r'(?![0-9a-zA-Z])', str(self.locvars[v]), val)
  762. # Make all others 0
  763. val = re.sub(r'\$[0-9a-zA-Z](?![0-9a-zA-Z])', "0", val)
  764. # Change x with *
  765. val = re.sub(r'[xX]', "*", val)
  766. # Eval() and store.
  767. self.locvars[var] = eval(val)
  768. continue
  769. ### Primitives
  770. # Each is an array. The first identifies the primitive, while the
  771. # rest depend on the primitive. All are strings representing a
  772. # number and may contain variable definition. The values of these
  773. # variables are defined in an aperture definition.
  774. match = ApertureMacro.amprim_re.search(part)
  775. if match:
  776. ## Replace all variables
  777. for v in self.locvars:
  778. part = re.sub(r'\$' + str(v) + r'(?![0-9a-zA-Z])', str(self.locvars[v]), part)
  779. # Make all others 0
  780. part = re.sub(r'\$[0-9a-zA-Z](?![0-9a-zA-Z])', "0", part)
  781. # Change x with *
  782. part = re.sub(r'[xX]', "*", part)
  783. ## Store
  784. elements = part.split(",")
  785. self.primitives.append([eval(x) for x in elements])
  786. continue
  787. log.warning("Unknown syntax of aperture macro part: %s" % str(part))
  788. def append(self, data):
  789. """
  790. Appends a string to the raw macro.
  791. :param data: Part of the macro.
  792. :type data: str
  793. :return: None
  794. """
  795. self.raw += data
  796. @staticmethod
  797. def default2zero(n, mods):
  798. """
  799. Pads the ``mods`` list with zeros resulting in an
  800. list of length n.
  801. :param n: Length of the resulting list.
  802. :type n: int
  803. :param mods: List to be padded.
  804. :type mods: list
  805. :return: Zero-padded list.
  806. :rtype: list
  807. """
  808. x = [0.0] * n
  809. na = len(mods)
  810. x[0:na] = mods
  811. return x
  812. @staticmethod
  813. def make_circle(mods):
  814. """
  815. :param mods: (Exposure 0/1, Diameter >=0, X-coord, Y-coord)
  816. :return:
  817. """
  818. pol, dia, x, y = ApertureMacro.default2zero(4, mods)
  819. return {"pol": int(pol), "geometry": Point(x, y).buffer(dia/2)}
  820. @staticmethod
  821. def make_vectorline(mods):
  822. """
  823. :param mods: (Exposure 0/1, Line width >= 0, X-start, Y-start, X-end, Y-end,
  824. rotation angle around origin in degrees)
  825. :return:
  826. """
  827. pol, width, xs, ys, xe, ye, angle = ApertureMacro.default2zero(7, mods)
  828. line = LineString([(xs, ys), (xe, ye)])
  829. box = line.buffer(width/2, cap_style=2)
  830. box_rotated = affinity.rotate(box, angle, origin=(0, 0))
  831. return {"pol": int(pol), "geometry": box_rotated}
  832. @staticmethod
  833. def make_centerline(mods):
  834. """
  835. :param mods: (Exposure 0/1, width >=0, height >=0, x-center, y-center,
  836. rotation angle around origin in degrees)
  837. :return:
  838. """
  839. pol, width, height, x, y, angle = ApertureMacro.default2zero(6, mods)
  840. box = shply_box(x-width/2, y-height/2, x+width/2, y+height/2)
  841. box_rotated = affinity.rotate(box, angle, origin=(0, 0))
  842. return {"pol": int(pol), "geometry": box_rotated}
  843. @staticmethod
  844. def make_lowerleftline(mods):
  845. """
  846. :param mods: (exposure 0/1, width >=0, height >=0, x-lowerleft, y-lowerleft,
  847. rotation angle around origin in degrees)
  848. :return:
  849. """
  850. pol, width, height, x, y, angle = ApertureMacro.default2zero(6, mods)
  851. box = shply_box(x, y, x+width, y+height)
  852. box_rotated = affinity.rotate(box, angle, origin=(0, 0))
  853. return {"pol": int(pol), "geometry": box_rotated}
  854. @staticmethod
  855. def make_outline(mods):
  856. """
  857. :param mods:
  858. :return:
  859. """
  860. pol = mods[0]
  861. n = mods[1]
  862. points = [(0, 0)]*(n+1)
  863. for i in range(n+1):
  864. points[i] = mods[2*i + 2:2*i + 4]
  865. angle = mods[2*n + 4]
  866. poly = Polygon(points)
  867. poly_rotated = affinity.rotate(poly, angle, origin=(0, 0))
  868. return {"pol": int(pol), "geometry": poly_rotated}
  869. @staticmethod
  870. def make_polygon(mods):
  871. """
  872. Note: Specs indicate that rotation is only allowed if the center
  873. (x, y) == (0, 0). I will tolerate breaking this rule.
  874. :param mods: (exposure 0/1, n_verts 3<=n<=12, x-center, y-center,
  875. diameter of circumscribed circle >=0, rotation angle around origin)
  876. :return:
  877. """
  878. pol, nverts, x, y, dia, angle = ApertureMacro.default2zero(6, mods)
  879. points = [(0, 0)]*nverts
  880. for i in range(nverts):
  881. points[i] = (x + 0.5 * dia * cos(2*pi * i/nverts),
  882. y + 0.5 * dia * sin(2*pi * i/nverts))
  883. poly = Polygon(points)
  884. poly_rotated = affinity.rotate(poly, angle, origin=(0, 0))
  885. return {"pol": int(pol), "geometry": poly_rotated}
  886. @staticmethod
  887. def make_moire(mods):
  888. """
  889. Note: Specs indicate that rotation is only allowed if the center
  890. (x, y) == (0, 0). I will tolerate breaking this rule.
  891. :param mods: (x-center, y-center, outer_dia_outer_ring, ring thickness,
  892. gap, max_rings, crosshair_thickness, crosshair_len, rotation
  893. angle around origin in degrees)
  894. :return:
  895. """
  896. x, y, dia, thickness, gap, nrings, cross_th, cross_len, angle = ApertureMacro.default2zero(9, mods)
  897. r = dia/2 - thickness/2
  898. result = Point((x, y)).buffer(r).exterior.buffer(thickness/2.0)
  899. ring = Point((x, y)).buffer(r).exterior.buffer(thickness/2.0) # Need a copy!
  900. i = 1 # Number of rings created so far
  901. ## If the ring does not have an interior it means that it is
  902. ## a disk. Then stop.
  903. while len(ring.interiors) > 0 and i < nrings:
  904. r -= thickness + gap
  905. if r <= 0:
  906. break
  907. ring = Point((x, y)).buffer(r).exterior.buffer(thickness/2.0)
  908. result = cascaded_union([result, ring])
  909. i += 1
  910. ## Crosshair
  911. hor = LineString([(x - cross_len, y), (x + cross_len, y)]).buffer(cross_th/2.0, cap_style=2)
  912. ver = LineString([(x, y-cross_len), (x, y + cross_len)]).buffer(cross_th/2.0, cap_style=2)
  913. result = cascaded_union([result, hor, ver])
  914. return {"pol": 1, "geometry": result}
  915. @staticmethod
  916. def make_thermal(mods):
  917. """
  918. Note: Specs indicate that rotation is only allowed if the center
  919. (x, y) == (0, 0). I will tolerate breaking this rule.
  920. :param mods: [x-center, y-center, diameter-outside, diameter-inside,
  921. gap-thickness, rotation angle around origin]
  922. :return:
  923. """
  924. x, y, dout, din, t, angle = ApertureMacro.default2zero(6, mods)
  925. ring = Point((x, y)).buffer(dout/2.0).difference(Point((x, y)).buffer(din/2.0))
  926. hline = LineString([(x - dout/2.0, y), (x + dout/2.0, y)]).buffer(t/2.0, cap_style=3)
  927. vline = LineString([(x, y - dout/2.0), (x, y + dout/2.0)]).buffer(t/2.0, cap_style=3)
  928. thermal = ring.difference(hline.union(vline))
  929. return {"pol": 1, "geometry": thermal}
  930. def make_geometry(self, modifiers):
  931. """
  932. Runs the macro for the given modifiers and generates
  933. the corresponding geometry.
  934. :param modifiers: Modifiers (parameters) for this macro
  935. :type modifiers: list
  936. """
  937. ## Primitive makers
  938. makers = {
  939. "1": ApertureMacro.make_circle,
  940. "2": ApertureMacro.make_vectorline,
  941. "20": ApertureMacro.make_vectorline,
  942. "21": ApertureMacro.make_centerline,
  943. "22": ApertureMacro.make_lowerleftline,
  944. "4": ApertureMacro.make_outline,
  945. "5": ApertureMacro.make_polygon,
  946. "6": ApertureMacro.make_moire,
  947. "7": ApertureMacro.make_thermal
  948. }
  949. ## Store modifiers as local variables
  950. modifiers = modifiers or []
  951. modifiers = [float(m) for m in modifiers]
  952. self.locvars = {}
  953. for i in range(0, len(modifiers)):
  954. self.locvars[str(i+1)] = modifiers[i]
  955. ## Parse
  956. self.primitives = [] # Cleanup
  957. self.geometry = None
  958. self.parse_content()
  959. ## Make the geometry
  960. for primitive in self.primitives:
  961. # Make the primitive
  962. prim_geo = makers[str(int(primitive[0]))](primitive[1:])
  963. # Add it (according to polarity)
  964. if self.geometry is None and prim_geo['pol'] == 1:
  965. self.geometry = prim_geo['geometry']
  966. continue
  967. if prim_geo['pol'] == 1:
  968. self.geometry = self.geometry.union(prim_geo['geometry'])
  969. continue
  970. if prim_geo['pol'] == 0:
  971. self.geometry = self.geometry.difference(prim_geo['geometry'])
  972. continue
  973. return self.geometry
  974. class Gerber (Geometry):
  975. """
  976. **ATTRIBUTES**
  977. * ``apertures`` (dict): The keys are names/identifiers of each aperture.
  978. The values are dictionaries key/value pairs which describe the aperture. The
  979. type key is always present and the rest depend on the key:
  980. +-----------+-----------------------------------+
  981. | Key | Value |
  982. +===========+===================================+
  983. | type | (str) "C", "R", "O", "P", or "AP" |
  984. +-----------+-----------------------------------+
  985. | others | Depend on ``type`` |
  986. +-----------+-----------------------------------+
  987. * ``aperture_macros`` (dictionary): Are predefined geometrical structures
  988. that can be instanciated with different parameters in an aperture
  989. definition. See ``apertures`` above. The key is the name of the macro,
  990. and the macro itself, the value, is a ``Aperture_Macro`` object.
  991. * ``flash_geometry`` (list): List of (Shapely) geometric object resulting
  992. from ``flashes``. These are generated from ``flashes`` in ``do_flashes()``.
  993. * ``buffered_paths`` (list): List of (Shapely) polygons resulting from
  994. *buffering* (or thickening) the ``paths`` with the aperture. These are
  995. generated from ``paths`` in ``buffer_paths()``.
  996. **USAGE**::
  997. g = Gerber()
  998. g.parse_file(filename)
  999. g.create_geometry()
  1000. do_something(s.solid_geometry)
  1001. """
  1002. defaults = {
  1003. "steps_per_circle": 40,
  1004. "use_buffer_for_union": True
  1005. }
  1006. def __init__(self, steps_per_circle=None):
  1007. """
  1008. The constructor takes no parameters. Use ``gerber.parse_files()``
  1009. or ``gerber.parse_lines()`` to populate the object from Gerber source.
  1010. :return: Gerber object
  1011. :rtype: Gerber
  1012. """
  1013. # Initialize parent
  1014. Geometry.__init__(self)
  1015. self.solid_geometry = Polygon()
  1016. # Number format
  1017. self.int_digits = 3
  1018. """Number of integer digits in Gerber numbers. Used during parsing."""
  1019. self.frac_digits = 4
  1020. """Number of fraction digits in Gerber numbers. Used during parsing."""
  1021. ## Gerber elements ##
  1022. # Apertures {'id':{'type':chr,
  1023. # ['size':float], ['width':float],
  1024. # ['height':float]}, ...}
  1025. self.apertures = {}
  1026. # Aperture Macros
  1027. self.aperture_macros = {}
  1028. # Attributes to be included in serialization
  1029. # Always append to it because it carries contents
  1030. # from Geometry.
  1031. self.ser_attrs += ['int_digits', 'frac_digits', 'apertures',
  1032. 'aperture_macros', 'solid_geometry']
  1033. #### Parser patterns ####
  1034. # FS - Format Specification
  1035. # The format of X and Y must be the same!
  1036. # L-omit leading zeros, T-omit trailing zeros
  1037. # A-absolute notation, I-incremental notation
  1038. self.fmt_re = re.compile(r'%FS([LT])([AI])X(\d)(\d)Y\d\d\*%$')
  1039. # Mode (IN/MM)
  1040. self.mode_re = re.compile(r'^%MO(IN|MM)\*%$')
  1041. # Comment G04|G4
  1042. self.comm_re = re.compile(r'^G0?4(.*)$')
  1043. # AD - Aperture definition
  1044. # Aperture Macro names: Name = [a-zA-Z_.$]{[a-zA-Z_.0-9]+}
  1045. # NOTE: Adding "-" to support output from Upverter.
  1046. self.ad_re = re.compile(r'^%ADD(\d\d+)([a-zA-Z_$\.][a-zA-Z0-9_$\.\-]*)(?:,(.*))?\*%$')
  1047. # AM - Aperture Macro
  1048. # Beginning of macro (Ends with *%):
  1049. #self.am_re = re.compile(r'^%AM([a-zA-Z0-9]*)\*')
  1050. # Tool change
  1051. # May begin with G54 but that is deprecated
  1052. self.tool_re = re.compile(r'^(?:G54)?D(\d\d+)\*$')
  1053. # G01... - Linear interpolation plus flashes with coordinates
  1054. # Operation code (D0x) missing is deprecated... oh well I will support it.
  1055. self.lin_re = re.compile(r'^(?:G0?(1))?(?=.*X([\+-]?\d+))?(?=.*Y([\+-]?\d+))?[XY][^DIJ]*(?:D0?([123]))?\*$')
  1056. # Operation code alone, usually just D03 (Flash)
  1057. self.opcode_re = re.compile(r'^D0?([123])\*$')
  1058. # G02/3... - Circular interpolation with coordinates
  1059. # 2-clockwise, 3-counterclockwise
  1060. # Operation code (D0x) missing is deprecated... oh well I will support it.
  1061. # Optional start with G02 or G03, optional end with D01 or D02 with
  1062. # optional coordinates but at least one in any order.
  1063. self.circ_re = re.compile(r'^(?:G0?([23]))?(?=.*X([\+-]?\d+))?(?=.*Y([\+-]?\d+))' +
  1064. '?(?=.*I([\+-]?\d+))?(?=.*J([\+-]?\d+))?[XYIJ][^D]*(?:D0([12]))?\*$')
  1065. # G01/2/3 Occurring without coordinates
  1066. self.interp_re = re.compile(r'^(?:G0?([123]))\*')
  1067. # Single D74 or multi D75 quadrant for circular interpolation
  1068. self.quad_re = re.compile(r'^G7([45])\*$')
  1069. # Region mode on
  1070. # In region mode, D01 starts a region
  1071. # and D02 ends it. A new region can be started again
  1072. # with D01. All contours must be closed before
  1073. # D02 or G37.
  1074. self.regionon_re = re.compile(r'^G36\*$')
  1075. # Region mode off
  1076. # Will end a region and come off region mode.
  1077. # All contours must be closed before D02 or G37.
  1078. self.regionoff_re = re.compile(r'^G37\*$')
  1079. # End of file
  1080. self.eof_re = re.compile(r'^M02\*')
  1081. # IP - Image polarity
  1082. self.pol_re = re.compile(r'^%IP(POS|NEG)\*%$')
  1083. # LP - Level polarity
  1084. self.lpol_re = re.compile(r'^%LP([DC])\*%$')
  1085. # Units (OBSOLETE)
  1086. self.units_re = re.compile(r'^G7([01])\*$')
  1087. # Absolute/Relative G90/1 (OBSOLETE)
  1088. self.absrel_re = re.compile(r'^G9([01])\*$')
  1089. # Aperture macros
  1090. self.am1_re = re.compile(r'^%AM([^\*]+)\*([^%]+)?(%)?$')
  1091. self.am2_re = re.compile(r'(.*)%$')
  1092. # How to discretize a circle.
  1093. self.steps_per_circ = steps_per_circle or Gerber.defaults['steps_per_circle']
  1094. self.use_buffer_for_union = self.defaults["use_buffer_for_union"]
  1095. def scale(self, factor):
  1096. """
  1097. Scales the objects' geometry on the XY plane by a given factor.
  1098. These are:
  1099. * ``buffered_paths``
  1100. * ``flash_geometry``
  1101. * ``solid_geometry``
  1102. * ``regions``
  1103. NOTE:
  1104. Does not modify the data used to create these elements. If these
  1105. are recreated, the scaling will be lost. This behavior was modified
  1106. because of the complexity reached in this class.
  1107. :param factor: Number by which to scale.
  1108. :type factor: float
  1109. :rtype : None
  1110. """
  1111. ## solid_geometry ???
  1112. # It's a cascaded union of objects.
  1113. self.solid_geometry = affinity.scale(self.solid_geometry, factor,
  1114. factor, origin=(0, 0))
  1115. # # Now buffered_paths, flash_geometry and solid_geometry
  1116. # self.create_geometry()
  1117. def offset(self, vect):
  1118. """
  1119. Offsets the objects' geometry on the XY plane by a given vector.
  1120. These are:
  1121. * ``buffered_paths``
  1122. * ``flash_geometry``
  1123. * ``solid_geometry``
  1124. * ``regions``
  1125. NOTE:
  1126. Does not modify the data used to create these elements. If these
  1127. are recreated, the scaling will be lost. This behavior was modified
  1128. because of the complexity reached in this class.
  1129. :param vect: (x, y) offset vector.
  1130. :type vect: tuple
  1131. :return: None
  1132. """
  1133. dx, dy = vect
  1134. ## Solid geometry
  1135. self.solid_geometry = affinity.translate(self.solid_geometry, xoff=dx, yoff=dy)
  1136. def mirror(self, axis, point):
  1137. """
  1138. Mirrors the object around a specified axis passign through
  1139. the given point. What is affected:
  1140. * ``buffered_paths``
  1141. * ``flash_geometry``
  1142. * ``solid_geometry``
  1143. * ``regions``
  1144. NOTE:
  1145. Does not modify the data used to create these elements. If these
  1146. are recreated, the scaling will be lost. This behavior was modified
  1147. because of the complexity reached in this class.
  1148. :param axis: "X" or "Y" indicates around which axis to mirror.
  1149. :type axis: str
  1150. :param point: [x, y] point belonging to the mirror axis.
  1151. :type point: list
  1152. :return: None
  1153. """
  1154. px, py = point
  1155. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  1156. ## solid_geometry ???
  1157. # It's a cascaded union of objects.
  1158. self.solid_geometry = affinity.scale(self.solid_geometry,
  1159. xscale, yscale, origin=(px, py))
  1160. def aperture_parse(self, apertureId, apertureType, apParameters):
  1161. """
  1162. Parse gerber aperture definition into dictionary of apertures.
  1163. The following kinds and their attributes are supported:
  1164. * *Circular (C)*: size (float)
  1165. * *Rectangle (R)*: width (float), height (float)
  1166. * *Obround (O)*: width (float), height (float).
  1167. * *Polygon (P)*: diameter(float), vertices(int), [rotation(float)]
  1168. * *Aperture Macro (AM)*: macro (ApertureMacro), modifiers (list)
  1169. :param apertureId: Id of the aperture being defined.
  1170. :param apertureType: Type of the aperture.
  1171. :param apParameters: Parameters of the aperture.
  1172. :type apertureId: str
  1173. :type apertureType: str
  1174. :type apParameters: str
  1175. :return: Identifier of the aperture.
  1176. :rtype: str
  1177. """
  1178. # Found some Gerber with a leading zero in the aperture id and the
  1179. # referenced it without the zero, so this is a hack to handle that.
  1180. apid = str(int(apertureId))
  1181. try: # Could be empty for aperture macros
  1182. paramList = apParameters.split('X')
  1183. except:
  1184. paramList = None
  1185. if apertureType == "C": # Circle, example: %ADD11C,0.1*%
  1186. self.apertures[apid] = {"type": "C",
  1187. "size": float(paramList[0])}
  1188. return apid
  1189. if apertureType == "R": # Rectangle, example: %ADD15R,0.05X0.12*%
  1190. self.apertures[apid] = {"type": "R",
  1191. "width": float(paramList[0]),
  1192. "height": float(paramList[1]),
  1193. "size": sqrt(float(paramList[0])**2 + float(paramList[1])**2)} # Hack
  1194. return apid
  1195. if apertureType == "O": # Obround
  1196. self.apertures[apid] = {"type": "O",
  1197. "width": float(paramList[0]),
  1198. "height": float(paramList[1]),
  1199. "size": sqrt(float(paramList[0])**2 + float(paramList[1])**2)} # Hack
  1200. return apid
  1201. if apertureType == "P": # Polygon (regular)
  1202. self.apertures[apid] = {"type": "P",
  1203. "diam": float(paramList[0]),
  1204. "nVertices": int(paramList[1]),
  1205. "size": float(paramList[0])} # Hack
  1206. if len(paramList) >= 3:
  1207. self.apertures[apid]["rotation"] = float(paramList[2])
  1208. return apid
  1209. if apertureType in self.aperture_macros:
  1210. self.apertures[apid] = {"type": "AM",
  1211. "macro": self.aperture_macros[apertureType],
  1212. "modifiers": paramList}
  1213. return apid
  1214. log.warning("Aperture not implemented: %s" % str(apertureType))
  1215. return None
  1216. def parse_file(self, filename, follow=False):
  1217. """
  1218. Calls Gerber.parse_lines() with generator of lines
  1219. read from the given file. Will split the lines if multiple
  1220. statements are found in a single original line.
  1221. The following line is split into two::
  1222. G54D11*G36*
  1223. First is ``G54D11*`` and seconds is ``G36*``.
  1224. :param filename: Gerber file to parse.
  1225. :type filename: str
  1226. :param follow: If true, will not create polygons, just lines
  1227. following the gerber path.
  1228. :type follow: bool
  1229. :return: None
  1230. """
  1231. with open(filename, 'r') as gfile:
  1232. def line_generator():
  1233. for line in gfile:
  1234. line = line.strip(' \r\n')
  1235. while len(line) > 0:
  1236. # If ends with '%' leave as is.
  1237. if line[-1] == '%':
  1238. yield line
  1239. break
  1240. # Split after '*' if any.
  1241. starpos = line.find('*')
  1242. if starpos > -1:
  1243. cleanline = line[:starpos + 1]
  1244. yield cleanline
  1245. line = line[starpos + 1:]
  1246. # Otherwise leave as is.
  1247. else:
  1248. yield cleanline
  1249. break
  1250. self.parse_lines(line_generator(), follow=follow)
  1251. #@profile
  1252. def parse_lines(self, glines, follow=False):
  1253. """
  1254. Main Gerber parser. Reads Gerber and populates ``self.paths``, ``self.apertures``,
  1255. ``self.flashes``, ``self.regions`` and ``self.units``.
  1256. :param glines: Gerber code as list of strings, each element being
  1257. one line of the source file.
  1258. :type glines: list
  1259. :param follow: If true, will not create polygons, just lines
  1260. following the gerber path.
  1261. :type follow: bool
  1262. :return: None
  1263. :rtype: None
  1264. """
  1265. # Coordinates of the current path, each is [x, y]
  1266. path = []
  1267. # Polygons are stored here until there is a change in polarity.
  1268. # Only then they are combined via cascaded_union and added or
  1269. # subtracted from solid_geometry. This is ~100 times faster than
  1270. # applyng a union for every new polygon.
  1271. poly_buffer = []
  1272. last_path_aperture = None
  1273. current_aperture = None
  1274. # 1,2 or 3 from "G01", "G02" or "G03"
  1275. current_interpolation_mode = None
  1276. # 1 or 2 from "D01" or "D02"
  1277. # Note this is to support deprecated Gerber not putting
  1278. # an operation code at the end of every coordinate line.
  1279. current_operation_code = None
  1280. # Current coordinates
  1281. current_x = None
  1282. current_y = None
  1283. # Absolute or Relative/Incremental coordinates
  1284. # Not implemented
  1285. absolute = True
  1286. # How to interpret circular interpolation: SINGLE or MULTI
  1287. quadrant_mode = None
  1288. # Indicates we are parsing an aperture macro
  1289. current_macro = None
  1290. # Indicates the current polarity: D-Dark, C-Clear
  1291. current_polarity = 'D'
  1292. # If a region is being defined
  1293. making_region = False
  1294. #### Parsing starts here ####
  1295. line_num = 0
  1296. gline = ""
  1297. try:
  1298. for gline in glines:
  1299. line_num += 1
  1300. ### Cleanup
  1301. gline = gline.strip(' \r\n')
  1302. #log.debug("%3s %s" % (line_num, gline))
  1303. ### Aperture Macros
  1304. # Having this at the beggining will slow things down
  1305. # but macros can have complicated statements than could
  1306. # be caught by other patterns.
  1307. if current_macro is None: # No macro started yet
  1308. match = self.am1_re.search(gline)
  1309. # Start macro if match, else not an AM, carry on.
  1310. if match:
  1311. log.info("Starting macro. Line %d: %s" % (line_num, gline))
  1312. current_macro = match.group(1)
  1313. self.aperture_macros[current_macro] = ApertureMacro(name=current_macro)
  1314. if match.group(2): # Append
  1315. self.aperture_macros[current_macro].append(match.group(2))
  1316. if match.group(3): # Finish macro
  1317. #self.aperture_macros[current_macro].parse_content()
  1318. current_macro = None
  1319. log.info("Macro complete in 1 line.")
  1320. continue
  1321. else: # Continue macro
  1322. log.info("Continuing macro. Line %d." % line_num)
  1323. match = self.am2_re.search(gline)
  1324. if match: # Finish macro
  1325. log.info("End of macro. Line %d." % line_num)
  1326. self.aperture_macros[current_macro].append(match.group(1))
  1327. #self.aperture_macros[current_macro].parse_content()
  1328. current_macro = None
  1329. else: # Append
  1330. self.aperture_macros[current_macro].append(gline)
  1331. continue
  1332. ### G01 - Linear interpolation plus flashes
  1333. # Operation code (D0x) missing is deprecated... oh well I will support it.
  1334. # REGEX: r'^(?:G0?(1))?(?:X(-?\d+))?(?:Y(-?\d+))?(?:D0([123]))?\*$'
  1335. match = self.lin_re.search(gline)
  1336. if match:
  1337. # Dxx alone?
  1338. # if match.group(1) is None and match.group(2) is None and match.group(3) is None:
  1339. # try:
  1340. # current_operation_code = int(match.group(4))
  1341. # except:
  1342. # pass # A line with just * will match too.
  1343. # continue
  1344. # NOTE: Letting it continue allows it to react to the
  1345. # operation code.
  1346. # Parse coordinates
  1347. if match.group(2) is not None:
  1348. current_x = parse_gerber_number(match.group(2), self.frac_digits)
  1349. if match.group(3) is not None:
  1350. current_y = parse_gerber_number(match.group(3), self.frac_digits)
  1351. # Parse operation code
  1352. if match.group(4) is not None:
  1353. current_operation_code = int(match.group(4))
  1354. # Pen down: add segment
  1355. if current_operation_code == 1:
  1356. path.append([current_x, current_y])
  1357. last_path_aperture = current_aperture
  1358. elif current_operation_code == 2:
  1359. if len(path) > 1:
  1360. ## --- BUFFERED ---
  1361. if making_region:
  1362. geo = Polygon(path)
  1363. else:
  1364. if last_path_aperture is None:
  1365. log.warning("No aperture defined for curent path. (%d)" % line_num)
  1366. width = self.apertures[last_path_aperture]["size"] # TODO: WARNING this should fail!
  1367. #log.debug("Line %d: Setting aperture to %s before buffering." % (line_num, last_path_aperture))
  1368. if follow:
  1369. geo = LineString(path)
  1370. else:
  1371. geo = LineString(path).buffer(width / 2)
  1372. if not geo.is_empty: poly_buffer.append(geo)
  1373. path = [[current_x, current_y]] # Start new path
  1374. # Flash
  1375. # Not allowed in region mode.
  1376. elif current_operation_code == 3:
  1377. # Create path draw so far.
  1378. if len(path) > 1:
  1379. # --- Buffered ----
  1380. width = self.apertures[last_path_aperture]["size"]
  1381. geo = LineString(path).buffer(width / 2)
  1382. if not geo.is_empty: poly_buffer.append(geo)
  1383. # Reset path starting point
  1384. path = [[current_x, current_y]]
  1385. # --- BUFFERED ---
  1386. # Draw the flash
  1387. flash = Gerber.create_flash_geometry(Point([current_x, current_y]),
  1388. self.apertures[current_aperture])
  1389. if not flash.is_empty: poly_buffer.append(flash)
  1390. continue
  1391. ### G02/3 - Circular interpolation
  1392. # 2-clockwise, 3-counterclockwise
  1393. match = self.circ_re.search(gline)
  1394. if match:
  1395. arcdir = [None, None, "cw", "ccw"]
  1396. mode, x, y, i, j, d = match.groups()
  1397. try:
  1398. x = parse_gerber_number(x, self.frac_digits)
  1399. except:
  1400. x = current_x
  1401. try:
  1402. y = parse_gerber_number(y, self.frac_digits)
  1403. except:
  1404. y = current_y
  1405. try:
  1406. i = parse_gerber_number(i, self.frac_digits)
  1407. except:
  1408. i = 0
  1409. try:
  1410. j = parse_gerber_number(j, self.frac_digits)
  1411. except:
  1412. j = 0
  1413. if quadrant_mode is None:
  1414. log.error("Found arc without preceding quadrant specification G74 or G75. (%d)" % line_num)
  1415. log.error(gline)
  1416. continue
  1417. if mode is None and current_interpolation_mode not in [2, 3]:
  1418. log.error("Found arc without circular interpolation mode defined. (%d)" % line_num)
  1419. log.error(gline)
  1420. continue
  1421. elif mode is not None:
  1422. current_interpolation_mode = int(mode)
  1423. # Set operation code if provided
  1424. if d is not None:
  1425. current_operation_code = int(d)
  1426. # Nothing created! Pen Up.
  1427. if current_operation_code == 2:
  1428. log.warning("Arc with D2. (%d)" % line_num)
  1429. if len(path) > 1:
  1430. if last_path_aperture is None:
  1431. log.warning("No aperture defined for curent path. (%d)" % line_num)
  1432. # --- BUFFERED ---
  1433. width = self.apertures[last_path_aperture]["size"]
  1434. buffered = LineString(path).buffer(width / 2)
  1435. if not buffered.is_empty: poly_buffer.append(buffered)
  1436. current_x = x
  1437. current_y = y
  1438. path = [[current_x, current_y]] # Start new path
  1439. continue
  1440. # Flash should not happen here
  1441. if current_operation_code == 3:
  1442. log.error("Trying to flash within arc. (%d)" % line_num)
  1443. continue
  1444. if quadrant_mode == 'MULTI':
  1445. center = [i + current_x, j + current_y]
  1446. radius = sqrt(i ** 2 + j ** 2)
  1447. start = arctan2(-j, -i) # Start angle
  1448. # Numerical errors might prevent start == stop therefore
  1449. # we check ahead of time. This should result in a
  1450. # 360 degree arc.
  1451. if current_x == x and current_y == y:
  1452. stop = start
  1453. else:
  1454. stop = arctan2(-center[1] + y, -center[0] + x) # Stop angle
  1455. this_arc = arc(center, radius, start, stop,
  1456. arcdir[current_interpolation_mode],
  1457. self.steps_per_circ)
  1458. # The last point in the computed arc can have
  1459. # numerical errors. The exact final point is the
  1460. # specified (x, y). Replace.
  1461. this_arc[-1] = (x, y)
  1462. # Last point in path is current point
  1463. # current_x = this_arc[-1][0]
  1464. # current_y = this_arc[-1][1]
  1465. current_x, current_y = x, y
  1466. # Append
  1467. path += this_arc
  1468. last_path_aperture = current_aperture
  1469. continue
  1470. if quadrant_mode == 'SINGLE':
  1471. center_candidates = [
  1472. [i + current_x, j + current_y],
  1473. [-i + current_x, j + current_y],
  1474. [i + current_x, -j + current_y],
  1475. [-i + current_x, -j + current_y]
  1476. ]
  1477. valid = False
  1478. log.debug("I: %f J: %f" % (i, j))
  1479. for center in center_candidates:
  1480. radius = sqrt(i ** 2 + j ** 2)
  1481. # Make sure radius to start is the same as radius to end.
  1482. radius2 = sqrt((center[0] - x) ** 2 + (center[1] - y) ** 2)
  1483. if radius2 < radius * 0.95 or radius2 > radius * 1.05:
  1484. continue # Not a valid center.
  1485. # Correct i and j and continue as with multi-quadrant.
  1486. i = center[0] - current_x
  1487. j = center[1] - current_y
  1488. start = arctan2(-j, -i) # Start angle
  1489. stop = arctan2(-center[1] + y, -center[0] + x) # Stop angle
  1490. angle = abs(arc_angle(start, stop, arcdir[current_interpolation_mode]))
  1491. log.debug("ARC START: %f, %f CENTER: %f, %f STOP: %f, %f" %
  1492. (current_x, current_y, center[0], center[1], x, y))
  1493. log.debug("START Ang: %f, STOP Ang: %f, DIR: %s, ABS: %.12f <= %.12f: %s" %
  1494. (start * 180 / pi, stop * 180 / pi, arcdir[current_interpolation_mode],
  1495. angle * 180 / pi, pi / 2 * 180 / pi, angle <= (pi + 1e-6) / 2))
  1496. if angle <= (pi + 1e-6) / 2:
  1497. log.debug("########## ACCEPTING ARC ############")
  1498. this_arc = arc(center, radius, start, stop,
  1499. arcdir[current_interpolation_mode],
  1500. self.steps_per_circ)
  1501. # Replace with exact values
  1502. this_arc[-1] = (x, y)
  1503. # current_x = this_arc[-1][0]
  1504. # current_y = this_arc[-1][1]
  1505. current_x, current_y = x, y
  1506. path += this_arc
  1507. last_path_aperture = current_aperture
  1508. valid = True
  1509. break
  1510. if valid:
  1511. continue
  1512. else:
  1513. log.warning("Invalid arc in line %d." % line_num)
  1514. ### Operation code alone
  1515. # Operation code alone, usually just D03 (Flash)
  1516. # self.opcode_re = re.compile(r'^D0?([123])\*$')
  1517. match = self.opcode_re.search(gline)
  1518. if match:
  1519. current_operation_code = int(match.group(1))
  1520. if current_operation_code == 3:
  1521. ## --- Buffered ---
  1522. try:
  1523. log.debug("Bare op-code %d." % current_operation_code)
  1524. # flash = Gerber.create_flash_geometry(Point(path[-1]),
  1525. # self.apertures[current_aperture])
  1526. flash = Gerber.create_flash_geometry(Point(current_x, current_y),
  1527. self.apertures[current_aperture])
  1528. if not flash.is_empty: poly_buffer.append(flash)
  1529. except IndexError:
  1530. log.warning("Line %d: %s -> Nothing there to flash!" % (line_num, gline))
  1531. continue
  1532. ### G74/75* - Single or multiple quadrant arcs
  1533. match = self.quad_re.search(gline)
  1534. if match:
  1535. if match.group(1) == '4':
  1536. quadrant_mode = 'SINGLE'
  1537. else:
  1538. quadrant_mode = 'MULTI'
  1539. continue
  1540. ### G36* - Begin region
  1541. if self.regionon_re.search(gline):
  1542. if len(path) > 1:
  1543. # Take care of what is left in the path
  1544. ## --- Buffered ---
  1545. width = self.apertures[last_path_aperture]["size"]
  1546. geo = LineString(path).buffer(width/2)
  1547. if not geo.is_empty: poly_buffer.append(geo)
  1548. path = [path[-1]]
  1549. making_region = True
  1550. continue
  1551. ### G37* - End region
  1552. if self.regionoff_re.search(gline):
  1553. making_region = False
  1554. # Only one path defines region?
  1555. # This can happen if D02 happened before G37 and
  1556. # is not and error.
  1557. if len(path) < 3:
  1558. # print "ERROR: Path contains less than 3 points:"
  1559. # print path
  1560. # print "Line (%d): " % line_num, gline
  1561. # path = []
  1562. #path = [[current_x, current_y]]
  1563. continue
  1564. # For regions we may ignore an aperture that is None
  1565. # self.regions.append({"polygon": Polygon(path),
  1566. # "aperture": last_path_aperture})
  1567. # --- Buffered ---
  1568. region = Polygon(path)
  1569. if not region.is_valid:
  1570. region = region.buffer(0)
  1571. if not region.is_empty: poly_buffer.append(region)
  1572. path = [[current_x, current_y]] # Start new path
  1573. continue
  1574. ### Aperture definitions %ADD...
  1575. match = self.ad_re.search(gline)
  1576. if match:
  1577. log.info("Found aperture definition. Line %d: %s" % (line_num, gline))
  1578. self.aperture_parse(match.group(1), match.group(2), match.group(3))
  1579. continue
  1580. ### G01/2/3* - Interpolation mode change
  1581. # Can occur along with coordinates and operation code but
  1582. # sometimes by itself (handled here).
  1583. # Example: G01*
  1584. match = self.interp_re.search(gline)
  1585. if match:
  1586. current_interpolation_mode = int(match.group(1))
  1587. continue
  1588. ### Tool/aperture change
  1589. # Example: D12*
  1590. match = self.tool_re.search(gline)
  1591. if match:
  1592. current_aperture = match.group(1)
  1593. log.debug("Line %d: Aperture change to (%s)" % (line_num, match.group(1)))
  1594. log.debug(self.apertures[current_aperture])
  1595. # Take care of the current path with the previous tool
  1596. if len(path) > 1:
  1597. # --- Buffered ----
  1598. width = self.apertures[last_path_aperture]["size"]
  1599. geo = LineString(path).buffer(width / 2)
  1600. if not geo.is_empty: poly_buffer.append(geo)
  1601. path = [path[-1]]
  1602. continue
  1603. ### Polarity change
  1604. # Example: %LPD*% or %LPC*%
  1605. # If polarity changes, creates geometry from current
  1606. # buffer, then adds or subtracts accordingly.
  1607. match = self.lpol_re.search(gline)
  1608. if match:
  1609. if len(path) > 1 and current_polarity != match.group(1):
  1610. # --- Buffered ----
  1611. width = self.apertures[last_path_aperture]["size"]
  1612. geo = LineString(path).buffer(width / 2)
  1613. if not geo.is_empty: poly_buffer.append(geo)
  1614. path = [path[-1]]
  1615. # --- Apply buffer ---
  1616. # If added for testing of bug #83
  1617. # TODO: Remove when bug fixed
  1618. if len(poly_buffer) > 0:
  1619. if current_polarity == 'D':
  1620. self.solid_geometry = self.solid_geometry.union(cascaded_union(poly_buffer))
  1621. else:
  1622. self.solid_geometry = self.solid_geometry.difference(cascaded_union(poly_buffer))
  1623. poly_buffer = []
  1624. current_polarity = match.group(1)
  1625. continue
  1626. ### Number format
  1627. # Example: %FSLAX24Y24*%
  1628. # TODO: This is ignoring most of the format. Implement the rest.
  1629. match = self.fmt_re.search(gline)
  1630. if match:
  1631. absolute = {'A': True, 'I': False}
  1632. self.int_digits = int(match.group(3))
  1633. self.frac_digits = int(match.group(4))
  1634. continue
  1635. ### Mode (IN/MM)
  1636. # Example: %MOIN*%
  1637. match = self.mode_re.search(gline)
  1638. if match:
  1639. #self.units = match.group(1)
  1640. # Changed for issue #80
  1641. self.convert_units(match.group(1))
  1642. continue
  1643. ### Units (G70/1) OBSOLETE
  1644. match = self.units_re.search(gline)
  1645. if match:
  1646. #self.units = {'0': 'IN', '1': 'MM'}[match.group(1)]
  1647. # Changed for issue #80
  1648. self.convert_units({'0': 'IN', '1': 'MM'}[match.group(1)])
  1649. continue
  1650. ### Absolute/relative coordinates G90/1 OBSOLETE
  1651. match = self.absrel_re.search(gline)
  1652. if match:
  1653. absolute = {'0': True, '1': False}[match.group(1)]
  1654. continue
  1655. #### Ignored lines
  1656. ## Comments
  1657. match = self.comm_re.search(gline)
  1658. if match:
  1659. continue
  1660. ## EOF
  1661. match = self.eof_re.search(gline)
  1662. if match:
  1663. continue
  1664. ### Line did not match any pattern. Warn user.
  1665. log.warning("Line ignored (%d): %s" % (line_num, gline))
  1666. if len(path) > 1:
  1667. # EOF, create shapely LineString if something still in path
  1668. ## --- Buffered ---
  1669. width = self.apertures[last_path_aperture]["size"]
  1670. geo = LineString(path).buffer(width / 2)
  1671. if not geo.is_empty: poly_buffer.append(geo)
  1672. # --- Apply buffer ---
  1673. log.warn("Joining %d polygons." % len(poly_buffer))
  1674. if self.use_buffer_for_union:
  1675. log.debug("Union by buffer...")
  1676. new_poly = MultiPolygon(poly_buffer)
  1677. new_poly = new_poly.buffer(0.00000001)
  1678. new_poly = new_poly.buffer(-0.00000001)
  1679. log.warn("Union(buffer) done.")
  1680. else:
  1681. log.debug("Union by union()...")
  1682. new_poly = cascaded_union(poly_buffer)
  1683. new_poly = new_poly.buffer(0)
  1684. log.warn("Union done.")
  1685. if current_polarity == 'D':
  1686. self.solid_geometry = self.solid_geometry.union(new_poly)
  1687. else:
  1688. self.solid_geometry = self.solid_geometry.difference(new_poly)
  1689. except Exception, err:
  1690. ex_type, ex, tb = sys.exc_info()
  1691. traceback.print_tb(tb)
  1692. #print traceback.format_exc()
  1693. log.error("PARSING FAILED. Line %d: %s" % (line_num, gline))
  1694. raise ParseError("Line %d: %s" % (line_num, gline), repr(err))
  1695. @staticmethod
  1696. def create_flash_geometry(location, aperture):
  1697. log.debug('Flashing @%s, Aperture: %s' % (location, aperture))
  1698. if type(location) == list:
  1699. location = Point(location)
  1700. if aperture['type'] == 'C': # Circles
  1701. return location.buffer(aperture['size'] / 2)
  1702. if aperture['type'] == 'R': # Rectangles
  1703. loc = location.coords[0]
  1704. width = aperture['width']
  1705. height = aperture['height']
  1706. minx = loc[0] - width / 2
  1707. maxx = loc[0] + width / 2
  1708. miny = loc[1] - height / 2
  1709. maxy = loc[1] + height / 2
  1710. return shply_box(minx, miny, maxx, maxy)
  1711. if aperture['type'] == 'O': # Obround
  1712. loc = location.coords[0]
  1713. width = aperture['width']
  1714. height = aperture['height']
  1715. if width > height:
  1716. p1 = Point(loc[0] + 0.5 * (width - height), loc[1])
  1717. p2 = Point(loc[0] - 0.5 * (width - height), loc[1])
  1718. c1 = p1.buffer(height * 0.5)
  1719. c2 = p2.buffer(height * 0.5)
  1720. else:
  1721. p1 = Point(loc[0], loc[1] + 0.5 * (height - width))
  1722. p2 = Point(loc[0], loc[1] - 0.5 * (height - width))
  1723. c1 = p1.buffer(width * 0.5)
  1724. c2 = p2.buffer(width * 0.5)
  1725. return cascaded_union([c1, c2]).convex_hull
  1726. if aperture['type'] == 'P': # Regular polygon
  1727. loc = location.coords[0]
  1728. diam = aperture['diam']
  1729. n_vertices = aperture['nVertices']
  1730. points = []
  1731. for i in range(0, n_vertices):
  1732. x = loc[0] + 0.5 * diam * (cos(2 * pi * i / n_vertices))
  1733. y = loc[1] + 0.5 * diam * (sin(2 * pi * i / n_vertices))
  1734. points.append((x, y))
  1735. ply = Polygon(points)
  1736. if 'rotation' in aperture:
  1737. ply = affinity.rotate(ply, aperture['rotation'])
  1738. return ply
  1739. if aperture['type'] == 'AM': # Aperture Macro
  1740. loc = location.coords[0]
  1741. flash_geo = aperture['macro'].make_geometry(aperture['modifiers'])
  1742. return affinity.translate(flash_geo, xoff=loc[0], yoff=loc[1])
  1743. return None
  1744. def create_geometry(self):
  1745. """
  1746. Geometry from a Gerber file is made up entirely of polygons.
  1747. Every stroke (linear or circular) has an aperture which gives
  1748. it thickness. Additionally, aperture strokes have non-zero area,
  1749. and regions naturally do as well.
  1750. :rtype : None
  1751. :return: None
  1752. """
  1753. # self.buffer_paths()
  1754. #
  1755. # self.fix_regions()
  1756. #
  1757. # self.do_flashes()
  1758. #
  1759. # self.solid_geometry = cascaded_union(self.buffered_paths +
  1760. # [poly['polygon'] for poly in self.regions] +
  1761. # self.flash_geometry)
  1762. def get_bounding_box(self, margin=0.0, rounded=False):
  1763. """
  1764. Creates and returns a rectangular polygon bounding at a distance of
  1765. margin from the object's ``solid_geometry``. If margin > 0, the polygon
  1766. can optionally have rounded corners of radius equal to margin.
  1767. :param margin: Distance to enlarge the rectangular bounding
  1768. box in both positive and negative, x and y axes.
  1769. :type margin: float
  1770. :param rounded: Wether or not to have rounded corners.
  1771. :type rounded: bool
  1772. :return: The bounding box.
  1773. :rtype: Shapely.Polygon
  1774. """
  1775. bbox = self.solid_geometry.envelope.buffer(margin)
  1776. if not rounded:
  1777. bbox = bbox.envelope
  1778. return bbox
  1779. class Excellon(Geometry):
  1780. """
  1781. *ATTRIBUTES*
  1782. * ``tools`` (dict): The key is the tool name and the value is
  1783. a dictionary specifying the tool:
  1784. ================ ====================================
  1785. Key Value
  1786. ================ ====================================
  1787. C Diameter of the tool
  1788. Others Not supported (Ignored).
  1789. ================ ====================================
  1790. * ``drills`` (list): Each is a dictionary:
  1791. ================ ====================================
  1792. Key Value
  1793. ================ ====================================
  1794. point (Shapely.Point) Where to drill
  1795. tool (str) A key in ``tools``
  1796. ================ ====================================
  1797. """
  1798. defaults = {
  1799. "zeros": "L"
  1800. }
  1801. def __init__(self, zeros=None):
  1802. """
  1803. The constructor takes no parameters.
  1804. :return: Excellon object.
  1805. :rtype: Excellon
  1806. """
  1807. Geometry.__init__(self)
  1808. self.tools = {}
  1809. self.drills = []
  1810. ## IN|MM -> Units are inherited from Geometry
  1811. #self.units = units
  1812. # Trailing "T" or leading "L" (default)
  1813. #self.zeros = "T"
  1814. self.zeros = zeros or self.defaults["zeros"]
  1815. # Attributes to be included in serialization
  1816. # Always append to it because it carries contents
  1817. # from Geometry.
  1818. self.ser_attrs += ['tools', 'drills', 'zeros']
  1819. #### Patterns ####
  1820. # Regex basics:
  1821. # ^ - beginning
  1822. # $ - end
  1823. # *: 0 or more, +: 1 or more, ?: 0 or 1
  1824. # M48 - Beggining of Part Program Header
  1825. self.hbegin_re = re.compile(r'^M48$')
  1826. # M95 or % - End of Part Program Header
  1827. # NOTE: % has different meaning in the body
  1828. self.hend_re = re.compile(r'^(?:M95|%)$')
  1829. # FMAT Excellon format
  1830. # Ignored in the parser
  1831. #self.fmat_re = re.compile(r'^FMAT,([12])$')
  1832. # Number format and units
  1833. # INCH uses 6 digits
  1834. # METRIC uses 5/6
  1835. self.units_re = re.compile(r'^(INCH|METRIC)(?:,([TL])Z)?$')
  1836. # Tool definition/parameters (?= is look-ahead
  1837. # NOTE: This might be an overkill!
  1838. # self.toolset_re = re.compile(r'^T(0?\d|\d\d)(?=.*C(\d*\.?\d*))?' +
  1839. # r'(?=.*F(\d*\.?\d*))?(?=.*S(\d*\.?\d*))?' +
  1840. # r'(?=.*B(\d*\.?\d*))?(?=.*H(\d*\.?\d*))?' +
  1841. # r'(?=.*Z([-\+]?\d*\.?\d*))?[CFSBHT]')
  1842. self.toolset_re = re.compile(r'^T(\d+)(?=.*C(\d*\.?\d*))?' +
  1843. r'(?=.*F(\d*\.?\d*))?(?=.*S(\d*\.?\d*))?' +
  1844. r'(?=.*B(\d*\.?\d*))?(?=.*H(\d*\.?\d*))?' +
  1845. r'(?=.*Z([-\+]?\d*\.?\d*))?[CFSBHT]')
  1846. # Tool select
  1847. # Can have additional data after tool number but
  1848. # is ignored if present in the header.
  1849. # Warning: This will match toolset_re too.
  1850. # self.toolsel_re = re.compile(r'^T((?:\d\d)|(?:\d))')
  1851. self.toolsel_re = re.compile(r'^T(\d+)')
  1852. # Comment
  1853. self.comm_re = re.compile(r'^;(.*)$')
  1854. # Absolute/Incremental G90/G91
  1855. self.absinc_re = re.compile(r'^G9([01])$')
  1856. # Modes of operation
  1857. # 1-linear, 2-circCW, 3-cirCCW, 4-vardwell, 5-Drill
  1858. self.modes_re = re.compile(r'^G0([012345])')
  1859. # Measuring mode
  1860. # 1-metric, 2-inch
  1861. self.meas_re = re.compile(r'^M7([12])$')
  1862. # Coordinates
  1863. #self.xcoord_re = re.compile(r'^X(\d*\.?\d*)(?:Y\d*\.?\d*)?$')
  1864. #self.ycoord_re = re.compile(r'^(?:X\d*\.?\d*)?Y(\d*\.?\d*)$')
  1865. self.coordsperiod_re = re.compile(r'(?=.*X([-\+]?\d*\.\d*))?(?=.*Y([-\+]?\d*\.\d*))?[XY]')
  1866. self.coordsnoperiod_re = re.compile(r'(?!.*\.)(?=.*X([-\+]?\d*))?(?=.*Y([-\+]?\d*))?[XY]')
  1867. # R - Repeat hole (# times, X offset, Y offset)
  1868. self.rep_re = re.compile(r'^R(\d+)(?=.*[XY])+(?:X([-\+]?\d*\.?\d*))?(?:Y([-\+]?\d*\.?\d*))?$')
  1869. # Various stop/pause commands
  1870. self.stop_re = re.compile(r'^((G04)|(M09)|(M06)|(M00)|(M30))')
  1871. # Parse coordinates
  1872. self.leadingzeros_re = re.compile(r'^[-\+]?(0*)(\d*)')
  1873. def parse_file(self, filename):
  1874. """
  1875. Reads the specified file as array of lines as
  1876. passes it to ``parse_lines()``.
  1877. :param filename: The file to be read and parsed.
  1878. :type filename: str
  1879. :return: None
  1880. """
  1881. efile = open(filename, 'r')
  1882. estr = efile.readlines()
  1883. efile.close()
  1884. self.parse_lines(estr)
  1885. def parse_lines(self, elines):
  1886. """
  1887. Main Excellon parser.
  1888. :param elines: List of strings, each being a line of Excellon code.
  1889. :type elines: list
  1890. :return: None
  1891. """
  1892. # State variables
  1893. current_tool = ""
  1894. in_header = False
  1895. current_x = None
  1896. current_y = None
  1897. #### Parsing starts here ####
  1898. line_num = 0 # Line number
  1899. eline = ""
  1900. try:
  1901. for eline in elines:
  1902. line_num += 1
  1903. #log.debug("%3d %s" % (line_num, str(eline)))
  1904. ### Cleanup lines
  1905. eline = eline.strip(' \r\n')
  1906. ## Header Begin (M48) ##
  1907. if self.hbegin_re.search(eline):
  1908. in_header = True
  1909. continue
  1910. ## Header End ##
  1911. if self.hend_re.search(eline):
  1912. in_header = False
  1913. continue
  1914. ## Alternative units format M71/M72
  1915. # Supposed to be just in the body (yes, the body)
  1916. # but some put it in the header (PADS for example).
  1917. # Will detect anywhere. Occurrence will change the
  1918. # object's units.
  1919. match = self.meas_re.match(eline)
  1920. if match:
  1921. #self.units = {"1": "MM", "2": "IN"}[match.group(1)]
  1922. # Modified for issue #80
  1923. self.convert_units({"1": "MM", "2": "IN"}[match.group(1)])
  1924. log.debug(" Units: %s" % self.units)
  1925. continue
  1926. #### Body ####
  1927. if not in_header:
  1928. ## Tool change ##
  1929. match = self.toolsel_re.search(eline)
  1930. if match:
  1931. current_tool = str(int(match.group(1)))
  1932. log.debug("Tool change: %s" % current_tool)
  1933. continue
  1934. ## Coordinates without period ##
  1935. match = self.coordsnoperiod_re.search(eline)
  1936. if match:
  1937. try:
  1938. #x = float(match.group(1))/10000
  1939. x = self.parse_number(match.group(1))
  1940. current_x = x
  1941. except TypeError:
  1942. x = current_x
  1943. try:
  1944. #y = float(match.group(2))/10000
  1945. y = self.parse_number(match.group(2))
  1946. current_y = y
  1947. except TypeError:
  1948. y = current_y
  1949. if x is None or y is None:
  1950. log.error("Missing coordinates")
  1951. continue
  1952. self.drills.append({'point': Point((x, y)), 'tool': current_tool})
  1953. log.debug("{:15} {:8} {:8}".format(eline, x, y))
  1954. continue
  1955. ## Coordinates with period: Use literally. ##
  1956. match = self.coordsperiod_re.search(eline)
  1957. if match:
  1958. try:
  1959. x = float(match.group(1))
  1960. current_x = x
  1961. except TypeError:
  1962. x = current_x
  1963. try:
  1964. y = float(match.group(2))
  1965. current_y = y
  1966. except TypeError:
  1967. y = current_y
  1968. if x is None or y is None:
  1969. log.error("Missing coordinates")
  1970. continue
  1971. self.drills.append({'point': Point((x, y)), 'tool': current_tool})
  1972. log.debug("{:15} {:8} {:8}".format(eline, x, y))
  1973. continue
  1974. #### Header ####
  1975. if in_header:
  1976. ## Tool definitions ##
  1977. match = self.toolset_re.search(eline)
  1978. if match:
  1979. name = str(int(match.group(1)))
  1980. spec = {
  1981. "C": float(match.group(2)),
  1982. # "F": float(match.group(3)),
  1983. # "S": float(match.group(4)),
  1984. # "B": float(match.group(5)),
  1985. # "H": float(match.group(6)),
  1986. # "Z": float(match.group(7))
  1987. }
  1988. self.tools[name] = spec
  1989. log.debug(" Tool definition: %s %s" % (name, spec))
  1990. continue
  1991. ## Units and number format ##
  1992. match = self.units_re.match(eline)
  1993. if match:
  1994. self.zeros = match.group(2) or self.zeros # "T" or "L". Might be empty
  1995. #self.units = {"INCH": "IN", "METRIC": "MM"}[match.group(1)]
  1996. # Modified for issue #80
  1997. self.convert_units({"INCH": "IN", "METRIC": "MM"}[match.group(1)])
  1998. log.debug(" Units/Format: %s %s" % (self.units, self.zeros))
  1999. continue
  2000. log.warning("Line ignored: %s" % eline)
  2001. log.info("Zeros: %s, Units %s." % (self.zeros, self.units))
  2002. except Exception as e:
  2003. log.error("PARSING FAILED. Line %d: %s" % (line_num, eline))
  2004. raise
  2005. def parse_number(self, number_str):
  2006. """
  2007. Parses coordinate numbers without period.
  2008. :param number_str: String representing the numerical value.
  2009. :type number_str: str
  2010. :return: Floating point representation of the number
  2011. :rtype: foat
  2012. """
  2013. if self.zeros == "L":
  2014. # With leading zeros, when you type in a coordinate,
  2015. # the leading zeros must always be included. Trailing zeros
  2016. # are unneeded and may be left off. The CNC-7 will automatically add them.
  2017. # r'^[-\+]?(0*)(\d*)'
  2018. # 6 digits are divided by 10^4
  2019. # If less than size digits, they are automatically added,
  2020. # 5 digits then are divided by 10^3 and so on.
  2021. match = self.leadingzeros_re.search(number_str)
  2022. if self.units.lower() == "in":
  2023. return float(number_str) / \
  2024. (10 ** (len(match.group(1)) + len(match.group(2)) - 2))
  2025. else:
  2026. return float(number_str) / \
  2027. (10 ** (len(match.group(1)) + len(match.group(2)) - 3))
  2028. else: # Trailing
  2029. # You must show all zeros to the right of the number and can omit
  2030. # all zeros to the left of the number. The CNC-7 will count the number
  2031. # of digits you typed and automatically fill in the missing zeros.
  2032. if self.units.lower() == "in": # Inches is 00.0000
  2033. return float(number_str) / 10000
  2034. else:
  2035. return float(number_str) / 1000 # Metric is 000.000
  2036. def create_geometry(self):
  2037. """
  2038. Creates circles of the tool diameter at every point
  2039. specified in ``self.drills``.
  2040. :return: None
  2041. """
  2042. self.solid_geometry = []
  2043. for drill in self.drills:
  2044. # poly = drill['point'].buffer(self.tools[drill['tool']]["C"]/2.0)
  2045. tooldia = self.tools[drill['tool']]['C']
  2046. poly = drill['point'].buffer(tooldia / 2.0)
  2047. self.solid_geometry.append(poly)
  2048. def scale(self, factor):
  2049. """
  2050. Scales geometry on the XY plane in the object by a given factor.
  2051. Tool sizes, feedrates an Z-plane dimensions are untouched.
  2052. :param factor: Number by which to scale the object.
  2053. :type factor: float
  2054. :return: None
  2055. :rtype: NOne
  2056. """
  2057. # Drills
  2058. for drill in self.drills:
  2059. drill['point'] = affinity.scale(drill['point'], factor, factor, origin=(0, 0))
  2060. self.create_geometry()
  2061. def offset(self, vect):
  2062. """
  2063. Offsets geometry on the XY plane in the object by a given vector.
  2064. :param vect: (x, y) offset vector.
  2065. :type vect: tuple
  2066. :return: None
  2067. """
  2068. dx, dy = vect
  2069. # Drills
  2070. for drill in self.drills:
  2071. drill['point'] = affinity.translate(drill['point'], xoff=dx, yoff=dy)
  2072. # Recreate geometry
  2073. self.create_geometry()
  2074. def mirror(self, axis, point):
  2075. """
  2076. :param axis: "X" or "Y" indicates around which axis to mirror.
  2077. :type axis: str
  2078. :param point: [x, y] point belonging to the mirror axis.
  2079. :type point: list
  2080. :return: None
  2081. """
  2082. px, py = point
  2083. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  2084. # Modify data
  2085. for drill in self.drills:
  2086. drill['point'] = affinity.scale(drill['point'], xscale, yscale, origin=(px, py))
  2087. # Recreate geometry
  2088. self.create_geometry()
  2089. def convert_units(self, units):
  2090. factor = Geometry.convert_units(self, units)
  2091. # Tools
  2092. for tname in self.tools:
  2093. self.tools[tname]["C"] *= factor
  2094. self.create_geometry()
  2095. return factor
  2096. class CNCjob(Geometry):
  2097. """
  2098. Represents work to be done by a CNC machine.
  2099. *ATTRIBUTES*
  2100. * ``gcode_parsed`` (list): Each is a dictionary:
  2101. ===================== =========================================
  2102. Key Value
  2103. ===================== =========================================
  2104. geom (Shapely.LineString) Tool path (XY plane)
  2105. kind (string) "AB", A is "T" (travel) or
  2106. "C" (cut). B is "F" (fast) or "S" (slow).
  2107. ===================== =========================================
  2108. """
  2109. defaults = {
  2110. "zdownrate": None,
  2111. "coordinate_format": "X%.4fY%.4f"
  2112. }
  2113. def __init__(self,
  2114. units="in",
  2115. kind="generic",
  2116. z_move=0.1,
  2117. feedrate=3.0,
  2118. z_cut=-0.002,
  2119. tooldia=0.0,
  2120. zdownrate=None,
  2121. spindlespeed=None):
  2122. Geometry.__init__(self)
  2123. self.kind = kind
  2124. self.units = units
  2125. self.z_cut = z_cut
  2126. self.z_move = z_move
  2127. self.feedrate = feedrate
  2128. self.tooldia = tooldia
  2129. self.unitcode = {"IN": "G20", "MM": "G21"}
  2130. self.pausecode = "G04 P1"
  2131. self.feedminutecode = "G94"
  2132. self.absolutecode = "G90"
  2133. self.gcode = ""
  2134. self.input_geometry_bounds = None
  2135. self.gcode_parsed = None
  2136. self.steps_per_circ = 20 # Used when parsing G-code arcs
  2137. if zdownrate is not None:
  2138. self.zdownrate = float(zdownrate)
  2139. elif CNCjob.defaults["zdownrate"] is not None:
  2140. self.zdownrate = float(CNCjob.defaults["zdownrate"])
  2141. else:
  2142. self.zdownrate = None
  2143. self.spindlespeed = spindlespeed
  2144. # Attributes to be included in serialization
  2145. # Always append to it because it carries contents
  2146. # from Geometry.
  2147. self.ser_attrs += ['kind', 'z_cut', 'z_move', 'feedrate', 'tooldia',
  2148. 'gcode', 'input_geometry_bounds', 'gcode_parsed',
  2149. 'steps_per_circ']
  2150. def convert_units(self, units):
  2151. factor = Geometry.convert_units(self, units)
  2152. log.debug("CNCjob.convert_units()")
  2153. self.z_cut *= factor
  2154. self.z_move *= factor
  2155. self.feedrate *= factor
  2156. self.tooldia *= factor
  2157. return factor
  2158. def generate_from_excellon_by_tool(self, exobj, tools="all",
  2159. toolchange=False, toolchangez=0.1):
  2160. """
  2161. Creates gcode for this object from an Excellon object
  2162. for the specified tools.
  2163. :param exobj: Excellon object to process
  2164. :type exobj: Excellon
  2165. :param tools: Comma separated tool names
  2166. :type: tools: str
  2167. :return: None
  2168. :rtype: None
  2169. """
  2170. log.debug("Creating CNC Job from Excellon...")
  2171. # Tools
  2172. if tools == "all":
  2173. tools = [tool for tool in exobj.tools]
  2174. else:
  2175. tools = [x.strip() for x in tools.split(",")]
  2176. tools = filter(lambda i: i in exobj.tools, tools)
  2177. log.debug("Tools are: %s" % str(tools))
  2178. # Points (Group by tool)
  2179. points = {}
  2180. for drill in exobj.drills:
  2181. if drill['tool'] in tools:
  2182. try:
  2183. points[drill['tool']].append(drill['point'])
  2184. except KeyError:
  2185. points[drill['tool']] = [drill['point']]
  2186. #log.debug("Found %d drills." % len(points))
  2187. self.gcode = []
  2188. # Basic G-Code macros
  2189. t = "G00 " + CNCjob.defaults["coordinate_format"] + "\n"
  2190. down = "G01 Z%.4f\n" % self.z_cut
  2191. up = "G01 Z%.4f\n" % self.z_move
  2192. # Initialization
  2193. gcode = self.unitcode[self.units.upper()] + "\n"
  2194. gcode += self.absolutecode + "\n"
  2195. gcode += self.feedminutecode + "\n"
  2196. gcode += "F%.2f\n" % self.feedrate
  2197. gcode += "G00 Z%.4f\n" % self.z_move # Move to travel height
  2198. if self.spindlespeed is not None:
  2199. gcode += "M03 S%d\n" % int(self.spindlespeed) # Spindle start with configured speed
  2200. else:
  2201. gcode += "M03\n" # Spindle start
  2202. gcode += self.pausecode + "\n"
  2203. for tool in points:
  2204. # Tool change sequence (optional)
  2205. if toolchange:
  2206. gcode += "G00 Z%.4f\n" % toolchangez
  2207. gcode += "T%d\n" % int(tool) # Indicate tool slot (for automatic tool changer)
  2208. gcode += "M5\n" # Spindle Stop
  2209. gcode += "M6\n" # Tool change
  2210. gcode += "(MSG, Change to tool dia=%.4f)\n" % exobj.tools[tool]["C"]
  2211. gcode += "M0\n" # Temporary machine stop
  2212. if self.spindlespeed is not None:
  2213. gcode += "M03 S%d\n" % int(self.spindlespeed) # Spindle start with configured speed
  2214. else:
  2215. gcode += "M03\n" # Spindle start
  2216. # Drillling!
  2217. for point in points[tool]:
  2218. x, y = point.coords.xy
  2219. gcode += t % (x[0], y[0])
  2220. gcode += down + up
  2221. gcode += t % (0, 0)
  2222. gcode += "M05\n" # Spindle stop
  2223. self.gcode = gcode
  2224. def generate_from_geometry_2(self,
  2225. geometry,
  2226. append=True,
  2227. tooldia=None,
  2228. tolerance=0,
  2229. multidepth=False,
  2230. depthpercut=None):
  2231. """
  2232. Second algorithm to generate from Geometry.
  2233. ALgorithm description:
  2234. ----------------------
  2235. Uses RTree to find the nearest path to follow.
  2236. :param geometry:
  2237. :param append:
  2238. :param tooldia:
  2239. :param tolerance:
  2240. :param multidepth: If True, use multiple passes to reach
  2241. the desired depth.
  2242. :param depthpercut: Maximum depth in each pass.
  2243. :return: None
  2244. """
  2245. assert isinstance(geometry, Geometry), \
  2246. "Expected a Geometry, got %s" % type(geometry)
  2247. log.debug("generate_from_geometry_2()")
  2248. ## Flatten the geometry
  2249. # Only linear elements (no polygons) remain.
  2250. flat_geometry = geometry.flatten(pathonly=True)
  2251. log.debug("%d paths" % len(flat_geometry))
  2252. ## Index first and last points in paths
  2253. # What points to index.
  2254. def get_pts(o):
  2255. return [o.coords[0], o.coords[-1]]
  2256. # Create the indexed storage.
  2257. storage = FlatCAMRTreeStorage()
  2258. storage.get_points = get_pts
  2259. # Store the geometry
  2260. log.debug("Indexing geometry before generating G-Code...")
  2261. for shape in flat_geometry:
  2262. if shape is not None: # TODO: This shouldn't have happened.
  2263. storage.insert(shape)
  2264. if tooldia is not None:
  2265. self.tooldia = tooldia
  2266. # self.input_geometry_bounds = geometry.bounds()
  2267. if not append:
  2268. self.gcode = ""
  2269. # Initial G-Code
  2270. self.gcode = self.unitcode[self.units.upper()] + "\n"
  2271. self.gcode += self.absolutecode + "\n"
  2272. self.gcode += self.feedminutecode + "\n"
  2273. self.gcode += "F%.2f\n" % self.feedrate
  2274. self.gcode += "G00 Z%.4f\n" % self.z_move # Move (up) to travel height
  2275. if self.spindlespeed is not None:
  2276. self.gcode += "M03 S%d\n" % int(self.spindlespeed) # Spindle start with configured speed
  2277. else:
  2278. self.gcode += "M03\n" # Spindle start
  2279. self.gcode += self.pausecode + "\n"
  2280. ## Iterate over geometry paths getting the nearest each time.
  2281. log.debug("Starting G-Code...")
  2282. path_count = 0
  2283. current_pt = (0, 0)
  2284. pt, geo = storage.nearest(current_pt)
  2285. try:
  2286. while True:
  2287. path_count += 1
  2288. #print "Current: ", "(%.3f, %.3f)" % current_pt
  2289. # Remove before modifying, otherwise
  2290. # deletion will fail.
  2291. storage.remove(geo)
  2292. # If last point in geometry is the nearest
  2293. # but prefer the first one if last point == first point
  2294. # then reverse coordinates.
  2295. if pt != geo.coords[0] and pt == geo.coords[-1]:
  2296. geo.coords = list(geo.coords)[::-1]
  2297. #---------- Single depth/pass --------
  2298. if not multidepth:
  2299. # G-code
  2300. # Note: self.linear2gcode() and self.point2gcode() will
  2301. # lower and raise the tool every time.
  2302. if type(geo) == LineString or type(geo) == LinearRing:
  2303. self.gcode += self.linear2gcode(geo, tolerance=tolerance)
  2304. elif type(geo) == Point:
  2305. self.gcode += self.point2gcode(geo)
  2306. else:
  2307. log.warning("G-code generation not implemented for %s" % (str(type(geo))))
  2308. #--------- Multi-pass ---------
  2309. else:
  2310. if isinstance(self.z_cut, Decimal):
  2311. z_cut = self.z_cut
  2312. else:
  2313. z_cut = Decimal(self.z_cut).quantize(Decimal('0.000000001'))
  2314. if depthpercut is None:
  2315. depthpercut = z_cut
  2316. elif not isinstance(depthpercut, Decimal):
  2317. depthpercut = Decimal(depthpercut).quantize(Decimal('0.000000001'))
  2318. depth = 0
  2319. reverse = False
  2320. while depth > z_cut:
  2321. # Increase depth. Limit to z_cut.
  2322. depth -= depthpercut
  2323. if depth < z_cut:
  2324. depth = z_cut
  2325. # Cut at specific depth and do not lift the tool.
  2326. # Note: linear2gcode() will use G00 to move to the
  2327. # first point in the path, but it should be already
  2328. # at the first point if the tool is down (in the material).
  2329. # So, an extra G00 should show up but is inconsequential.
  2330. if type(geo) == LineString or type(geo) == LinearRing:
  2331. self.gcode += self.linear2gcode(geo, tolerance=tolerance,
  2332. zcut=depth,
  2333. up=False)
  2334. # Ignore multi-pass for points.
  2335. elif type(geo) == Point:
  2336. self.gcode += self.point2gcode(geo)
  2337. break # Ignoring ...
  2338. else:
  2339. log.warning("G-code generation not implemented for %s" % (str(type(geo))))
  2340. # Reverse coordinates if not a loop so we can continue
  2341. # cutting without returning to the beginhing.
  2342. if type(geo) == LineString:
  2343. geo.coords = list(geo.coords)[::-1]
  2344. reverse = True
  2345. # If geometry is reversed, revert.
  2346. if reverse:
  2347. if type(geo) == LineString:
  2348. geo.coords = list(geo.coords)[::-1]
  2349. # Lift the tool
  2350. self.gcode += "G00 Z%.4f\n" % self.z_move
  2351. # self.gcode += "( End of path. )\n"
  2352. # Did deletion at the beginning.
  2353. # Delete from index, update current location and continue.
  2354. #rti.delete(hits[0], geo.coords[0])
  2355. #rti.delete(hits[0], geo.coords[-1])
  2356. current_pt = geo.coords[-1]
  2357. # Next
  2358. pt, geo = storage.nearest(current_pt)
  2359. except StopIteration: # Nothing found in storage.
  2360. pass
  2361. log.debug("%s paths traced." % path_count)
  2362. # Finish
  2363. self.gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  2364. self.gcode += "G00 X0Y0\n"
  2365. self.gcode += "M05\n" # Spindle stop
  2366. def pre_parse(self, gtext):
  2367. """
  2368. Separates parts of the G-Code text into a list of dictionaries.
  2369. Used by ``self.gcode_parse()``.
  2370. :param gtext: A single string with g-code
  2371. """
  2372. # Units: G20-inches, G21-mm
  2373. units_re = re.compile(r'^G2([01])')
  2374. # TODO: This has to be re-done
  2375. gcmds = []
  2376. lines = gtext.split("\n") # TODO: This is probably a lot of work!
  2377. for line in lines:
  2378. # Clean up
  2379. line = line.strip()
  2380. # Remove comments
  2381. # NOTE: Limited to 1 bracket pair
  2382. op = line.find("(")
  2383. cl = line.find(")")
  2384. #if op > -1 and cl > op:
  2385. if cl > op > -1:
  2386. #comment = line[op+1:cl]
  2387. line = line[:op] + line[(cl+1):]
  2388. # Units
  2389. match = units_re.match(line)
  2390. if match:
  2391. self.units = {'0': "IN", '1': "MM"}[match.group(1)]
  2392. # Parse GCode
  2393. # 0 4 12
  2394. # G01 X-0.007 Y-0.057
  2395. # --> codes_idx = [0, 4, 12]
  2396. codes = "NMGXYZIJFPST"
  2397. codes_idx = []
  2398. i = 0
  2399. for ch in line:
  2400. if ch in codes:
  2401. codes_idx.append(i)
  2402. i += 1
  2403. n_codes = len(codes_idx)
  2404. if n_codes == 0:
  2405. continue
  2406. # Separate codes in line
  2407. parts = []
  2408. for p in range(n_codes - 1):
  2409. parts.append(line[codes_idx[p]:codes_idx[p+1]].strip())
  2410. parts.append(line[codes_idx[-1]:].strip())
  2411. # Separate codes from values
  2412. cmds = {}
  2413. for part in parts:
  2414. cmds[part[0]] = float(part[1:])
  2415. gcmds.append(cmds)
  2416. return gcmds
  2417. def gcode_parse(self):
  2418. """
  2419. G-Code parser (from self.gcode). Generates dictionary with
  2420. single-segment LineString's and "kind" indicating cut or travel,
  2421. fast or feedrate speed.
  2422. """
  2423. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  2424. # Results go here
  2425. geometry = []
  2426. # TODO: Merge into single parser?
  2427. gobjs = self.pre_parse(self.gcode)
  2428. # Last known instruction
  2429. current = {'X': 0.0, 'Y': 0.0, 'Z': 0.0, 'G': 0}
  2430. # Current path: temporary storage until tool is
  2431. # lifted or lowered.
  2432. path = [(0, 0)]
  2433. # Process every instruction
  2434. for gobj in gobjs:
  2435. ## Changing height
  2436. if 'Z' in gobj:
  2437. if ('X' in gobj or 'Y' in gobj) and gobj['Z'] != current['Z']:
  2438. log.warning("Non-orthogonal motion: From %s" % str(current))
  2439. log.warning(" To: %s" % str(gobj))
  2440. current['Z'] = gobj['Z']
  2441. # Store the path into geometry and reset path
  2442. if len(path) > 1:
  2443. geometry.append({"geom": LineString(path),
  2444. "kind": kind})
  2445. path = [path[-1]] # Start with the last point of last path.
  2446. if 'G' in gobj:
  2447. current['G'] = int(gobj['G'])
  2448. if 'X' in gobj or 'Y' in gobj:
  2449. if 'X' in gobj:
  2450. x = gobj['X']
  2451. else:
  2452. x = current['X']
  2453. if 'Y' in gobj:
  2454. y = gobj['Y']
  2455. else:
  2456. y = current['Y']
  2457. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  2458. if current['Z'] > 0:
  2459. kind[0] = 'T'
  2460. if current['G'] > 0:
  2461. kind[1] = 'S'
  2462. arcdir = [None, None, "cw", "ccw"]
  2463. if current['G'] in [0, 1]: # line
  2464. path.append((x, y))
  2465. if current['G'] in [2, 3]: # arc
  2466. center = [gobj['I'] + current['X'], gobj['J'] + current['Y']]
  2467. radius = sqrt(gobj['I']**2 + gobj['J']**2)
  2468. start = arctan2(-gobj['J'], -gobj['I'])
  2469. stop = arctan2(-center[1]+y, -center[0]+x)
  2470. path += arc(center, radius, start, stop,
  2471. arcdir[current['G']],
  2472. self.steps_per_circ)
  2473. # Update current instruction
  2474. for code in gobj:
  2475. current[code] = gobj[code]
  2476. # There might not be a change in height at the
  2477. # end, therefore, see here too if there is
  2478. # a final path.
  2479. if len(path) > 1:
  2480. geometry.append({"geom": LineString(path),
  2481. "kind": kind})
  2482. self.gcode_parsed = geometry
  2483. return geometry
  2484. # def plot(self, tooldia=None, dpi=75, margin=0.1,
  2485. # color={"T": ["#F0E24D", "#B5AB3A"], "C": ["#5E6CFF", "#4650BD"]},
  2486. # alpha={"T": 0.3, "C": 1.0}):
  2487. # """
  2488. # Creates a Matplotlib figure with a plot of the
  2489. # G-code job.
  2490. # """
  2491. # if tooldia is None:
  2492. # tooldia = self.tooldia
  2493. #
  2494. # fig = Figure(dpi=dpi)
  2495. # ax = fig.add_subplot(111)
  2496. # ax.set_aspect(1)
  2497. # xmin, ymin, xmax, ymax = self.input_geometry_bounds
  2498. # ax.set_xlim(xmin-margin, xmax+margin)
  2499. # ax.set_ylim(ymin-margin, ymax+margin)
  2500. #
  2501. # if tooldia == 0:
  2502. # for geo in self.gcode_parsed:
  2503. # linespec = '--'
  2504. # linecolor = color[geo['kind'][0]][1]
  2505. # if geo['kind'][0] == 'C':
  2506. # linespec = 'k-'
  2507. # x, y = geo['geom'].coords.xy
  2508. # ax.plot(x, y, linespec, color=linecolor)
  2509. # else:
  2510. # for geo in self.gcode_parsed:
  2511. # poly = geo['geom'].buffer(tooldia/2.0)
  2512. # patch = PolygonPatch(poly, facecolor=color[geo['kind'][0]][0],
  2513. # edgecolor=color[geo['kind'][0]][1],
  2514. # alpha=alpha[geo['kind'][0]], zorder=2)
  2515. # ax.add_patch(patch)
  2516. #
  2517. # return fig
  2518. def plot2(self, axes, tooldia=None, dpi=75, margin=0.1,
  2519. color={"T": ["#F0E24D", "#B5AB3A"], "C": ["#5E6CFF", "#4650BD"]},
  2520. alpha={"T": 0.3, "C": 1.0}, tool_tolerance=0.0005):
  2521. """
  2522. Plots the G-code job onto the given axes.
  2523. :param axes: Matplotlib axes on which to plot.
  2524. :param tooldia: Tool diameter.
  2525. :param dpi: Not used!
  2526. :param margin: Not used!
  2527. :param color: Color specification.
  2528. :param alpha: Transparency specification.
  2529. :param tool_tolerance: Tolerance when drawing the toolshape.
  2530. :return: None
  2531. """
  2532. path_num = 0
  2533. if tooldia is None:
  2534. tooldia = self.tooldia
  2535. if tooldia == 0:
  2536. for geo in self.gcode_parsed:
  2537. linespec = '--'
  2538. linecolor = color[geo['kind'][0]][1]
  2539. if geo['kind'][0] == 'C':
  2540. linespec = 'k-'
  2541. x, y = geo['geom'].coords.xy
  2542. axes.plot(x, y, linespec, color=linecolor)
  2543. else:
  2544. for geo in self.gcode_parsed:
  2545. path_num += 1
  2546. axes.annotate(str(path_num), xy=geo['geom'].coords[0],
  2547. xycoords='data')
  2548. poly = geo['geom'].buffer(tooldia / 2.0).simplify(tool_tolerance)
  2549. patch = PolygonPatch(poly, facecolor=color[geo['kind'][0]][0],
  2550. edgecolor=color[geo['kind'][0]][1],
  2551. alpha=alpha[geo['kind'][0]], zorder=2)
  2552. axes.add_patch(patch)
  2553. def create_geometry(self):
  2554. # TODO: This takes forever. Too much data?
  2555. self.solid_geometry = cascaded_union([geo['geom'] for geo in self.gcode_parsed])
  2556. def linear2gcode(self, linear, tolerance=0, down=True, up=True,
  2557. zcut=None, ztravel=None, downrate=None,
  2558. feedrate=None, cont=False):
  2559. """
  2560. Generates G-code to cut along the linear feature.
  2561. :param linear: The path to cut along.
  2562. :type: Shapely.LinearRing or Shapely.Linear String
  2563. :param tolerance: All points in the simplified object will be within the
  2564. tolerance distance of the original geometry.
  2565. :type tolerance: float
  2566. :return: G-code to cut along the linear feature.
  2567. :rtype: str
  2568. """
  2569. if zcut is None:
  2570. zcut = self.z_cut
  2571. if ztravel is None:
  2572. ztravel = self.z_move
  2573. if downrate is None:
  2574. downrate = self.zdownrate
  2575. if feedrate is None:
  2576. feedrate = self.feedrate
  2577. t = "G0%d " + CNCjob.defaults["coordinate_format"] + "\n"
  2578. # Simplify paths?
  2579. if tolerance > 0:
  2580. target_linear = linear.simplify(tolerance)
  2581. else:
  2582. target_linear = linear
  2583. gcode = ""
  2584. path = list(target_linear.coords)
  2585. # Move fast to 1st point
  2586. if not cont:
  2587. gcode += t % (0, path[0][0], path[0][1]) # Move to first point
  2588. # Move down to cutting depth
  2589. if down:
  2590. # Different feedrate for vertical cut?
  2591. if self.zdownrate is not None:
  2592. gcode += "F%.2f\n" % downrate
  2593. gcode += "G01 Z%.4f\n" % zcut # Start cutting
  2594. gcode += "F%.2f\n" % feedrate # Restore feedrate
  2595. else:
  2596. gcode += "G01 Z%.4f\n" % zcut # Start cutting
  2597. # Cutting...
  2598. for pt in path[1:]:
  2599. gcode += t % (1, pt[0], pt[1]) # Linear motion to point
  2600. # Up to travelling height.
  2601. if up:
  2602. gcode += "G00 Z%.4f\n" % ztravel # Stop cutting
  2603. return gcode
  2604. def point2gcode(self, point):
  2605. gcode = ""
  2606. #t = "G0%d X%.4fY%.4f\n"
  2607. t = "G0%d " + CNCjob.defaults["coordinate_format"] + "\n"
  2608. path = list(point.coords)
  2609. gcode += t % (0, path[0][0], path[0][1]) # Move to first point
  2610. if self.zdownrate is not None:
  2611. gcode += "F%.2f\n" % self.zdownrate
  2612. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  2613. gcode += "F%.2f\n" % self.feedrate
  2614. else:
  2615. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  2616. gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  2617. return gcode
  2618. def scale(self, factor):
  2619. """
  2620. Scales all the geometry on the XY plane in the object by the
  2621. given factor. Tool sizes, feedrates, or Z-axis dimensions are
  2622. not altered.
  2623. :param factor: Number by which to scale the object.
  2624. :type factor: float
  2625. :return: None
  2626. :rtype: None
  2627. """
  2628. for g in self.gcode_parsed:
  2629. g['geom'] = affinity.scale(g['geom'], factor, factor, origin=(0, 0))
  2630. self.create_geometry()
  2631. def offset(self, vect):
  2632. """
  2633. Offsets all the geometry on the XY plane in the object by the
  2634. given vector.
  2635. :param vect: (x, y) offset vector.
  2636. :type vect: tuple
  2637. :return: None
  2638. """
  2639. dx, dy = vect
  2640. for g in self.gcode_parsed:
  2641. g['geom'] = affinity.translate(g['geom'], xoff=dx, yoff=dy)
  2642. self.create_geometry()
  2643. # def get_bounds(geometry_set):
  2644. # xmin = Inf
  2645. # ymin = Inf
  2646. # xmax = -Inf
  2647. # ymax = -Inf
  2648. #
  2649. # #print "Getting bounds of:", str(geometry_set)
  2650. # for gs in geometry_set:
  2651. # try:
  2652. # gxmin, gymin, gxmax, gymax = geometry_set[gs].bounds()
  2653. # xmin = min([xmin, gxmin])
  2654. # ymin = min([ymin, gymin])
  2655. # xmax = max([xmax, gxmax])
  2656. # ymax = max([ymax, gymax])
  2657. # except:
  2658. # print "DEV WARNING: Tried to get bounds of empty geometry."
  2659. #
  2660. # return [xmin, ymin, xmax, ymax]
  2661. def get_bounds(geometry_list):
  2662. xmin = Inf
  2663. ymin = Inf
  2664. xmax = -Inf
  2665. ymax = -Inf
  2666. #print "Getting bounds of:", str(geometry_set)
  2667. for gs in geometry_list:
  2668. try:
  2669. gxmin, gymin, gxmax, gymax = gs.bounds()
  2670. xmin = min([xmin, gxmin])
  2671. ymin = min([ymin, gymin])
  2672. xmax = max([xmax, gxmax])
  2673. ymax = max([ymax, gymax])
  2674. except:
  2675. log.warning("DEVELOPMENT: Tried to get bounds of empty geometry.")
  2676. return [xmin, ymin, xmax, ymax]
  2677. def arc(center, radius, start, stop, direction, steps_per_circ):
  2678. """
  2679. Creates a list of point along the specified arc.
  2680. :param center: Coordinates of the center [x, y]
  2681. :type center: list
  2682. :param radius: Radius of the arc.
  2683. :type radius: float
  2684. :param start: Starting angle in radians
  2685. :type start: float
  2686. :param stop: End angle in radians
  2687. :type stop: float
  2688. :param direction: Orientation of the arc, "CW" or "CCW"
  2689. :type direction: string
  2690. :param steps_per_circ: Number of straight line segments to
  2691. represent a circle.
  2692. :type steps_per_circ: int
  2693. :return: The desired arc, as list of tuples
  2694. :rtype: list
  2695. """
  2696. # TODO: Resolution should be established by maximum error from the exact arc.
  2697. da_sign = {"cw": -1.0, "ccw": 1.0}
  2698. points = []
  2699. if direction == "ccw" and stop <= start:
  2700. stop += 2 * pi
  2701. if direction == "cw" and stop >= start:
  2702. stop -= 2 * pi
  2703. angle = abs(stop - start)
  2704. #angle = stop-start
  2705. steps = max([int(ceil(angle / (2 * pi) * steps_per_circ)), 2])
  2706. delta_angle = da_sign[direction] * angle * 1.0 / steps
  2707. for i in range(steps + 1):
  2708. theta = start + delta_angle * i
  2709. points.append((center[0] + radius * cos(theta), center[1] + radius * sin(theta)))
  2710. return points
  2711. def arc2(p1, p2, center, direction, steps_per_circ):
  2712. r = sqrt((center[0] - p1[0]) ** 2 + (center[1] - p1[1]) ** 2)
  2713. start = arctan2(p1[1] - center[1], p1[0] - center[0])
  2714. stop = arctan2(p2[1] - center[1], p2[0] - center[0])
  2715. return arc(center, r, start, stop, direction, steps_per_circ)
  2716. def arc_angle(start, stop, direction):
  2717. if direction == "ccw" and stop <= start:
  2718. stop += 2 * pi
  2719. if direction == "cw" and stop >= start:
  2720. stop -= 2 * pi
  2721. angle = abs(stop - start)
  2722. return angle
  2723. # def find_polygon(poly, point):
  2724. # """
  2725. # Find an object that object.contains(Point(point)) in
  2726. # poly, which can can be iterable, contain iterable of, or
  2727. # be itself an implementer of .contains().
  2728. #
  2729. # :param poly: See description
  2730. # :return: Polygon containing point or None.
  2731. # """
  2732. #
  2733. # if poly is None:
  2734. # return None
  2735. #
  2736. # try:
  2737. # for sub_poly in poly:
  2738. # p = find_polygon(sub_poly, point)
  2739. # if p is not None:
  2740. # return p
  2741. # except TypeError:
  2742. # try:
  2743. # if poly.contains(Point(point)):
  2744. # return poly
  2745. # except AttributeError:
  2746. # return None
  2747. #
  2748. # return None
  2749. def to_dict(obj):
  2750. """
  2751. Makes the following types into serializable form:
  2752. * ApertureMacro
  2753. * BaseGeometry
  2754. :param obj: Shapely geometry.
  2755. :type obj: BaseGeometry
  2756. :return: Dictionary with serializable form if ``obj`` was
  2757. BaseGeometry or ApertureMacro, otherwise returns ``obj``.
  2758. """
  2759. if isinstance(obj, ApertureMacro):
  2760. return {
  2761. "__class__": "ApertureMacro",
  2762. "__inst__": obj.to_dict()
  2763. }
  2764. if isinstance(obj, BaseGeometry):
  2765. return {
  2766. "__class__": "Shply",
  2767. "__inst__": sdumps(obj)
  2768. }
  2769. return obj
  2770. def dict2obj(d):
  2771. """
  2772. Default deserializer.
  2773. :param d: Serializable dictionary representation of an object
  2774. to be reconstructed.
  2775. :return: Reconstructed object.
  2776. """
  2777. if '__class__' in d and '__inst__' in d:
  2778. if d['__class__'] == "Shply":
  2779. return sloads(d['__inst__'])
  2780. if d['__class__'] == "ApertureMacro":
  2781. am = ApertureMacro()
  2782. am.from_dict(d['__inst__'])
  2783. return am
  2784. return d
  2785. else:
  2786. return d
  2787. def plotg(geo, solid_poly=False, color="black"):
  2788. try:
  2789. _ = iter(geo)
  2790. except:
  2791. geo = [geo]
  2792. for g in geo:
  2793. if type(g) == Polygon:
  2794. if solid_poly:
  2795. patch = PolygonPatch(g,
  2796. facecolor="#BBF268",
  2797. edgecolor="#006E20",
  2798. alpha=0.75,
  2799. zorder=2)
  2800. ax = subplot(111)
  2801. ax.add_patch(patch)
  2802. else:
  2803. x, y = g.exterior.coords.xy
  2804. plot(x, y, color=color)
  2805. for ints in g.interiors:
  2806. x, y = ints.coords.xy
  2807. plot(x, y, color=color)
  2808. continue
  2809. if type(g) == LineString or type(g) == LinearRing:
  2810. x, y = g.coords.xy
  2811. plot(x, y, color=color)
  2812. continue
  2813. if type(g) == Point:
  2814. x, y = g.coords.xy
  2815. plot(x, y, 'o')
  2816. continue
  2817. try:
  2818. _ = iter(g)
  2819. plotg(g, color=color)
  2820. except:
  2821. log.error("Cannot plot: " + str(type(g)))
  2822. continue
  2823. def parse_gerber_number(strnumber, frac_digits):
  2824. """
  2825. Parse a single number of Gerber coordinates.
  2826. :param strnumber: String containing a number in decimal digits
  2827. from a coordinate data block, possibly with a leading sign.
  2828. :type strnumber: str
  2829. :param frac_digits: Number of digits used for the fractional
  2830. part of the number
  2831. :type frac_digits: int
  2832. :return: The number in floating point.
  2833. :rtype: float
  2834. """
  2835. return int(strnumber) * (10 ** (-frac_digits))
  2836. # def voronoi(P):
  2837. # """
  2838. # Returns a list of all edges of the voronoi diagram for the given input points.
  2839. # """
  2840. # delauny = Delaunay(P)
  2841. # triangles = delauny.points[delauny.vertices]
  2842. #
  2843. # circum_centers = np.array([triangle_csc(tri) for tri in triangles])
  2844. # long_lines_endpoints = []
  2845. #
  2846. # lineIndices = []
  2847. # for i, triangle in enumerate(triangles):
  2848. # circum_center = circum_centers[i]
  2849. # for j, neighbor in enumerate(delauny.neighbors[i]):
  2850. # if neighbor != -1:
  2851. # lineIndices.append((i, neighbor))
  2852. # else:
  2853. # ps = triangle[(j+1)%3] - triangle[(j-1)%3]
  2854. # ps = np.array((ps[1], -ps[0]))
  2855. #
  2856. # middle = (triangle[(j+1)%3] + triangle[(j-1)%3]) * 0.5
  2857. # di = middle - triangle[j]
  2858. #
  2859. # ps /= np.linalg.norm(ps)
  2860. # di /= np.linalg.norm(di)
  2861. #
  2862. # if np.dot(di, ps) < 0.0:
  2863. # ps *= -1000.0
  2864. # else:
  2865. # ps *= 1000.0
  2866. #
  2867. # long_lines_endpoints.append(circum_center + ps)
  2868. # lineIndices.append((i, len(circum_centers) + len(long_lines_endpoints)-1))
  2869. #
  2870. # vertices = np.vstack((circum_centers, long_lines_endpoints))
  2871. #
  2872. # # filter out any duplicate lines
  2873. # lineIndicesSorted = np.sort(lineIndices) # make (1,2) and (2,1) both (1,2)
  2874. # lineIndicesTupled = [tuple(row) for row in lineIndicesSorted]
  2875. # lineIndicesUnique = np.unique(lineIndicesTupled)
  2876. #
  2877. # return vertices, lineIndicesUnique
  2878. #
  2879. #
  2880. # def triangle_csc(pts):
  2881. # rows, cols = pts.shape
  2882. #
  2883. # A = np.bmat([[2 * np.dot(pts, pts.T), np.ones((rows, 1))],
  2884. # [np.ones((1, rows)), np.zeros((1, 1))]])
  2885. #
  2886. # b = np.hstack((np.sum(pts * pts, axis=1), np.ones((1))))
  2887. # x = np.linalg.solve(A,b)
  2888. # bary_coords = x[:-1]
  2889. # return np.sum(pts * np.tile(bary_coords.reshape((pts.shape[0], 1)), (1, pts.shape[1])), axis=0)
  2890. #
  2891. #
  2892. # def voronoi_cell_lines(points, vertices, lineIndices):
  2893. # """
  2894. # Returns a mapping from a voronoi cell to its edges.
  2895. #
  2896. # :param points: shape (m,2)
  2897. # :param vertices: shape (n,2)
  2898. # :param lineIndices: shape (o,2)
  2899. # :rtype: dict point index -> list of shape (n,2) with vertex indices
  2900. # """
  2901. # kd = KDTree(points)
  2902. #
  2903. # cells = collections.defaultdict(list)
  2904. # for i1, i2 in lineIndices:
  2905. # v1, v2 = vertices[i1], vertices[i2]
  2906. # mid = (v1+v2)/2
  2907. # _, (p1Idx, p2Idx) = kd.query(mid, 2)
  2908. # cells[p1Idx].append((i1, i2))
  2909. # cells[p2Idx].append((i1, i2))
  2910. #
  2911. # return cells
  2912. #
  2913. #
  2914. # def voronoi_edges2polygons(cells):
  2915. # """
  2916. # Transforms cell edges into polygons.
  2917. #
  2918. # :param cells: as returned from voronoi_cell_lines
  2919. # :rtype: dict point index -> list of vertex indices which form a polygon
  2920. # """
  2921. #
  2922. # # first, close the outer cells
  2923. # for pIdx, lineIndices_ in cells.items():
  2924. # dangling_lines = []
  2925. # for i1, i2 in lineIndices_:
  2926. # connections = filter(lambda (i1_, i2_): (i1, i2) != (i1_, i2_) and (i1 == i1_ or i1 == i2_ or i2 == i1_ or i2 == i2_), lineIndices_)
  2927. # assert 1 <= len(connections) <= 2
  2928. # if len(connections) == 1:
  2929. # dangling_lines.append((i1, i2))
  2930. # assert len(dangling_lines) in [0, 2]
  2931. # if len(dangling_lines) == 2:
  2932. # (i11, i12), (i21, i22) = dangling_lines
  2933. #
  2934. # # determine which line ends are unconnected
  2935. # connected = filter(lambda (i1,i2): (i1,i2) != (i11,i12) and (i1 == i11 or i2 == i11), lineIndices_)
  2936. # i11Unconnected = len(connected) == 0
  2937. #
  2938. # connected = filter(lambda (i1,i2): (i1,i2) != (i21,i22) and (i1 == i21 or i2 == i21), lineIndices_)
  2939. # i21Unconnected = len(connected) == 0
  2940. #
  2941. # startIdx = i11 if i11Unconnected else i12
  2942. # endIdx = i21 if i21Unconnected else i22
  2943. #
  2944. # cells[pIdx].append((startIdx, endIdx))
  2945. #
  2946. # # then, form polygons by storing vertex indices in (counter-)clockwise order
  2947. # polys = dict()
  2948. # for pIdx, lineIndices_ in cells.items():
  2949. # # get a directed graph which contains both directions and arbitrarily follow one of both
  2950. # directedGraph = lineIndices_ + [(i2, i1) for (i1, i2) in lineIndices_]
  2951. # directedGraphMap = collections.defaultdict(list)
  2952. # for (i1, i2) in directedGraph:
  2953. # directedGraphMap[i1].append(i2)
  2954. # orderedEdges = []
  2955. # currentEdge = directedGraph[0]
  2956. # while len(orderedEdges) < len(lineIndices_):
  2957. # i1 = currentEdge[1]
  2958. # i2 = directedGraphMap[i1][0] if directedGraphMap[i1][0] != currentEdge[0] else directedGraphMap[i1][1]
  2959. # nextEdge = (i1, i2)
  2960. # orderedEdges.append(nextEdge)
  2961. # currentEdge = nextEdge
  2962. #
  2963. # polys[pIdx] = [i1 for (i1, i2) in orderedEdges]
  2964. #
  2965. # return polys
  2966. #
  2967. #
  2968. # def voronoi_polygons(points):
  2969. # """
  2970. # Returns the voronoi polygon for each input point.
  2971. #
  2972. # :param points: shape (n,2)
  2973. # :rtype: list of n polygons where each polygon is an array of vertices
  2974. # """
  2975. # vertices, lineIndices = voronoi(points)
  2976. # cells = voronoi_cell_lines(points, vertices, lineIndices)
  2977. # polys = voronoi_edges2polygons(cells)
  2978. # polylist = []
  2979. # for i in xrange(len(points)):
  2980. # poly = vertices[np.asarray(polys[i])]
  2981. # polylist.append(poly)
  2982. # return polylist
  2983. #
  2984. #
  2985. # class Zprofile:
  2986. # def __init__(self):
  2987. #
  2988. # # data contains lists of [x, y, z]
  2989. # self.data = []
  2990. #
  2991. # # Computed voronoi polygons (shapely)
  2992. # self.polygons = []
  2993. # pass
  2994. #
  2995. # def plot_polygons(self):
  2996. # axes = plt.subplot(1, 1, 1)
  2997. #
  2998. # plt.axis([-0.05, 1.05, -0.05, 1.05])
  2999. #
  3000. # for poly in self.polygons:
  3001. # p = PolygonPatch(poly, facecolor=np.random.rand(3, 1), alpha=0.3)
  3002. # axes.add_patch(p)
  3003. #
  3004. # def init_from_csv(self, filename):
  3005. # pass
  3006. #
  3007. # def init_from_string(self, zpstring):
  3008. # pass
  3009. #
  3010. # def init_from_list(self, zplist):
  3011. # self.data = zplist
  3012. #
  3013. # def generate_polygons(self):
  3014. # self.polygons = [Polygon(p) for p in voronoi_polygons(array([[x[0], x[1]] for x in self.data]))]
  3015. #
  3016. # def normalize(self, origin):
  3017. # pass
  3018. #
  3019. # def paste(self, path):
  3020. # """
  3021. # Return a list of dictionaries containing the parts of the original
  3022. # path and their z-axis offset.
  3023. # """
  3024. #
  3025. # # At most one region/polygon will contain the path
  3026. # containing = [i for i in range(len(self.polygons)) if self.polygons[i].contains(path)]
  3027. #
  3028. # if len(containing) > 0:
  3029. # return [{"path": path, "z": self.data[containing[0]][2]}]
  3030. #
  3031. # # All region indexes that intersect with the path
  3032. # crossing = [i for i in range(len(self.polygons)) if self.polygons[i].intersects(path)]
  3033. #
  3034. # return [{"path": path.intersection(self.polygons[i]),
  3035. # "z": self.data[i][2]} for i in crossing]
  3036. def autolist(obj):
  3037. try:
  3038. _ = iter(obj)
  3039. return obj
  3040. except TypeError:
  3041. return [obj]
  3042. def three_point_circle(p1, p2, p3):
  3043. """
  3044. Computes the center and radius of a circle from
  3045. 3 points on its circumference.
  3046. :param p1: Point 1
  3047. :param p2: Point 2
  3048. :param p3: Point 3
  3049. :return: center, radius
  3050. """
  3051. # Midpoints
  3052. a1 = (p1 + p2) / 2.0
  3053. a2 = (p2 + p3) / 2.0
  3054. # Normals
  3055. b1 = dot((p2 - p1), array([[0, -1], [1, 0]], dtype=float32))
  3056. b2 = dot((p3 - p2), array([[0, 1], [-1, 0]], dtype=float32))
  3057. # Params
  3058. T = solve(transpose(array([-b1, b2])), a1 - a2)
  3059. # Center
  3060. center = a1 + b1 * T[0]
  3061. # Radius
  3062. radius = norm(center - p1)
  3063. return center, radius, T[0]
  3064. def distance(pt1, pt2):
  3065. return sqrt((pt1[0] - pt2[0]) ** 2 + (pt1[1] - pt2[1]) ** 2)
  3066. class FlatCAMRTree(object):
  3067. def __init__(self):
  3068. # Python RTree Index
  3069. self.rti = rtindex.Index()
  3070. ## Track object-point relationship
  3071. # Each is list of points in object.
  3072. self.obj2points = []
  3073. # Index is index in rtree, value is index of
  3074. # object in obj2points.
  3075. self.points2obj = []
  3076. self.get_points = lambda go: go.coords
  3077. def grow_obj2points(self, idx):
  3078. """
  3079. Increases the size of self.obj2points to fit
  3080. idx + 1 items.
  3081. :param idx: Index to fit into list.
  3082. :return: None
  3083. """
  3084. if len(self.obj2points) > idx:
  3085. # len == 2, idx == 1, ok.
  3086. return
  3087. else:
  3088. # len == 2, idx == 2, need 1 more.
  3089. # range(2, 3)
  3090. for i in range(len(self.obj2points), idx + 1):
  3091. self.obj2points.append([])
  3092. def insert(self, objid, obj):
  3093. self.grow_obj2points(objid)
  3094. self.obj2points[objid] = []
  3095. for pt in self.get_points(obj):
  3096. self.rti.insert(len(self.points2obj), (pt[0], pt[1], pt[0], pt[1]), obj=objid)
  3097. self.obj2points[objid].append(len(self.points2obj))
  3098. self.points2obj.append(objid)
  3099. def remove_obj(self, objid, obj):
  3100. # Use all ptids to delete from index
  3101. for i, pt in enumerate(self.get_points(obj)):
  3102. self.rti.delete(self.obj2points[objid][i], (pt[0], pt[1], pt[0], pt[1]))
  3103. def nearest(self, pt):
  3104. """
  3105. Will raise StopIteration if no items are found.
  3106. :param pt:
  3107. :return:
  3108. """
  3109. return self.rti.nearest(pt, objects=True).next()
  3110. class FlatCAMRTreeStorage(FlatCAMRTree):
  3111. def __init__(self):
  3112. super(FlatCAMRTreeStorage, self).__init__()
  3113. self.objects = []
  3114. # Optimization attempt!
  3115. self.indexes = {}
  3116. def insert(self, obj):
  3117. self.objects.append(obj)
  3118. idx = len(self.objects) - 1
  3119. # Note: Shapely objects are not hashable any more, althought
  3120. # there seem to be plans to re-introduce the feature in
  3121. # version 2.0. For now, we will index using the object's id,
  3122. # but it's important to remember that shapely geometry is
  3123. # mutable, ie. it can be modified to a totally different shape
  3124. # and continue to have the same id.
  3125. # self.indexes[obj] = idx
  3126. self.indexes[id(obj)] = idx
  3127. super(FlatCAMRTreeStorage, self).insert(idx, obj)
  3128. #@profile
  3129. def remove(self, obj):
  3130. # See note about self.indexes in insert().
  3131. # objidx = self.indexes[obj]
  3132. objidx = self.indexes[id(obj)]
  3133. # Remove from list
  3134. self.objects[objidx] = None
  3135. # Remove from index
  3136. self.remove_obj(objidx, obj)
  3137. def get_objects(self):
  3138. return (o for o in self.objects if o is not None)
  3139. def nearest(self, pt):
  3140. """
  3141. Returns the nearest matching points and the object
  3142. it belongs to.
  3143. :param pt: Query point.
  3144. :return: (match_x, match_y), Object owner of
  3145. matching point.
  3146. :rtype: tuple
  3147. """
  3148. tidx = super(FlatCAMRTreeStorage, self).nearest(pt)
  3149. return (tidx.bbox[0], tidx.bbox[1]), self.objects[tidx.object]
  3150. # class myO:
  3151. # def __init__(self, coords):
  3152. # self.coords = coords
  3153. #
  3154. #
  3155. # def test_rti():
  3156. #
  3157. # o1 = myO([(0, 0), (0, 1), (1, 1)])
  3158. # o2 = myO([(2, 0), (2, 1), (2, 1)])
  3159. # o3 = myO([(2, 0), (2, 1), (3, 1)])
  3160. #
  3161. # os = [o1, o2]
  3162. #
  3163. # idx = FlatCAMRTree()
  3164. #
  3165. # for o in range(len(os)):
  3166. # idx.insert(o, os[o])
  3167. #
  3168. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  3169. #
  3170. # idx.remove_obj(0, o1)
  3171. #
  3172. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  3173. #
  3174. # idx.remove_obj(1, o2)
  3175. #
  3176. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  3177. #
  3178. #
  3179. # def test_rtis():
  3180. #
  3181. # o1 = myO([(0, 0), (0, 1), (1, 1)])
  3182. # o2 = myO([(2, 0), (2, 1), (2, 1)])
  3183. # o3 = myO([(2, 0), (2, 1), (3, 1)])
  3184. #
  3185. # os = [o1, o2]
  3186. #
  3187. # idx = FlatCAMRTreeStorage()
  3188. #
  3189. # for o in range(len(os)):
  3190. # idx.insert(os[o])
  3191. #
  3192. # #os = None
  3193. # #o1 = None
  3194. # #o2 = None
  3195. #
  3196. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  3197. #
  3198. # idx.remove(idx.nearest((2,0))[1])
  3199. #
  3200. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  3201. #
  3202. # idx.remove(idx.nearest((0,0))[1])
  3203. #
  3204. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]