camlib.py 231 KB

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