camlib.py 135 KB

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