camlib.py 146 KB

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