camlib.py 141 KB

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