camlib.py 142 KB

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