camlib.py 145 KB

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