camlib.py 139 KB

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