camlib.py 138 KB

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