camlib.py 214 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481
  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 io import StringIO
  9. import numpy as np
  10. from numpy import arctan2, Inf, array, sqrt, pi, ceil, sin, cos, dot, float32, \
  11. transpose
  12. from numpy.linalg import solve, norm
  13. import re, sys, os, platform
  14. import math
  15. from copy import deepcopy
  16. import traceback
  17. from decimal import Decimal
  18. from rtree import index as rtindex
  19. from lxml import etree as ET
  20. # See: http://toblerity.org/shapely/manual.html
  21. from shapely.geometry import Polygon, LineString, Point, LinearRing, MultiLineString
  22. from shapely.geometry import MultiPoint, MultiPolygon
  23. from shapely.geometry import box as shply_box
  24. from shapely.ops import cascaded_union, unary_union, polygonize
  25. import shapely.affinity as affinity
  26. from shapely.wkt import loads as sloads
  27. from shapely.wkt import dumps as sdumps
  28. from shapely.geometry.base import BaseGeometry
  29. from shapely.geometry import shape
  30. # needed for legacy mode
  31. # Used for solid polygons in Matplotlib
  32. from descartes.patch import PolygonPatch
  33. import collections
  34. from collections import Iterable
  35. import rasterio
  36. from rasterio.features import shapes
  37. import ezdxf
  38. # TODO: Commented for FlatCAM packaging with cx_freeze
  39. # from scipy.spatial import KDTree, Delaunay
  40. # from scipy.spatial import Delaunay
  41. from flatcamParsers.ParseGerber import ApertureMacro
  42. from flatcamParsers.ParseSVG import *
  43. from flatcamParsers.ParseDXF import *
  44. if platform.architecture()[0] == '64bit':
  45. from ortools.constraint_solver import pywrapcp
  46. from ortools.constraint_solver import routing_enums_pb2
  47. import logging
  48. import FlatCAMApp
  49. import gettext
  50. import FlatCAMTranslation as fcTranslate
  51. import builtins
  52. fcTranslate.apply_language('strings')
  53. log = logging.getLogger('base2')
  54. log.setLevel(logging.DEBUG)
  55. formatter = logging.Formatter('[%(levelname)s] %(message)s')
  56. handler = logging.StreamHandler()
  57. handler.setFormatter(formatter)
  58. log.addHandler(handler)
  59. if '_' not in builtins.__dict__:
  60. _ = gettext.gettext
  61. class ParseError(Exception):
  62. pass
  63. class Geometry(object):
  64. """
  65. Base geometry class.
  66. """
  67. defaults = {
  68. "units": 'in',
  69. "geo_steps_per_circle": 128
  70. }
  71. def __init__(self, geo_steps_per_circle=None):
  72. # Units (in or mm)
  73. self.units = Geometry.defaults["units"]
  74. # Final geometry: MultiPolygon or list (of geometry constructs)
  75. self.solid_geometry = None
  76. # Final geometry: MultiLineString or list (of LineString or Points)
  77. self.follow_geometry = None
  78. # Attributes to be included in serialization
  79. self.ser_attrs = ["units", 'solid_geometry', 'follow_geometry']
  80. # Flattened geometry (list of paths only)
  81. self.flat_geometry = []
  82. # this is the calculated conversion factor when the file units are different than the ones in the app
  83. self.file_units_factor = 1
  84. # Index
  85. self.index = None
  86. self.geo_steps_per_circle = geo_steps_per_circle
  87. # variables to display the percentage of work done
  88. self.geo_len = 0
  89. self.old_disp_number = 0
  90. self.el_count = 0
  91. if self.app.is_legacy is False:
  92. self.temp_shapes = self.app.plotcanvas.new_shape_group()
  93. else:
  94. from flatcamGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  95. self.temp_shapes = ShapeCollectionLegacy(obj=self, app=self.app, name='camlib.geometry')
  96. # if geo_steps_per_circle is None:
  97. # geo_steps_per_circle = int(Geometry.defaults["geo_steps_per_circle"])
  98. # self.geo_steps_per_circle = geo_steps_per_circle
  99. def plot_temp_shapes(self, element, color='red'):
  100. try:
  101. for sub_el in element:
  102. self.plot_temp_shapes(sub_el)
  103. except TypeError: # Element is not iterable...
  104. # self.add_shape(shape=element, color=color, visible=visible, layer=0)
  105. self.temp_shapes.add(tolerance=float(self.app.defaults["global_tolerance"]),
  106. shape=element, color=color, visible=True, layer=0)
  107. def make_index(self):
  108. self.flatten()
  109. self.index = FlatCAMRTree()
  110. for i, g in enumerate(self.flat_geometry):
  111. self.index.insert(i, g)
  112. def add_circle(self, origin, radius):
  113. """
  114. Adds a circle to the object.
  115. :param origin: Center of the circle.
  116. :param radius: Radius of the circle.
  117. :return: None
  118. """
  119. if self.solid_geometry is None:
  120. self.solid_geometry = []
  121. if type(self.solid_geometry) is list:
  122. self.solid_geometry.append(Point(origin).buffer(
  123. radius, int(int(self.geo_steps_per_circle) / 4)))
  124. return
  125. try:
  126. self.solid_geometry = self.solid_geometry.union(Point(origin).buffer(
  127. radius, int(int(self.geo_steps_per_circle) / 4)))
  128. except Exception as e:
  129. log.error("Failed to run union on polygons. %s" % str(e))
  130. return
  131. def add_polygon(self, points):
  132. """
  133. Adds a polygon to the object (by union)
  134. :param points: The vertices of the polygon.
  135. :return: None
  136. """
  137. if self.solid_geometry is None:
  138. self.solid_geometry = []
  139. if type(self.solid_geometry) is list:
  140. self.solid_geometry.append(Polygon(points))
  141. return
  142. try:
  143. self.solid_geometry = self.solid_geometry.union(Polygon(points))
  144. except Exception as e:
  145. log.error("Failed to run union on polygons. %s" % str(e))
  146. return
  147. def add_polyline(self, points):
  148. """
  149. Adds a polyline to the object (by union)
  150. :param points: The vertices of the polyline.
  151. :return: None
  152. """
  153. if self.solid_geometry is None:
  154. self.solid_geometry = []
  155. if type(self.solid_geometry) is list:
  156. self.solid_geometry.append(LineString(points))
  157. return
  158. try:
  159. self.solid_geometry = self.solid_geometry.union(LineString(points))
  160. except Exception as e:
  161. log.error("Failed to run union on polylines. %s" % str(e))
  162. return
  163. def is_empty(self):
  164. if isinstance(self.solid_geometry, BaseGeometry):
  165. return self.solid_geometry.is_empty
  166. if isinstance(self.solid_geometry, list):
  167. return len(self.solid_geometry) == 0
  168. self.app.inform.emit('[ERROR_NOTCL] %s' %
  169. _("self.solid_geometry is neither BaseGeometry or list."))
  170. return
  171. def subtract_polygon(self, points):
  172. """
  173. Subtract polygon from the given object. This only operates on the paths in the original geometry,
  174. i.e. it converts polygons into paths.
  175. :param points: The vertices of the polygon.
  176. :return: none
  177. """
  178. if self.solid_geometry is None:
  179. self.solid_geometry = []
  180. # pathonly should be allways True, otherwise polygons are not subtracted
  181. flat_geometry = self.flatten(pathonly=True)
  182. log.debug("%d paths" % len(flat_geometry))
  183. polygon = Polygon(points)
  184. toolgeo = cascaded_union(polygon)
  185. diffs = []
  186. for target in flat_geometry:
  187. if type(target) == LineString or type(target) == LinearRing:
  188. diffs.append(target.difference(toolgeo))
  189. else:
  190. log.warning("Not implemented.")
  191. self.solid_geometry = cascaded_union(diffs)
  192. def bounds(self):
  193. """
  194. Returns coordinates of rectangular bounds
  195. of geometry: (xmin, ymin, xmax, ymax).
  196. """
  197. # fixed issue of getting bounds only for one level lists of objects
  198. # now it can get bounds for nested lists of objects
  199. log.debug("camlib.Geometry.bounds()")
  200. if self.solid_geometry is None:
  201. log.debug("solid_geometry is None")
  202. return 0, 0, 0, 0
  203. def bounds_rec(obj):
  204. if type(obj) is list:
  205. minx = Inf
  206. miny = Inf
  207. maxx = -Inf
  208. maxy = -Inf
  209. for k in obj:
  210. if type(k) is dict:
  211. for key in k:
  212. minx_, miny_, maxx_, maxy_ = bounds_rec(k[key])
  213. minx = min(minx, minx_)
  214. miny = min(miny, miny_)
  215. maxx = max(maxx, maxx_)
  216. maxy = max(maxy, maxy_)
  217. else:
  218. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  219. minx = min(minx, minx_)
  220. miny = min(miny, miny_)
  221. maxx = max(maxx, maxx_)
  222. maxy = max(maxy, maxy_)
  223. return minx, miny, maxx, maxy
  224. else:
  225. # it's a Shapely object, return it's bounds
  226. return obj.bounds
  227. if self.multigeo is True:
  228. minx_list = []
  229. miny_list = []
  230. maxx_list = []
  231. maxy_list = []
  232. for tool in self.tools:
  233. minx, miny, maxx, maxy = bounds_rec(self.tools[tool]['solid_geometry'])
  234. minx_list.append(minx)
  235. miny_list.append(miny)
  236. maxx_list.append(maxx)
  237. maxy_list.append(maxy)
  238. return(min(minx_list), min(miny_list), max(maxx_list), max(maxy_list))
  239. else:
  240. bounds_coords = bounds_rec(self.solid_geometry)
  241. return bounds_coords
  242. # try:
  243. # # from here: http://rightfootin.blogspot.com/2006/09/more-on-python-flatten.html
  244. # def flatten(l, ltypes=(list, tuple)):
  245. # ltype = type(l)
  246. # l = list(l)
  247. # i = 0
  248. # while i < len(l):
  249. # while isinstance(l[i], ltypes):
  250. # if not l[i]:
  251. # l.pop(i)
  252. # i -= 1
  253. # break
  254. # else:
  255. # l[i:i + 1] = l[i]
  256. # i += 1
  257. # return ltype(l)
  258. #
  259. # log.debug("Geometry->bounds()")
  260. # if self.solid_geometry is None:
  261. # log.debug("solid_geometry is None")
  262. # return 0, 0, 0, 0
  263. #
  264. # if type(self.solid_geometry) is list:
  265. # # TODO: This can be done faster. See comment from Shapely mailing lists.
  266. # if len(self.solid_geometry) == 0:
  267. # log.debug('solid_geometry is empty []')
  268. # return 0, 0, 0, 0
  269. # return cascaded_union(flatten(self.solid_geometry)).bounds
  270. # else:
  271. # return self.solid_geometry.bounds
  272. # except Exception as e:
  273. # self.app.inform.emit("[ERROR_NOTCL] Error cause: %s" % str(e))
  274. # log.debug("Geometry->bounds()")
  275. # if self.solid_geometry is None:
  276. # log.debug("solid_geometry is None")
  277. # return 0, 0, 0, 0
  278. #
  279. # if type(self.solid_geometry) is list:
  280. # # TODO: This can be done faster. See comment from Shapely mailing lists.
  281. # if len(self.solid_geometry) == 0:
  282. # log.debug('solid_geometry is empty []')
  283. # return 0, 0, 0, 0
  284. # return cascaded_union(self.solid_geometry).bounds
  285. # else:
  286. # return self.solid_geometry.bounds
  287. def find_polygon(self, point, geoset=None):
  288. """
  289. Find an object that object.contains(Point(point)) in
  290. poly, which can can be iterable, contain iterable of, or
  291. be itself an implementer of .contains().
  292. :param point: See description
  293. :param geoset: a polygon or list of polygons where to find if the param point is contained
  294. :return: Polygon containing point or None.
  295. """
  296. if geoset is None:
  297. geoset = self.solid_geometry
  298. try: # Iterable
  299. for sub_geo in geoset:
  300. p = self.find_polygon(point, geoset=sub_geo)
  301. if p is not None:
  302. return p
  303. except TypeError: # Non-iterable
  304. try: # Implements .contains()
  305. if isinstance(geoset, LinearRing):
  306. geoset = Polygon(geoset)
  307. if geoset.contains(Point(point)):
  308. return geoset
  309. except AttributeError: # Does not implement .contains()
  310. return None
  311. return None
  312. def get_interiors(self, geometry=None):
  313. interiors = []
  314. if geometry is None:
  315. geometry = self.solid_geometry
  316. # ## If iterable, expand recursively.
  317. try:
  318. for geo in geometry:
  319. interiors.extend(self.get_interiors(geometry=geo))
  320. # ## Not iterable, get the interiors if polygon.
  321. except TypeError:
  322. if type(geometry) == Polygon:
  323. interiors.extend(geometry.interiors)
  324. return interiors
  325. def get_exteriors(self, geometry=None):
  326. """
  327. Returns all exteriors of polygons in geometry. Uses
  328. ``self.solid_geometry`` if geometry is not provided.
  329. :param geometry: Shapely type or list or list of list of such.
  330. :return: List of paths constituting the exteriors
  331. of polygons in geometry.
  332. """
  333. exteriors = []
  334. if geometry is None:
  335. geometry = self.solid_geometry
  336. # ## If iterable, expand recursively.
  337. try:
  338. for geo in geometry:
  339. exteriors.extend(self.get_exteriors(geometry=geo))
  340. # ## Not iterable, get the exterior if polygon.
  341. except TypeError:
  342. if type(geometry) == Polygon:
  343. exteriors.append(geometry.exterior)
  344. return exteriors
  345. def flatten(self, geometry=None, reset=True, pathonly=False):
  346. """
  347. Creates a list of non-iterable linear geometry objects.
  348. Polygons are expanded into its exterior and interiors if specified.
  349. Results are placed in self.flat_geometry
  350. :param geometry: Shapely type or list or list of list of such.
  351. :param reset: Clears the contents of self.flat_geometry.
  352. :param pathonly: Expands polygons into linear elements.
  353. """
  354. if geometry is None:
  355. geometry = self.solid_geometry
  356. if reset:
  357. self.flat_geometry = []
  358. # ## If iterable, expand recursively.
  359. try:
  360. for geo in geometry:
  361. if geo is not None:
  362. self.flatten(geometry=geo,
  363. reset=False,
  364. pathonly=pathonly)
  365. # ## Not iterable, do the actual indexing and add.
  366. except TypeError:
  367. if pathonly and type(geometry) == Polygon:
  368. self.flat_geometry.append(geometry.exterior)
  369. self.flatten(geometry=geometry.interiors,
  370. reset=False,
  371. pathonly=True)
  372. else:
  373. self.flat_geometry.append(geometry)
  374. return self.flat_geometry
  375. # def make2Dstorage(self):
  376. #
  377. # self.flatten()
  378. #
  379. # def get_pts(o):
  380. # pts = []
  381. # if type(o) == Polygon:
  382. # g = o.exterior
  383. # pts += list(g.coords)
  384. # for i in o.interiors:
  385. # pts += list(i.coords)
  386. # else:
  387. # pts += list(o.coords)
  388. # return pts
  389. #
  390. # storage = FlatCAMRTreeStorage()
  391. # storage.get_points = get_pts
  392. # for shape in self.flat_geometry:
  393. # storage.insert(shape)
  394. # return storage
  395. # def flatten_to_paths(self, geometry=None, reset=True):
  396. # """
  397. # Creates a list of non-iterable linear geometry elements and
  398. # indexes them in rtree.
  399. #
  400. # :param geometry: Iterable geometry
  401. # :param reset: Wether to clear (True) or append (False) to self.flat_geometry
  402. # :return: self.flat_geometry, self.flat_geometry_rtree
  403. # """
  404. #
  405. # if geometry is None:
  406. # geometry = self.solid_geometry
  407. #
  408. # if reset:
  409. # self.flat_geometry = []
  410. #
  411. # # ## If iterable, expand recursively.
  412. # try:
  413. # for geo in geometry:
  414. # self.flatten_to_paths(geometry=geo, reset=False)
  415. #
  416. # # ## Not iterable, do the actual indexing and add.
  417. # except TypeError:
  418. # if type(geometry) == Polygon:
  419. # g = geometry.exterior
  420. # self.flat_geometry.append(g)
  421. #
  422. # # ## Add first and last points of the path to the index.
  423. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[0])
  424. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[-1])
  425. #
  426. # for interior in geometry.interiors:
  427. # g = interior
  428. # self.flat_geometry.append(g)
  429. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[0])
  430. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[-1])
  431. # else:
  432. # g = geometry
  433. # self.flat_geometry.append(g)
  434. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[0])
  435. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[-1])
  436. #
  437. # return self.flat_geometry, self.flat_geometry_rtree
  438. def isolation_geometry(self, offset, iso_type=2, corner=None, follow=None, passes=0):
  439. """
  440. Creates contours around geometry at a given
  441. offset distance.
  442. :param offset: Offset distance.
  443. :type offset: float
  444. :param iso_type: type of isolation, can be 0 = exteriors or 1 = interiors or 2 = both (complete)
  445. :param corner: type of corner for the isolation: 0 = round; 1 = square; 2= beveled (line that connects the ends)
  446. :param follow: whether the geometry to be isolated is a follow_geometry
  447. :param passes: current pass out of possible multiple passes for which the isolation is done
  448. :return: The buffered geometry.
  449. :rtype: Shapely.MultiPolygon or Shapely.Polygon
  450. """
  451. if self.app.abort_flag:
  452. # graceful abort requested by the user
  453. raise FlatCAMApp.GracefulException
  454. geo_iso = []
  455. if offset == 0:
  456. if follow:
  457. geo_iso = self.follow_geometry
  458. else:
  459. geo_iso = self.solid_geometry
  460. else:
  461. if follow:
  462. geo_iso = self.follow_geometry
  463. else:
  464. if isinstance(self.solid_geometry, list):
  465. temp_geo = cascaded_union(self.solid_geometry)
  466. else:
  467. temp_geo = self.solid_geometry
  468. # Remember: do not make a buffer for each element in the solid_geometry because it will cut into
  469. # other copper features
  470. # if corner is None:
  471. # geo_iso = temp_geo.buffer(offset, int(int(self.geo_steps_per_circle) / 4))
  472. # else:
  473. # geo_iso = temp_geo.buffer(offset, int(int(self.geo_steps_per_circle) / 4),
  474. # join_style=corner)
  475. # variables to display the percentage of work done
  476. geo_len = 0
  477. try:
  478. for pol in self.solid_geometry:
  479. geo_len += 1
  480. except TypeError:
  481. geo_len = 1
  482. disp_number = 0
  483. old_disp_number = 0
  484. pol_nr = 0
  485. # yet, it can be done by issuing an unary_union in the end, thus getting rid of the overlapping geo
  486. try:
  487. for pol in self.solid_geometry:
  488. if self.app.abort_flag:
  489. # graceful abort requested by the user
  490. raise FlatCAMApp.GracefulException
  491. if corner is None:
  492. geo_iso.append(pol.buffer(offset, int(int(self.geo_steps_per_circle) / 4)))
  493. else:
  494. geo_iso.append(pol.buffer(offset, int(int(self.geo_steps_per_circle) / 4)),
  495. join_style=corner)
  496. pol_nr += 1
  497. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  498. if old_disp_number < disp_number <= 100:
  499. self.app.proc_container.update_view_text(' %s %d: %d%%' %
  500. (_("Pass"), int(passes + 1), int(disp_number)))
  501. old_disp_number = disp_number
  502. except TypeError:
  503. # taking care of the case when the self.solid_geometry is just a single Polygon, not a list or a
  504. # MultiPolygon (not an iterable)
  505. if corner is None:
  506. geo_iso.append(self.solid_geometry.buffer(offset, int(int(self.geo_steps_per_circle) / 4)))
  507. else:
  508. geo_iso.append(self.solid_geometry.buffer(offset, int(int(self.geo_steps_per_circle) / 4)),
  509. join_style=corner)
  510. self.app.proc_container.update_view_text(' %s' % _("Buffering"))
  511. geo_iso = unary_union(geo_iso)
  512. self.app.proc_container.update_view_text('')
  513. # end of replaced block
  514. if follow:
  515. return geo_iso
  516. elif iso_type == 2:
  517. return geo_iso
  518. elif iso_type == 0:
  519. self.app.proc_container.update_view_text(' %s' % _("Get Exteriors"))
  520. return self.get_exteriors(geo_iso)
  521. elif iso_type == 1:
  522. self.app.proc_container.update_view_text(' %s' % _("Get Interiors"))
  523. return self.get_interiors(geo_iso)
  524. else:
  525. log.debug("Geometry.isolation_geometry() --> Type of isolation not supported")
  526. return "fail"
  527. def flatten_list(self, list):
  528. for item in list:
  529. if isinstance(item, Iterable) and not isinstance(item, (str, bytes)):
  530. yield from self.flatten_list(item)
  531. else:
  532. yield item
  533. def import_svg(self, filename, object_type=None, flip=True, units='MM'):
  534. """
  535. Imports shapes from an SVG file into the object's geometry.
  536. :param filename: Path to the SVG file.
  537. :type filename: str
  538. :param object_type: parameter passed further along
  539. :param flip: Flip the vertically.
  540. :type flip: bool
  541. :param units: FlatCAM units
  542. :return: None
  543. """
  544. # Parse into list of shapely objects
  545. svg_tree = ET.parse(filename)
  546. svg_root = svg_tree.getroot()
  547. # Change origin to bottom left
  548. # h = float(svg_root.get('height'))
  549. # w = float(svg_root.get('width'))
  550. h = svgparselength(svg_root.get('height'))[0] # TODO: No units support yet
  551. geos = getsvggeo(svg_root, object_type)
  552. if flip:
  553. geos = [translate(scale(g, 1.0, -1.0, origin=(0, 0)), yoff=h) for g in geos]
  554. # Add to object
  555. if self.solid_geometry is None:
  556. self.solid_geometry = []
  557. if type(self.solid_geometry) is list:
  558. # self.solid_geometry.append(cascaded_union(geos))
  559. if type(geos) is list:
  560. self.solid_geometry += geos
  561. else:
  562. self.solid_geometry.append(geos)
  563. else: # It's shapely geometry
  564. # self.solid_geometry = cascaded_union([self.solid_geometry,
  565. # cascaded_union(geos)])
  566. self.solid_geometry = [self.solid_geometry, geos]
  567. # flatten the self.solid_geometry list for import_svg() to import SVG as Gerber
  568. self.solid_geometry = list(self.flatten_list(self.solid_geometry))
  569. geos_text = getsvgtext(svg_root, object_type, units=units)
  570. if geos_text is not None:
  571. geos_text_f = []
  572. if flip:
  573. # Change origin to bottom left
  574. for i in geos_text:
  575. _, minimy, _, maximy = i.bounds
  576. h2 = (maximy - minimy) * 0.5
  577. geos_text_f.append(translate(scale(i, 1.0, -1.0, origin=(0, 0)), yoff=(h + h2)))
  578. if geos_text_f:
  579. self.solid_geometry = self.solid_geometry + geos_text_f
  580. def import_dxf(self, filename, object_type=None, units='MM'):
  581. """
  582. Imports shapes from an DXF file into the object's geometry.
  583. :param filename: Path to the DXF file.
  584. :type filename: str
  585. :param units: Application units
  586. :type flip: str
  587. :return: None
  588. """
  589. # Parse into list of shapely objects
  590. dxf = ezdxf.readfile(filename)
  591. geos = getdxfgeo(dxf)
  592. # Add to object
  593. if self.solid_geometry is None:
  594. self.solid_geometry = []
  595. if type(self.solid_geometry) is list:
  596. if type(geos) is list:
  597. self.solid_geometry += geos
  598. else:
  599. self.solid_geometry.append(geos)
  600. else: # It's shapely geometry
  601. self.solid_geometry = [self.solid_geometry, geos]
  602. # flatten the self.solid_geometry list for import_dxf() to import DXF as Gerber
  603. self.solid_geometry = list(self.flatten_list(self.solid_geometry))
  604. if self.solid_geometry is not None:
  605. self.solid_geometry = cascaded_union(self.solid_geometry)
  606. else:
  607. return
  608. # commented until this function is ready
  609. # geos_text = getdxftext(dxf, object_type, units=units)
  610. # if geos_text is not None:
  611. # geos_text_f = []
  612. # self.solid_geometry = [self.solid_geometry, geos_text_f]
  613. def import_image(self, filename, flip=True, units='MM', dpi=96, mode='black', mask=[128, 128, 128, 128]):
  614. """
  615. Imports shapes from an IMAGE file into the object's geometry.
  616. :param filename: Path to the IMAGE file.
  617. :type filename: str
  618. :param flip: Flip the object vertically.
  619. :type flip: bool
  620. :param units: FlatCAM units
  621. :param dpi: dots per inch on the imported image
  622. :param mode: how to import the image: as 'black' or 'color'
  623. :param mask: level of detail for the import
  624. :return: None
  625. """
  626. scale_factor = 0.264583333
  627. if units.lower() == 'mm':
  628. scale_factor = 25.4 / dpi
  629. else:
  630. scale_factor = 1 / dpi
  631. geos = []
  632. unscaled_geos = []
  633. with rasterio.open(filename) as src:
  634. # if filename.lower().rpartition('.')[-1] == 'bmp':
  635. # red = green = blue = src.read(1)
  636. # print("BMP")
  637. # elif filename.lower().rpartition('.')[-1] == 'png':
  638. # red, green, blue, alpha = src.read()
  639. # elif filename.lower().rpartition('.')[-1] == 'jpg':
  640. # red, green, blue = src.read()
  641. red = green = blue = src.read(1)
  642. try:
  643. green = src.read(2)
  644. except Exception as e:
  645. pass
  646. try:
  647. blue = src.read(3)
  648. except Exception as e:
  649. pass
  650. if mode == 'black':
  651. mask_setting = red <= mask[0]
  652. total = red
  653. log.debug("Image import as monochrome.")
  654. else:
  655. mask_setting = (red <= mask[1]) + (green <= mask[2]) + (blue <= mask[3])
  656. total = np.zeros(red.shape, dtype=float32)
  657. for band in red, green, blue:
  658. total += band
  659. total /= 3
  660. log.debug("Image import as colored. Thresholds are: R = %s , G = %s, B = %s" %
  661. (str(mask[1]), str(mask[2]), str(mask[3])))
  662. for geom, val in shapes(total, mask=mask_setting):
  663. unscaled_geos.append(shape(geom))
  664. for g in unscaled_geos:
  665. geos.append(scale(g, scale_factor, scale_factor, origin=(0, 0)))
  666. if flip:
  667. geos = [translate(scale(g, 1.0, -1.0, origin=(0, 0))) for g in geos]
  668. # Add to object
  669. if self.solid_geometry is None:
  670. self.solid_geometry = []
  671. if type(self.solid_geometry) is list:
  672. # self.solid_geometry.append(cascaded_union(geos))
  673. if type(geos) is list:
  674. self.solid_geometry += geos
  675. else:
  676. self.solid_geometry.append(geos)
  677. else: # It's shapely geometry
  678. self.solid_geometry = [self.solid_geometry, geos]
  679. # flatten the self.solid_geometry list for import_svg() to import SVG as Gerber
  680. self.solid_geometry = list(self.flatten_list(self.solid_geometry))
  681. self.solid_geometry = cascaded_union(self.solid_geometry)
  682. # self.solid_geometry = MultiPolygon(self.solid_geometry)
  683. # self.solid_geometry = self.solid_geometry.buffer(0.00000001)
  684. # self.solid_geometry = self.solid_geometry.buffer(-0.00000001)
  685. def size(self):
  686. """
  687. Returns (width, height) of rectangular
  688. bounds of geometry.
  689. """
  690. if self.solid_geometry is None:
  691. log.warning("Solid_geometry not computed yet.")
  692. return 0
  693. bounds = self.bounds()
  694. return bounds[2] - bounds[0], bounds[3] - bounds[1]
  695. def get_empty_area(self, boundary=None):
  696. """
  697. Returns the complement of self.solid_geometry within
  698. the given boundary polygon. If not specified, it defaults to
  699. the rectangular bounding box of self.solid_geometry.
  700. """
  701. if boundary is None:
  702. boundary = self.solid_geometry.envelope
  703. return boundary.difference(self.solid_geometry)
  704. def clear_polygon(self, polygon, tooldia, steps_per_circle, overlap=0.15, connect=True, contour=True,
  705. prog_plot=False):
  706. """
  707. Creates geometry inside a polygon for a tool to cover
  708. the whole area.
  709. This algorithm shrinks the edges of the polygon and takes
  710. the resulting edges as toolpaths.
  711. :param polygon: Polygon to clear.
  712. :param tooldia: Diameter of the tool.
  713. :param steps_per_circle: number of linear segments to be used to approximate a circle
  714. :param overlap: Overlap of toolpasses.
  715. :param connect: Draw lines between disjoint segments to
  716. minimize tool lifts.
  717. :param contour: Paint around the edges. Inconsequential in
  718. this painting method.
  719. :param prog_plot: boolean; if Ture use the progressive plotting
  720. :return:
  721. """
  722. # log.debug("camlib.clear_polygon()")
  723. assert type(polygon) == Polygon or type(polygon) == MultiPolygon, \
  724. "Expected a Polygon or MultiPolygon, got %s" % type(polygon)
  725. # ## The toolpaths
  726. # Index first and last points in paths
  727. def get_pts(o):
  728. return [o.coords[0], o.coords[-1]]
  729. geoms = FlatCAMRTreeStorage()
  730. geoms.get_points = get_pts
  731. # Can only result in a Polygon or MultiPolygon
  732. # NOTE: The resulting polygon can be "empty".
  733. current = polygon.buffer((-tooldia / 1.999999), int(int(steps_per_circle) / 4))
  734. if current.area == 0:
  735. # Otherwise, trying to to insert current.exterior == None
  736. # into the FlatCAMStorage will fail.
  737. # print("Area is None")
  738. return None
  739. # current can be a MultiPolygon
  740. try:
  741. for p in current:
  742. geoms.insert(p.exterior)
  743. for i in p.interiors:
  744. geoms.insert(i)
  745. # Not a Multipolygon. Must be a Polygon
  746. except TypeError:
  747. geoms.insert(current.exterior)
  748. for i in current.interiors:
  749. geoms.insert(i)
  750. while True:
  751. if self.app.abort_flag:
  752. # graceful abort requested by the user
  753. raise FlatCAMApp.GracefulException
  754. # Can only result in a Polygon or MultiPolygon
  755. current = current.buffer(-tooldia * (1 - overlap), int(int(steps_per_circle) / 4))
  756. if current.area > 0:
  757. # current can be a MultiPolygon
  758. try:
  759. for p in current:
  760. geoms.insert(p.exterior)
  761. for i in p.interiors:
  762. geoms.insert(i)
  763. if prog_plot:
  764. self.plot_temp_shapes(p)
  765. # Not a Multipolygon. Must be a Polygon
  766. except TypeError:
  767. geoms.insert(current.exterior)
  768. if prog_plot:
  769. self.plot_temp_shapes(current.exterior)
  770. for i in current.interiors:
  771. geoms.insert(i)
  772. if prog_plot:
  773. self.plot_temp_shapes(i)
  774. else:
  775. log.debug("camlib.Geometry.clear_polygon() --> Current Area is zero")
  776. break
  777. if prog_plot:
  778. self.temp_shapes.redraw()
  779. # Optimization: Reduce lifts
  780. if connect:
  781. # log.debug("Reducing tool lifts...")
  782. geoms = Geometry.paint_connect(geoms, polygon, tooldia, int(steps_per_circle))
  783. return geoms
  784. def clear_polygon2(self, polygon_to_clear, tooldia, steps_per_circle, seedpoint=None, overlap=0.15,
  785. connect=True, contour=True, prog_plot=False):
  786. """
  787. Creates geometry inside a polygon for a tool to cover
  788. the whole area.
  789. This algorithm starts with a seed point inside the polygon
  790. and draws circles around it. Arcs inside the polygons are
  791. valid cuts. Finalizes by cutting around the inside edge of
  792. the polygon.
  793. :param polygon_to_clear: Shapely.geometry.Polygon
  794. :param steps_per_circle: how many linear segments to use to approximate a circle
  795. :param tooldia: Diameter of the tool
  796. :param seedpoint: Shapely.geometry.Point or None
  797. :param overlap: Tool fraction overlap bewteen passes
  798. :param connect: Connect disjoint segment to minumize tool lifts
  799. :param contour: Cut countour inside the polygon.
  800. :return: List of toolpaths covering polygon.
  801. :rtype: FlatCAMRTreeStorage | None
  802. :param prog_plot: boolean; if True use the progressive plotting
  803. """
  804. # log.debug("camlib.clear_polygon2()")
  805. # Current buffer radius
  806. radius = tooldia / 2 * (1 - overlap)
  807. # ## The toolpaths
  808. # Index first and last points in paths
  809. def get_pts(o):
  810. return [o.coords[0], o.coords[-1]]
  811. geoms = FlatCAMRTreeStorage()
  812. geoms.get_points = get_pts
  813. # Path margin
  814. path_margin = polygon_to_clear.buffer(-tooldia / 2, int(steps_per_circle / 4))
  815. if path_margin.is_empty or path_margin is None:
  816. return
  817. # Estimate good seedpoint if not provided.
  818. if seedpoint is None:
  819. seedpoint = path_margin.representative_point()
  820. # Grow from seed until outside the box. The polygons will
  821. # never have an interior, so take the exterior LinearRing.
  822. while True:
  823. if self.app.abort_flag:
  824. # graceful abort requested by the user
  825. raise FlatCAMApp.GracefulException
  826. path = Point(seedpoint).buffer(radius, int(steps_per_circle / 4)).exterior
  827. path = path.intersection(path_margin)
  828. # Touches polygon?
  829. if path.is_empty:
  830. break
  831. else:
  832. # geoms.append(path)
  833. # geoms.insert(path)
  834. # path can be a collection of paths.
  835. try:
  836. for p in path:
  837. geoms.insert(p)
  838. if prog_plot:
  839. self.plot_temp_shapes(p)
  840. except TypeError:
  841. geoms.insert(path)
  842. if prog_plot:
  843. self.plot_temp_shapes(path)
  844. if prog_plot:
  845. self.temp_shapes.redraw()
  846. radius += tooldia * (1 - overlap)
  847. # Clean inside edges (contours) of the original polygon
  848. if contour:
  849. outer_edges = [x.exterior for x in autolist(
  850. polygon_to_clear.buffer(-tooldia / 2, int(steps_per_circle / 4)))]
  851. inner_edges = []
  852. # Over resulting polygons
  853. for x in autolist(polygon_to_clear.buffer(-tooldia / 2, int(steps_per_circle / 4))):
  854. for y in x.interiors: # Over interiors of each polygon
  855. inner_edges.append(y)
  856. # geoms += outer_edges + inner_edges
  857. for g in outer_edges + inner_edges:
  858. geoms.insert(g)
  859. if prog_plot:
  860. self.plot_temp_shapes(g)
  861. if prog_plot:
  862. self.temp_shapes.redraw()
  863. # Optimization connect touching paths
  864. # log.debug("Connecting paths...")
  865. # geoms = Geometry.path_connect(geoms)
  866. # Optimization: Reduce lifts
  867. if connect:
  868. # log.debug("Reducing tool lifts...")
  869. geoms = Geometry.paint_connect(geoms, polygon_to_clear, tooldia, steps_per_circle)
  870. return geoms
  871. def clear_polygon3(self, polygon, tooldia, steps_per_circle, overlap=0.15, connect=True, contour=True,
  872. prog_plot=False):
  873. """
  874. Creates geometry inside a polygon for a tool to cover
  875. the whole area.
  876. This algorithm draws horizontal lines inside the polygon.
  877. :param polygon: The polygon being painted.
  878. :type polygon: shapely.geometry.Polygon
  879. :param tooldia: Tool diameter.
  880. :param steps_per_circle: how many linear segments to use to approximate a circle
  881. :param overlap: Tool path overlap percentage.
  882. :param connect: Connect lines to avoid tool lifts.
  883. :param contour: Paint around the edges.
  884. :param prog_plot: boolean; if to use the progressive plotting
  885. :return:
  886. """
  887. # log.debug("camlib.clear_polygon3()")
  888. # ## The toolpaths
  889. # Index first and last points in paths
  890. def get_pts(o):
  891. return [o.coords[0], o.coords[-1]]
  892. geoms = FlatCAMRTreeStorage()
  893. geoms.get_points = get_pts
  894. lines_trimmed = []
  895. # Bounding box
  896. left, bot, right, top = polygon.bounds
  897. margin_poly = polygon.buffer(-tooldia / 1.99999999, (int(steps_per_circle)))
  898. # First line
  899. y = top - tooldia / 1.99999999
  900. while y > bot + tooldia / 1.999999999:
  901. if self.app.abort_flag:
  902. # graceful abort requested by the user
  903. raise FlatCAMApp.GracefulException
  904. line = LineString([(left, y), (right, y)])
  905. line = line.intersection(margin_poly)
  906. lines_trimmed.append(line)
  907. y -= tooldia * (1 - overlap)
  908. if prog_plot:
  909. self.plot_temp_shapes(line)
  910. self.temp_shapes.redraw()
  911. # Last line
  912. y = bot + tooldia / 2
  913. line = LineString([(left, y), (right, y)])
  914. line = line.intersection(margin_poly)
  915. for ll in line:
  916. lines_trimmed.append(ll)
  917. if prog_plot:
  918. self.plot_temp_shapes(line)
  919. # Combine
  920. # linesgeo = unary_union(lines)
  921. # Trim to the polygon
  922. # margin_poly = polygon.buffer(-tooldia / 1.99999999, (int(steps_per_circle)))
  923. # lines_trimmed = linesgeo.intersection(margin_poly)
  924. if prog_plot:
  925. self.temp_shapes.redraw()
  926. lines_trimmed = unary_union(lines_trimmed)
  927. # Add lines to storage
  928. try:
  929. for line in lines_trimmed:
  930. geoms.insert(line)
  931. except TypeError:
  932. # in case lines_trimmed are not iterable (Linestring, LinearRing)
  933. geoms.insert(lines_trimmed)
  934. # Add margin (contour) to storage
  935. if contour:
  936. if isinstance(margin_poly, Polygon):
  937. geoms.insert(margin_poly.exterior)
  938. if prog_plot:
  939. self.plot_temp_shapes(margin_poly.exterior)
  940. for ints in margin_poly.interiors:
  941. geoms.insert(ints)
  942. if prog_plot:
  943. self.plot_temp_shapes(ints)
  944. elif isinstance(margin_poly, MultiPolygon):
  945. for poly in margin_poly:
  946. geoms.insert(poly.exterior)
  947. if prog_plot:
  948. self.plot_temp_shapes(poly.exterior)
  949. for ints in poly.interiors:
  950. geoms.insert(ints)
  951. if prog_plot:
  952. self.plot_temp_shapes(ints)
  953. if prog_plot:
  954. self.temp_shapes.redraw()
  955. # Optimization: Reduce lifts
  956. if connect:
  957. # log.debug("Reducing tool lifts...")
  958. geoms = Geometry.paint_connect(geoms, polygon, tooldia, steps_per_circle)
  959. return geoms
  960. def scale(self, xfactor, yfactor, point=None):
  961. """
  962. Scales all of the object's geometry by a given factor. Override
  963. this method.
  964. :param xfactor: Number by which to scale on X axis.
  965. :type xfactor: float
  966. :param yfactor: Number by which to scale on Y axis.
  967. :type yfactor: float
  968. :param point: point to be used as reference for scaling; a tuple
  969. :return: None
  970. :rtype: None
  971. """
  972. return
  973. def offset(self, vect):
  974. """
  975. Offset the geometry by the given vector. Override this method.
  976. :param vect: (x, y) vector by which to offset the object.
  977. :type vect: tuple
  978. :return: None
  979. """
  980. return
  981. @staticmethod
  982. def paint_connect(storage, boundary, tooldia, steps_per_circle, max_walk=None):
  983. """
  984. Connects paths that results in a connection segment that is
  985. within the paint area. This avoids unnecessary tool lifting.
  986. :param storage: Geometry to be optimized.
  987. :type storage: FlatCAMRTreeStorage
  988. :param boundary: Polygon defining the limits of the paintable area.
  989. :type boundary: Polygon
  990. :param tooldia: Tool diameter.
  991. :rtype tooldia: float
  992. :param steps_per_circle: how many linear segments to use to approximate a circle
  993. :param max_walk: Maximum allowable distance without lifting tool.
  994. :type max_walk: float or None
  995. :return: Optimized geometry.
  996. :rtype: FlatCAMRTreeStorage
  997. """
  998. # If max_walk is not specified, the maximum allowed is
  999. # 10 times the tool diameter
  1000. max_walk = max_walk or 10 * tooldia
  1001. # Assuming geolist is a flat list of flat elements
  1002. # ## Index first and last points in paths
  1003. def get_pts(o):
  1004. return [o.coords[0], o.coords[-1]]
  1005. # storage = FlatCAMRTreeStorage()
  1006. # storage.get_points = get_pts
  1007. #
  1008. # for shape in geolist:
  1009. # if shape is not None: # TODO: This shouldn't have happened.
  1010. # # Make LlinearRings into linestrings otherwise
  1011. # # When chaining the coordinates path is messed up.
  1012. # storage.insert(LineString(shape))
  1013. # #storage.insert(shape)
  1014. # ## Iterate over geometry paths getting the nearest each time.
  1015. #optimized_paths = []
  1016. optimized_paths = FlatCAMRTreeStorage()
  1017. optimized_paths.get_points = get_pts
  1018. path_count = 0
  1019. current_pt = (0, 0)
  1020. pt, geo = storage.nearest(current_pt)
  1021. storage.remove(geo)
  1022. geo = LineString(geo)
  1023. current_pt = geo.coords[-1]
  1024. try:
  1025. while True:
  1026. path_count += 1
  1027. # log.debug("Path %d" % path_count)
  1028. pt, candidate = storage.nearest(current_pt)
  1029. storage.remove(candidate)
  1030. candidate = LineString(candidate)
  1031. # If last point in geometry is the nearest
  1032. # then reverse coordinates.
  1033. # but prefer the first one if last == first
  1034. if pt != candidate.coords[0] and pt == candidate.coords[-1]:
  1035. candidate.coords = list(candidate.coords)[::-1]
  1036. # Straight line from current_pt to pt.
  1037. # Is the toolpath inside the geometry?
  1038. walk_path = LineString([current_pt, pt])
  1039. walk_cut = walk_path.buffer(tooldia / 2, int(steps_per_circle / 4))
  1040. if walk_cut.within(boundary) and walk_path.length < max_walk:
  1041. # log.debug("Walk to path #%d is inside. Joining." % path_count)
  1042. # Completely inside. Append...
  1043. geo.coords = list(geo.coords) + list(candidate.coords)
  1044. # try:
  1045. # last = optimized_paths[-1]
  1046. # last.coords = list(last.coords) + list(geo.coords)
  1047. # except IndexError:
  1048. # optimized_paths.append(geo)
  1049. else:
  1050. # Have to lift tool. End path.
  1051. # log.debug("Path #%d not within boundary. Next." % path_count)
  1052. # optimized_paths.append(geo)
  1053. optimized_paths.insert(geo)
  1054. geo = candidate
  1055. current_pt = geo.coords[-1]
  1056. # Next
  1057. # pt, geo = storage.nearest(current_pt)
  1058. except StopIteration: # Nothing left in storage.
  1059. # pass
  1060. optimized_paths.insert(geo)
  1061. return optimized_paths
  1062. @staticmethod
  1063. def path_connect(storage, origin=(0, 0)):
  1064. """
  1065. Simplifies paths in the FlatCAMRTreeStorage storage by
  1066. connecting paths that touch on their enpoints.
  1067. :param storage: Storage containing the initial paths.
  1068. :rtype storage: FlatCAMRTreeStorage
  1069. :return: Simplified storage.
  1070. :rtype: FlatCAMRTreeStorage
  1071. """
  1072. log.debug("path_connect()")
  1073. # ## Index first and last points in paths
  1074. def get_pts(o):
  1075. return [o.coords[0], o.coords[-1]]
  1076. #
  1077. # storage = FlatCAMRTreeStorage()
  1078. # storage.get_points = get_pts
  1079. #
  1080. # for shape in pathlist:
  1081. # if shape is not None: # TODO: This shouldn't have happened.
  1082. # storage.insert(shape)
  1083. path_count = 0
  1084. pt, geo = storage.nearest(origin)
  1085. storage.remove(geo)
  1086. # optimized_geometry = [geo]
  1087. optimized_geometry = FlatCAMRTreeStorage()
  1088. optimized_geometry.get_points = get_pts
  1089. # optimized_geometry.insert(geo)
  1090. try:
  1091. while True:
  1092. path_count += 1
  1093. _, left = storage.nearest(geo.coords[0])
  1094. # If left touches geo, remove left from original
  1095. # storage and append to geo.
  1096. if type(left) == LineString:
  1097. if left.coords[0] == geo.coords[0]:
  1098. storage.remove(left)
  1099. geo.coords = list(geo.coords)[::-1] + list(left.coords)
  1100. continue
  1101. if left.coords[-1] == geo.coords[0]:
  1102. storage.remove(left)
  1103. geo.coords = list(left.coords) + list(geo.coords)
  1104. continue
  1105. if left.coords[0] == geo.coords[-1]:
  1106. storage.remove(left)
  1107. geo.coords = list(geo.coords) + list(left.coords)
  1108. continue
  1109. if left.coords[-1] == geo.coords[-1]:
  1110. storage.remove(left)
  1111. geo.coords = list(geo.coords) + list(left.coords)[::-1]
  1112. continue
  1113. _, right = storage.nearest(geo.coords[-1])
  1114. # If right touches geo, remove left from original
  1115. # storage and append to geo.
  1116. if type(right) == LineString:
  1117. if right.coords[0] == geo.coords[-1]:
  1118. storage.remove(right)
  1119. geo.coords = list(geo.coords) + list(right.coords)
  1120. continue
  1121. if right.coords[-1] == geo.coords[-1]:
  1122. storage.remove(right)
  1123. geo.coords = list(geo.coords) + list(right.coords)[::-1]
  1124. continue
  1125. if right.coords[0] == geo.coords[0]:
  1126. storage.remove(right)
  1127. geo.coords = list(geo.coords)[::-1] + list(right.coords)
  1128. continue
  1129. if right.coords[-1] == geo.coords[0]:
  1130. storage.remove(right)
  1131. geo.coords = list(left.coords) + list(geo.coords)
  1132. continue
  1133. # right is either a LinearRing or it does not connect
  1134. # to geo (nothing left to connect to geo), so we continue
  1135. # with right as geo.
  1136. storage.remove(right)
  1137. if type(right) == LinearRing:
  1138. optimized_geometry.insert(right)
  1139. else:
  1140. # Cannot extend geo any further. Put it away.
  1141. optimized_geometry.insert(geo)
  1142. # Continue with right.
  1143. geo = right
  1144. except StopIteration: # Nothing found in storage.
  1145. optimized_geometry.insert(geo)
  1146. # print path_count
  1147. log.debug("path_count = %d" % path_count)
  1148. return optimized_geometry
  1149. def convert_units(self, units):
  1150. """
  1151. Converts the units of the object to ``units`` by scaling all
  1152. the geometry appropriately. This call ``scale()``. Don't call
  1153. it again in descendents.
  1154. :param units: "IN" or "MM"
  1155. :type units: str
  1156. :return: Scaling factor resulting from unit change.
  1157. :rtype: float
  1158. """
  1159. log.debug("camlib.Geometry.convert_units()")
  1160. if units.upper() == self.units.upper():
  1161. return 1.0
  1162. if units.upper() == "MM":
  1163. factor = 25.4
  1164. elif units.upper() == "IN":
  1165. factor = 1 / 25.4
  1166. else:
  1167. log.error("Unsupported units: %s" % str(units))
  1168. return 1.0
  1169. self.units = units
  1170. self.scale(factor, factor)
  1171. self.file_units_factor = factor
  1172. return factor
  1173. def to_dict(self):
  1174. """
  1175. Returns a representation of the object as a dictionary.
  1176. Attributes to include are listed in ``self.ser_attrs``.
  1177. :return: A dictionary-encoded copy of the object.
  1178. :rtype: dict
  1179. """
  1180. d = {}
  1181. for attr in self.ser_attrs:
  1182. d[attr] = getattr(self, attr)
  1183. return d
  1184. def from_dict(self, d):
  1185. """
  1186. Sets object's attributes from a dictionary.
  1187. Attributes to include are listed in ``self.ser_attrs``.
  1188. This method will look only for only and all the
  1189. attributes in ``self.ser_attrs``. They must all
  1190. be present. Use only for deserializing saved
  1191. objects.
  1192. :param d: Dictionary of attributes to set in the object.
  1193. :type d: dict
  1194. :return: None
  1195. """
  1196. for attr in self.ser_attrs:
  1197. setattr(self, attr, d[attr])
  1198. def union(self):
  1199. """
  1200. Runs a cascaded union on the list of objects in
  1201. solid_geometry.
  1202. :return: None
  1203. """
  1204. self.solid_geometry = [cascaded_union(self.solid_geometry)]
  1205. def export_svg(self, scale_factor=0.00):
  1206. """
  1207. Exports the Geometry Object as a SVG Element
  1208. :return: SVG Element
  1209. """
  1210. # Make sure we see a Shapely Geometry class and not a list
  1211. if str(type(self)) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  1212. flat_geo = []
  1213. if self.multigeo:
  1214. for tool in self.tools:
  1215. flat_geo += self.flatten(self.tools[tool]['solid_geometry'])
  1216. geom = cascaded_union(flat_geo)
  1217. else:
  1218. geom = cascaded_union(self.flatten())
  1219. else:
  1220. geom = cascaded_union(self.flatten())
  1221. # scale_factor is a multiplication factor for the SVG stroke-width used within shapely's svg export
  1222. # If 0 or less which is invalid then default to 0.05
  1223. # This value appears to work for zooming, and getting the output svg line width
  1224. # to match that viewed on screen with FlatCam
  1225. # MS: I choose a factor of 0.01 so the scale is right for PCB UV film
  1226. if scale_factor <= 0:
  1227. scale_factor = 0.01
  1228. # Convert to a SVG
  1229. svg_elem = geom.svg(scale_factor=scale_factor)
  1230. return svg_elem
  1231. def mirror(self, axis, point):
  1232. """
  1233. Mirrors the object around a specified axis passign through
  1234. the given point.
  1235. :param axis: "X" or "Y" indicates around which axis to mirror.
  1236. :type axis: str
  1237. :param point: [x, y] point belonging to the mirror axis.
  1238. :type point: list
  1239. :return: None
  1240. """
  1241. log.debug("camlib.Geometry.mirror()")
  1242. px, py = point
  1243. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  1244. def mirror_geom(obj):
  1245. if type(obj) is list:
  1246. new_obj = []
  1247. for g in obj:
  1248. new_obj.append(mirror_geom(g))
  1249. return new_obj
  1250. else:
  1251. try:
  1252. self.el_count += 1
  1253. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  1254. if self.old_disp_number < disp_number <= 100:
  1255. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1256. self.old_disp_number = disp_number
  1257. return affinity.scale(obj, xscale, yscale, origin=(px, py))
  1258. except AttributeError:
  1259. return obj
  1260. try:
  1261. if self.multigeo is True:
  1262. for tool in self.tools:
  1263. # variables to display the percentage of work done
  1264. self.geo_len = 0
  1265. try:
  1266. for g in self.tools[tool]['solid_geometry']:
  1267. self.geo_len += 1
  1268. except TypeError:
  1269. self.geo_len = 1
  1270. self.old_disp_number = 0
  1271. self.el_count = 0
  1272. self.tools[tool]['solid_geometry'] = mirror_geom(self.tools[tool]['solid_geometry'])
  1273. else:
  1274. # variables to display the percentage of work done
  1275. self.geo_len = 0
  1276. try:
  1277. for g in self.solid_geometry:
  1278. self.geo_len += 1
  1279. except TypeError:
  1280. self.geo_len = 1
  1281. self.old_disp_number = 0
  1282. self.el_count = 0
  1283. self.solid_geometry = mirror_geom(self.solid_geometry)
  1284. self.app.inform.emit('[success] %s...' %
  1285. _('Object was mirrored'))
  1286. except AttributeError:
  1287. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1288. _("Failed to mirror. No object selected"))
  1289. self.app.proc_container.new_text = ''
  1290. def rotate(self, angle, point):
  1291. """
  1292. Rotate an object by an angle (in degrees) around the provided coordinates.
  1293. Parameters
  1294. ----------
  1295. The angle of rotation are specified in degrees (default). Positive angles are
  1296. counter-clockwise and negative are clockwise rotations.
  1297. The point of origin can be a keyword 'center' for the bounding box
  1298. center (default), 'centroid' for the geometry's centroid, a Point object
  1299. or a coordinate tuple (x0, y0).
  1300. See shapely manual for more information:
  1301. http://toblerity.org/shapely/manual.html#affine-transformations
  1302. """
  1303. log.debug("camlib.Geometry.rotate()")
  1304. px, py = point
  1305. def rotate_geom(obj):
  1306. if type(obj) is list:
  1307. new_obj = []
  1308. for g in obj:
  1309. new_obj.append(rotate_geom(g))
  1310. return new_obj
  1311. else:
  1312. try:
  1313. self.el_count += 1
  1314. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  1315. if self.old_disp_number < disp_number <= 100:
  1316. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1317. self.old_disp_number = disp_number
  1318. return affinity.rotate(obj, angle, origin=(px, py))
  1319. except AttributeError:
  1320. return obj
  1321. try:
  1322. if self.multigeo is True:
  1323. for tool in self.tools:
  1324. # variables to display the percentage of work done
  1325. self.geo_len = 0
  1326. try:
  1327. for g in self.tools[tool]['solid_geometry']:
  1328. self.geo_len += 1
  1329. except TypeError:
  1330. self.geo_len = 1
  1331. self.old_disp_number = 0
  1332. self.el_count = 0
  1333. self.tools[tool]['solid_geometry'] = rotate_geom(self.tools[tool]['solid_geometry'])
  1334. else:
  1335. # variables to display the percentage of work done
  1336. self.geo_len = 0
  1337. try:
  1338. for g in self.solid_geometry:
  1339. self.geo_len += 1
  1340. except TypeError:
  1341. self.geo_len = 1
  1342. self.old_disp_number = 0
  1343. self.el_count = 0
  1344. self.solid_geometry = rotate_geom(self.solid_geometry)
  1345. self.app.inform.emit('[success] %s...' %
  1346. _('Object was rotated'))
  1347. except AttributeError:
  1348. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1349. _("Failed to rotate. No object selected"))
  1350. self.app.proc_container.new_text = ''
  1351. def skew(self, angle_x, angle_y, point):
  1352. """
  1353. Shear/Skew the geometries of an object by angles along x and y dimensions.
  1354. Parameters
  1355. ----------
  1356. angle_x, angle_y : float, float
  1357. The shear angle(s) for the x and y axes respectively. These can be
  1358. specified in either degrees (default) or radians by setting
  1359. use_radians=True.
  1360. point: tuple of coordinates (x,y)
  1361. See shapely manual for more information:
  1362. http://toblerity.org/shapely/manual.html#affine-transformations
  1363. """
  1364. log.debug("camlib.Geometry.skew()")
  1365. px, py = point
  1366. def skew_geom(obj):
  1367. if type(obj) is list:
  1368. new_obj = []
  1369. for g in obj:
  1370. new_obj.append(skew_geom(g))
  1371. return new_obj
  1372. else:
  1373. try:
  1374. self.el_count += 1
  1375. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  1376. if self.old_disp_number < disp_number <= 100:
  1377. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1378. self.old_disp_number = disp_number
  1379. return affinity.skew(obj, angle_x, angle_y, origin=(px, py))
  1380. except AttributeError:
  1381. return obj
  1382. try:
  1383. if self.multigeo is True:
  1384. for tool in self.tools:
  1385. # variables to display the percentage of work done
  1386. self.geo_len = 0
  1387. try:
  1388. for g in self.tools[tool]['solid_geometry']:
  1389. self.geo_len += 1
  1390. except TypeError:
  1391. self.geo_len = 1
  1392. self.old_disp_number = 0
  1393. self.el_count = 0
  1394. self.tools[tool]['solid_geometry'] = skew_geom(self.tools[tool]['solid_geometry'])
  1395. else:
  1396. # variables to display the percentage of work done
  1397. self.geo_len = 0
  1398. try:
  1399. for g in self.solid_geometry:
  1400. self.geo_len += 1
  1401. except TypeError:
  1402. self.geo_len = 1
  1403. self.old_disp_number = 0
  1404. self.el_count = 0
  1405. self.solid_geometry = skew_geom(self.solid_geometry)
  1406. self.app.inform.emit('[success] %s...' %
  1407. _('Object was skewed'))
  1408. except AttributeError:
  1409. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1410. _("Failed to skew. No object selected"))
  1411. self.app.proc_container.new_text = ''
  1412. # if type(self.solid_geometry) == list:
  1413. # self.solid_geometry = [affinity.skew(g, angle_x, angle_y, origin=(px, py))
  1414. # for g in self.solid_geometry]
  1415. # else:
  1416. # self.solid_geometry = affinity.skew(self.solid_geometry, angle_x, angle_y,
  1417. # origin=(px, py))
  1418. class AttrDict(dict):
  1419. def __init__(self, *args, **kwargs):
  1420. super(AttrDict, self).__init__(*args, **kwargs)
  1421. self.__dict__ = self
  1422. class CNCjob(Geometry):
  1423. """
  1424. Represents work to be done by a CNC machine.
  1425. *ATTRIBUTES*
  1426. * ``gcode_parsed`` (list): Each is a dictionary:
  1427. ===================== =========================================
  1428. Key Value
  1429. ===================== =========================================
  1430. geom (Shapely.LineString) Tool path (XY plane)
  1431. kind (string) "AB", A is "T" (travel) or
  1432. "C" (cut). B is "F" (fast) or "S" (slow).
  1433. ===================== =========================================
  1434. """
  1435. defaults = {
  1436. "global_zdownrate": None,
  1437. "pp_geometry_name":'default',
  1438. "pp_excellon_name":'default',
  1439. "excellon_optimization_type": "B",
  1440. }
  1441. def __init__(self,
  1442. units="in", kind="generic", tooldia=0.0,
  1443. z_cut=-0.002, z_move=0.1,
  1444. feedrate=3.0, feedrate_z=3.0, feedrate_rapid=3.0, feedrate_probe=3.0,
  1445. pp_geometry_name='default', pp_excellon_name='default',
  1446. depthpercut=0.1,z_pdepth=-0.02,
  1447. spindlespeed=None, spindledir='CW', dwell=True, dwelltime=1000,
  1448. toolchangez=0.787402, toolchange_xy=[0.0, 0.0],
  1449. endz=2.0,
  1450. segx=None,
  1451. segy=None,
  1452. steps_per_circle=None):
  1453. # Used when parsing G-code arcs
  1454. self.steps_per_circle = int(self.app.defaults['cncjob_steps_per_circle'])
  1455. Geometry.__init__(self, geo_steps_per_circle=self.steps_per_circle)
  1456. self.kind = kind
  1457. self.origin_kind = None
  1458. self.units = units
  1459. self.z_cut = z_cut
  1460. self.tool_offset = {}
  1461. self.z_move = z_move
  1462. self.feedrate = feedrate
  1463. self.z_feedrate = feedrate_z
  1464. self.feedrate_rapid = feedrate_rapid
  1465. self.tooldia = tooldia
  1466. self.z_toolchange = toolchangez
  1467. self.xy_toolchange = toolchange_xy
  1468. self.toolchange_xy_type = None
  1469. self.toolC = tooldia
  1470. self.z_end = endz
  1471. self.z_depthpercut = depthpercut
  1472. self.unitcode = {"IN": "G20", "MM": "G21"}
  1473. self.feedminutecode = "G94"
  1474. # self.absolutecode = "G90"
  1475. # self.incrementalcode = "G91"
  1476. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  1477. self.gcode = ""
  1478. self.gcode_parsed = None
  1479. self.pp_geometry_name = pp_geometry_name
  1480. self.pp_geometry = self.app.postprocessors[self.pp_geometry_name]
  1481. self.pp_excellon_name = pp_excellon_name
  1482. self.pp_excellon = self.app.postprocessors[self.pp_excellon_name]
  1483. self.pp_solderpaste_name = None
  1484. # Controls if the move from Z_Toolchange to Z_Move is done fast with G0 or normally with G1
  1485. self.f_plunge = None
  1486. # Controls if the move from Z_Cutto Z_Move is done fast with G0 or G1 until zero and then G0 to Z_move
  1487. self.f_retract = None
  1488. # how much depth the probe can probe before error
  1489. self.z_pdepth = z_pdepth if z_pdepth else None
  1490. # the feedrate(speed) with which the probel travel while probing
  1491. self.feedrate_probe = feedrate_probe if feedrate_probe else None
  1492. self.spindlespeed = spindlespeed
  1493. self.spindledir = spindledir
  1494. self.dwell = dwell
  1495. self.dwelltime = dwelltime
  1496. self.segx = float(segx) if segx is not None else 0.0
  1497. self.segy = float(segy) if segy is not None else 0.0
  1498. self.input_geometry_bounds = None
  1499. self.oldx = None
  1500. self.oldy = None
  1501. self.tool = 0.0
  1502. # here store the travelled distance
  1503. self.travel_distance = 0.0
  1504. # here store the routing time
  1505. self.routing_time = 0.0
  1506. # used for creating drill CCode geometry; will be updated in the generate_from_excellon_by_tool()
  1507. self.exc_drills = None
  1508. self.exc_tools = None
  1509. # search for toolchange parameters in the Toolchange Custom Code
  1510. self.re_toolchange_custom = re.compile(r'(%[a-zA-Z0-9\-_]+%)')
  1511. # search for toolchange code: M6
  1512. self.re_toolchange = re.compile(r'^\s*(M6)$')
  1513. # Attributes to be included in serialization
  1514. # Always append to it because it carries contents
  1515. # from Geometry.
  1516. self.ser_attrs += ['kind', 'z_cut', 'z_move', 'z_toolchange', 'feedrate', 'z_feedrate', 'feedrate_rapid',
  1517. 'tooldia', 'gcode', 'input_geometry_bounds', 'gcode_parsed', 'steps_per_circle',
  1518. 'z_depthpercut', 'spindlespeed', 'dwell', 'dwelltime']
  1519. @property
  1520. def postdata(self):
  1521. return self.__dict__
  1522. def convert_units(self, units):
  1523. log.debug("camlib.CNCJob.convert_units()")
  1524. factor = Geometry.convert_units(self, units)
  1525. self.z_cut = float(self.z_cut) * factor
  1526. self.z_move *= factor
  1527. self.feedrate *= factor
  1528. self.z_feedrate *= factor
  1529. self.feedrate_rapid *= factor
  1530. self.tooldia *= factor
  1531. self.z_toolchange *= factor
  1532. self.z_end *= factor
  1533. self.z_depthpercut = float(self.z_depthpercut) * factor
  1534. return factor
  1535. def doformat(self, fun, **kwargs):
  1536. return self.doformat2(fun, **kwargs) + "\n"
  1537. def doformat2(self, fun, **kwargs):
  1538. attributes = AttrDict()
  1539. attributes.update(self.postdata)
  1540. attributes.update(kwargs)
  1541. try:
  1542. returnvalue = fun(attributes)
  1543. return returnvalue
  1544. except Exception as e:
  1545. self.app.log.error('Exception occurred within a postprocessor: ' + traceback.format_exc())
  1546. return ''
  1547. def parse_custom_toolchange_code(self, data):
  1548. text = data
  1549. match_list = self.re_toolchange_custom.findall(text)
  1550. if match_list:
  1551. for match in match_list:
  1552. command = match.strip('%')
  1553. try:
  1554. value = getattr(self, command)
  1555. except AttributeError:
  1556. self.app.inform.emit('[ERROR] %s: %s' %
  1557. (_("There is no such parameter"), str(match)))
  1558. log.debug("CNCJob.parse_custom_toolchange_code() --> AttributeError ")
  1559. return 'fail'
  1560. text = text.replace(match, str(value))
  1561. return text
  1562. def optimized_travelling_salesman(self, points, start=None):
  1563. """
  1564. As solving the problem in the brute force way is too slow,
  1565. this function implements a simple heuristic: always
  1566. go to the nearest city.
  1567. Even if this algorithm is extremely simple, it works pretty well
  1568. giving a solution only about 25%% longer than the optimal one (cit. Wikipedia),
  1569. and runs very fast in O(N^2) time complexity.
  1570. >>> optimized_travelling_salesman([[i,j] for i in range(5) for j in range(5)])
  1571. [[0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [1, 4], [1, 3], [1, 2], [1, 1], [1, 0], [2, 0], [2, 1], [2, 2],
  1572. [2, 3], [2, 4], [3, 4], [3, 3], [3, 2], [3, 1], [3, 0], [4, 0], [4, 1], [4, 2], [4, 3], [4, 4]]
  1573. >>> optimized_travelling_salesman([[0,0],[10,0],[6,0]])
  1574. [[0, 0], [6, 0], [10, 0]]
  1575. """
  1576. if start is None:
  1577. start = points[0]
  1578. must_visit = points
  1579. path = [start]
  1580. # must_visit.remove(start)
  1581. while must_visit:
  1582. nearest = min(must_visit, key=lambda x: distance(path[-1], x))
  1583. path.append(nearest)
  1584. must_visit.remove(nearest)
  1585. return path
  1586. def generate_from_excellon_by_tool(
  1587. self, exobj, tools="all", drillz = 3.0,
  1588. toolchange=False, toolchangez=0.1, toolchangexy='',
  1589. endz=2.0, startz=None,
  1590. excellon_optimization_type='B'):
  1591. """
  1592. Creates gcode for this object from an Excellon object
  1593. for the specified tools.
  1594. :param exobj: Excellon object to process
  1595. :type exobj: Excellon
  1596. :param tools: Comma separated tool names
  1597. :type: tools: str
  1598. :param drillz: drill Z depth
  1599. :type drillz: float
  1600. :param toolchange: Use tool change sequence between tools.
  1601. :type toolchange: bool
  1602. :param toolchangez: Height at which to perform the tool change.
  1603. :type toolchangez: float
  1604. :param toolchangexy: Toolchange X,Y position
  1605. :type toolchangexy: String containing 2 floats separated by comma
  1606. :param startz: Z position just before starting the job
  1607. :type startz: float
  1608. :param endz: final Z position to move to at the end of the CNC job
  1609. :type endz: float
  1610. :param excellon_optimization_type: Single character that defines which drill re-ordering optimisation algorithm
  1611. is to be used: 'M' for meta-heuristic and 'B' for basic
  1612. :type excellon_optimization_type: string
  1613. :return: None
  1614. :rtype: None
  1615. """
  1616. # create a local copy of the exobj.drills so it can be used for creating drill CCode geometry
  1617. self.exc_drills = deepcopy(exobj.drills)
  1618. self.exc_tools = deepcopy(exobj.tools)
  1619. if drillz > 0:
  1620. self.app.inform.emit('[WARNING] %s' %
  1621. _("The Cut Z parameter has positive value. "
  1622. "It is the depth value to drill into material.\n"
  1623. "The Cut Z parameter needs to have a negative value, assuming it is a typo "
  1624. "therefore the app will convert the value to negative. "
  1625. "Check the resulting CNC code (Gcode etc)."))
  1626. self.z_cut = -drillz
  1627. elif drillz == 0:
  1628. self.app.inform.emit('[WARNING] %s: %s' %
  1629. (_("The Cut Z parameter is zero. There will be no cut, skipping file"),
  1630. exobj.options['name']))
  1631. return 'fail'
  1632. else:
  1633. self.z_cut = drillz
  1634. self.z_toolchange = toolchangez
  1635. try:
  1636. if toolchangexy == '':
  1637. self.xy_toolchange = None
  1638. else:
  1639. self.xy_toolchange = [float(eval(a)) for a in toolchangexy.split(",")]
  1640. if len(self.xy_toolchange) < 2:
  1641. self.app.inform.emit('[ERROR]%s' %
  1642. _("The Toolchange X,Y field in Edit -> Preferences has to be "
  1643. "in the format (x, y) \nbut now there is only one value, not two. "))
  1644. return 'fail'
  1645. except Exception as e:
  1646. log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> %s" % str(e))
  1647. pass
  1648. self.startz = startz
  1649. self.z_end = endz
  1650. self.pp_excellon = self.app.postprocessors[self.pp_excellon_name]
  1651. p = self.pp_excellon
  1652. log.debug("Creating CNC Job from Excellon...")
  1653. # Tools
  1654. # sort the tools list by the second item in tuple (here we have a dict with diameter of the tool)
  1655. # so we actually are sorting the tools by diameter
  1656. #sorted_tools = sorted(exobj.tools.items(), key=lambda t1: t1['C'])
  1657. sort = []
  1658. for k, v in list(exobj.tools.items()):
  1659. sort.append((k, v.get('C')))
  1660. sorted_tools = sorted(sort,key=lambda t1: t1[1])
  1661. if tools == "all":
  1662. tools = [i[0] for i in sorted_tools] # we get a array of ordered tools
  1663. log.debug("Tools 'all' and sorted are: %s" % str(tools))
  1664. else:
  1665. selected_tools = [x.strip() for x in tools.split(",")] # we strip spaces and also separate the tools by ','
  1666. selected_tools = [t1 for t1 in selected_tools if t1 in selected_tools]
  1667. # Create a sorted list of selected tools from the sorted_tools list
  1668. tools = [i for i, j in sorted_tools for k in selected_tools if i == k]
  1669. log.debug("Tools selected and sorted are: %s" % str(tools))
  1670. self.app.inform.emit(_("Creating a list of points to drill..."))
  1671. # Points (Group by tool)
  1672. points = {}
  1673. for drill in exobj.drills:
  1674. if self.app.abort_flag:
  1675. # graceful abort requested by the user
  1676. raise FlatCAMApp.GracefulException
  1677. if drill['tool'] in tools:
  1678. try:
  1679. points[drill['tool']].append(drill['point'])
  1680. except KeyError:
  1681. points[drill['tool']] = [drill['point']]
  1682. #log.debug("Found %d drills." % len(points))
  1683. self.gcode = []
  1684. self.f_plunge = self.app.defaults["excellon_f_plunge"]
  1685. self.f_retract = self.app.defaults["excellon_f_retract"]
  1686. # Initialization
  1687. gcode = self.doformat(p.start_code)
  1688. gcode += self.doformat(p.feedrate_code)
  1689. if toolchange is False:
  1690. if self.xy_toolchange is not None:
  1691. gcode += self.doformat(p.lift_code, x=self.xy_toolchange[0], y=self.xy_toolchange[1])
  1692. gcode += self.doformat(p.startz_code, x=self.xy_toolchange[0], y=self.xy_toolchange[1])
  1693. else:
  1694. gcode += self.doformat(p.lift_code, x=0.0, y=0.0)
  1695. gcode += self.doformat(p.startz_code, x=0.0, y=0.0)
  1696. # Distance callback
  1697. class CreateDistanceCallback(object):
  1698. """Create callback to calculate distances between points."""
  1699. def __init__(self):
  1700. """Initialize distance array."""
  1701. locations = create_data_array()
  1702. size = len(locations)
  1703. self.matrix = {}
  1704. for from_node in range(size):
  1705. self.matrix[from_node] = {}
  1706. for to_node in range(size):
  1707. if from_node == to_node:
  1708. self.matrix[from_node][to_node] = 0
  1709. else:
  1710. x1 = locations[from_node][0]
  1711. y1 = locations[from_node][1]
  1712. x2 = locations[to_node][0]
  1713. y2 = locations[to_node][1]
  1714. self.matrix[from_node][to_node] = distance_euclidian(x1, y1, x2, y2)
  1715. # def Distance(self, from_node, to_node):
  1716. # return int(self.matrix[from_node][to_node])
  1717. def Distance(self, from_index, to_index):
  1718. # Convert from routing variable Index to distance matrix NodeIndex.
  1719. from_node = manager.IndexToNode(from_index)
  1720. to_node = manager.IndexToNode(to_index)
  1721. return self.matrix[from_node][to_node]
  1722. # Create the data.
  1723. def create_data_array():
  1724. locations = []
  1725. for point in points[tool]:
  1726. locations.append((point.coords.xy[0][0], point.coords.xy[1][0]))
  1727. return locations
  1728. if self.xy_toolchange is not None:
  1729. self.oldx = self.xy_toolchange[0]
  1730. self.oldy = self.xy_toolchange[1]
  1731. else:
  1732. self.oldx = 0.0
  1733. self.oldy = 0.0
  1734. measured_distance = 0.0
  1735. measured_down_distance = 0.0
  1736. measured_up_to_zero_distance = 0.0
  1737. measured_lift_distance = 0.0
  1738. self.app.inform.emit('%s...' %
  1739. _("Starting G-Code"))
  1740. current_platform = platform.architecture()[0]
  1741. if current_platform == '64bit':
  1742. used_excellon_optimization_type = excellon_optimization_type
  1743. if used_excellon_optimization_type == 'M':
  1744. log.debug("Using OR-Tools Metaheuristic Guided Local Search drill path optimization.")
  1745. if exobj.drills:
  1746. for tool in tools:
  1747. self.tool=tool
  1748. self.postdata['toolC'] = exobj.tools[tool]["C"]
  1749. self.tooldia = exobj.tools[tool]["C"]
  1750. if self.app.abort_flag:
  1751. # graceful abort requested by the user
  1752. raise FlatCAMApp.GracefulException
  1753. # ###############################################
  1754. # ############ Create the data. #################
  1755. # ###############################################
  1756. node_list = []
  1757. locations = create_data_array()
  1758. tsp_size = len(locations)
  1759. num_routes = 1 # The number of routes, which is 1 in the TSP.
  1760. # Nodes are indexed from 0 to tsp_size - 1. The depot is the starting node of the route.
  1761. depot = 0
  1762. # Create routing model.
  1763. if tsp_size > 0:
  1764. manager = pywrapcp.RoutingIndexManager(tsp_size, num_routes, depot)
  1765. routing = pywrapcp.RoutingModel(manager)
  1766. search_parameters = pywrapcp.DefaultRoutingSearchParameters()
  1767. search_parameters.local_search_metaheuristic = (
  1768. routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH)
  1769. # Set search time limit in milliseconds.
  1770. if float(self.app.defaults["excellon_search_time"]) != 0:
  1771. search_parameters.time_limit.seconds = int(
  1772. float(self.app.defaults["excellon_search_time"]))
  1773. else:
  1774. search_parameters.time_limit.seconds = 3
  1775. # Callback to the distance function. The callback takes two
  1776. # arguments (the from and to node indices) and returns the distance between them.
  1777. dist_between_locations = CreateDistanceCallback()
  1778. dist_callback = dist_between_locations.Distance
  1779. transit_callback_index = routing.RegisterTransitCallback(dist_callback)
  1780. routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)
  1781. # Solve, returns a solution if any.
  1782. assignment = routing.SolveWithParameters(search_parameters)
  1783. if assignment:
  1784. # Solution cost.
  1785. log.info("Total distance: " + str(assignment.ObjectiveValue()))
  1786. # Inspect solution.
  1787. # Only one route here; otherwise iterate from 0 to routing.vehicles() - 1.
  1788. route_number = 0
  1789. node = routing.Start(route_number)
  1790. start_node = node
  1791. while not routing.IsEnd(node):
  1792. if self.app.abort_flag:
  1793. # graceful abort requested by the user
  1794. raise FlatCAMApp.GracefulException
  1795. node_list.append(node)
  1796. node = assignment.Value(routing.NextVar(node))
  1797. else:
  1798. log.warning('No solution found.')
  1799. else:
  1800. log.warning('Specify an instance greater than 0.')
  1801. # ############################################# ##
  1802. # Only if tool has points.
  1803. if tool in points:
  1804. if self.app.abort_flag:
  1805. # graceful abort requested by the user
  1806. raise FlatCAMApp.GracefulException
  1807. # Tool change sequence (optional)
  1808. if toolchange:
  1809. gcode += self.doformat(p.toolchange_code,toolchangexy=(self.oldx, self.oldy))
  1810. gcode += self.doformat(p.spindle_code) # Spindle start
  1811. if self.dwell is True:
  1812. gcode += self.doformat(p.dwell_code) # Dwell time
  1813. else:
  1814. gcode += self.doformat(p.spindle_code)
  1815. if self.dwell is True:
  1816. gcode += self.doformat(p.dwell_code) # Dwell time
  1817. if self.units == 'MM':
  1818. current_tooldia = float('%.2f' % float(exobj.tools[tool]["C"]))
  1819. else:
  1820. current_tooldia = float('%.4f' % float(exobj.tools[tool]["C"]))
  1821. self.app.inform.emit(
  1822. '%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  1823. str(current_tooldia),
  1824. str(self.units))
  1825. )
  1826. # TODO apply offset only when using the GUI, for TclCommand this will create an error
  1827. # because the values for Z offset are created in build_ui()
  1828. try:
  1829. z_offset = float(self.tool_offset[current_tooldia]) * (-1)
  1830. except KeyError:
  1831. z_offset = 0
  1832. self.z_cut += z_offset
  1833. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  1834. if self.coordinates_type == "G90":
  1835. # Drillling! for Absolute coordinates type G90
  1836. # variables to display the percentage of work done
  1837. geo_len = len(node_list)
  1838. disp_number = 0
  1839. old_disp_number = 0
  1840. log.warning("Number of drills for which to generate GCode: %s" % str(geo_len))
  1841. loc_nr = 0
  1842. for k in node_list:
  1843. if self.app.abort_flag:
  1844. # graceful abort requested by the user
  1845. raise FlatCAMApp.GracefulException
  1846. locx = locations[k][0]
  1847. locy = locations[k][1]
  1848. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  1849. gcode += self.doformat(p.down_code, x=locx, y=locy)
  1850. measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  1851. if self.f_retract is False:
  1852. gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  1853. measured_up_to_zero_distance += abs(self.z_cut)
  1854. measured_lift_distance += abs(self.z_move)
  1855. else:
  1856. measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  1857. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  1858. measured_distance += abs(distance_euclidian(locx, locy, self.oldx, self.oldy))
  1859. self.oldx = locx
  1860. self.oldy = locy
  1861. loc_nr += 1
  1862. disp_number = int(np.interp(loc_nr, [0, geo_len], [0, 100]))
  1863. if old_disp_number < disp_number <= 100:
  1864. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1865. old_disp_number = disp_number
  1866. else:
  1867. self.app.inform.emit('[ERROR_NOTCL] %s...' %
  1868. _('G91 coordinates not implemented'))
  1869. return 'fail'
  1870. else:
  1871. log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> "
  1872. "The loaded Excellon file has no drills ...")
  1873. self.app.inform.emit('[ERROR_NOTCL] %s...' %
  1874. _('The loaded Excellon file has no drills'))
  1875. return 'fail'
  1876. log.debug("The total travel distance with OR-TOOLS Metaheuristics is: %s" % str(measured_distance))
  1877. if used_excellon_optimization_type == 'B':
  1878. log.debug("Using OR-Tools Basic drill path optimization.")
  1879. if exobj.drills:
  1880. for tool in tools:
  1881. if self.app.abort_flag:
  1882. # graceful abort requested by the user
  1883. raise FlatCAMApp.GracefulException
  1884. self.tool=tool
  1885. self.postdata['toolC']=exobj.tools[tool]["C"]
  1886. self.tooldia = exobj.tools[tool]["C"]
  1887. # ############################################# ##
  1888. node_list = []
  1889. locations = create_data_array()
  1890. tsp_size = len(locations)
  1891. num_routes = 1 # The number of routes, which is 1 in the TSP.
  1892. # Nodes are indexed from 0 to tsp_size - 1. The depot is the starting node of the route.
  1893. depot = 0
  1894. # Create routing model.
  1895. if tsp_size > 0:
  1896. manager = pywrapcp.RoutingIndexManager(tsp_size, num_routes, depot)
  1897. routing = pywrapcp.RoutingModel(manager)
  1898. search_parameters = pywrapcp.DefaultRoutingSearchParameters()
  1899. # Callback to the distance function. The callback takes two
  1900. # arguments (the from and to node indices) and returns the distance between them.
  1901. dist_between_locations = CreateDistanceCallback()
  1902. dist_callback = dist_between_locations.Distance
  1903. transit_callback_index = routing.RegisterTransitCallback(dist_callback)
  1904. routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)
  1905. # Solve, returns a solution if any.
  1906. assignment = routing.SolveWithParameters(search_parameters)
  1907. if assignment:
  1908. # Solution cost.
  1909. log.info("Total distance: " + str(assignment.ObjectiveValue()))
  1910. # Inspect solution.
  1911. # Only one route here; otherwise iterate from 0 to routing.vehicles() - 1.
  1912. route_number = 0
  1913. node = routing.Start(route_number)
  1914. start_node = node
  1915. while not routing.IsEnd(node):
  1916. node_list.append(node)
  1917. node = assignment.Value(routing.NextVar(node))
  1918. else:
  1919. log.warning('No solution found.')
  1920. else:
  1921. log.warning('Specify an instance greater than 0.')
  1922. # ############################################# ##
  1923. # Only if tool has points.
  1924. if tool in points:
  1925. if self.app.abort_flag:
  1926. # graceful abort requested by the user
  1927. raise FlatCAMApp.GracefulException
  1928. # Tool change sequence (optional)
  1929. if toolchange:
  1930. gcode += self.doformat(p.toolchange_code,toolchangexy=(self.oldx, self.oldy))
  1931. gcode += self.doformat(p.spindle_code) # Spindle start)
  1932. if self.dwell is True:
  1933. gcode += self.doformat(p.dwell_code) # Dwell time
  1934. else:
  1935. gcode += self.doformat(p.spindle_code)
  1936. if self.dwell is True:
  1937. gcode += self.doformat(p.dwell_code) # Dwell time
  1938. if self.units == 'MM':
  1939. current_tooldia = float('%.2f' % float(exobj.tools[tool]["C"]))
  1940. else:
  1941. current_tooldia = float('%.4f' % float(exobj.tools[tool]["C"]))
  1942. self.app.inform.emit(
  1943. '%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  1944. str(current_tooldia),
  1945. str(self.units))
  1946. )
  1947. # TODO apply offset only when using the GUI, for TclCommand this will create an error
  1948. # because the values for Z offset are created in build_ui()
  1949. try:
  1950. z_offset = float(self.tool_offset[current_tooldia]) * (-1)
  1951. except KeyError:
  1952. z_offset = 0
  1953. self.z_cut += z_offset
  1954. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  1955. if self.coordinates_type == "G90":
  1956. # Drillling! for Absolute coordinates type G90
  1957. # variables to display the percentage of work done
  1958. geo_len = len(node_list)
  1959. disp_number = 0
  1960. old_disp_number = 0
  1961. log.warning("Number of drills for which to generate GCode: %s" % str(geo_len))
  1962. loc_nr = 0
  1963. for k in node_list:
  1964. if self.app.abort_flag:
  1965. # graceful abort requested by the user
  1966. raise FlatCAMApp.GracefulException
  1967. locx = locations[k][0]
  1968. locy = locations[k][1]
  1969. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  1970. gcode += self.doformat(p.down_code, x=locx, y=locy)
  1971. measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  1972. if self.f_retract is False:
  1973. gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  1974. measured_up_to_zero_distance += abs(self.z_cut)
  1975. measured_lift_distance += abs(self.z_move)
  1976. else:
  1977. measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  1978. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  1979. measured_distance += abs(distance_euclidian(locx, locy, self.oldx, self.oldy))
  1980. self.oldx = locx
  1981. self.oldy = locy
  1982. loc_nr += 1
  1983. disp_number = int(np.interp(loc_nr, [0, geo_len], [0, 100]))
  1984. if old_disp_number < disp_number <= 100:
  1985. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1986. old_disp_number = disp_number
  1987. else:
  1988. self.app.inform.emit('[ERROR_NOTCL] %s...' %
  1989. _('G91 coordinates not implemented'))
  1990. return 'fail'
  1991. else:
  1992. log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> "
  1993. "The loaded Excellon file has no drills ...")
  1994. self.app.inform.emit('[ERROR_NOTCL] %s...' %
  1995. _('The loaded Excellon file has no drills'))
  1996. return 'fail'
  1997. log.debug("The total travel distance with OR-TOOLS Basic Algorithm is: %s" % str(measured_distance))
  1998. else:
  1999. used_excellon_optimization_type = 'T'
  2000. if used_excellon_optimization_type == 'T':
  2001. log.debug("Using Travelling Salesman drill path optimization.")
  2002. for tool in tools:
  2003. if self.app.abort_flag:
  2004. # graceful abort requested by the user
  2005. raise FlatCAMApp.GracefulException
  2006. if exobj.drills:
  2007. self.tool = tool
  2008. self.postdata['toolC'] = exobj.tools[tool]["C"]
  2009. self.tooldia = exobj.tools[tool]["C"]
  2010. # Only if tool has points.
  2011. if tool in points:
  2012. if self.app.abort_flag:
  2013. # graceful abort requested by the user
  2014. raise FlatCAMApp.GracefulException
  2015. # Tool change sequence (optional)
  2016. if toolchange:
  2017. gcode += self.doformat(p.toolchange_code, toolchangexy=(self.oldx, self.oldy))
  2018. gcode += self.doformat(p.spindle_code) # Spindle start)
  2019. if self.dwell is True:
  2020. gcode += self.doformat(p.dwell_code) # Dwell time
  2021. else:
  2022. gcode += self.doformat(p.spindle_code)
  2023. if self.dwell is True:
  2024. gcode += self.doformat(p.dwell_code) # Dwell time
  2025. if self.units == 'MM':
  2026. current_tooldia = float('%.2f' % float(exobj.tools[tool]["C"]))
  2027. else:
  2028. current_tooldia = float('%.4f' % float(exobj.tools[tool]["C"]))
  2029. self.app.inform.emit(
  2030. '%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  2031. str(current_tooldia),
  2032. str(self.units))
  2033. )
  2034. # TODO apply offset only when using the GUI, for TclCommand this will create an error
  2035. # because the values for Z offset are created in build_ui()
  2036. try:
  2037. z_offset = float(self.tool_offset[current_tooldia]) * (-1)
  2038. except KeyError:
  2039. z_offset = 0
  2040. self.z_cut += z_offset
  2041. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  2042. if self.coordinates_type == "G90":
  2043. # Drillling! for Absolute coordinates type G90
  2044. altPoints = []
  2045. for point in points[tool]:
  2046. altPoints.append((point.coords.xy[0][0], point.coords.xy[1][0]))
  2047. node_list = self.optimized_travelling_salesman(altPoints)
  2048. # variables to display the percentage of work done
  2049. geo_len = len(node_list)
  2050. disp_number = 0
  2051. old_disp_number = 0
  2052. log.warning("Number of drills for which to generate GCode: %s" % str(geo_len))
  2053. loc_nr = 0
  2054. for point in node_list:
  2055. if self.app.abort_flag:
  2056. # graceful abort requested by the user
  2057. raise FlatCAMApp.GracefulException
  2058. gcode += self.doformat(p.rapid_code, x=point[0], y=point[1])
  2059. gcode += self.doformat(p.down_code, x=point[0], y=point[1])
  2060. measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  2061. if self.f_retract is False:
  2062. gcode += self.doformat(p.up_to_zero_code, x=point[0], y=point[1])
  2063. measured_up_to_zero_distance += abs(self.z_cut)
  2064. measured_lift_distance += abs(self.z_move)
  2065. else:
  2066. measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  2067. gcode += self.doformat(p.lift_code, x=point[0], y=point[1])
  2068. measured_distance += abs(distance_euclidian(point[0], point[1], self.oldx, self.oldy))
  2069. self.oldx = point[0]
  2070. self.oldy = point[1]
  2071. loc_nr += 1
  2072. disp_number = int(np.interp(loc_nr, [0, geo_len], [0, 100]))
  2073. if old_disp_number < disp_number <= 100:
  2074. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  2075. old_disp_number = disp_number
  2076. else:
  2077. self.app.inform.emit('[ERROR_NOTCL] %s...' %
  2078. _('G91 coordinates not implemented'))
  2079. return 'fail'
  2080. else:
  2081. log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> "
  2082. "The loaded Excellon file has no drills ...")
  2083. self.app.inform.emit('[ERROR_NOTCL] %s...' %
  2084. _('The loaded Excellon file has no drills'))
  2085. return 'fail'
  2086. log.debug("The total travel distance with Travelling Salesman Algorithm is: %s" % str(measured_distance))
  2087. gcode += self.doformat(p.spindle_stop_code) # Spindle stop
  2088. gcode += self.doformat(p.end_code, x=0, y=0)
  2089. measured_distance += abs(distance_euclidian(self.oldx, self.oldy, 0, 0))
  2090. log.debug("The total travel distance including travel to end position is: %s" %
  2091. str(measured_distance) + '\n')
  2092. self.travel_distance = measured_distance
  2093. # I use the value of self.feedrate_rapid for the feadrate in case of the measure_lift_distance and for
  2094. # traveled_time because it is not always possible to determine the feedrate that the CNC machine uses
  2095. # for G0 move (the fastest speed available to the CNC router). Although self.feedrate_rapids is used only with
  2096. # Marlin postprocessor and derivatives.
  2097. self.routing_time = (measured_down_distance + measured_up_to_zero_distance) / self.feedrate
  2098. lift_time = measured_lift_distance / self.feedrate_rapid
  2099. traveled_time = measured_distance / self.feedrate_rapid
  2100. self.routing_time += lift_time + traveled_time
  2101. self.gcode = gcode
  2102. self.app.inform.emit(_("Finished G-Code generation..."))
  2103. return 'OK'
  2104. def generate_from_multitool_geometry(self, geometry, append=True,
  2105. tooldia=None, offset=0.0, tolerance=0, z_cut=1.0, z_move=2.0,
  2106. feedrate=2.0, feedrate_z=2.0, feedrate_rapid=30,
  2107. spindlespeed=None, spindledir='CW', dwell=False, dwelltime=1.0,
  2108. multidepth=False, depthpercut=None,
  2109. toolchange=False, toolchangez=1.0, toolchangexy="0.0, 0.0", extracut=False,
  2110. startz=None, endz=2.0, pp_geometry_name=None, tool_no=1):
  2111. """
  2112. Algorithm to generate from multitool Geometry.
  2113. Algorithm description:
  2114. ----------------------
  2115. Uses RTree to find the nearest path to follow.
  2116. :param geometry:
  2117. :param append:
  2118. :param tooldia:
  2119. :param tolerance:
  2120. :param multidepth: If True, use multiple passes to reach
  2121. the desired depth.
  2122. :param depthpercut: Maximum depth in each pass.
  2123. :param extracut: Adds (or not) an extra cut at the end of each path
  2124. overlapping the first point in path to ensure complete copper removal
  2125. :return: GCode - string
  2126. """
  2127. log.debug("Generate_from_multitool_geometry()")
  2128. temp_solid_geometry = []
  2129. if offset != 0.0:
  2130. for it in geometry:
  2131. # if the geometry is a closed shape then create a Polygon out of it
  2132. if isinstance(it, LineString):
  2133. c = it.coords
  2134. if c[0] == c[-1]:
  2135. it = Polygon(it)
  2136. temp_solid_geometry.append(it.buffer(offset, join_style=2))
  2137. else:
  2138. temp_solid_geometry = geometry
  2139. # ## Flatten the geometry. Only linear elements (no polygons) remain.
  2140. flat_geometry = self.flatten(temp_solid_geometry, pathonly=True)
  2141. log.debug("%d paths" % len(flat_geometry))
  2142. self.tooldia = float(tooldia) if tooldia else None
  2143. self.z_cut = float(z_cut) if z_cut else None
  2144. self.z_move = float(z_move) if z_move else None
  2145. self.feedrate = float(feedrate) if feedrate else None
  2146. self.z_feedrate = float(feedrate_z) if feedrate_z else None
  2147. self.feedrate_rapid = float(feedrate_rapid) if feedrate_rapid else None
  2148. self.spindlespeed = int(spindlespeed) if spindlespeed else None
  2149. self.spindledir = spindledir
  2150. self.dwell = dwell
  2151. self.dwelltime = float(dwelltime) if dwelltime else None
  2152. self.startz = float(startz) if startz else None
  2153. self.z_end = float(endz) if endz else None
  2154. self.z_depthpercut = float(depthpercut) if depthpercut else None
  2155. self.multidepth = multidepth
  2156. self.z_toolchange = float(toolchangez) if toolchangez else None
  2157. # it servers in the postprocessor file
  2158. self.tool = tool_no
  2159. try:
  2160. if toolchangexy == '':
  2161. self.xy_toolchange = None
  2162. else:
  2163. self.xy_toolchange = [float(eval(a)) for a in toolchangexy.split(",")]
  2164. if len(self.xy_toolchange) < 2:
  2165. self.app.inform.emit('[ERROR] %s' % _("The Toolchange X,Y field in Edit -> Preferences has to be "
  2166. "in the format (x, y) \n"
  2167. "but now there is only one value, not two."))
  2168. return 'fail'
  2169. except Exception as e:
  2170. log.debug("camlib.CNCJob.generate_from_multitool_geometry() --> %s" % str(e))
  2171. pass
  2172. self.pp_geometry_name = pp_geometry_name if pp_geometry_name else 'default'
  2173. self.f_plunge = self.app.defaults["geometry_f_plunge"]
  2174. if self.z_cut is None:
  2175. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2176. _("Cut_Z parameter is None or zero. Most likely a bad combinations of "
  2177. "other parameters."))
  2178. return 'fail'
  2179. if self.z_cut > 0:
  2180. self.app.inform.emit('[WARNING] %s' %
  2181. _("The Cut Z parameter has positive value. "
  2182. "It is the depth value to cut into material.\n"
  2183. "The Cut Z parameter needs to have a negative value, assuming it is a typo "
  2184. "therefore the app will convert the value to negative."
  2185. "Check the resulting CNC code (Gcode etc)."))
  2186. self.z_cut = -self.z_cut
  2187. elif self.z_cut == 0:
  2188. self.app.inform.emit('[WARNING] %s: %s' %
  2189. (_("The Cut Z parameter is zero. There will be no cut, skipping file"),
  2190. self.options['name']))
  2191. return 'fail'
  2192. # made sure that depth_per_cut is no more then the z_cut
  2193. if abs(self.z_cut) < self.z_depthpercut:
  2194. self.z_depthpercut = abs(self.z_cut)
  2195. if self.z_move is None:
  2196. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2197. _("Travel Z parameter is None or zero."))
  2198. return 'fail'
  2199. if self.z_move < 0:
  2200. self.app.inform.emit('[WARNING] %s' %
  2201. _("The Travel Z parameter has negative value. "
  2202. "It is the height value to travel between cuts.\n"
  2203. "The Z Travel parameter needs to have a positive value, assuming it is a typo "
  2204. "therefore the app will convert the value to positive."
  2205. "Check the resulting CNC code (Gcode etc)."))
  2206. self.z_move = -self.z_move
  2207. elif self.z_move == 0:
  2208. self.app.inform.emit('[WARNING] %s: %s' %
  2209. (_("The Z Travel parameter is zero. This is dangerous, skipping file"),
  2210. self.options['name']))
  2211. return 'fail'
  2212. # ## Index first and last points in paths
  2213. # What points to index.
  2214. def get_pts(o):
  2215. return [o.coords[0], o.coords[-1]]
  2216. # Create the indexed storage.
  2217. storage = FlatCAMRTreeStorage()
  2218. storage.get_points = get_pts
  2219. # Store the geometry
  2220. log.debug("Indexing geometry before generating G-Code...")
  2221. self.app.inform.emit(_("Indexing geometry before generating G-Code..."))
  2222. for shape in flat_geometry:
  2223. if self.app.abort_flag:
  2224. # graceful abort requested by the user
  2225. raise FlatCAMApp.GracefulException
  2226. if shape is not None: # TODO: This shouldn't have happened.
  2227. storage.insert(shape)
  2228. # self.input_geometry_bounds = geometry.bounds()
  2229. if not append:
  2230. self.gcode = ""
  2231. # tell postprocessor the number of tool (for toolchange)
  2232. self.tool = tool_no
  2233. # this is the tool diameter, it is used as such to accommodate the postprocessor who need the tool diameter
  2234. # given under the name 'toolC'
  2235. self.postdata['toolC'] = self.tooldia
  2236. # Initial G-Code
  2237. self.pp_geometry = self.app.postprocessors[self.pp_geometry_name]
  2238. p = self.pp_geometry
  2239. self.gcode = self.doformat(p.start_code)
  2240. self.gcode += self.doformat(p.feedrate_code) # sets the feed rate
  2241. if toolchange is False:
  2242. self.gcode += self.doformat(p.lift_code, x=0, y=0) # Move (up) to travel height
  2243. self.gcode += self.doformat(p.startz_code, x=0, y=0)
  2244. if toolchange:
  2245. # if "line_xyz" in self.pp_geometry_name:
  2246. # self.gcode += self.doformat(p.toolchange_code, x=self.xy_toolchange[0], y=self.xy_toolchange[1])
  2247. # else:
  2248. # self.gcode += self.doformat(p.toolchange_code)
  2249. self.gcode += self.doformat(p.toolchange_code)
  2250. if 'laser' not in self.pp_geometry_name:
  2251. self.gcode += self.doformat(p.spindle_code) # Spindle start
  2252. else:
  2253. # for laser this will disable the laser
  2254. self.gcode += self.doformat(p.lift_code, x=self.oldx, y=self.oldy) # Move (up) to travel height
  2255. if self.dwell is True:
  2256. self.gcode += self.doformat(p.dwell_code) # Dwell time
  2257. else:
  2258. if 'laser' not in self.pp_geometry_name:
  2259. self.gcode += self.doformat(p.spindle_code) # Spindle start
  2260. if self.dwell is True:
  2261. self.gcode += self.doformat(p.dwell_code) # Dwell time
  2262. total_travel = 0.0
  2263. total_cut = 0.0
  2264. # ## Iterate over geometry paths getting the nearest each time.
  2265. log.debug("Starting G-Code...")
  2266. self.app.inform.emit(_("Starting G-Code..."))
  2267. path_count = 0
  2268. current_pt = (0, 0)
  2269. # variables to display the percentage of work done
  2270. geo_len = len(flat_geometry)
  2271. disp_number = 0
  2272. old_disp_number = 0
  2273. log.warning("Number of paths for which to generate GCode: %s" % str(geo_len))
  2274. if self.units == 'MM':
  2275. current_tooldia = float('%.2f' % float(self.tooldia))
  2276. else:
  2277. current_tooldia = float('%.4f' % float(self.tooldia))
  2278. self.app.inform.emit(
  2279. '%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  2280. str(current_tooldia),
  2281. str(self.units))
  2282. )
  2283. pt, geo = storage.nearest(current_pt)
  2284. try:
  2285. while True:
  2286. if self.app.abort_flag:
  2287. # graceful abort requested by the user
  2288. raise FlatCAMApp.GracefulException
  2289. path_count += 1
  2290. # Remove before modifying, otherwise deletion will fail.
  2291. storage.remove(geo)
  2292. # If last point in geometry is the nearest but prefer the first one if last point == first point
  2293. # then reverse coordinates.
  2294. if pt != geo.coords[0] and pt == geo.coords[-1]:
  2295. geo.coords = list(geo.coords)[::-1]
  2296. # ---------- Single depth/pass --------
  2297. if not multidepth:
  2298. # calculate the cut distance
  2299. total_cut = total_cut + geo.length
  2300. self.gcode += self.create_gcode_single_pass(geo, extracut, tolerance, old_point=current_pt)
  2301. # --------- Multi-pass ---------
  2302. else:
  2303. # calculate the cut distance
  2304. # due of the number of cuts (multi depth) it has to multiplied by the number of cuts
  2305. nr_cuts = 0
  2306. depth = abs(self.z_cut)
  2307. while depth > 0:
  2308. nr_cuts += 1
  2309. depth -= float(self.z_depthpercut)
  2310. total_cut += (geo.length * nr_cuts)
  2311. self.gcode += self.create_gcode_multi_pass(geo, extracut, tolerance,
  2312. postproc=p, old_point=current_pt)
  2313. # calculate the total distance
  2314. total_travel = total_travel + abs(distance(pt1=current_pt, pt2=pt))
  2315. current_pt = geo.coords[-1]
  2316. pt, geo = storage.nearest(current_pt) # Next
  2317. disp_number = int(np.interp(path_count, [0, geo_len], [0, 100]))
  2318. if old_disp_number < disp_number <= 100:
  2319. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  2320. old_disp_number = disp_number
  2321. except StopIteration: # Nothing found in storage.
  2322. pass
  2323. log.debug("Finished G-Code... %s paths traced." % path_count)
  2324. # add move to end position
  2325. total_travel += abs(distance_euclidian(current_pt[0], current_pt[1], 0, 0))
  2326. self.travel_distance += total_travel + total_cut
  2327. self.routing_time += total_cut / self.feedrate
  2328. # Finish
  2329. self.gcode += self.doformat(p.spindle_stop_code)
  2330. self.gcode += self.doformat(p.lift_code, x=current_pt[0], y=current_pt[1])
  2331. self.gcode += self.doformat(p.end_code, x=0, y=0)
  2332. self.app.inform.emit('%s... %s %s.' %
  2333. (_("Finished G-Code generation"),
  2334. str(path_count),
  2335. _("paths traced")
  2336. )
  2337. )
  2338. return self.gcode
  2339. def generate_from_geometry_2(
  2340. self, geometry, append=True,
  2341. tooldia=None, offset=0.0, tolerance=0,
  2342. z_cut=1.0, z_move=2.0,
  2343. feedrate=2.0, feedrate_z=2.0, feedrate_rapid=30,
  2344. spindlespeed=None, spindledir='CW', dwell=False, dwelltime=1.0,
  2345. multidepth=False, depthpercut=None,
  2346. toolchange=False, toolchangez=1.0, toolchangexy="0.0, 0.0",
  2347. extracut=False, startz=None, endz=2.0,
  2348. pp_geometry_name=None, tool_no=1):
  2349. """
  2350. Second algorithm to generate from Geometry.
  2351. Algorithm description:
  2352. ----------------------
  2353. Uses RTree to find the nearest path to follow.
  2354. :param geometry:
  2355. :param append:
  2356. :param tooldia:
  2357. :param tolerance:
  2358. :param multidepth: If True, use multiple passes to reach
  2359. the desired depth.
  2360. :param depthpercut: Maximum depth in each pass.
  2361. :param extracut: Adds (or not) an extra cut at the end of each path
  2362. overlapping the first point in path to ensure complete copper removal
  2363. :return: None
  2364. """
  2365. if not isinstance(geometry, Geometry):
  2366. self.app.inform.emit('[ERROR] %s: %s' %
  2367. (_("Expected a Geometry, got"), type(geometry)))
  2368. return 'fail'
  2369. log.debug("Generate_from_geometry_2()")
  2370. # if solid_geometry is empty raise an exception
  2371. if not geometry.solid_geometry:
  2372. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2373. _("Trying to generate a CNC Job "
  2374. "from a Geometry object without solid_geometry."))
  2375. temp_solid_geometry = []
  2376. def bounds_rec(obj):
  2377. if type(obj) is list:
  2378. minx = Inf
  2379. miny = Inf
  2380. maxx = -Inf
  2381. maxy = -Inf
  2382. for k in obj:
  2383. if type(k) is dict:
  2384. for key in k:
  2385. minx_, miny_, maxx_, maxy_ = bounds_rec(k[key])
  2386. minx = min(minx, minx_)
  2387. miny = min(miny, miny_)
  2388. maxx = max(maxx, maxx_)
  2389. maxy = max(maxy, maxy_)
  2390. else:
  2391. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  2392. minx = min(minx, minx_)
  2393. miny = min(miny, miny_)
  2394. maxx = max(maxx, maxx_)
  2395. maxy = max(maxy, maxy_)
  2396. return minx, miny, maxx, maxy
  2397. else:
  2398. # it's a Shapely object, return it's bounds
  2399. return obj.bounds
  2400. if offset != 0.0:
  2401. offset_for_use = offset
  2402. if offset < 0:
  2403. a, b, c, d = bounds_rec(geometry.solid_geometry)
  2404. # if the offset is less than half of the total length or less than half of the total width of the
  2405. # solid geometry it's obvious we can't do the offset
  2406. if -offset > ((c - a) / 2) or -offset > ((d - b) / 2):
  2407. self.app.inform.emit('[ERROR_NOTCL] %s' % _(
  2408. "The Tool Offset value is too negative to use "
  2409. "for the current_geometry.\n"
  2410. "Raise the value (in module) and try again."))
  2411. return 'fail'
  2412. # hack: make offset smaller by 0.0000000001 which is insignificant difference but allow the job
  2413. # to continue
  2414. elif -offset == ((c - a) / 2) or -offset == ((d - b) / 2):
  2415. offset_for_use = offset - 0.0000000001
  2416. for it in geometry.solid_geometry:
  2417. # if the geometry is a closed shape then create a Polygon out of it
  2418. if isinstance(it, LineString):
  2419. c = it.coords
  2420. if c[0] == c[-1]:
  2421. it = Polygon(it)
  2422. temp_solid_geometry.append(it.buffer(offset_for_use, join_style=2))
  2423. else:
  2424. temp_solid_geometry = geometry.solid_geometry
  2425. # ## Flatten the geometry. Only linear elements (no polygons) remain.
  2426. flat_geometry = self.flatten(temp_solid_geometry, pathonly=True)
  2427. log.debug("%d paths" % len(flat_geometry))
  2428. try:
  2429. self.tooldia = float(tooldia) if tooldia else None
  2430. except ValueError:
  2431. self.tooldia = [float(el) for el in tooldia.split(',') if el != ''] if tooldia else None
  2432. self.z_cut = float(z_cut) if z_cut else None
  2433. self.z_move = float(z_move) if z_move else None
  2434. self.feedrate = float(feedrate) if feedrate else None
  2435. self.z_feedrate = float(feedrate_z) if feedrate_z else None
  2436. self.feedrate_rapid = float(feedrate_rapid) if feedrate_rapid else None
  2437. self.spindlespeed = int(spindlespeed) if spindlespeed else None
  2438. self.spindledir = spindledir
  2439. self.dwell = dwell
  2440. self.dwelltime = float(dwelltime) if dwelltime else None
  2441. self.startz = float(startz) if startz else None
  2442. self.z_end = float(endz) if endz else None
  2443. self.z_depthpercut = float(depthpercut) if depthpercut else None
  2444. self.multidepth = multidepth
  2445. self.z_toolchange = float(toolchangez) if toolchangez else None
  2446. try:
  2447. if toolchangexy == '':
  2448. self.xy_toolchange = None
  2449. else:
  2450. self.xy_toolchange = [float(eval(a)) for a in toolchangexy.split(",")]
  2451. if len(self.xy_toolchange) < 2:
  2452. self.app.inform.emit('[ERROR] %s' %
  2453. _("The Toolchange X,Y field in Edit -> Preferences has to be "
  2454. "in the format (x, y) \nbut now there is only one value, not two. "))
  2455. return 'fail'
  2456. except Exception as e:
  2457. log.debug("camlib.CNCJob.generate_from_geometry_2() --> %s" % str(e))
  2458. pass
  2459. self.pp_geometry_name = pp_geometry_name if pp_geometry_name else 'default'
  2460. self.f_plunge = self.app.defaults["geometry_f_plunge"]
  2461. if self.z_cut is None:
  2462. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2463. _("Cut_Z parameter is None or zero. Most likely a bad combinations of "
  2464. "other parameters."))
  2465. return 'fail'
  2466. if self.z_cut > 0:
  2467. self.app.inform.emit('[WARNING] %s' %
  2468. _("The Cut Z parameter has positive value. "
  2469. "It is the depth value to cut into material.\n"
  2470. "The Cut Z parameter needs to have a negative value, assuming it is a typo "
  2471. "therefore the app will convert the value to negative."
  2472. "Check the resulting CNC code (Gcode etc)."))
  2473. self.z_cut = -self.z_cut
  2474. elif self.z_cut == 0:
  2475. self.app.inform.emit('[WARNING] %s: %s' %
  2476. (_("The Cut Z parameter is zero. There will be no cut, skipping file"),
  2477. geometry.options['name']))
  2478. return 'fail'
  2479. if self.z_move is None:
  2480. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2481. _("Travel Z parameter is None or zero."))
  2482. return 'fail'
  2483. if self.z_move < 0:
  2484. self.app.inform.emit('[WARNING] %s' %
  2485. _("The Travel Z parameter has negative value. "
  2486. "It is the height value to travel between cuts.\n"
  2487. "The Z Travel parameter needs to have a positive value, assuming it is a typo "
  2488. "therefore the app will convert the value to positive."
  2489. "Check the resulting CNC code (Gcode etc)."))
  2490. self.z_move = -self.z_move
  2491. elif self.z_move == 0:
  2492. self.app.inform.emit('[WARNING] %s: %s' %
  2493. (_("The Z Travel parameter is zero. "
  2494. "This is dangerous, skipping file"), self.options['name']))
  2495. return 'fail'
  2496. # made sure that depth_per_cut is no more then the z_cut
  2497. if abs(self.z_cut) < self.z_depthpercut:
  2498. self.z_depthpercut = abs(self.z_cut)
  2499. # ## Index first and last points in paths
  2500. # What points to index.
  2501. def get_pts(o):
  2502. return [o.coords[0], o.coords[-1]]
  2503. # Create the indexed storage.
  2504. storage = FlatCAMRTreeStorage()
  2505. storage.get_points = get_pts
  2506. # Store the geometry
  2507. log.debug("Indexing geometry before generating G-Code...")
  2508. self.app.inform.emit(_("Indexing geometry before generating G-Code..."))
  2509. for shape in flat_geometry:
  2510. if self.app.abort_flag:
  2511. # graceful abort requested by the user
  2512. raise FlatCAMApp.GracefulException
  2513. if shape is not None: # TODO: This shouldn't have happened.
  2514. storage.insert(shape)
  2515. if not append:
  2516. self.gcode = ""
  2517. # tell postprocessor the number of tool (for toolchange)
  2518. self.tool = tool_no
  2519. # this is the tool diameter, it is used as such to accommodate the postprocessor who need the tool diameter
  2520. # given under the name 'toolC'
  2521. self.postdata['toolC'] = self.tooldia
  2522. # Initial G-Code
  2523. self.pp_geometry = self.app.postprocessors[self.pp_geometry_name]
  2524. p = self.pp_geometry
  2525. self.oldx = 0.0
  2526. self.oldy = 0.0
  2527. self.gcode = self.doformat(p.start_code)
  2528. self.gcode += self.doformat(p.feedrate_code) # sets the feed rate
  2529. if toolchange is False:
  2530. self.gcode += self.doformat(p.lift_code, x=self.oldx , y=self.oldy ) # Move (up) to travel height
  2531. self.gcode += self.doformat(p.startz_code, x=self.oldx , y=self.oldy )
  2532. if toolchange:
  2533. # if "line_xyz" in self.pp_geometry_name:
  2534. # self.gcode += self.doformat(p.toolchange_code, x=self.xy_toolchange[0], y=self.xy_toolchange[1])
  2535. # else:
  2536. # self.gcode += self.doformat(p.toolchange_code)
  2537. self.gcode += self.doformat(p.toolchange_code)
  2538. if 'laser' not in self.pp_geometry_name:
  2539. self.gcode += self.doformat(p.spindle_code) # Spindle start
  2540. else:
  2541. # for laser this will disable the laser
  2542. self.gcode += self.doformat(p.lift_code, x=self.oldx, y=self.oldy) # Move (up) to travel height
  2543. if self.dwell is True:
  2544. self.gcode += self.doformat(p.dwell_code) # Dwell time
  2545. else:
  2546. if 'laser' not in self.pp_geometry_name:
  2547. self.gcode += self.doformat(p.spindle_code) # Spindle start
  2548. if self.dwell is True:
  2549. self.gcode += self.doformat(p.dwell_code) # Dwell time
  2550. total_travel = 0.0
  2551. total_cut = 0.0
  2552. # Iterate over geometry paths getting the nearest each time.
  2553. log.debug("Starting G-Code...")
  2554. self.app.inform.emit(_("Starting G-Code..."))
  2555. # variables to display the percentage of work done
  2556. geo_len = len(flat_geometry)
  2557. disp_number = 0
  2558. old_disp_number = 0
  2559. log.warning("Number of paths for which to generate GCode: %s" % str(geo_len))
  2560. if self.units == 'MM':
  2561. current_tooldia = float('%.2f' % float(self.tooldia))
  2562. else:
  2563. current_tooldia = float('%.4f' % float(self.tooldia))
  2564. self.app.inform.emit(
  2565. '%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  2566. str(current_tooldia),
  2567. str(self.units))
  2568. )
  2569. path_count = 0
  2570. current_pt = (0, 0)
  2571. pt, geo = storage.nearest(current_pt)
  2572. try:
  2573. while True:
  2574. if self.app.abort_flag:
  2575. # graceful abort requested by the user
  2576. raise FlatCAMApp.GracefulException
  2577. path_count += 1
  2578. # Remove before modifying, otherwise deletion will fail.
  2579. storage.remove(geo)
  2580. # If last point in geometry is the nearest but prefer the first one if last point == first point
  2581. # then reverse coordinates.
  2582. if pt != geo.coords[0] and pt == geo.coords[-1]:
  2583. geo.coords = list(geo.coords)[::-1]
  2584. # ---------- Single depth/pass --------
  2585. if not multidepth:
  2586. # calculate the cut distance
  2587. total_cut += geo.length
  2588. self.gcode += self.create_gcode_single_pass(geo, extracut, tolerance, old_point=current_pt)
  2589. # --------- Multi-pass ---------
  2590. else:
  2591. # calculate the cut distance
  2592. # due of the number of cuts (multi depth) it has to multiplied by the number of cuts
  2593. nr_cuts = 0
  2594. depth = abs(self.z_cut)
  2595. while depth > 0:
  2596. nr_cuts += 1
  2597. depth -= float(self.z_depthpercut)
  2598. total_cut += (geo.length * nr_cuts)
  2599. self.gcode += self.create_gcode_multi_pass(geo, extracut, tolerance,
  2600. postproc=p, old_point=current_pt)
  2601. # calculate the travel distance
  2602. total_travel += abs(distance(pt1=current_pt, pt2=pt))
  2603. current_pt = geo.coords[-1]
  2604. pt, geo = storage.nearest(current_pt) # Next
  2605. disp_number = int(np.interp(path_count, [0, geo_len], [0, 100]))
  2606. if old_disp_number < disp_number <= 100:
  2607. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  2608. old_disp_number = disp_number
  2609. except StopIteration: # Nothing found in storage.
  2610. pass
  2611. log.debug("Finishing G-Code... %s paths traced." % path_count)
  2612. # add move to end position
  2613. total_travel += abs(distance_euclidian(current_pt[0], current_pt[1], 0, 0))
  2614. self.travel_distance += total_travel + total_cut
  2615. self.routing_time += total_cut / self.feedrate
  2616. # Finish
  2617. self.gcode += self.doformat(p.spindle_stop_code)
  2618. self.gcode += self.doformat(p.lift_code, x=current_pt[0], y=current_pt[1])
  2619. self.gcode += self.doformat(p.end_code, x=0, y=0)
  2620. self.app.inform.emit('%s... %s %s' %
  2621. (_("Finished G-Code generation"),
  2622. str(path_count),
  2623. _(" paths traced.")
  2624. )
  2625. )
  2626. return self.gcode
  2627. def generate_gcode_from_solderpaste_geo(self, **kwargs):
  2628. """
  2629. Algorithm to generate from multitool Geometry.
  2630. Algorithm description:
  2631. ----------------------
  2632. Uses RTree to find the nearest path to follow.
  2633. :return: Gcode string
  2634. """
  2635. log.debug("Generate_from_solderpaste_geometry()")
  2636. # ## Index first and last points in paths
  2637. # What points to index.
  2638. def get_pts(o):
  2639. return [o.coords[0], o.coords[-1]]
  2640. self.gcode = ""
  2641. if not kwargs:
  2642. log.debug("camlib.generate_from_solderpaste_geo() --> No tool in the solderpaste geometry.")
  2643. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2644. _("There is no tool data in the SolderPaste geometry."))
  2645. # this is the tool diameter, it is used as such to accommodate the postprocessor who need the tool diameter
  2646. # given under the name 'toolC'
  2647. self.postdata['z_start'] = kwargs['data']['tools_solderpaste_z_start']
  2648. self.postdata['z_dispense'] = kwargs['data']['tools_solderpaste_z_dispense']
  2649. self.postdata['z_stop'] = kwargs['data']['tools_solderpaste_z_stop']
  2650. self.postdata['z_travel'] = kwargs['data']['tools_solderpaste_z_travel']
  2651. self.postdata['z_toolchange'] = kwargs['data']['tools_solderpaste_z_toolchange']
  2652. self.postdata['xy_toolchange'] = kwargs['data']['tools_solderpaste_xy_toolchange']
  2653. self.postdata['frxy'] = kwargs['data']['tools_solderpaste_frxy']
  2654. self.postdata['frz'] = kwargs['data']['tools_solderpaste_frz']
  2655. self.postdata['frz_dispense'] = kwargs['data']['tools_solderpaste_frz_dispense']
  2656. self.postdata['speedfwd'] = kwargs['data']['tools_solderpaste_speedfwd']
  2657. self.postdata['dwellfwd'] = kwargs['data']['tools_solderpaste_dwellfwd']
  2658. self.postdata['speedrev'] = kwargs['data']['tools_solderpaste_speedrev']
  2659. self.postdata['dwellrev'] = kwargs['data']['tools_solderpaste_dwellrev']
  2660. self.postdata['pp_solderpaste_name'] = kwargs['data']['tools_solderpaste_pp']
  2661. self.postdata['toolC'] = kwargs['tooldia']
  2662. self.pp_solderpaste_name = kwargs['data']['tools_solderpaste_pp'] if kwargs['data']['tools_solderpaste_pp'] \
  2663. else self.app.defaults['tools_solderpaste_pp']
  2664. p = self.app.postprocessors[self.pp_solderpaste_name]
  2665. # ## Flatten the geometry. Only linear elements (no polygons) remain.
  2666. flat_geometry = self.flatten(kwargs['solid_geometry'], pathonly=True)
  2667. log.debug("%d paths" % len(flat_geometry))
  2668. # Create the indexed storage.
  2669. storage = FlatCAMRTreeStorage()
  2670. storage.get_points = get_pts
  2671. # Store the geometry
  2672. log.debug("Indexing geometry before generating G-Code...")
  2673. for shape in flat_geometry:
  2674. if shape is not None:
  2675. storage.insert(shape)
  2676. # Initial G-Code
  2677. self.gcode = self.doformat(p.start_code)
  2678. self.gcode += self.doformat(p.spindle_off_code)
  2679. self.gcode += self.doformat(p.toolchange_code)
  2680. # ## Iterate over geometry paths getting the nearest each time.
  2681. log.debug("Starting SolderPaste G-Code...")
  2682. path_count = 0
  2683. current_pt = (0, 0)
  2684. # variables to display the percentage of work done
  2685. geo_len = len(flat_geometry)
  2686. disp_number = 0
  2687. old_disp_number = 0
  2688. pt, geo = storage.nearest(current_pt)
  2689. try:
  2690. while True:
  2691. if self.app.abort_flag:
  2692. # graceful abort requested by the user
  2693. raise FlatCAMApp.GracefulException
  2694. path_count += 1
  2695. # Remove before modifying, otherwise deletion will fail.
  2696. storage.remove(geo)
  2697. # If last point in geometry is the nearest but prefer the first one if last point == first point
  2698. # then reverse coordinates.
  2699. if pt != geo.coords[0] and pt == geo.coords[-1]:
  2700. geo.coords = list(geo.coords)[::-1]
  2701. self.gcode += self.create_soldepaste_gcode(geo, p=p, old_point=current_pt)
  2702. current_pt = geo.coords[-1]
  2703. pt, geo = storage.nearest(current_pt) # Next
  2704. disp_number = int(np.interp(path_count, [0, geo_len], [0, 100]))
  2705. if old_disp_number < disp_number <= 100:
  2706. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  2707. old_disp_number = disp_number
  2708. except StopIteration: # Nothing found in storage.
  2709. pass
  2710. log.debug("Finishing SolderPste G-Code... %s paths traced." % path_count)
  2711. self.app.inform.emit('%s... %s %s' %
  2712. (_("Finished SolderPste G-Code generation"),
  2713. str(path_count),
  2714. _("paths traced.")
  2715. )
  2716. )
  2717. # Finish
  2718. self.gcode += self.doformat(p.lift_code)
  2719. self.gcode += self.doformat(p.end_code)
  2720. return self.gcode
  2721. def create_soldepaste_gcode(self, geometry, p, old_point=(0, 0)):
  2722. gcode = ''
  2723. path = geometry.coords
  2724. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  2725. if self.coordinates_type == "G90":
  2726. # For Absolute coordinates type G90
  2727. first_x = path[0][0]
  2728. first_y = path[0][1]
  2729. else:
  2730. # For Incremental coordinates type G91
  2731. first_x = path[0][0] - old_point[0]
  2732. first_y = path[0][1] - old_point[1]
  2733. if type(geometry) == LineString or type(geometry) == LinearRing:
  2734. # Move fast to 1st point
  2735. gcode += self.doformat(p.rapid_code, x=first_x, y=first_y) # Move to first point
  2736. # Move down to cutting depth
  2737. gcode += self.doformat(p.z_feedrate_code)
  2738. gcode += self.doformat(p.down_z_start_code)
  2739. gcode += self.doformat(p.spindle_fwd_code) # Start dispensing
  2740. gcode += self.doformat(p.dwell_fwd_code)
  2741. gcode += self.doformat(p.feedrate_z_dispense_code)
  2742. gcode += self.doformat(p.lift_z_dispense_code)
  2743. gcode += self.doformat(p.feedrate_xy_code)
  2744. # Cutting...
  2745. prev_x = first_x
  2746. prev_y = first_y
  2747. for pt in path[1:]:
  2748. if self.coordinates_type == "G90":
  2749. # For Absolute coordinates type G90
  2750. next_x = pt[0]
  2751. next_y = pt[1]
  2752. else:
  2753. # For Incremental coordinates type G91
  2754. next_x = pt[0] - prev_x
  2755. next_y = pt[1] - prev_y
  2756. gcode += self.doformat(p.linear_code, x=next_x, y=next_y) # Linear motion to point
  2757. prev_x = next_x
  2758. prev_y = next_y
  2759. # Up to travelling height.
  2760. gcode += self.doformat(p.spindle_off_code) # Stop dispensing
  2761. gcode += self.doformat(p.spindle_rev_code)
  2762. gcode += self.doformat(p.down_z_stop_code)
  2763. gcode += self.doformat(p.spindle_off_code)
  2764. gcode += self.doformat(p.dwell_rev_code)
  2765. gcode += self.doformat(p.z_feedrate_code)
  2766. gcode += self.doformat(p.lift_code)
  2767. elif type(geometry) == Point:
  2768. gcode += self.doformat(p.linear_code, x=first_x, y=first_y) # Move to first point
  2769. gcode += self.doformat(p.feedrate_z_dispense_code)
  2770. gcode += self.doformat(p.down_z_start_code)
  2771. gcode += self.doformat(p.spindle_fwd_code) # Start dispensing
  2772. gcode += self.doformat(p.dwell_fwd_code)
  2773. gcode += self.doformat(p.lift_z_dispense_code)
  2774. gcode += self.doformat(p.spindle_off_code) # Stop dispensing
  2775. gcode += self.doformat(p.spindle_rev_code)
  2776. gcode += self.doformat(p.spindle_off_code)
  2777. gcode += self.doformat(p.down_z_stop_code)
  2778. gcode += self.doformat(p.dwell_rev_code)
  2779. gcode += self.doformat(p.z_feedrate_code)
  2780. gcode += self.doformat(p.lift_code)
  2781. return gcode
  2782. def create_gcode_single_pass(self, geometry, extracut, tolerance, old_point=(0, 0)):
  2783. # G-code. Note: self.linear2gcode() and self.point2gcode() will lower and raise the tool every time.
  2784. gcode_single_pass = ''
  2785. if type(geometry) == LineString or type(geometry) == LinearRing:
  2786. if extracut is False:
  2787. gcode_single_pass = self.linear2gcode(geometry, tolerance=tolerance, old_point=old_point)
  2788. else:
  2789. if geometry.is_ring:
  2790. gcode_single_pass = self.linear2gcode_extra(geometry, tolerance=tolerance, old_point=old_point)
  2791. else:
  2792. gcode_single_pass = self.linear2gcode(geometry, tolerance=tolerance, old_point=old_point)
  2793. elif type(geometry) == Point:
  2794. gcode_single_pass = self.point2gcode(geometry)
  2795. else:
  2796. log.warning("G-code generation not implemented for %s" % (str(type(geometry))))
  2797. return
  2798. return gcode_single_pass
  2799. def create_gcode_multi_pass(self, geometry, extracut, tolerance, postproc, old_point=(0, 0)):
  2800. gcode_multi_pass = ''
  2801. if isinstance(self.z_cut, Decimal):
  2802. z_cut = self.z_cut
  2803. else:
  2804. z_cut = Decimal(self.z_cut).quantize(Decimal('0.000000001'))
  2805. if self.z_depthpercut is None:
  2806. self.z_depthpercut = z_cut
  2807. elif not isinstance(self.z_depthpercut, Decimal):
  2808. self.z_depthpercut = Decimal(self.z_depthpercut).quantize(Decimal('0.000000001'))
  2809. depth = 0
  2810. reverse = False
  2811. while depth > z_cut:
  2812. # Increase depth. Limit to z_cut.
  2813. depth -= self.z_depthpercut
  2814. if depth < z_cut:
  2815. depth = z_cut
  2816. # Cut at specific depth and do not lift the tool.
  2817. # Note: linear2gcode() will use G00 to move to the first point in the path, but it should be already
  2818. # at the first point if the tool is down (in the material). So, an extra G00 should show up but
  2819. # is inconsequential.
  2820. if type(geometry) == LineString or type(geometry) == LinearRing:
  2821. if extracut is False:
  2822. gcode_multi_pass += self.linear2gcode(geometry, tolerance=tolerance, z_cut=depth, up=False,
  2823. old_point=old_point)
  2824. else:
  2825. if geometry.is_ring:
  2826. gcode_multi_pass += self.linear2gcode_extra(geometry, tolerance=tolerance, z_cut=depth,
  2827. up=False, old_point=old_point)
  2828. else:
  2829. gcode_multi_pass += self.linear2gcode(geometry, tolerance=tolerance, z_cut=depth, up=False,
  2830. old_point=old_point)
  2831. # Ignore multi-pass for points.
  2832. elif type(geometry) == Point:
  2833. gcode_multi_pass += self.point2gcode(geometry, old_point=old_point)
  2834. break # Ignoring ...
  2835. else:
  2836. log.warning("G-code generation not implemented for %s" % (str(type(geometry))))
  2837. # Reverse coordinates if not a loop so we can continue cutting without returning to the beginning.
  2838. if type(geometry) == LineString:
  2839. geometry.coords = list(geometry.coords)[::-1]
  2840. reverse = True
  2841. # If geometry is reversed, revert.
  2842. if reverse:
  2843. if type(geometry) == LineString:
  2844. geometry.coords = list(geometry.coords)[::-1]
  2845. # Lift the tool
  2846. gcode_multi_pass += self.doformat(postproc.lift_code, x=old_point[0], y=old_point[1])
  2847. return gcode_multi_pass
  2848. def codes_split(self, gline):
  2849. """
  2850. Parses a line of G-Code such as "G01 X1234 Y987" into
  2851. a dictionary: {'G': 1.0, 'X': 1234.0, 'Y': 987.0}
  2852. :param gline: G-Code line string
  2853. :return: Dictionary with parsed line.
  2854. """
  2855. command = {}
  2856. if 'Roland' in self.pp_excellon_name or 'Roland' in self.pp_geometry_name:
  2857. match_z = re.search(r"^Z(\s*-?\d+\.\d+?),(\s*\s*-?\d+\.\d+?),(\s*\s*-?\d+\.\d+?)*;$", gline)
  2858. if match_z:
  2859. command['G'] = 0
  2860. command['X'] = float(match_z.group(1).replace(" ", "")) * 0.025
  2861. command['Y'] = float(match_z.group(2).replace(" ", "")) * 0.025
  2862. command['Z'] = float(match_z.group(3).replace(" ", "")) * 0.025
  2863. elif 'hpgl' in self.pp_excellon_name or 'hpgl' in self.pp_geometry_name:
  2864. match_pa = re.search(r"^PA(\s*-?\d+\.\d+?),(\s*\s*-?\d+\.\d+?)*;$", gline)
  2865. if match_pa:
  2866. command['G'] = 0
  2867. command['X'] = float(match_pa.group(1).replace(" ", ""))
  2868. command['Y'] = float(match_pa.group(2).replace(" ", ""))
  2869. match_pen = re.search(r"^(P[U|D])", gline)
  2870. if match_pen:
  2871. if match_pen.group(1) == 'PU':
  2872. # the value does not matter, only that it is positive so the gcode_parse() know it is > 0,
  2873. # therefore the move is of kind T (travel)
  2874. command['Z'] = 1
  2875. else:
  2876. command['Z'] = 0
  2877. elif 'grbl_laser' in self.pp_excellon_name or 'grbl_laser' in self.pp_geometry_name or \
  2878. (self.pp_solderpaste_name is not None and 'Paste' in self.pp_solderpaste_name):
  2879. match_lsr = re.search(r"X([\+-]?\d+.[\+-]?\d+)\s*Y([\+-]?\d+.[\+-]?\d+)", gline)
  2880. if match_lsr:
  2881. command['X'] = float(match_lsr.group(1).replace(" ", ""))
  2882. command['Y'] = float(match_lsr.group(2).replace(" ", ""))
  2883. match_lsr_pos = re.search(r"^(M0[3|5])", gline)
  2884. if match_lsr_pos:
  2885. if 'M05' in match_lsr_pos.group(1):
  2886. # the value does not matter, only that it is positive so the gcode_parse() know it is > 0,
  2887. # therefore the move is of kind T (travel)
  2888. command['Z'] = 1
  2889. else:
  2890. command['Z'] = 0
  2891. elif self.pp_solderpaste_name is not None:
  2892. if 'Paste' in self.pp_solderpaste_name:
  2893. match_paste = re.search(r"X([\+-]?\d+.[\+-]?\d+)\s*Y([\+-]?\d+.[\+-]?\d+)", gline)
  2894. if match_paste:
  2895. command['X'] = float(match_paste.group(1).replace(" ", ""))
  2896. command['Y'] = float(match_paste.group(2).replace(" ", ""))
  2897. else:
  2898. match = re.search(r'^\s*([A-Z])\s*([\+\-\.\d\s]+)', gline)
  2899. while match:
  2900. command[match.group(1)] = float(match.group(2).replace(" ", ""))
  2901. gline = gline[match.end():]
  2902. match = re.search(r'^\s*([A-Z])\s*([\+\-\.\d\s]+)', gline)
  2903. return command
  2904. def gcode_parse(self):
  2905. """
  2906. G-Code parser (from self.gcode). Generates dictionary with
  2907. single-segment LineString's and "kind" indicating cut or travel,
  2908. fast or feedrate speed.
  2909. """
  2910. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  2911. # Results go here
  2912. geometry = []
  2913. # Last known instruction
  2914. current = {'X': 0.0, 'Y': 0.0, 'Z': 0.0, 'G': 0}
  2915. # Current path: temporary storage until tool is
  2916. # lifted or lowered.
  2917. if self.toolchange_xy_type == "excellon":
  2918. if self.app.defaults["excellon_toolchangexy"] == '':
  2919. pos_xy = [0, 0]
  2920. else:
  2921. pos_xy = [float(eval(a)) for a in self.app.defaults["excellon_toolchangexy"].split(",")]
  2922. else:
  2923. if self.app.defaults["geometry_toolchangexy"] == '':
  2924. pos_xy = [0, 0]
  2925. else:
  2926. pos_xy = [float(eval(a)) for a in self.app.defaults["geometry_toolchangexy"].split(",")]
  2927. path = [pos_xy]
  2928. # path = [(0, 0)]
  2929. # Process every instruction
  2930. for line in StringIO(self.gcode):
  2931. if '%MO' in line or '%' in line or 'MOIN' in line or 'MOMM' in line:
  2932. return "fail"
  2933. gobj = self.codes_split(line)
  2934. # ## Units
  2935. if 'G' in gobj and (gobj['G'] == 20.0 or gobj['G'] == 21.0):
  2936. self.units = {20.0: "IN", 21.0: "MM"}[gobj['G']]
  2937. continue
  2938. # ## Changing height
  2939. if 'Z' in gobj:
  2940. if 'Roland' in self.pp_excellon_name or 'Roland' in self.pp_geometry_name:
  2941. pass
  2942. elif 'hpgl' in self.pp_excellon_name or 'hpgl' in self.pp_geometry_name:
  2943. pass
  2944. elif 'laser' in self.pp_excellon_name or 'laser' in self.pp_geometry_name:
  2945. pass
  2946. elif ('X' in gobj or 'Y' in gobj) and gobj['Z'] != current['Z']:
  2947. if self.pp_geometry_name == 'line_xyz' or self.pp_excellon_name == 'line_xyz':
  2948. pass
  2949. else:
  2950. log.warning("Non-orthogonal motion: From %s" % str(current))
  2951. log.warning(" To: %s" % str(gobj))
  2952. current['Z'] = gobj['Z']
  2953. # Store the path into geometry and reset path
  2954. if len(path) > 1:
  2955. geometry.append({"geom": LineString(path),
  2956. "kind": kind})
  2957. path = [path[-1]] # Start with the last point of last path.
  2958. # create the geometry for the holes created when drilling Excellon drills
  2959. if self.origin_kind == 'excellon':
  2960. if current['Z'] < 0:
  2961. current_drill_point_coords = (float('%.4f' % current['X']), float('%.4f' % current['Y']))
  2962. # find the drill diameter knowing the drill coordinates
  2963. for pt_dict in self.exc_drills:
  2964. point_in_dict_coords = (float('%.4f' % pt_dict['point'].x),
  2965. float('%.4f' % pt_dict['point'].y))
  2966. if point_in_dict_coords == current_drill_point_coords:
  2967. tool = pt_dict['tool']
  2968. dia = self.exc_tools[tool]['C']
  2969. kind = ['C', 'F']
  2970. geometry.append({"geom": Point(current_drill_point_coords).
  2971. buffer(dia/2).exterior,
  2972. "kind": kind})
  2973. break
  2974. if 'G' in gobj:
  2975. current['G'] = int(gobj['G'])
  2976. if 'X' in gobj or 'Y' in gobj:
  2977. if 'X' in gobj:
  2978. x = gobj['X']
  2979. # current['X'] = x
  2980. else:
  2981. x = current['X']
  2982. if 'Y' in gobj:
  2983. y = gobj['Y']
  2984. else:
  2985. y = current['Y']
  2986. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  2987. if current['Z'] > 0:
  2988. kind[0] = 'T'
  2989. if current['G'] > 0:
  2990. kind[1] = 'S'
  2991. if current['G'] in [0, 1]: # line
  2992. path.append((x, y))
  2993. arcdir = [None, None, "cw", "ccw"]
  2994. if current['G'] in [2, 3]: # arc
  2995. center = [gobj['I'] + current['X'], gobj['J'] + current['Y']]
  2996. radius = sqrt(gobj['I']**2 + gobj['J']**2)
  2997. start = arctan2(-gobj['J'], -gobj['I'])
  2998. stop = arctan2(-center[1] + y, -center[0] + x)
  2999. path += arc(center, radius, start, stop, arcdir[current['G']], int(self.steps_per_circle / 4))
  3000. # Update current instruction
  3001. for code in gobj:
  3002. current[code] = gobj[code]
  3003. # There might not be a change in height at the
  3004. # end, therefore, see here too if there is
  3005. # a final path.
  3006. if len(path) > 1:
  3007. geometry.append({"geom": LineString(path),
  3008. "kind": kind})
  3009. self.gcode_parsed = geometry
  3010. return geometry
  3011. # def plot(self, tooldia=None, dpi=75, margin=0.1,
  3012. # color={"T": ["#F0E24D", "#B5AB3A"], "C": ["#5E6CFF", "#4650BD"]},
  3013. # alpha={"T": 0.3, "C": 1.0}):
  3014. # """
  3015. # Creates a Matplotlib figure with a plot of the
  3016. # G-code job.
  3017. # """
  3018. # if tooldia is None:
  3019. # tooldia = self.tooldia
  3020. #
  3021. # fig = Figure(dpi=dpi)
  3022. # ax = fig.add_subplot(111)
  3023. # ax.set_aspect(1)
  3024. # xmin, ymin, xmax, ymax = self.input_geometry_bounds
  3025. # ax.set_xlim(xmin-margin, xmax+margin)
  3026. # ax.set_ylim(ymin-margin, ymax+margin)
  3027. #
  3028. # if tooldia == 0:
  3029. # for geo in self.gcode_parsed:
  3030. # linespec = '--'
  3031. # linecolor = color[geo['kind'][0]][1]
  3032. # if geo['kind'][0] == 'C':
  3033. # linespec = 'k-'
  3034. # x, y = geo['geom'].coords.xy
  3035. # ax.plot(x, y, linespec, color=linecolor)
  3036. # else:
  3037. # for geo in self.gcode_parsed:
  3038. # poly = geo['geom'].buffer(tooldia/2.0)
  3039. # patch = PolygonPatch(poly, facecolor=color[geo['kind'][0]][0],
  3040. # edgecolor=color[geo['kind'][0]][1],
  3041. # alpha=alpha[geo['kind'][0]], zorder=2)
  3042. # ax.add_patch(patch)
  3043. #
  3044. # return fig
  3045. def plot2(self, tooldia=None, dpi=75, margin=0.1, gcode_parsed=None,
  3046. color={"T": ["#F0E24D4C", "#B5AB3A4C"], "C": ["#5E6CFFFF", "#4650BDFF"]},
  3047. alpha={"T": 0.3, "C": 1.0}, tool_tolerance=0.0005, obj=None, visible=False, kind='all'):
  3048. """
  3049. Plots the G-code job onto the given axes.
  3050. :param tooldia: Tool diameter.
  3051. :param dpi: Not used!
  3052. :param margin: Not used!
  3053. :param color: Color specification.
  3054. :param alpha: Transparency specification.
  3055. :param tool_tolerance: Tolerance when drawing the toolshape.
  3056. :param obj
  3057. :param visible
  3058. :param kind
  3059. :return: None
  3060. """
  3061. # units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3062. gcode_parsed = gcode_parsed if gcode_parsed else self.gcode_parsed
  3063. path_num = 0
  3064. if tooldia is None:
  3065. tooldia = self.tooldia
  3066. # this should be unlikely unless when upstream the tooldia is a tuple made by one dia and a comma like (2.4,)
  3067. if isinstance(tooldia, list):
  3068. tooldia = tooldia[0] if tooldia[0] is not None else self.tooldia
  3069. if tooldia == 0:
  3070. for geo in gcode_parsed:
  3071. if kind == 'all':
  3072. obj.add_shape(shape=geo['geom'], color=color[geo['kind'][0]][1], visible=visible)
  3073. elif kind == 'travel':
  3074. if geo['kind'][0] == 'T':
  3075. obj.add_shape(shape=geo['geom'], color=color['T'][1], visible=visible)
  3076. elif kind == 'cut':
  3077. if geo['kind'][0] == 'C':
  3078. obj.add_shape(shape=geo['geom'], color=color['C'][1], visible=visible)
  3079. else:
  3080. text = []
  3081. pos = []
  3082. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  3083. if self.coordinates_type == "G90":
  3084. # For Absolute coordinates type G90
  3085. for geo in gcode_parsed:
  3086. if geo['kind'][0] == 'T':
  3087. current_position = geo['geom'].coords[0]
  3088. if current_position not in pos:
  3089. pos.append(current_position)
  3090. path_num += 1
  3091. text.append(str(path_num))
  3092. current_position = geo['geom'].coords[-1]
  3093. if current_position not in pos:
  3094. pos.append(current_position)
  3095. path_num += 1
  3096. text.append(str(path_num))
  3097. # plot the geometry of Excellon objects
  3098. if self.origin_kind == 'excellon':
  3099. try:
  3100. poly = Polygon(geo['geom'])
  3101. except ValueError:
  3102. # if the geos are travel lines it will enter into Exception
  3103. poly = geo['geom'].buffer(distance=(tooldia / 1.99999999), resolution=self.steps_per_circle)
  3104. poly = poly.simplify(tool_tolerance)
  3105. else:
  3106. # plot the geometry of any objects other than Excellon
  3107. poly = geo['geom'].buffer(distance=(tooldia / 1.99999999), resolution=self.steps_per_circle)
  3108. poly = poly.simplify(tool_tolerance)
  3109. if kind == 'all':
  3110. obj.add_shape(shape=poly, color=color[geo['kind'][0]][1], face_color=color[geo['kind'][0]][0],
  3111. visible=visible, layer=1 if geo['kind'][0] == 'C' else 2)
  3112. elif kind == 'travel':
  3113. if geo['kind'][0] == 'T':
  3114. obj.add_shape(shape=poly, color=color['T'][1], face_color=color['T'][0],
  3115. visible=visible, layer=2)
  3116. elif kind == 'cut':
  3117. if geo['kind'][0] == 'C':
  3118. obj.add_shape(shape=poly, color=color['C'][1], face_color=color['C'][0],
  3119. visible=visible, layer=1)
  3120. else:
  3121. # For Incremental coordinates type G91
  3122. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3123. _('G91 coordinates not implemented ...'))
  3124. for geo in gcode_parsed:
  3125. if geo['kind'][0] == 'T':
  3126. current_position = geo['geom'].coords[0]
  3127. if current_position not in pos:
  3128. pos.append(current_position)
  3129. path_num += 1
  3130. text.append(str(path_num))
  3131. current_position = geo['geom'].coords[-1]
  3132. if current_position not in pos:
  3133. pos.append(current_position)
  3134. path_num += 1
  3135. text.append(str(path_num))
  3136. # plot the geometry of Excellon objects
  3137. if self.origin_kind == 'excellon':
  3138. try:
  3139. poly = Polygon(geo['geom'])
  3140. except ValueError:
  3141. # if the geos are travel lines it will enter into Exception
  3142. poly = geo['geom'].buffer(distance=(tooldia / 1.99999999), resolution=self.steps_per_circle)
  3143. poly = poly.simplify(tool_tolerance)
  3144. else:
  3145. # plot the geometry of any objects other than Excellon
  3146. poly = geo['geom'].buffer(distance=(tooldia / 1.99999999), resolution=self.steps_per_circle)
  3147. poly = poly.simplify(tool_tolerance)
  3148. if kind == 'all':
  3149. obj.add_shape(shape=poly, color=color[geo['kind'][0]][1], face_color=color[geo['kind'][0]][0],
  3150. visible=visible, layer=1 if geo['kind'][0] == 'C' else 2)
  3151. elif kind == 'travel':
  3152. if geo['kind'][0] == 'T':
  3153. obj.add_shape(shape=poly, color=color['T'][1], face_color=color['T'][0],
  3154. visible=visible, layer=2)
  3155. elif kind == 'cut':
  3156. if geo['kind'][0] == 'C':
  3157. obj.add_shape(shape=poly, color=color['C'][1], face_color=color['C'][0],
  3158. visible=visible, layer=1)
  3159. # current_x = gcode_parsed[0]['geom'].coords[0][0]
  3160. # current_y = gcode_parsed[0]['geom'].coords[0][1]
  3161. # old_pos = (
  3162. # current_x,
  3163. # current_y
  3164. # )
  3165. #
  3166. # for geo in gcode_parsed:
  3167. # if geo['kind'][0] == 'T':
  3168. # current_position = (
  3169. # geo['geom'].coords[0][0] + old_pos[0],
  3170. # geo['geom'].coords[0][1] + old_pos[1]
  3171. # )
  3172. # if current_position not in pos:
  3173. # pos.append(current_position)
  3174. # path_num += 1
  3175. # text.append(str(path_num))
  3176. #
  3177. # delta = (
  3178. # geo['geom'].coords[-1][0] - geo['geom'].coords[0][0],
  3179. # geo['geom'].coords[-1][1] - geo['geom'].coords[0][1]
  3180. # )
  3181. # current_position = (
  3182. # current_position[0] + geo['geom'].coords[-1][0],
  3183. # current_position[1] + geo['geom'].coords[-1][1]
  3184. # )
  3185. # if current_position not in pos:
  3186. # pos.append(current_position)
  3187. # path_num += 1
  3188. # text.append(str(path_num))
  3189. #
  3190. # # plot the geometry of Excellon objects
  3191. # if self.origin_kind == 'excellon':
  3192. # if isinstance(geo['geom'], Point):
  3193. # # if geo is Point
  3194. # current_position = (
  3195. # current_position[0] + geo['geom'].x,
  3196. # current_position[1] + geo['geom'].y
  3197. # )
  3198. # poly = Polygon(Point(current_position))
  3199. # elif isinstance(geo['geom'], LineString):
  3200. # # if the geos are travel lines (LineStrings)
  3201. # new_line_pts = []
  3202. # old_line_pos = deepcopy(current_position)
  3203. # for p in list(geo['geom'].coords):
  3204. # current_position = (
  3205. # current_position[0] + p[0],
  3206. # current_position[1] + p[1]
  3207. # )
  3208. # new_line_pts.append(current_position)
  3209. # old_line_pos = p
  3210. # new_line = LineString(new_line_pts)
  3211. #
  3212. # poly = new_line.buffer(distance=(tooldia / 1.99999999), resolution=self.steps_per_circle)
  3213. # poly = poly.simplify(tool_tolerance)
  3214. # else:
  3215. # # plot the geometry of any objects other than Excellon
  3216. # new_line_pts = []
  3217. # old_line_pos = deepcopy(current_position)
  3218. # for p in list(geo['geom'].coords):
  3219. # current_position = (
  3220. # current_position[0] + p[0],
  3221. # current_position[1] + p[1]
  3222. # )
  3223. # new_line_pts.append(current_position)
  3224. # old_line_pos = p
  3225. # new_line = LineString(new_line_pts)
  3226. #
  3227. # poly = new_line.buffer(distance=(tooldia / 1.99999999), resolution=self.steps_per_circle)
  3228. # poly = poly.simplify(tool_tolerance)
  3229. #
  3230. # old_pos = deepcopy(current_position)
  3231. #
  3232. # if kind == 'all':
  3233. # obj.add_shape(shape=poly, color=color[geo['kind'][0]][1], face_color=color[geo['kind'][0]][0],
  3234. # visible=visible, layer=1 if geo['kind'][0] == 'C' else 2)
  3235. # elif kind == 'travel':
  3236. # if geo['kind'][0] == 'T':
  3237. # obj.add_shape(shape=poly, color=color['T'][1], face_color=color['T'][0],
  3238. # visible=visible, layer=2)
  3239. # elif kind == 'cut':
  3240. # if geo['kind'][0] == 'C':
  3241. # obj.add_shape(shape=poly, color=color['C'][1], face_color=color['C'][0],
  3242. # visible=visible, layer=1)
  3243. try:
  3244. obj.annotation.set(text=text, pos=pos, visible=obj.options['plot'],
  3245. font_size=self.app.defaults["cncjob_annotation_fontsize"],
  3246. color=self.app.defaults["cncjob_annotation_fontcolor"])
  3247. except Exception as e:
  3248. pass
  3249. def create_geometry(self):
  3250. # TODO: This takes forever. Too much data?
  3251. self.solid_geometry = cascaded_union([geo['geom'] for geo in self.gcode_parsed])
  3252. return self.solid_geometry
  3253. # code snippet added by Lei Zheng in a rejected pull request on FlatCAM https://bitbucket.org/realthunder/
  3254. def segment(self, coords):
  3255. """
  3256. break long linear lines to make it more auto level friendly
  3257. """
  3258. if len(coords) < 2 or self.segx <= 0 and self.segy <= 0:
  3259. return list(coords)
  3260. path = [coords[0]]
  3261. # break the line in either x or y dimension only
  3262. def linebreak_single(line, dim, dmax):
  3263. if dmax <= 0:
  3264. return None
  3265. if line[1][dim] > line[0][dim]:
  3266. sign = 1.0
  3267. d = line[1][dim] - line[0][dim]
  3268. else:
  3269. sign = -1.0
  3270. d = line[0][dim] - line[1][dim]
  3271. if d > dmax:
  3272. # make sure we don't make any new lines too short
  3273. if d > dmax * 2:
  3274. dd = dmax
  3275. else:
  3276. dd = d / 2
  3277. other = dim ^ 1
  3278. return (line[0][dim] + dd * sign, line[0][other] + \
  3279. dd * (line[1][other] - line[0][other]) / d)
  3280. return None
  3281. # recursively breaks down a given line until it is within the
  3282. # required step size
  3283. def linebreak(line):
  3284. pt_new = linebreak_single(line, 0, self.segx)
  3285. if pt_new is None:
  3286. pt_new2 = linebreak_single(line, 1, self.segy)
  3287. else:
  3288. pt_new2 = linebreak_single((line[0], pt_new), 1, self.segy)
  3289. if pt_new2 is not None:
  3290. pt_new = pt_new2[::-1]
  3291. if pt_new is None:
  3292. path.append(line[1])
  3293. else:
  3294. path.append(pt_new)
  3295. linebreak((pt_new, line[1]))
  3296. for pt in coords[1:]:
  3297. linebreak((path[-1], pt))
  3298. return path
  3299. def linear2gcode(self, linear, tolerance=0, down=True, up=True,
  3300. z_cut=None, z_move=None, zdownrate=None,
  3301. feedrate=None, feedrate_z=None, feedrate_rapid=None, cont=False, old_point=(0, 0)):
  3302. """
  3303. Generates G-code to cut along the linear feature.
  3304. :param linear: The path to cut along.
  3305. :type: Shapely.LinearRing or Shapely.Linear String
  3306. :param tolerance: All points in the simplified object will be within the
  3307. tolerance distance of the original geometry.
  3308. :type tolerance: float
  3309. :param feedrate: speed for cut on X - Y plane
  3310. :param feedrate_z: speed for cut on Z plane
  3311. :param feedrate_rapid: speed to move between cuts; usually is G0 but some CNC require to specify it
  3312. :return: G-code to cut along the linear feature.
  3313. :rtype: str
  3314. """
  3315. if z_cut is None:
  3316. z_cut = self.z_cut
  3317. if z_move is None:
  3318. z_move = self.z_move
  3319. #
  3320. # if zdownrate is None:
  3321. # zdownrate = self.zdownrate
  3322. if feedrate is None:
  3323. feedrate = self.feedrate
  3324. if feedrate_z is None:
  3325. feedrate_z = self.z_feedrate
  3326. if feedrate_rapid is None:
  3327. feedrate_rapid = self.feedrate_rapid
  3328. # Simplify paths?
  3329. if tolerance > 0:
  3330. target_linear = linear.simplify(tolerance)
  3331. else:
  3332. target_linear = linear
  3333. gcode = ""
  3334. # path = list(target_linear.coords)
  3335. path = self.segment(target_linear.coords)
  3336. p = self.pp_geometry
  3337. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  3338. if self.coordinates_type == "G90":
  3339. # For Absolute coordinates type G90
  3340. first_x = path[0][0]
  3341. first_y = path[0][1]
  3342. else:
  3343. # For Incremental coordinates type G91
  3344. first_x = path[0][0] - old_point[0]
  3345. first_y = path[0][1] - old_point[1]
  3346. # Move fast to 1st point
  3347. if not cont:
  3348. gcode += self.doformat(p.rapid_code, x=first_x, y=first_y) # Move to first point
  3349. # Move down to cutting depth
  3350. if down:
  3351. # Different feedrate for vertical cut?
  3352. gcode += self.doformat(p.z_feedrate_code)
  3353. # gcode += self.doformat(p.feedrate_code)
  3354. gcode += self.doformat(p.down_code, x=first_x, y=first_y, z_cut=z_cut)
  3355. gcode += self.doformat(p.feedrate_code, feedrate=feedrate)
  3356. # Cutting...
  3357. prev_x = first_x
  3358. prev_y = first_y
  3359. for pt in path[1:]:
  3360. if self.app.abort_flag:
  3361. # graceful abort requested by the user
  3362. raise FlatCAMApp.GracefulException
  3363. if self.coordinates_type == "G90":
  3364. # For Absolute coordinates type G90
  3365. next_x = pt[0]
  3366. next_y = pt[1]
  3367. else:
  3368. # For Incremental coordinates type G91
  3369. # next_x = pt[0] - prev_x
  3370. # next_y = pt[1] - prev_y
  3371. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3372. _('G91 coordinates not implemented ...'))
  3373. next_x = pt[0]
  3374. next_y = pt[1]
  3375. gcode += self.doformat(p.linear_code, x=next_x, y=next_y, z=z_cut) # Linear motion to point
  3376. prev_x = pt[0]
  3377. prev_y = pt[1]
  3378. # Up to travelling height.
  3379. if up:
  3380. gcode += self.doformat(p.lift_code, x=prev_x, y=prev_y, z_move=z_move) # Stop cutting
  3381. return gcode
  3382. def linear2gcode_extra(self, linear, tolerance=0, down=True, up=True,
  3383. z_cut=None, z_move=None, zdownrate=None,
  3384. feedrate=None, feedrate_z=None, feedrate_rapid=None, cont=False, old_point=(0, 0)):
  3385. """
  3386. Generates G-code to cut along the linear feature.
  3387. :param linear: The path to cut along.
  3388. :type: Shapely.LinearRing or Shapely.Linear String
  3389. :param tolerance: All points in the simplified object will be within the
  3390. tolerance distance of the original geometry.
  3391. :type tolerance: float
  3392. :param feedrate: speed for cut on X - Y plane
  3393. :param feedrate_z: speed for cut on Z plane
  3394. :param feedrate_rapid: speed to move between cuts; usually is G0 but some CNC require to specify it
  3395. :return: G-code to cut along the linear feature.
  3396. :rtype: str
  3397. """
  3398. if z_cut is None:
  3399. z_cut = self.z_cut
  3400. if z_move is None:
  3401. z_move = self.z_move
  3402. #
  3403. # if zdownrate is None:
  3404. # zdownrate = self.zdownrate
  3405. if feedrate is None:
  3406. feedrate = self.feedrate
  3407. if feedrate_z is None:
  3408. feedrate_z = self.z_feedrate
  3409. if feedrate_rapid is None:
  3410. feedrate_rapid = self.feedrate_rapid
  3411. # Simplify paths?
  3412. if tolerance > 0:
  3413. target_linear = linear.simplify(tolerance)
  3414. else:
  3415. target_linear = linear
  3416. gcode = ""
  3417. path = list(target_linear.coords)
  3418. p = self.pp_geometry
  3419. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  3420. if self.coordinates_type == "G90":
  3421. # For Absolute coordinates type G90
  3422. first_x = path[0][0]
  3423. first_y = path[0][1]
  3424. else:
  3425. # For Incremental coordinates type G91
  3426. first_x = path[0][0] - old_point[0]
  3427. first_y = path[0][1] - old_point[1]
  3428. # Move fast to 1st point
  3429. if not cont:
  3430. gcode += self.doformat(p.rapid_code, x=first_x, y=first_y) # Move to first point
  3431. # Move down to cutting depth
  3432. if down:
  3433. # Different feedrate for vertical cut?
  3434. if self.z_feedrate is not None:
  3435. gcode += self.doformat(p.z_feedrate_code)
  3436. # gcode += self.doformat(p.feedrate_code)
  3437. gcode += self.doformat(p.down_code, x=first_x, y=first_y, z_cut=z_cut)
  3438. gcode += self.doformat(p.feedrate_code, feedrate=feedrate)
  3439. else:
  3440. gcode += self.doformat(p.down_code, x=first_x, y=first_y, z_cut=z_cut) # Start cutting
  3441. # Cutting...
  3442. prev_x = first_x
  3443. prev_y = first_y
  3444. for pt in path[1:]:
  3445. if self.app.abort_flag:
  3446. # graceful abort requested by the user
  3447. raise FlatCAMApp.GracefulException
  3448. if self.coordinates_type == "G90":
  3449. # For Absolute coordinates type G90
  3450. next_x = pt[0]
  3451. next_y = pt[1]
  3452. else:
  3453. # For Incremental coordinates type G91
  3454. # For Incremental coordinates type G91
  3455. # next_x = pt[0] - prev_x
  3456. # next_y = pt[1] - prev_y
  3457. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3458. _('G91 coordinates not implemented ...'))
  3459. next_x = pt[0]
  3460. next_y = pt[1]
  3461. gcode += self.doformat(p.linear_code, x=next_x, y=next_y, z=z_cut) # Linear motion to point
  3462. prev_x = pt[0]
  3463. prev_y = pt[1]
  3464. # this line is added to create an extra cut over the first point in patch
  3465. # to make sure that we remove the copper leftovers
  3466. # Linear motion to the 1st point in the cut path
  3467. if self.coordinates_type == "G90":
  3468. # For Absolute coordinates type G90
  3469. last_x = path[1][0]
  3470. last_y = path[1][1]
  3471. else:
  3472. # For Incremental coordinates type G91
  3473. last_x = path[1][0] - first_x
  3474. last_y = path[1][1] - first_y
  3475. gcode += self.doformat(p.linear_code, x=last_x, y=last_y)
  3476. # Up to travelling height.
  3477. if up:
  3478. gcode += self.doformat(p.lift_code, x=last_x, y=last_y, z_move=z_move) # Stop cutting
  3479. return gcode
  3480. def point2gcode(self, point, old_point=(0, 0)):
  3481. gcode = ""
  3482. if self.app.abort_flag:
  3483. # graceful abort requested by the user
  3484. raise FlatCAMApp.GracefulException
  3485. path = list(point.coords)
  3486. p = self.pp_geometry
  3487. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  3488. if self.coordinates_type == "G90":
  3489. # For Absolute coordinates type G90
  3490. first_x = path[0][0]
  3491. first_y = path[0][1]
  3492. else:
  3493. # For Incremental coordinates type G91
  3494. # first_x = path[0][0] - old_point[0]
  3495. # first_y = path[0][1] - old_point[1]
  3496. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3497. _('G91 coordinates not implemented ...'))
  3498. first_x = path[0][0]
  3499. first_y = path[0][1]
  3500. gcode += self.doformat(p.linear_code, x=first_x, y=first_y) # Move to first point
  3501. if self.z_feedrate is not None:
  3502. gcode += self.doformat(p.z_feedrate_code)
  3503. gcode += self.doformat(p.down_code, x=first_x, y=first_y, z_cut = self.z_cut)
  3504. gcode += self.doformat(p.feedrate_code)
  3505. else:
  3506. gcode += self.doformat(p.down_code, x=first_x, y=first_y, z_cut = self.z_cut) # Start cutting
  3507. gcode += self.doformat(p.lift_code, x=first_x, y=first_y) # Stop cutting
  3508. return gcode
  3509. def export_svg(self, scale_factor=0.00):
  3510. """
  3511. Exports the CNC Job as a SVG Element
  3512. :scale_factor: float
  3513. :return: SVG Element string
  3514. """
  3515. # scale_factor is a multiplication factor for the SVG stroke-width used within shapely's svg export
  3516. # If not specified then try and use the tool diameter
  3517. # This way what is on screen will match what is outputed for the svg
  3518. # This is quite a useful feature for svg's used with visicut
  3519. if scale_factor <= 0:
  3520. scale_factor = self.options['tooldia'] / 2
  3521. # If still 0 then default to 0.05
  3522. # This value appears to work for zooming, and getting the output svg line width
  3523. # to match that viewed on screen with FlatCam
  3524. if scale_factor == 0:
  3525. scale_factor = 0.01
  3526. # Separate the list of cuts and travels into 2 distinct lists
  3527. # This way we can add different formatting / colors to both
  3528. cuts = []
  3529. travels = []
  3530. for g in self.gcode_parsed:
  3531. if self.app.abort_flag:
  3532. # graceful abort requested by the user
  3533. raise FlatCAMApp.GracefulException
  3534. if g['kind'][0] == 'C': cuts.append(g)
  3535. if g['kind'][0] == 'T': travels.append(g)
  3536. # Used to determine the overall board size
  3537. self.solid_geometry = cascaded_union([geo['geom'] for geo in self.gcode_parsed])
  3538. # Convert the cuts and travels into single geometry objects we can render as svg xml
  3539. if travels:
  3540. travelsgeom = cascaded_union([geo['geom'] for geo in travels])
  3541. if self.app.abort_flag:
  3542. # graceful abort requested by the user
  3543. raise FlatCAMApp.GracefulException
  3544. if cuts:
  3545. cutsgeom = cascaded_union([geo['geom'] for geo in cuts])
  3546. # Render the SVG Xml
  3547. # The scale factor affects the size of the lines, and the stroke color adds different formatting for each set
  3548. # It's better to have the travels sitting underneath the cuts for visicut
  3549. svg_elem = ""
  3550. if travels:
  3551. svg_elem = travelsgeom.svg(scale_factor=scale_factor, stroke_color="#F0E24D")
  3552. if cuts:
  3553. svg_elem += cutsgeom.svg(scale_factor=scale_factor, stroke_color="#5E6CFF")
  3554. return svg_elem
  3555. def bounds(self):
  3556. """
  3557. Returns coordinates of rectangular bounds
  3558. of geometry: (xmin, ymin, xmax, ymax).
  3559. """
  3560. # fixed issue of getting bounds only for one level lists of objects
  3561. # now it can get bounds for nested lists of objects
  3562. log.debug("camlib.CNCJob.bounds()")
  3563. def bounds_rec(obj):
  3564. if type(obj) is list:
  3565. minx = Inf
  3566. miny = Inf
  3567. maxx = -Inf
  3568. maxy = -Inf
  3569. for k in obj:
  3570. if type(k) is dict:
  3571. for key in k:
  3572. minx_, miny_, maxx_, maxy_ = bounds_rec(k[key])
  3573. minx = min(minx, minx_)
  3574. miny = min(miny, miny_)
  3575. maxx = max(maxx, maxx_)
  3576. maxy = max(maxy, maxy_)
  3577. else:
  3578. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  3579. minx = min(minx, minx_)
  3580. miny = min(miny, miny_)
  3581. maxx = max(maxx, maxx_)
  3582. maxy = max(maxy, maxy_)
  3583. return minx, miny, maxx, maxy
  3584. else:
  3585. # it's a Shapely object, return it's bounds
  3586. return obj.bounds
  3587. if self.multitool is False:
  3588. log.debug("CNCJob->bounds()")
  3589. if self.solid_geometry is None:
  3590. log.debug("solid_geometry is None")
  3591. return 0, 0, 0, 0
  3592. bounds_coords = bounds_rec(self.solid_geometry)
  3593. else:
  3594. minx = Inf
  3595. miny = Inf
  3596. maxx = -Inf
  3597. maxy = -Inf
  3598. for k, v in self.cnc_tools.items():
  3599. minx = Inf
  3600. miny = Inf
  3601. maxx = -Inf
  3602. maxy = -Inf
  3603. try:
  3604. for k in v['solid_geometry']:
  3605. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  3606. minx = min(minx, minx_)
  3607. miny = min(miny, miny_)
  3608. maxx = max(maxx, maxx_)
  3609. maxy = max(maxy, maxy_)
  3610. except TypeError:
  3611. minx_, miny_, maxx_, maxy_ = bounds_rec(v['solid_geometry'])
  3612. minx = min(minx, minx_)
  3613. miny = min(miny, miny_)
  3614. maxx = max(maxx, maxx_)
  3615. maxy = max(maxy, maxy_)
  3616. bounds_coords = minx, miny, maxx, maxy
  3617. return bounds_coords
  3618. # TODO This function should be replaced at some point with a "real" function. Until then it's an ugly hack ...
  3619. def scale(self, xfactor, yfactor=None, point=None):
  3620. """
  3621. Scales all the geometry on the XY plane in the object by the
  3622. given factor. Tool sizes, feedrates, or Z-axis dimensions are
  3623. not altered.
  3624. :param factor: Number by which to scale the object.
  3625. :type factor: float
  3626. :param point: the (x,y) coords for the point of origin of scale
  3627. :type tuple of floats
  3628. :return: None
  3629. :rtype: None
  3630. """
  3631. log.debug("camlib.CNCJob.scale()")
  3632. if yfactor is None:
  3633. yfactor = xfactor
  3634. if point is None:
  3635. px = 0
  3636. py = 0
  3637. else:
  3638. px, py = point
  3639. def scale_g(g):
  3640. """
  3641. :param g: 'g' parameter it's a gcode string
  3642. :return: scaled gcode string
  3643. """
  3644. temp_gcode = ''
  3645. header_start = False
  3646. header_stop = False
  3647. units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3648. lines = StringIO(g)
  3649. for line in lines:
  3650. # this changes the GCODE header ---- UGLY HACK
  3651. if "TOOL DIAMETER" in line or "Feedrate:" in line:
  3652. header_start = True
  3653. if "G20" in line or "G21" in line:
  3654. header_start = False
  3655. header_stop = True
  3656. if header_start is True:
  3657. header_stop = False
  3658. if "in" in line:
  3659. if units == 'MM':
  3660. line = line.replace("in", "mm")
  3661. if "mm" in line:
  3662. if units == 'IN':
  3663. line = line.replace("mm", "in")
  3664. # find any float number in header (even multiple on the same line) and convert it
  3665. numbers_in_header = re.findall(self.g_nr_re, line)
  3666. if numbers_in_header:
  3667. for nr in numbers_in_header:
  3668. new_nr = float(nr) * xfactor
  3669. # replace the updated string
  3670. line = line.replace(nr, ('%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_nr))
  3671. )
  3672. # this scales all the X and Y and Z and F values and also the Tool Dia in the toolchange message
  3673. if header_stop is True:
  3674. if "G20" in line:
  3675. if units == 'MM':
  3676. line = line.replace("G20", "G21")
  3677. if "G21" in line:
  3678. if units == 'IN':
  3679. line = line.replace("G21", "G20")
  3680. # find the X group
  3681. match_x = self.g_x_re.search(line)
  3682. if match_x:
  3683. if match_x.group(1) is not None:
  3684. new_x = float(match_x.group(1)[1:]) * xfactor
  3685. # replace the updated string
  3686. line = line.replace(
  3687. match_x.group(1),
  3688. 'X%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_x)
  3689. )
  3690. # find the Y group
  3691. match_y = self.g_y_re.search(line)
  3692. if match_y:
  3693. if match_y.group(1) is not None:
  3694. new_y = float(match_y.group(1)[1:]) * yfactor
  3695. line = line.replace(
  3696. match_y.group(1),
  3697. 'Y%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_y)
  3698. )
  3699. # find the Z group
  3700. match_z = self.g_z_re.search(line)
  3701. if match_z:
  3702. if match_z.group(1) is not None:
  3703. new_z = float(match_z.group(1)[1:]) * xfactor
  3704. line = line.replace(
  3705. match_z.group(1),
  3706. 'Z%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_z)
  3707. )
  3708. # find the F group
  3709. match_f = self.g_f_re.search(line)
  3710. if match_f:
  3711. if match_f.group(1) is not None:
  3712. new_f = float(match_f.group(1)[1:]) * xfactor
  3713. line = line.replace(
  3714. match_f.group(1),
  3715. 'F%.*f' % (self.app.defaults["cncjob_fr_decimals"], new_f)
  3716. )
  3717. # find the T group (tool dia on toolchange)
  3718. match_t = self.g_t_re.search(line)
  3719. if match_t:
  3720. if match_t.group(1) is not None:
  3721. new_t = float(match_t.group(1)[1:]) * xfactor
  3722. line = line.replace(
  3723. match_t.group(1),
  3724. '= %.*f' % (self.app.defaults["cncjob_coords_decimals"], new_t)
  3725. )
  3726. temp_gcode += line
  3727. lines.close()
  3728. header_stop = False
  3729. return temp_gcode
  3730. if self.multitool is False:
  3731. # offset Gcode
  3732. self.gcode = scale_g(self.gcode)
  3733. # variables to display the percentage of work done
  3734. self.geo_len = 0
  3735. try:
  3736. for g in self.gcode_parsed:
  3737. self.geo_len += 1
  3738. except TypeError:
  3739. self.geo_len = 1
  3740. self.old_disp_number = 0
  3741. self.el_count = 0
  3742. # scale geometry
  3743. for g in self.gcode_parsed:
  3744. try:
  3745. g['geom'] = affinity.scale(g['geom'], xfactor, yfactor, origin=(px, py))
  3746. except AttributeError:
  3747. return g['geom']
  3748. self.el_count += 1
  3749. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  3750. if self.old_disp_number < disp_number <= 100:
  3751. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  3752. self.old_disp_number = disp_number
  3753. self.create_geometry()
  3754. else:
  3755. for k, v in self.cnc_tools.items():
  3756. # scale Gcode
  3757. v['gcode'] = scale_g(v['gcode'])
  3758. # variables to display the percentage of work done
  3759. self.geo_len = 0
  3760. try:
  3761. for g in v['gcode_parsed']:
  3762. self.geo_len += 1
  3763. except TypeError:
  3764. self.geo_len = 1
  3765. self.old_disp_number = 0
  3766. self.el_count = 0
  3767. # scale gcode_parsed
  3768. for g in v['gcode_parsed']:
  3769. try:
  3770. g['geom'] = affinity.scale(g['geom'], xfactor, yfactor, origin=(px, py))
  3771. except AttributeError:
  3772. return g['geom']
  3773. self.el_count += 1
  3774. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  3775. if self.old_disp_number < disp_number <= 100:
  3776. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  3777. self.old_disp_number = disp_number
  3778. v['solid_geometry'] = cascaded_union([geo['geom'] for geo in v['gcode_parsed']])
  3779. self.create_geometry()
  3780. self.app.proc_container.new_text = ''
  3781. def offset(self, vect):
  3782. """
  3783. Offsets all the geometry on the XY plane in the object by the
  3784. given vector.
  3785. Offsets all the GCODE on the XY plane in the object by the
  3786. given vector.
  3787. g_offsetx_re, g_offsety_re, multitool, cnnc_tools are attributes of FlatCAMCNCJob class in camlib
  3788. :param vect: (x, y) offset vector.
  3789. :type vect: tuple
  3790. :return: None
  3791. """
  3792. log.debug("camlib.CNCJob.offset()")
  3793. dx, dy = vect
  3794. def offset_g(g):
  3795. """
  3796. :param g: 'g' parameter it's a gcode string
  3797. :return: offseted gcode string
  3798. """
  3799. temp_gcode = ''
  3800. lines = StringIO(g)
  3801. for line in lines:
  3802. # find the X group
  3803. match_x = self.g_x_re.search(line)
  3804. if match_x:
  3805. if match_x.group(1) is not None:
  3806. # get the coordinate and add X offset
  3807. new_x = float(match_x.group(1)[1:]) + dx
  3808. # replace the updated string
  3809. line = line.replace(
  3810. match_x.group(1),
  3811. 'X%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_x)
  3812. )
  3813. match_y = self.g_y_re.search(line)
  3814. if match_y:
  3815. if match_y.group(1) is not None:
  3816. new_y = float(match_y.group(1)[1:]) + dy
  3817. line = line.replace(
  3818. match_y.group(1),
  3819. 'Y%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_y)
  3820. )
  3821. temp_gcode += line
  3822. lines.close()
  3823. return temp_gcode
  3824. if self.multitool is False:
  3825. # offset Gcode
  3826. self.gcode = offset_g(self.gcode)
  3827. # variables to display the percentage of work done
  3828. self.geo_len = 0
  3829. try:
  3830. for g in self.gcode_parsed:
  3831. self.geo_len += 1
  3832. except TypeError:
  3833. self.geo_len = 1
  3834. self.old_disp_number = 0
  3835. self.el_count = 0
  3836. # offset geometry
  3837. for g in self.gcode_parsed:
  3838. try:
  3839. g['geom'] = affinity.translate(g['geom'], xoff=dx, yoff=dy)
  3840. except AttributeError:
  3841. return g['geom']
  3842. self.el_count += 1
  3843. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  3844. if self.old_disp_number < disp_number <= 100:
  3845. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  3846. self.old_disp_number = disp_number
  3847. self.create_geometry()
  3848. else:
  3849. for k, v in self.cnc_tools.items():
  3850. # offset Gcode
  3851. v['gcode'] = offset_g(v['gcode'])
  3852. # variables to display the percentage of work done
  3853. self.geo_len = 0
  3854. try:
  3855. for g in v['gcode_parsed']:
  3856. self.geo_len += 1
  3857. except TypeError:
  3858. self.geo_len = 1
  3859. self.old_disp_number = 0
  3860. self.el_count = 0
  3861. # offset gcode_parsed
  3862. for g in v['gcode_parsed']:
  3863. try:
  3864. g['geom'] = affinity.translate(g['geom'], xoff=dx, yoff=dy)
  3865. except AttributeError:
  3866. return g['geom']
  3867. self.el_count += 1
  3868. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  3869. if self.old_disp_number < disp_number <= 100:
  3870. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  3871. self.old_disp_number = disp_number
  3872. # for the bounding box
  3873. v['solid_geometry'] = cascaded_union([geo['geom'] for geo in v['gcode_parsed']])
  3874. self.app.proc_container.new_text = ''
  3875. def mirror(self, axis, point):
  3876. """
  3877. Mirror the geometrys of an object by an given axis around the coordinates of the 'point'
  3878. :param angle:
  3879. :param point: tupple of coordinates (x,y)
  3880. :return:
  3881. """
  3882. log.debug("camlib.CNCJob.mirror()")
  3883. px, py = point
  3884. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  3885. # variables to display the percentage of work done
  3886. self.geo_len = 0
  3887. try:
  3888. for g in self.gcode_parsed:
  3889. self.geo_len += 1
  3890. except TypeError:
  3891. self.geo_len = 1
  3892. self.old_disp_number = 0
  3893. self.el_count = 0
  3894. for g in self.gcode_parsed:
  3895. try:
  3896. g['geom'] = affinity.scale(g['geom'], xscale, yscale, origin=(px, py))
  3897. except AttributeError:
  3898. return g['geom']
  3899. self.el_count += 1
  3900. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  3901. if self.old_disp_number < disp_number <= 100:
  3902. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  3903. self.old_disp_number = disp_number
  3904. self.create_geometry()
  3905. self.app.proc_container.new_text = ''
  3906. def skew(self, angle_x, angle_y, point):
  3907. """
  3908. Shear/Skew the geometries of an object by angles along x and y dimensions.
  3909. Parameters
  3910. ----------
  3911. angle_x, angle_y : float, float
  3912. The shear angle(s) for the x and y axes respectively. These can be
  3913. specified in either degrees (default) or radians by setting
  3914. use_radians=True.
  3915. point: tupple of coordinates (x,y)
  3916. See shapely manual for more information:
  3917. http://toblerity.org/shapely/manual.html#affine-transformations
  3918. """
  3919. log.debug("camlib.CNCJob.skew()")
  3920. px, py = point
  3921. # variables to display the percentage of work done
  3922. self.geo_len = 0
  3923. try:
  3924. for g in self.gcode_parsed:
  3925. self.geo_len += 1
  3926. except TypeError:
  3927. self.geo_len = 1
  3928. self.old_disp_number = 0
  3929. self.el_count = 0
  3930. for g in self.gcode_parsed:
  3931. try:
  3932. g['geom'] = affinity.skew(g['geom'], angle_x, angle_y, origin=(px, py))
  3933. except AttributeError:
  3934. return g['geom']
  3935. self.el_count += 1
  3936. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  3937. if self.old_disp_number < disp_number <= 100:
  3938. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  3939. self.old_disp_number = disp_number
  3940. self.create_geometry()
  3941. self.app.proc_container.new_text = ''
  3942. def rotate(self, angle, point):
  3943. """
  3944. Rotate the geometrys of an object by an given angle around the coordinates of the 'point'
  3945. :param angle:
  3946. :param point: tupple of coordinates (x,y)
  3947. :return:
  3948. """
  3949. log.debug("camlib.CNCJob.rotate()")
  3950. px, py = point
  3951. # variables to display the percentage of work done
  3952. self.geo_len = 0
  3953. try:
  3954. for g in self.gcode_parsed:
  3955. self.geo_len += 1
  3956. except TypeError:
  3957. self.geo_len = 1
  3958. self.old_disp_number = 0
  3959. self.el_count = 0
  3960. for g in self.gcode_parsed:
  3961. try:
  3962. g['geom'] = affinity.rotate(g['geom'], angle, origin=(px, py))
  3963. except AttributeError:
  3964. return g['geom']
  3965. self.el_count += 1
  3966. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  3967. if self.old_disp_number < disp_number <= 100:
  3968. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  3969. self.old_disp_number = disp_number
  3970. self.create_geometry()
  3971. self.app.proc_container.new_text = ''
  3972. def get_bounds(geometry_list):
  3973. xmin = Inf
  3974. ymin = Inf
  3975. xmax = -Inf
  3976. ymax = -Inf
  3977. for gs in geometry_list:
  3978. try:
  3979. gxmin, gymin, gxmax, gymax = gs.bounds()
  3980. xmin = min([xmin, gxmin])
  3981. ymin = min([ymin, gymin])
  3982. xmax = max([xmax, gxmax])
  3983. ymax = max([ymax, gymax])
  3984. except:
  3985. log.warning("DEVELOPMENT: Tried to get bounds of empty geometry.")
  3986. return [xmin, ymin, xmax, ymax]
  3987. def arc(center, radius, start, stop, direction, steps_per_circ):
  3988. """
  3989. Creates a list of point along the specified arc.
  3990. :param center: Coordinates of the center [x, y]
  3991. :type center: list
  3992. :param radius: Radius of the arc.
  3993. :type radius: float
  3994. :param start: Starting angle in radians
  3995. :type start: float
  3996. :param stop: End angle in radians
  3997. :type stop: float
  3998. :param direction: Orientation of the arc, "CW" or "CCW"
  3999. :type direction: string
  4000. :param steps_per_circ: Number of straight line segments to
  4001. represent a circle.
  4002. :type steps_per_circ: int
  4003. :return: The desired arc, as list of tuples
  4004. :rtype: list
  4005. """
  4006. # TODO: Resolution should be established by maximum error from the exact arc.
  4007. da_sign = {"cw": -1.0, "ccw": 1.0}
  4008. points = []
  4009. if direction == "ccw" and stop <= start:
  4010. stop += 2 * pi
  4011. if direction == "cw" and stop >= start:
  4012. stop -= 2 * pi
  4013. angle = abs(stop - start)
  4014. # angle = stop-start
  4015. steps = max([int(ceil(angle / (2 * pi) * steps_per_circ)), 2])
  4016. delta_angle = da_sign[direction] * angle * 1.0 / steps
  4017. for i in range(steps + 1):
  4018. theta = start + delta_angle * i
  4019. points.append((center[0] + radius * cos(theta), center[1] + radius * sin(theta)))
  4020. return points
  4021. def arc2(p1, p2, center, direction, steps_per_circ):
  4022. r = sqrt((center[0] - p1[0]) ** 2 + (center[1] - p1[1]) ** 2)
  4023. start = arctan2(p1[1] - center[1], p1[0] - center[0])
  4024. stop = arctan2(p2[1] - center[1], p2[0] - center[0])
  4025. return arc(center, r, start, stop, direction, steps_per_circ)
  4026. def arc_angle(start, stop, direction):
  4027. if direction == "ccw" and stop <= start:
  4028. stop += 2 * pi
  4029. if direction == "cw" and stop >= start:
  4030. stop -= 2 * pi
  4031. angle = abs(stop - start)
  4032. return angle
  4033. # def find_polygon(poly, point):
  4034. # """
  4035. # Find an object that object.contains(Point(point)) in
  4036. # poly, which can can be iterable, contain iterable of, or
  4037. # be itself an implementer of .contains().
  4038. #
  4039. # :param poly: See description
  4040. # :return: Polygon containing point or None.
  4041. # """
  4042. #
  4043. # if poly is None:
  4044. # return None
  4045. #
  4046. # try:
  4047. # for sub_poly in poly:
  4048. # p = find_polygon(sub_poly, point)
  4049. # if p is not None:
  4050. # return p
  4051. # except TypeError:
  4052. # try:
  4053. # if poly.contains(Point(point)):
  4054. # return poly
  4055. # except AttributeError:
  4056. # return None
  4057. #
  4058. # return None
  4059. def to_dict(obj):
  4060. """
  4061. Makes the following types into serializable form:
  4062. * ApertureMacro
  4063. * BaseGeometry
  4064. :param obj: Shapely geometry.
  4065. :type obj: BaseGeometry
  4066. :return: Dictionary with serializable form if ``obj`` was
  4067. BaseGeometry or ApertureMacro, otherwise returns ``obj``.
  4068. """
  4069. if isinstance(obj, ApertureMacro):
  4070. return {
  4071. "__class__": "ApertureMacro",
  4072. "__inst__": obj.to_dict()
  4073. }
  4074. if isinstance(obj, BaseGeometry):
  4075. return {
  4076. "__class__": "Shply",
  4077. "__inst__": sdumps(obj)
  4078. }
  4079. return obj
  4080. def dict2obj(d):
  4081. """
  4082. Default deserializer.
  4083. :param d: Serializable dictionary representation of an object
  4084. to be reconstructed.
  4085. :return: Reconstructed object.
  4086. """
  4087. if '__class__' in d and '__inst__' in d:
  4088. if d['__class__'] == "Shply":
  4089. return sloads(d['__inst__'])
  4090. if d['__class__'] == "ApertureMacro":
  4091. am = ApertureMacro()
  4092. am.from_dict(d['__inst__'])
  4093. return am
  4094. return d
  4095. else:
  4096. return d
  4097. # def plotg(geo, solid_poly=False, color="black"):
  4098. # try:
  4099. # __ = iter(geo)
  4100. # except:
  4101. # geo = [geo]
  4102. #
  4103. # for g in geo:
  4104. # if type(g) == Polygon:
  4105. # if solid_poly:
  4106. # patch = PolygonPatch(g,
  4107. # facecolor="#BBF268",
  4108. # edgecolor="#006E20",
  4109. # alpha=0.75,
  4110. # zorder=2)
  4111. # ax = subplot(111)
  4112. # ax.add_patch(patch)
  4113. # else:
  4114. # x, y = g.exterior.coords.xy
  4115. # plot(x, y, color=color)
  4116. # for ints in g.interiors:
  4117. # x, y = ints.coords.xy
  4118. # plot(x, y, color=color)
  4119. # continue
  4120. #
  4121. # if type(g) == LineString or type(g) == LinearRing:
  4122. # x, y = g.coords.xy
  4123. # plot(x, y, color=color)
  4124. # continue
  4125. #
  4126. # if type(g) == Point:
  4127. # x, y = g.coords.xy
  4128. # plot(x, y, 'o')
  4129. # continue
  4130. #
  4131. # try:
  4132. # __ = iter(g)
  4133. # plotg(g, color=color)
  4134. # except:
  4135. # log.error("Cannot plot: " + str(type(g)))
  4136. # continue
  4137. def parse_gerber_number(strnumber, int_digits, frac_digits, zeros):
  4138. """
  4139. Parse a single number of Gerber coordinates.
  4140. :param strnumber: String containing a number in decimal digits
  4141. from a coordinate data block, possibly with a leading sign.
  4142. :type strnumber: str
  4143. :param int_digits: Number of digits used for the integer
  4144. part of the number
  4145. :type frac_digits: int
  4146. :param frac_digits: Number of digits used for the fractional
  4147. part of the number
  4148. :type frac_digits: int
  4149. :param zeros: If 'L', leading zeros are removed and trailing zeros are kept. Same situation for 'D' when
  4150. no zero suppression is done. If 'T', is in reverse.
  4151. :type zeros: str
  4152. :return: The number in floating point.
  4153. :rtype: float
  4154. """
  4155. ret_val = None
  4156. if zeros == 'L' or zeros == 'D':
  4157. ret_val = int(strnumber) * (10 ** (-frac_digits))
  4158. if zeros == 'T':
  4159. int_val = int(strnumber)
  4160. ret_val = (int_val * (10 ** ((int_digits + frac_digits) - len(strnumber)))) * (10 ** (-frac_digits))
  4161. return ret_val
  4162. # def alpha_shape(points, alpha):
  4163. # """
  4164. # Compute the alpha shape (concave hull) of a set of points.
  4165. #
  4166. # @param points: Iterable container of points.
  4167. # @param alpha: alpha value to influence the gooeyness of the border. Smaller
  4168. # numbers don't fall inward as much as larger numbers. Too large,
  4169. # and you lose everything!
  4170. # """
  4171. # if len(points) < 4:
  4172. # # When you have a triangle, there is no sense in computing an alpha
  4173. # # shape.
  4174. # return MultiPoint(list(points)).convex_hull
  4175. #
  4176. # def add_edge(edges, edge_points, coords, i, j):
  4177. # """Add a line between the i-th and j-th points, if not in the list already"""
  4178. # if (i, j) in edges or (j, i) in edges:
  4179. # # already added
  4180. # return
  4181. # edges.add( (i, j) )
  4182. # edge_points.append(coords[ [i, j] ])
  4183. #
  4184. # coords = np.array([point.coords[0] for point in points])
  4185. #
  4186. # tri = Delaunay(coords)
  4187. # edges = set()
  4188. # edge_points = []
  4189. # # loop over triangles:
  4190. # # ia, ib, ic = indices of corner points of the triangle
  4191. # for ia, ib, ic in tri.vertices:
  4192. # pa = coords[ia]
  4193. # pb = coords[ib]
  4194. # pc = coords[ic]
  4195. #
  4196. # # Lengths of sides of triangle
  4197. # a = math.sqrt((pa[0]-pb[0])**2 + (pa[1]-pb[1])**2)
  4198. # b = math.sqrt((pb[0]-pc[0])**2 + (pb[1]-pc[1])**2)
  4199. # c = math.sqrt((pc[0]-pa[0])**2 + (pc[1]-pa[1])**2)
  4200. #
  4201. # # Semiperimeter of triangle
  4202. # s = (a + b + c)/2.0
  4203. #
  4204. # # Area of triangle by Heron's formula
  4205. # area = math.sqrt(s*(s-a)*(s-b)*(s-c))
  4206. # circum_r = a*b*c/(4.0*area)
  4207. #
  4208. # # Here's the radius filter.
  4209. # #print circum_r
  4210. # if circum_r < 1.0/alpha:
  4211. # add_edge(edges, edge_points, coords, ia, ib)
  4212. # add_edge(edges, edge_points, coords, ib, ic)
  4213. # add_edge(edges, edge_points, coords, ic, ia)
  4214. #
  4215. # m = MultiLineString(edge_points)
  4216. # triangles = list(polygonize(m))
  4217. # return cascaded_union(triangles), edge_points
  4218. # def voronoi(P):
  4219. # """
  4220. # Returns a list of all edges of the voronoi diagram for the given input points.
  4221. # """
  4222. # delauny = Delaunay(P)
  4223. # triangles = delauny.points[delauny.vertices]
  4224. #
  4225. # circum_centers = np.array([triangle_csc(tri) for tri in triangles])
  4226. # long_lines_endpoints = []
  4227. #
  4228. # lineIndices = []
  4229. # for i, triangle in enumerate(triangles):
  4230. # circum_center = circum_centers[i]
  4231. # for j, neighbor in enumerate(delauny.neighbors[i]):
  4232. # if neighbor != -1:
  4233. # lineIndices.append((i, neighbor))
  4234. # else:
  4235. # ps = triangle[(j+1)%3] - triangle[(j-1)%3]
  4236. # ps = np.array((ps[1], -ps[0]))
  4237. #
  4238. # middle = (triangle[(j+1)%3] + triangle[(j-1)%3]) * 0.5
  4239. # di = middle - triangle[j]
  4240. #
  4241. # ps /= np.linalg.norm(ps)
  4242. # di /= np.linalg.norm(di)
  4243. #
  4244. # if np.dot(di, ps) < 0.0:
  4245. # ps *= -1000.0
  4246. # else:
  4247. # ps *= 1000.0
  4248. #
  4249. # long_lines_endpoints.append(circum_center + ps)
  4250. # lineIndices.append((i, len(circum_centers) + len(long_lines_endpoints)-1))
  4251. #
  4252. # vertices = np.vstack((circum_centers, long_lines_endpoints))
  4253. #
  4254. # # filter out any duplicate lines
  4255. # lineIndicesSorted = np.sort(lineIndices) # make (1,2) and (2,1) both (1,2)
  4256. # lineIndicesTupled = [tuple(row) for row in lineIndicesSorted]
  4257. # lineIndicesUnique = np.unique(lineIndicesTupled)
  4258. #
  4259. # return vertices, lineIndicesUnique
  4260. #
  4261. #
  4262. # def triangle_csc(pts):
  4263. # rows, cols = pts.shape
  4264. #
  4265. # A = np.bmat([[2 * np.dot(pts, pts.T), np.ones((rows, 1))],
  4266. # [np.ones((1, rows)), np.zeros((1, 1))]])
  4267. #
  4268. # b = np.hstack((np.sum(pts * pts, axis=1), np.ones((1))))
  4269. # x = np.linalg.solve(A,b)
  4270. # bary_coords = x[:-1]
  4271. # return np.sum(pts * np.tile(bary_coords.reshape((pts.shape[0], 1)), (1, pts.shape[1])), axis=0)
  4272. #
  4273. #
  4274. # def voronoi_cell_lines(points, vertices, lineIndices):
  4275. # """
  4276. # Returns a mapping from a voronoi cell to its edges.
  4277. #
  4278. # :param points: shape (m,2)
  4279. # :param vertices: shape (n,2)
  4280. # :param lineIndices: shape (o,2)
  4281. # :rtype: dict point index -> list of shape (n,2) with vertex indices
  4282. # """
  4283. # kd = KDTree(points)
  4284. #
  4285. # cells = collections.defaultdict(list)
  4286. # for i1, i2 in lineIndices:
  4287. # v1, v2 = vertices[i1], vertices[i2]
  4288. # mid = (v1+v2)/2
  4289. # _, (p1Idx, p2Idx) = kd.query(mid, 2)
  4290. # cells[p1Idx].append((i1, i2))
  4291. # cells[p2Idx].append((i1, i2))
  4292. #
  4293. # return cells
  4294. #
  4295. #
  4296. # def voronoi_edges2polygons(cells):
  4297. # """
  4298. # Transforms cell edges into polygons.
  4299. #
  4300. # :param cells: as returned from voronoi_cell_lines
  4301. # :rtype: dict point index -> list of vertex indices which form a polygon
  4302. # """
  4303. #
  4304. # # first, close the outer cells
  4305. # for pIdx, lineIndices_ in cells.items():
  4306. # dangling_lines = []
  4307. # for i1, i2 in lineIndices_:
  4308. # p = (i1, i2)
  4309. # connections = filter(lambda k: p != k and
  4310. # (p[0] == k[0] or p[0] == k[1] or p[1] == k[0] or p[1] == k[1]), lineIndices_)
  4311. # # connections = filter(lambda (i1_, i2_): (i1, i2) != (i1_, i2_) and
  4312. # (i1 == i1_ or i1 == i2_ or i2 == i1_ or i2 == i2_), lineIndices_)
  4313. # assert 1 <= len(connections) <= 2
  4314. # if len(connections) == 1:
  4315. # dangling_lines.append((i1, i2))
  4316. # assert len(dangling_lines) in [0, 2]
  4317. # if len(dangling_lines) == 2:
  4318. # (i11, i12), (i21, i22) = dangling_lines
  4319. # s = (i11, i12)
  4320. # t = (i21, i22)
  4321. #
  4322. # # determine which line ends are unconnected
  4323. # connected = filter(lambda k: k != s and (k[0] == s[0] or k[1] == s[0]), lineIndices_)
  4324. # # connected = filter(lambda (i1,i2): (i1,i2) != (i11,i12) and (i1 == i11 or i2 == i11), lineIndices_)
  4325. # i11Unconnected = len(connected) == 0
  4326. #
  4327. # connected = filter(lambda k: k != t and (k[0] == t[0] or k[1] == t[0]), lineIndices_)
  4328. # # connected = filter(lambda (i1,i2): (i1,i2) != (i21,i22) and (i1 == i21 or i2 == i21), lineIndices_)
  4329. # i21Unconnected = len(connected) == 0
  4330. #
  4331. # startIdx = i11 if i11Unconnected else i12
  4332. # endIdx = i21 if i21Unconnected else i22
  4333. #
  4334. # cells[pIdx].append((startIdx, endIdx))
  4335. #
  4336. # # then, form polygons by storing vertex indices in (counter-)clockwise order
  4337. # polys = dict()
  4338. # for pIdx, lineIndices_ in cells.items():
  4339. # # get a directed graph which contains both directions and arbitrarily follow one of both
  4340. # directedGraph = lineIndices_ + [(i2, i1) for (i1, i2) in lineIndices_]
  4341. # directedGraphMap = collections.defaultdict(list)
  4342. # for (i1, i2) in directedGraph:
  4343. # directedGraphMap[i1].append(i2)
  4344. # orderedEdges = []
  4345. # currentEdge = directedGraph[0]
  4346. # while len(orderedEdges) < len(lineIndices_):
  4347. # i1 = currentEdge[1]
  4348. # i2 = directedGraphMap[i1][0] if directedGraphMap[i1][0] != currentEdge[0] else directedGraphMap[i1][1]
  4349. # nextEdge = (i1, i2)
  4350. # orderedEdges.append(nextEdge)
  4351. # currentEdge = nextEdge
  4352. #
  4353. # polys[pIdx] = [i1 for (i1, i2) in orderedEdges]
  4354. #
  4355. # return polys
  4356. #
  4357. #
  4358. # def voronoi_polygons(points):
  4359. # """
  4360. # Returns the voronoi polygon for each input point.
  4361. #
  4362. # :param points: shape (n,2)
  4363. # :rtype: list of n polygons where each polygon is an array of vertices
  4364. # """
  4365. # vertices, lineIndices = voronoi(points)
  4366. # cells = voronoi_cell_lines(points, vertices, lineIndices)
  4367. # polys = voronoi_edges2polygons(cells)
  4368. # polylist = []
  4369. # for i in range(len(points)):
  4370. # poly = vertices[np.asarray(polys[i])]
  4371. # polylist.append(poly)
  4372. # return polylist
  4373. #
  4374. #
  4375. # class Zprofile:
  4376. # def __init__(self):
  4377. #
  4378. # # data contains lists of [x, y, z]
  4379. # self.data = []
  4380. #
  4381. # # Computed voronoi polygons (shapely)
  4382. # self.polygons = []
  4383. # pass
  4384. #
  4385. # # def plot_polygons(self):
  4386. # # axes = plt.subplot(1, 1, 1)
  4387. # #
  4388. # # plt.axis([-0.05, 1.05, -0.05, 1.05])
  4389. # #
  4390. # # for poly in self.polygons:
  4391. # # p = PolygonPatch(poly, facecolor=np.random.rand(3, 1), alpha=0.3)
  4392. # # axes.add_patch(p)
  4393. #
  4394. # def init_from_csv(self, filename):
  4395. # pass
  4396. #
  4397. # def init_from_string(self, zpstring):
  4398. # pass
  4399. #
  4400. # def init_from_list(self, zplist):
  4401. # self.data = zplist
  4402. #
  4403. # def generate_polygons(self):
  4404. # self.polygons = [Polygon(p) for p in voronoi_polygons(array([[x[0], x[1]] for x in self.data]))]
  4405. #
  4406. # def normalize(self, origin):
  4407. # pass
  4408. #
  4409. # def paste(self, path):
  4410. # """
  4411. # Return a list of dictionaries containing the parts of the original
  4412. # path and their z-axis offset.
  4413. # """
  4414. #
  4415. # # At most one region/polygon will contain the path
  4416. # containing = [i for i in range(len(self.polygons)) if self.polygons[i].contains(path)]
  4417. #
  4418. # if len(containing) > 0:
  4419. # return [{"path": path, "z": self.data[containing[0]][2]}]
  4420. #
  4421. # # All region indexes that intersect with the path
  4422. # crossing = [i for i in range(len(self.polygons)) if self.polygons[i].intersects(path)]
  4423. #
  4424. # return [{"path": path.intersection(self.polygons[i]),
  4425. # "z": self.data[i][2]} for i in crossing]
  4426. def autolist(obj):
  4427. try:
  4428. __ = iter(obj)
  4429. return obj
  4430. except TypeError:
  4431. return [obj]
  4432. def three_point_circle(p1, p2, p3):
  4433. """
  4434. Computes the center and radius of a circle from
  4435. 3 points on its circumference.
  4436. :param p1: Point 1
  4437. :param p2: Point 2
  4438. :param p3: Point 3
  4439. :return: center, radius
  4440. """
  4441. # Midpoints
  4442. a1 = (p1 + p2) / 2.0
  4443. a2 = (p2 + p3) / 2.0
  4444. # Normals
  4445. b1 = dot((p2 - p1), array([[0, -1], [1, 0]], dtype=float32))
  4446. b2 = dot((p3 - p2), array([[0, 1], [-1, 0]], dtype=float32))
  4447. # Params
  4448. try:
  4449. T = solve(transpose(array([-b1, b2])), a1 - a2)
  4450. except Exception as e:
  4451. log.debug("camlib.three_point_circle() --> %s" % str(e))
  4452. return
  4453. # Center
  4454. center = a1 + b1 * T[0]
  4455. # Radius
  4456. radius = np.linalg.norm(center - p1)
  4457. return center, radius, T[0]
  4458. def distance(pt1, pt2):
  4459. return sqrt((pt1[0] - pt2[0]) ** 2 + (pt1[1] - pt2[1]) ** 2)
  4460. def distance_euclidian(x1, y1, x2, y2):
  4461. return sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
  4462. class FlatCAMRTree(object):
  4463. """
  4464. Indexes geometry (Any object with "cooords" property containing
  4465. a list of tuples with x, y values). Objects are indexed by
  4466. all their points by default. To index by arbitrary points,
  4467. override self.points2obj.
  4468. """
  4469. def __init__(self):
  4470. # Python RTree Index
  4471. self.rti = rtindex.Index()
  4472. # ## Track object-point relationship
  4473. # Each is list of points in object.
  4474. self.obj2points = []
  4475. # Index is index in rtree, value is index of
  4476. # object in obj2points.
  4477. self.points2obj = []
  4478. self.get_points = lambda go: go.coords
  4479. def grow_obj2points(self, idx):
  4480. """
  4481. Increases the size of self.obj2points to fit
  4482. idx + 1 items.
  4483. :param idx: Index to fit into list.
  4484. :return: None
  4485. """
  4486. if len(self.obj2points) > idx:
  4487. # len == 2, idx == 1, ok.
  4488. return
  4489. else:
  4490. # len == 2, idx == 2, need 1 more.
  4491. # range(2, 3)
  4492. for i in range(len(self.obj2points), idx + 1):
  4493. self.obj2points.append([])
  4494. def insert(self, objid, obj):
  4495. self.grow_obj2points(objid)
  4496. self.obj2points[objid] = []
  4497. for pt in self.get_points(obj):
  4498. self.rti.insert(len(self.points2obj), (pt[0], pt[1], pt[0], pt[1]), obj=objid)
  4499. self.obj2points[objid].append(len(self.points2obj))
  4500. self.points2obj.append(objid)
  4501. def remove_obj(self, objid, obj):
  4502. # Use all ptids to delete from index
  4503. for i, pt in enumerate(self.get_points(obj)):
  4504. try:
  4505. self.rti.delete(self.obj2points[objid][i], (pt[0], pt[1], pt[0], pt[1]))
  4506. except IndexError:
  4507. pass
  4508. def nearest(self, pt):
  4509. """
  4510. Will raise StopIteration if no items are found.
  4511. :param pt:
  4512. :return:
  4513. """
  4514. return next(self.rti.nearest(pt, objects=True))
  4515. class FlatCAMRTreeStorage(FlatCAMRTree):
  4516. """
  4517. Just like FlatCAMRTree it indexes geometry, but also serves
  4518. as storage for the geometry.
  4519. """
  4520. def __init__(self):
  4521. # super(FlatCAMRTreeStorage, self).__init__()
  4522. super().__init__()
  4523. self.objects = []
  4524. # Optimization attempt!
  4525. self.indexes = {}
  4526. def insert(self, obj):
  4527. self.objects.append(obj)
  4528. idx = len(self.objects) - 1
  4529. # Note: Shapely objects are not hashable any more, althought
  4530. # there seem to be plans to re-introduce the feature in
  4531. # version 2.0. For now, we will index using the object's id,
  4532. # but it's important to remember that shapely geometry is
  4533. # mutable, ie. it can be modified to a totally different shape
  4534. # and continue to have the same id.
  4535. # self.indexes[obj] = idx
  4536. self.indexes[id(obj)] = idx
  4537. # super(FlatCAMRTreeStorage, self).insert(idx, obj)
  4538. super().insert(idx, obj)
  4539. # @profile
  4540. def remove(self, obj):
  4541. # See note about self.indexes in insert().
  4542. # objidx = self.indexes[obj]
  4543. objidx = self.indexes[id(obj)]
  4544. # Remove from list
  4545. self.objects[objidx] = None
  4546. # Remove from index
  4547. self.remove_obj(objidx, obj)
  4548. def get_objects(self):
  4549. return (o for o in self.objects if o is not None)
  4550. def nearest(self, pt):
  4551. """
  4552. Returns the nearest matching points and the object
  4553. it belongs to.
  4554. :param pt: Query point.
  4555. :return: (match_x, match_y), Object owner of
  4556. matching point.
  4557. :rtype: tuple
  4558. """
  4559. tidx = super(FlatCAMRTreeStorage, self).nearest(pt)
  4560. return (tidx.bbox[0], tidx.bbox[1]), self.objects[tidx.object]
  4561. # class myO:
  4562. # def __init__(self, coords):
  4563. # self.coords = coords
  4564. #
  4565. #
  4566. # def test_rti():
  4567. #
  4568. # o1 = myO([(0, 0), (0, 1), (1, 1)])
  4569. # o2 = myO([(2, 0), (2, 1), (2, 1)])
  4570. # o3 = myO([(2, 0), (2, 1), (3, 1)])
  4571. #
  4572. # os = [o1, o2]
  4573. #
  4574. # idx = FlatCAMRTree()
  4575. #
  4576. # for o in range(len(os)):
  4577. # idx.insert(o, os[o])
  4578. #
  4579. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  4580. #
  4581. # idx.remove_obj(0, o1)
  4582. #
  4583. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  4584. #
  4585. # idx.remove_obj(1, o2)
  4586. #
  4587. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  4588. #
  4589. #
  4590. # def test_rtis():
  4591. #
  4592. # o1 = myO([(0, 0), (0, 1), (1, 1)])
  4593. # o2 = myO([(2, 0), (2, 1), (2, 1)])
  4594. # o3 = myO([(2, 0), (2, 1), (3, 1)])
  4595. #
  4596. # os = [o1, o2]
  4597. #
  4598. # idx = FlatCAMRTreeStorage()
  4599. #
  4600. # for o in range(len(os)):
  4601. # idx.insert(os[o])
  4602. #
  4603. # #os = None
  4604. # #o1 = None
  4605. # #o2 = None
  4606. #
  4607. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  4608. #
  4609. # idx.remove(idx.nearest((2,0))[1])
  4610. #
  4611. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  4612. #
  4613. # idx.remove(idx.nearest((0,0))[1])
  4614. #
  4615. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]