camlib.py 138 KB

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