camlib.py 134 KB

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