camlib.py 312 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596
  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. from numpy.linalg import solve, norm
  11. import platform
  12. from copy import deepcopy
  13. import traceback
  14. from decimal import Decimal
  15. from rtree import index as rtindex
  16. from lxml import etree as ET
  17. # See: http://toblerity.org/shapely/manual.html
  18. from shapely.geometry import Polygon, LineString, Point, LinearRing, MultiLineString, MultiPoint, MultiPolygon
  19. from shapely.geometry import box as shply_box
  20. from shapely.ops import cascaded_union, unary_union, substring, linemerge
  21. import shapely.affinity as affinity
  22. from shapely.wkt import loads as sloads
  23. from shapely.wkt import dumps as sdumps
  24. from shapely.geometry.base import BaseGeometry
  25. from shapely.geometry import shape
  26. # ---------------------------------------
  27. # NEEDED for Legacy mode
  28. # Used for solid polygons in Matplotlib
  29. from descartes.patch import PolygonPatch
  30. # ---------------------------------------
  31. from collections import Iterable
  32. import rasterio
  33. from rasterio.features import shapes
  34. import ezdxf
  35. from Common import GracefulException as grace
  36. # Commented for FlatCAM packaging with cx_freeze
  37. # from scipy.spatial import KDTree, Delaunay
  38. # from scipy.spatial import Delaunay
  39. from appParsers.ParseSVG import *
  40. from appParsers.ParseDXF import *
  41. if platform.architecture()[0] == '64bit':
  42. from ortools.constraint_solver import pywrapcp
  43. from ortools.constraint_solver import routing_enums_pb2
  44. import logging
  45. import gettext
  46. import appTranslation 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": 'mm',
  358. # "geo_steps_per_circle": 128
  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. self.drawing_tolerance = 0.0
  365. self.tools = None
  366. # Final geometry: MultiPolygon or list (of geometry constructs)
  367. self.solid_geometry = None
  368. # Final geometry: MultiLineString or list (of LineString or Points)
  369. self.follow_geometry = None
  370. # Attributes to be included in serialization
  371. self.ser_attrs = ["units", 'solid_geometry', 'follow_geometry']
  372. # Flattened geometry (list of paths only)
  373. self.flat_geometry = []
  374. # this is the calculated conversion factor when the file units are different than the ones in the app
  375. self.file_units_factor = 1
  376. # Index
  377. self.index = None
  378. self.geo_steps_per_circle = geo_steps_per_circle
  379. # variables to display the percentage of work done
  380. self.geo_len = 0
  381. self.old_disp_number = 0
  382. self.el_count = 0
  383. if self.app.is_legacy is False:
  384. self.temp_shapes = self.app.plotcanvas.new_shape_collection(layers=1)
  385. else:
  386. from appGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  387. self.temp_shapes = ShapeCollectionLegacy(obj=self, app=self.app, name='camlib.geometry')
  388. def plot_temp_shapes(self, element, color='red'):
  389. try:
  390. for sub_el in element:
  391. self.plot_temp_shapes(sub_el)
  392. except TypeError: # Element is not iterable...
  393. # self.add_shape(shape=element, color=color, visible=visible, layer=0)
  394. self.temp_shapes.add(tolerance=float(self.app.defaults["global_tolerance"]),
  395. shape=element, color=color, visible=True, layer=0)
  396. def make_index(self):
  397. self.flatten()
  398. self.index = FlatCAMRTree()
  399. for i, g in enumerate(self.flat_geometry):
  400. self.index.insert(i, g)
  401. def add_circle(self, origin, radius):
  402. """
  403. Adds a circle to the object.
  404. :param origin: Center of the circle.
  405. :param radius: Radius of the circle.
  406. :return: None
  407. """
  408. if self.solid_geometry is None:
  409. self.solid_geometry = []
  410. if type(self.solid_geometry) is list:
  411. self.solid_geometry.append(Point(origin).buffer(radius, int(self.geo_steps_per_circle)))
  412. return
  413. try:
  414. self.solid_geometry = self.solid_geometry.union(
  415. Point(origin).buffer(radius, int(self.geo_steps_per_circle))
  416. )
  417. except Exception as e:
  418. log.error("Failed to run union on polygons. %s" % str(e))
  419. return
  420. def add_polygon(self, points):
  421. """
  422. Adds a polygon to the object (by union)
  423. :param points: The vertices of the polygon.
  424. :return: None
  425. """
  426. if self.solid_geometry is None:
  427. self.solid_geometry = []
  428. if type(self.solid_geometry) is list:
  429. self.solid_geometry.append(Polygon(points))
  430. return
  431. try:
  432. self.solid_geometry = self.solid_geometry.union(Polygon(points))
  433. except Exception as e:
  434. log.error("Failed to run union on polygons. %s" % str(e))
  435. return
  436. def add_polyline(self, points):
  437. """
  438. Adds a polyline to the object (by union)
  439. :param points: The vertices of the polyline.
  440. :return: None
  441. """
  442. if self.solid_geometry is None:
  443. self.solid_geometry = []
  444. if type(self.solid_geometry) is list:
  445. self.solid_geometry.append(LineString(points))
  446. return
  447. try:
  448. self.solid_geometry = self.solid_geometry.union(LineString(points))
  449. except Exception as e:
  450. log.error("Failed to run union on polylines. %s" % str(e))
  451. return
  452. def is_empty(self):
  453. if isinstance(self.solid_geometry, BaseGeometry) or isinstance(self.solid_geometry, Polygon) or \
  454. isinstance(self.solid_geometry, MultiPolygon):
  455. return self.solid_geometry.is_empty
  456. if isinstance(self.solid_geometry, list):
  457. return len(self.solid_geometry) == 0
  458. self.app.inform.emit('[ERROR_NOTCL] %s' % _("self.solid_geometry is neither BaseGeometry or list."))
  459. return
  460. def subtract_polygon(self, points):
  461. """
  462. Subtract polygon from the given object. This only operates on the paths in the original geometry,
  463. i.e. it converts polygons into paths.
  464. :param points: The vertices of the polygon.
  465. :return: none
  466. """
  467. if self.solid_geometry is None:
  468. self.solid_geometry = []
  469. # pathonly should be allways True, otherwise polygons are not subtracted
  470. flat_geometry = self.flatten(pathonly=True)
  471. log.debug("%d paths" % len(flat_geometry))
  472. if not isinstance(points, Polygon):
  473. polygon = Polygon(points)
  474. else:
  475. polygon = points
  476. toolgeo = cascaded_union(polygon)
  477. diffs = []
  478. for target in flat_geometry:
  479. if isinstance(target, LineString) or isinstance(target, LineString) or isinstance(target, MultiLineString):
  480. diffs.append(target.difference(toolgeo))
  481. else:
  482. log.warning("Not implemented.")
  483. self.solid_geometry = unary_union(diffs)
  484. def bounds(self, flatten=False):
  485. """
  486. Returns coordinates of rectangular bounds
  487. of geometry: (xmin, ymin, xmax, ymax).
  488. :param flatten: will flatten the solid_geometry if True
  489. :return:
  490. """
  491. # fixed issue of getting bounds only for one level lists of objects
  492. # now it can get bounds for nested lists of objects
  493. log.debug("camlib.Geometry.bounds()")
  494. if self.solid_geometry is None:
  495. log.debug("solid_geometry is None")
  496. return 0, 0, 0, 0
  497. def bounds_rec(obj):
  498. if type(obj) is list:
  499. gminx = np.Inf
  500. gminy = np.Inf
  501. gmaxx = -np.Inf
  502. gmaxy = -np.Inf
  503. for k in obj:
  504. if type(k) is dict:
  505. for key in k:
  506. minx_, miny_, maxx_, maxy_ = bounds_rec(k[key])
  507. gminx = min(gminx, minx_)
  508. gminy = min(gminy, miny_)
  509. gmaxx = max(gmaxx, maxx_)
  510. gmaxy = max(gmaxy, maxy_)
  511. else:
  512. try:
  513. if k.is_empty:
  514. continue
  515. except Exception:
  516. pass
  517. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  518. gminx = min(gminx, minx_)
  519. gminy = min(gminy, miny_)
  520. gmaxx = max(gmaxx, maxx_)
  521. gmaxy = max(gmaxy, maxy_)
  522. return gminx, gminy, gmaxx, gmaxy
  523. else:
  524. # it's a Shapely object, return it's bounds
  525. return obj.bounds
  526. if self.multigeo is True:
  527. minx_list = []
  528. miny_list = []
  529. maxx_list = []
  530. maxy_list = []
  531. for tool in self.tools:
  532. working_geo = self.tools[tool]['solid_geometry']
  533. if flatten:
  534. self.flatten(geometry=working_geo, reset=True)
  535. working_geo = self.flat_geometry
  536. minx, miny, maxx, maxy = bounds_rec(working_geo)
  537. minx_list.append(minx)
  538. miny_list.append(miny)
  539. maxx_list.append(maxx)
  540. maxy_list.append(maxy)
  541. return min(minx_list), min(miny_list), max(maxx_list), max(maxy_list)
  542. else:
  543. if flatten:
  544. self.flatten(reset=True)
  545. self.solid_geometry = self.flat_geometry
  546. bounds_coords = bounds_rec(self.solid_geometry)
  547. return bounds_coords
  548. # try:
  549. # # from here: http://rightfootin.blogspot.com/2006/09/more-on-python-flatten.html
  550. # def flatten(l, ltypes=(list, tuple)):
  551. # ltype = type(l)
  552. # l = list(l)
  553. # i = 0
  554. # while i < len(l):
  555. # while isinstance(l[i], ltypes):
  556. # if not l[i]:
  557. # l.pop(i)
  558. # i -= 1
  559. # break
  560. # else:
  561. # l[i:i + 1] = l[i]
  562. # i += 1
  563. # return ltype(l)
  564. #
  565. # log.debug("Geometry->bounds()")
  566. # if self.solid_geometry is None:
  567. # log.debug("solid_geometry is None")
  568. # return 0, 0, 0, 0
  569. #
  570. # if type(self.solid_geometry) is list:
  571. # if len(self.solid_geometry) == 0:
  572. # log.debug('solid_geometry is empty []')
  573. # return 0, 0, 0, 0
  574. # return cascaded_union(flatten(self.solid_geometry)).bounds
  575. # else:
  576. # return self.solid_geometry.bounds
  577. # except Exception as e:
  578. # self.app.inform.emit("[ERROR_NOTCL] Error cause: %s" % str(e))
  579. # log.debug("Geometry->bounds()")
  580. # if self.solid_geometry is None:
  581. # log.debug("solid_geometry is None")
  582. # return 0, 0, 0, 0
  583. #
  584. # if type(self.solid_geometry) is list:
  585. # if len(self.solid_geometry) == 0:
  586. # log.debug('solid_geometry is empty []')
  587. # return 0, 0, 0, 0
  588. # return cascaded_union(self.solid_geometry).bounds
  589. # else:
  590. # return self.solid_geometry.bounds
  591. def find_polygon(self, point, geoset=None):
  592. """
  593. Find an object that object.contains(Point(point)) in
  594. poly, which can can be iterable, contain iterable of, or
  595. be itself an implementer of .contains().
  596. :param point: See description
  597. :param geoset: a polygon or list of polygons where to find if the param point is contained
  598. :return: Polygon containing point or None.
  599. """
  600. if geoset is None:
  601. geoset = self.solid_geometry
  602. try: # Iterable
  603. for sub_geo in geoset:
  604. p = self.find_polygon(point, geoset=sub_geo)
  605. if p is not None:
  606. return p
  607. except TypeError: # Non-iterable
  608. try: # Implements .contains()
  609. if isinstance(geoset, LinearRing):
  610. geoset = Polygon(geoset)
  611. if geoset.contains(Point(point)):
  612. return geoset
  613. except AttributeError: # Does not implement .contains()
  614. return None
  615. return None
  616. def get_interiors(self, geometry=None):
  617. interiors = []
  618. if geometry is None:
  619. geometry = self.solid_geometry
  620. # ## If iterable, expand recursively.
  621. try:
  622. for geo in geometry:
  623. interiors.extend(self.get_interiors(geometry=geo))
  624. # ## Not iterable, get the interiors if polygon.
  625. except TypeError:
  626. if type(geometry) == Polygon:
  627. interiors.extend(geometry.interiors)
  628. return interiors
  629. def get_exteriors(self, geometry=None):
  630. """
  631. Returns all exteriors of polygons in geometry. Uses
  632. ``self.solid_geometry`` if geometry is not provided.
  633. :param geometry: Shapely type or list or list of list of such.
  634. :return: List of paths constituting the exteriors
  635. of polygons in geometry.
  636. """
  637. exteriors = []
  638. if geometry is None:
  639. geometry = self.solid_geometry
  640. # ## If iterable, expand recursively.
  641. try:
  642. for geo in geometry:
  643. exteriors.extend(self.get_exteriors(geometry=geo))
  644. # ## Not iterable, get the exterior if polygon.
  645. except TypeError:
  646. if type(geometry) == Polygon:
  647. exteriors.append(geometry.exterior)
  648. return exteriors
  649. def flatten(self, geometry=None, reset=True, pathonly=False):
  650. """
  651. Creates a list of non-iterable linear geometry objects.
  652. Polygons are expanded into its exterior and interiors if specified.
  653. Results are placed in self.flat_geometry
  654. :param geometry: Shapely type or list or list of list of such.
  655. :param reset: Clears the contents of self.flat_geometry.
  656. :param pathonly: Expands polygons into linear elements.
  657. """
  658. if geometry is None:
  659. geometry = self.solid_geometry
  660. if reset:
  661. self.flat_geometry = []
  662. # ## If iterable, expand recursively.
  663. try:
  664. for geo in geometry:
  665. if geo is not None:
  666. self.flatten(geometry=geo,
  667. reset=False,
  668. pathonly=pathonly)
  669. # ## Not iterable, do the actual indexing and add.
  670. except TypeError:
  671. if pathonly and type(geometry) == Polygon:
  672. self.flat_geometry.append(geometry.exterior)
  673. self.flatten(geometry=geometry.interiors,
  674. reset=False,
  675. pathonly=True)
  676. else:
  677. self.flat_geometry.append(geometry)
  678. return self.flat_geometry
  679. # def make2Dstorage(self):
  680. #
  681. # self.flatten()
  682. #
  683. # def get_pts(o):
  684. # pts = []
  685. # if type(o) == Polygon:
  686. # g = o.exterior
  687. # pts += list(g.coords)
  688. # for i in o.interiors:
  689. # pts += list(i.coords)
  690. # else:
  691. # pts += list(o.coords)
  692. # return pts
  693. #
  694. # storage = FlatCAMRTreeStorage()
  695. # storage.get_points = get_pts
  696. # for shape in self.flat_geometry:
  697. # storage.insert(shape)
  698. # return storage
  699. # def flatten_to_paths(self, geometry=None, reset=True):
  700. # """
  701. # Creates a list of non-iterable linear geometry elements and
  702. # indexes them in rtree.
  703. #
  704. # :param geometry: Iterable geometry
  705. # :param reset: Wether to clear (True) or append (False) to self.flat_geometry
  706. # :return: self.flat_geometry, self.flat_geometry_rtree
  707. # """
  708. #
  709. # if geometry is None:
  710. # geometry = self.solid_geometry
  711. #
  712. # if reset:
  713. # self.flat_geometry = []
  714. #
  715. # # ## If iterable, expand recursively.
  716. # try:
  717. # for geo in geometry:
  718. # self.flatten_to_paths(geometry=geo, reset=False)
  719. #
  720. # # ## Not iterable, do the actual indexing and add.
  721. # except TypeError:
  722. # if type(geometry) == Polygon:
  723. # g = geometry.exterior
  724. # self.flat_geometry.append(g)
  725. #
  726. # # ## Add first and last points of the path to the index.
  727. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[0])
  728. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[-1])
  729. #
  730. # for interior in geometry.interiors:
  731. # g = interior
  732. # self.flat_geometry.append(g)
  733. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[0])
  734. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[-1])
  735. # else:
  736. # g = geometry
  737. # self.flat_geometry.append(g)
  738. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[0])
  739. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[-1])
  740. #
  741. # return self.flat_geometry, self.flat_geometry_rtree
  742. def isolation_geometry(self, offset, geometry=None, iso_type=2, corner=None, follow=None, passes=0,
  743. prog_plot=False):
  744. """
  745. Creates contours around geometry at a given
  746. offset distance.
  747. :param offset: Offset distance.
  748. :type offset: float
  749. :param geometry The geometry to work with
  750. :param iso_type: type of isolation, can be 0 = exteriors or 1 = interiors or 2 = both (complete)
  751. :param corner: type of corner for the isolation:
  752. 0 = round; 1 = square; 2= beveled (line that connects the ends)
  753. :param follow: whether the geometry to be isolated is a follow_geometry
  754. :param passes: current pass out of possible multiple passes for which the isolation is done
  755. :param prog_plot: type of plotting: "normal" or "progressive"
  756. :return: The buffered geometry.
  757. :rtype: Shapely.MultiPolygon or Shapely.Polygon
  758. """
  759. if self.app.abort_flag:
  760. # graceful abort requested by the user
  761. raise grace
  762. geo_iso = []
  763. if follow:
  764. return geometry
  765. if geometry:
  766. working_geo = geometry
  767. else:
  768. working_geo = self.solid_geometry
  769. try:
  770. geo_len = len(working_geo)
  771. except TypeError:
  772. geo_len = 1
  773. old_disp_number = 0
  774. pol_nr = 0
  775. # yet, it can be done by issuing an unary_union in the end, thus getting rid of the overlapping geo
  776. try:
  777. for pol in working_geo:
  778. if self.app.abort_flag:
  779. # graceful abort requested by the user
  780. raise grace
  781. if offset == 0:
  782. temp_geo = pol
  783. else:
  784. corner_type = 1 if corner is None else corner
  785. temp_geo = pol.buffer(offset, int(self.geo_steps_per_circle), join_style=corner_type)
  786. geo_iso.append(temp_geo)
  787. pol_nr += 1
  788. # activity view update
  789. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  790. if old_disp_number < disp_number <= 100:
  791. self.app.proc_container.update_view_text(' %s %d: %d%%' %
  792. (_("Pass"), int(passes + 1), int(disp_number)))
  793. old_disp_number = disp_number
  794. except TypeError:
  795. # taking care of the case when the self.solid_geometry is just a single Polygon, not a list or a
  796. # MultiPolygon (not an iterable)
  797. if offset == 0:
  798. temp_geo = working_geo
  799. else:
  800. corner_type = 1 if corner is None else corner
  801. temp_geo = working_geo.buffer(offset, int(self.geo_steps_per_circle), join_style=corner_type)
  802. geo_iso.append(temp_geo)
  803. self.app.proc_container.update_view_text(' %s' % _("Buffering"))
  804. geo_iso = unary_union(geo_iso)
  805. self.app.proc_container.update_view_text('')
  806. # end of replaced block
  807. if iso_type == 2:
  808. ret_geo = geo_iso
  809. elif iso_type == 0:
  810. self.app.proc_container.update_view_text(' %s' % _("Get Exteriors"))
  811. ret_geo = self.get_exteriors(geo_iso)
  812. elif iso_type == 1:
  813. self.app.proc_container.update_view_text(' %s' % _("Get Interiors"))
  814. ret_geo = self.get_interiors(geo_iso)
  815. else:
  816. log.debug("Geometry.isolation_geometry() --> Type of isolation not supported")
  817. return "fail"
  818. if prog_plot == 'progressive':
  819. for elem in ret_geo:
  820. self.plot_temp_shapes(elem)
  821. return ret_geo
  822. def flatten_list(self, obj_list):
  823. for item in obj_list:
  824. if isinstance(item, Iterable) and not isinstance(item, (str, bytes)):
  825. yield from self.flatten_list(item)
  826. else:
  827. yield item
  828. def import_svg(self, filename, object_type=None, flip=True, units='MM'):
  829. """
  830. Imports shapes from an SVG file into the object's geometry.
  831. :param filename: Path to the SVG file.
  832. :type filename: str
  833. :param object_type: parameter passed further along
  834. :param flip: Flip the vertically.
  835. :type flip: bool
  836. :param units: FlatCAM units
  837. :return: None
  838. """
  839. log.debug("camlib.Geometry.import_svg()")
  840. # Parse into list of shapely objects
  841. svg_tree = ET.parse(filename)
  842. svg_root = svg_tree.getroot()
  843. # Change origin to bottom left
  844. # h = float(svg_root.get('height'))
  845. # w = float(svg_root.get('width'))
  846. h = svgparselength(svg_root.get('height'))[0] # TODO: No units support yet
  847. geos = getsvggeo(svg_root, object_type)
  848. if flip:
  849. geos = [translate(scale(g, 1.0, -1.0, origin=(0, 0)), yoff=h) for g in geos]
  850. # trying to optimize the resulting geometry by merging contiguous lines
  851. geos = linemerge(geos)
  852. # Add to object
  853. if self.solid_geometry is None:
  854. self.solid_geometry = []
  855. if type(self.solid_geometry) is list:
  856. if type(geos) is list:
  857. self.solid_geometry += geos
  858. else:
  859. self.solid_geometry.append(geos)
  860. else: # It's shapely geometry
  861. self.solid_geometry = [self.solid_geometry, geos]
  862. # flatten the self.solid_geometry list for import_svg() to import SVG as Gerber
  863. self.solid_geometry = list(self.flatten_list(self.solid_geometry))
  864. geos_text = getsvgtext(svg_root, object_type, units=units)
  865. if geos_text is not None:
  866. geos_text_f = []
  867. if flip:
  868. # Change origin to bottom left
  869. for i in geos_text:
  870. _, minimy, _, maximy = i.bounds
  871. h2 = (maximy - minimy) * 0.5
  872. geos_text_f.append(translate(scale(i, 1.0, -1.0, origin=(0, 0)), yoff=(h + h2)))
  873. if geos_text_f:
  874. self.solid_geometry = self.solid_geometry + geos_text_f
  875. def import_dxf(self, filename, object_type=None, units='MM'):
  876. """
  877. Imports shapes from an DXF file into the object's geometry.
  878. :param filename: Path to the DXF file.
  879. :type filename: str
  880. :param object_type:
  881. :param units: Application units
  882. :return: None
  883. """
  884. # Parse into list of shapely objects
  885. dxf = ezdxf.readfile(filename)
  886. geos = getdxfgeo(dxf)
  887. # trying to optimize the resulting geometry by merging contiguous lines
  888. geos = linemerge(geos)
  889. # Add to object
  890. if self.solid_geometry is None:
  891. self.solid_geometry = []
  892. if type(self.solid_geometry) is list:
  893. if type(geos) is list:
  894. self.solid_geometry += geos
  895. else:
  896. self.solid_geometry.append(geos)
  897. else: # It's shapely geometry
  898. self.solid_geometry = [self.solid_geometry, geos]
  899. # flatten the self.solid_geometry list for import_dxf() to import DXF as Gerber
  900. self.solid_geometry = list(self.flatten_list(self.solid_geometry))
  901. if self.solid_geometry is not None:
  902. self.solid_geometry = cascaded_union(self.solid_geometry)
  903. else:
  904. return
  905. # commented until this function is ready
  906. # geos_text = getdxftext(dxf, object_type, units=units)
  907. # if geos_text is not None:
  908. # geos_text_f = []
  909. # self.solid_geometry = [self.solid_geometry, geos_text_f]
  910. def import_image(self, filename, flip=True, units='MM', dpi=96, mode='black', mask=None):
  911. """
  912. Imports shapes from an IMAGE file into the object's geometry.
  913. :param filename: Path to the IMAGE file.
  914. :type filename: str
  915. :param flip: Flip the object vertically.
  916. :type flip: bool
  917. :param units: FlatCAM units
  918. :type units: str
  919. :param dpi: dots per inch on the imported image
  920. :param mode: how to import the image: as 'black' or 'color'
  921. :type mode: str
  922. :param mask: level of detail for the import
  923. :return: None
  924. """
  925. if mask is None:
  926. mask = [128, 128, 128, 128]
  927. scale_factor = 25.4 / dpi if units.lower() == 'mm' else 1 / dpi
  928. geos = []
  929. unscaled_geos = []
  930. with rasterio.open(filename) as src:
  931. # if filename.lower().rpartition('.')[-1] == 'bmp':
  932. # red = green = blue = src.read(1)
  933. # print("BMP")
  934. # elif filename.lower().rpartition('.')[-1] == 'png':
  935. # red, green, blue, alpha = src.read()
  936. # elif filename.lower().rpartition('.')[-1] == 'jpg':
  937. # red, green, blue = src.read()
  938. red = green = blue = src.read(1)
  939. try:
  940. green = src.read(2)
  941. except Exception:
  942. pass
  943. try:
  944. blue = src.read(3)
  945. except Exception:
  946. pass
  947. if mode == 'black':
  948. mask_setting = red <= mask[0]
  949. total = red
  950. log.debug("Image import as monochrome.")
  951. else:
  952. mask_setting = (red <= mask[1]) + (green <= mask[2]) + (blue <= mask[3])
  953. total = np.zeros(red.shape, dtype=np.float32)
  954. for band in red, green, blue:
  955. total += band
  956. total /= 3
  957. log.debug("Image import as colored. Thresholds are: R = %s , G = %s, B = %s" %
  958. (str(mask[1]), str(mask[2]), str(mask[3])))
  959. for geom, val in shapes(total, mask=mask_setting):
  960. unscaled_geos.append(shape(geom))
  961. for g in unscaled_geos:
  962. geos.append(scale(g, scale_factor, scale_factor, origin=(0, 0)))
  963. if flip:
  964. geos = [translate(scale(g, 1.0, -1.0, origin=(0, 0))) for g in geos]
  965. # Add to object
  966. if self.solid_geometry is None:
  967. self.solid_geometry = []
  968. if type(self.solid_geometry) is list:
  969. # self.solid_geometry.append(cascaded_union(geos))
  970. if type(geos) is list:
  971. self.solid_geometry += geos
  972. else:
  973. self.solid_geometry.append(geos)
  974. else: # It's shapely geometry
  975. self.solid_geometry = [self.solid_geometry, geos]
  976. # flatten the self.solid_geometry list for import_svg() to import SVG as Gerber
  977. self.solid_geometry = list(self.flatten_list(self.solid_geometry))
  978. self.solid_geometry = cascaded_union(self.solid_geometry)
  979. # self.solid_geometry = MultiPolygon(self.solid_geometry)
  980. # self.solid_geometry = self.solid_geometry.buffer(0.00000001)
  981. # self.solid_geometry = self.solid_geometry.buffer(-0.00000001)
  982. def size(self):
  983. """
  984. Returns (width, height) of rectangular
  985. bounds of geometry.
  986. """
  987. if self.solid_geometry is None:
  988. log.warning("Solid_geometry not computed yet.")
  989. return 0
  990. bounds = self.bounds()
  991. return bounds[2] - bounds[0], bounds[3] - bounds[1]
  992. def get_empty_area(self, boundary=None):
  993. """
  994. Returns the complement of self.solid_geometry within
  995. the given boundary polygon. If not specified, it defaults to
  996. the rectangular bounding box of self.solid_geometry.
  997. """
  998. if boundary is None:
  999. boundary = self.solid_geometry.envelope
  1000. return boundary.difference(self.solid_geometry)
  1001. def clear_polygon(self, polygon, tooldia, steps_per_circle, overlap=0.15, connect=True, contour=True,
  1002. prog_plot=False):
  1003. """
  1004. Creates geometry inside a polygon for a tool to cover
  1005. the whole area.
  1006. This algorithm shrinks the edges of the polygon and takes
  1007. the resulting edges as toolpaths.
  1008. :param polygon: Polygon to clear.
  1009. :param tooldia: Diameter of the tool.
  1010. :param steps_per_circle: number of linear segments to be used to approximate a circle
  1011. :param overlap: Overlap of toolpasses.
  1012. :param connect: Draw lines between disjoint segments to
  1013. minimize tool lifts.
  1014. :param contour: Paint around the edges. Inconsequential in
  1015. this painting method.
  1016. :param prog_plot: boolean; if Ture use the progressive plotting
  1017. :return:
  1018. """
  1019. # log.debug("camlib.clear_polygon()")
  1020. assert type(polygon) == Polygon or type(polygon) == MultiPolygon, \
  1021. "Expected a Polygon or MultiPolygon, got %s" % type(polygon)
  1022. # ## The toolpaths
  1023. # Index first and last points in paths
  1024. def get_pts(o):
  1025. return [o.coords[0], o.coords[-1]]
  1026. geoms = FlatCAMRTreeStorage()
  1027. geoms.get_points = get_pts
  1028. # Can only result in a Polygon or MultiPolygon
  1029. # NOTE: The resulting polygon can be "empty".
  1030. current = polygon.buffer((-tooldia / 1.999999), int(steps_per_circle))
  1031. if current.area == 0:
  1032. # Otherwise, trying to to insert current.exterior == None
  1033. # into the FlatCAMStorage will fail.
  1034. # print("Area is None")
  1035. return None
  1036. # current can be a MultiPolygon
  1037. try:
  1038. for p in current:
  1039. geoms.insert(p.exterior)
  1040. for i in p.interiors:
  1041. geoms.insert(i)
  1042. # Not a Multipolygon. Must be a Polygon
  1043. except TypeError:
  1044. geoms.insert(current.exterior)
  1045. for i in current.interiors:
  1046. geoms.insert(i)
  1047. while True:
  1048. if self.app.abort_flag:
  1049. # graceful abort requested by the user
  1050. raise grace
  1051. # provide the app with a way to process the GUI events when in a blocking loop
  1052. QtWidgets.QApplication.processEvents()
  1053. # Can only result in a Polygon or MultiPolygon
  1054. current = current.buffer(-tooldia * (1 - overlap), int(steps_per_circle))
  1055. if current.area > 0:
  1056. # current can be a MultiPolygon
  1057. try:
  1058. for p in current:
  1059. geoms.insert(p.exterior)
  1060. for i in p.interiors:
  1061. geoms.insert(i)
  1062. if prog_plot:
  1063. self.plot_temp_shapes(p)
  1064. # Not a Multipolygon. Must be a Polygon
  1065. except TypeError:
  1066. geoms.insert(current.exterior)
  1067. if prog_plot:
  1068. self.plot_temp_shapes(current.exterior)
  1069. for i in current.interiors:
  1070. geoms.insert(i)
  1071. if prog_plot:
  1072. self.plot_temp_shapes(i)
  1073. else:
  1074. log.debug("camlib.Geometry.clear_polygon() --> Current Area is zero")
  1075. break
  1076. if prog_plot:
  1077. self.temp_shapes.redraw()
  1078. # Optimization: Reduce lifts
  1079. if connect:
  1080. # log.debug("Reducing tool lifts...")
  1081. geoms = Geometry.paint_connect(geoms, polygon, tooldia, int(steps_per_circle))
  1082. return geoms
  1083. def clear_polygon2(self, polygon_to_clear, tooldia, steps_per_circle, seedpoint=None, overlap=0.15,
  1084. connect=True, contour=True, prog_plot=False):
  1085. """
  1086. Creates geometry inside a polygon for a tool to cover
  1087. the whole area.
  1088. This algorithm starts with a seed point inside the polygon
  1089. and draws circles around it. Arcs inside the polygons are
  1090. valid cuts. Finalizes by cutting around the inside edge of
  1091. the polygon.
  1092. :param polygon_to_clear: Shapely.geometry.Polygon
  1093. :param steps_per_circle: how many linear segments to use to approximate a circle
  1094. :param tooldia: Diameter of the tool
  1095. :param seedpoint: Shapely.geometry.Point or None
  1096. :param overlap: Tool fraction overlap bewteen passes
  1097. :param connect: Connect disjoint segment to minumize tool lifts
  1098. :param contour: Cut countour inside the polygon.
  1099. :param prog_plot: boolean; if True use the progressive plotting
  1100. :return: List of toolpaths covering polygon.
  1101. :rtype: FlatCAMRTreeStorage | None
  1102. """
  1103. # log.debug("camlib.clear_polygon2()")
  1104. # Current buffer radius
  1105. radius = tooldia / 2 * (1 - overlap)
  1106. # ## The toolpaths
  1107. # Index first and last points in paths
  1108. def get_pts(o):
  1109. return [o.coords[0], o.coords[-1]]
  1110. geoms = FlatCAMRTreeStorage()
  1111. geoms.get_points = get_pts
  1112. # Path margin
  1113. path_margin = polygon_to_clear.buffer(-tooldia / 2, int(steps_per_circle))
  1114. if path_margin.is_empty or path_margin is None:
  1115. return None
  1116. # Estimate good seedpoint if not provided.
  1117. if seedpoint is None:
  1118. seedpoint = path_margin.representative_point()
  1119. # Grow from seed until outside the box. The polygons will
  1120. # never have an interior, so take the exterior LinearRing.
  1121. while True:
  1122. if self.app.abort_flag:
  1123. # graceful abort requested by the user
  1124. raise grace
  1125. # provide the app with a way to process the GUI events when in a blocking loop
  1126. QtWidgets.QApplication.processEvents()
  1127. path = Point(seedpoint).buffer(radius, int(steps_per_circle)).exterior
  1128. path = path.intersection(path_margin)
  1129. # Touches polygon?
  1130. if path.is_empty:
  1131. break
  1132. else:
  1133. # geoms.append(path)
  1134. # geoms.insert(path)
  1135. # path can be a collection of paths.
  1136. try:
  1137. for p in path:
  1138. geoms.insert(p)
  1139. if prog_plot:
  1140. self.plot_temp_shapes(p)
  1141. except TypeError:
  1142. geoms.insert(path)
  1143. if prog_plot:
  1144. self.plot_temp_shapes(path)
  1145. if prog_plot:
  1146. self.temp_shapes.redraw()
  1147. radius += tooldia * (1 - overlap)
  1148. # Clean inside edges (contours) of the original polygon
  1149. if contour:
  1150. buffered_poly = autolist(polygon_to_clear.buffer(-tooldia / 2, int(steps_per_circle)))
  1151. outer_edges = [x.exterior for x in buffered_poly]
  1152. inner_edges = []
  1153. # Over resulting polygons
  1154. for x in buffered_poly:
  1155. for y in x.interiors: # Over interiors of each polygon
  1156. inner_edges.append(y)
  1157. # geoms += outer_edges + inner_edges
  1158. for g in outer_edges + inner_edges:
  1159. if g and not g.is_empty:
  1160. geoms.insert(g)
  1161. if prog_plot:
  1162. self.plot_temp_shapes(g)
  1163. if prog_plot:
  1164. self.temp_shapes.redraw()
  1165. # Optimization connect touching paths
  1166. # log.debug("Connecting paths...")
  1167. # geoms = Geometry.path_connect(geoms)
  1168. # Optimization: Reduce lifts
  1169. if connect:
  1170. # log.debug("Reducing tool lifts...")
  1171. geoms_conn = Geometry.paint_connect(geoms, polygon_to_clear, tooldia, steps_per_circle)
  1172. if geoms_conn:
  1173. return geoms_conn
  1174. return geoms
  1175. def clear_polygon3(self, polygon, tooldia, steps_per_circle, overlap=0.15, connect=True, contour=True,
  1176. prog_plot=False):
  1177. """
  1178. Creates geometry inside a polygon for a tool to cover
  1179. the whole area.
  1180. This algorithm draws horizontal lines inside the polygon.
  1181. :param polygon: The polygon being painted.
  1182. :type polygon: shapely.geometry.Polygon
  1183. :param tooldia: Tool diameter.
  1184. :param steps_per_circle: how many linear segments to use to approximate a circle
  1185. :param overlap: Tool path overlap percentage.
  1186. :param connect: Connect lines to avoid tool lifts.
  1187. :param contour: Paint around the edges.
  1188. :param prog_plot: boolean; if to use the progressive plotting
  1189. :return:
  1190. """
  1191. # log.debug("camlib.clear_polygon3()")
  1192. if not isinstance(polygon, Polygon):
  1193. log.debug("camlib.Geometry.clear_polygon3() --> Not a Polygon but %s" % str(type(polygon)))
  1194. return None
  1195. # ## The toolpaths
  1196. # Index first and last points in paths
  1197. def get_pts(o):
  1198. return [o.coords[0], o.coords[-1]]
  1199. geoms = FlatCAMRTreeStorage()
  1200. geoms.get_points = get_pts
  1201. lines_trimmed = []
  1202. # Bounding box
  1203. left, bot, right, top = polygon.bounds
  1204. try:
  1205. margin_poly = polygon.buffer(-tooldia / 1.99999999, (int(steps_per_circle)))
  1206. except Exception:
  1207. log.debug("camlib.Geometry.clear_polygon3() --> Could not buffer the Polygon")
  1208. return None
  1209. # decide the direction of the lines
  1210. if abs(left - right) >= abs(top - bot):
  1211. # First line
  1212. try:
  1213. y = top - tooldia / 1.99999999
  1214. while y > bot + tooldia / 1.999999999:
  1215. if self.app.abort_flag:
  1216. # graceful abort requested by the user
  1217. raise grace
  1218. # provide the app with a way to process the GUI events when in a blocking loop
  1219. QtWidgets.QApplication.processEvents()
  1220. line = LineString([(left, y), (right, y)])
  1221. line = line.intersection(margin_poly)
  1222. lines_trimmed.append(line)
  1223. y -= tooldia * (1 - overlap)
  1224. if prog_plot:
  1225. self.plot_temp_shapes(line)
  1226. self.temp_shapes.redraw()
  1227. # Last line
  1228. y = bot + tooldia / 2
  1229. line = LineString([(left, y), (right, y)])
  1230. line = line.intersection(margin_poly)
  1231. try:
  1232. for ll in line:
  1233. lines_trimmed.append(ll)
  1234. if prog_plot:
  1235. self.plot_temp_shapes(ll)
  1236. except TypeError:
  1237. lines_trimmed.append(line)
  1238. if prog_plot:
  1239. self.plot_temp_shapes(line)
  1240. except Exception as e:
  1241. log.debug('camlib.Geometry.clear_polygon3() Processing poly --> %s' % str(e))
  1242. return None
  1243. else:
  1244. # First line
  1245. try:
  1246. x = left + tooldia / 1.99999999
  1247. while x < right - tooldia / 1.999999999:
  1248. if self.app.abort_flag:
  1249. # graceful abort requested by the user
  1250. raise grace
  1251. # provide the app with a way to process the GUI events when in a blocking loop
  1252. QtWidgets.QApplication.processEvents()
  1253. line = LineString([(x, top), (x, bot)])
  1254. line = line.intersection(margin_poly)
  1255. lines_trimmed.append(line)
  1256. x += tooldia * (1 - overlap)
  1257. if prog_plot:
  1258. self.plot_temp_shapes(line)
  1259. self.temp_shapes.redraw()
  1260. # Last line
  1261. x = right + tooldia / 2
  1262. line = LineString([(x, top), (x, bot)])
  1263. line = line.intersection(margin_poly)
  1264. try:
  1265. for ll in line:
  1266. lines_trimmed.append(ll)
  1267. if prog_plot:
  1268. self.plot_temp_shapes(ll)
  1269. except TypeError:
  1270. lines_trimmed.append(line)
  1271. if prog_plot:
  1272. self.plot_temp_shapes(line)
  1273. except Exception as e:
  1274. log.debug('camlib.Geometry.clear_polygon3() Processing poly --> %s' % str(e))
  1275. return None
  1276. if prog_plot:
  1277. self.temp_shapes.redraw()
  1278. lines_trimmed = unary_union(lines_trimmed)
  1279. # Add lines to storage
  1280. try:
  1281. for line in lines_trimmed:
  1282. if isinstance(line, LineString) or isinstance(line, LinearRing):
  1283. if not line.is_empty:
  1284. geoms.insert(line)
  1285. else:
  1286. log.debug("camlib.Geometry.clear_polygon3(). Not a line: %s" % str(type(line)))
  1287. except TypeError:
  1288. # in case lines_trimmed are not iterable (Linestring, LinearRing)
  1289. if not lines_trimmed.is_empty:
  1290. geoms.insert(lines_trimmed)
  1291. # Add margin (contour) to storage
  1292. if contour:
  1293. try:
  1294. for poly in margin_poly:
  1295. if isinstance(poly, Polygon) and not poly.is_empty:
  1296. geoms.insert(poly.exterior)
  1297. if prog_plot:
  1298. self.plot_temp_shapes(poly.exterior)
  1299. for ints in poly.interiors:
  1300. geoms.insert(ints)
  1301. if prog_plot:
  1302. self.plot_temp_shapes(ints)
  1303. except TypeError:
  1304. if isinstance(margin_poly, Polygon) and not margin_poly.is_empty:
  1305. marg_ext = margin_poly.exterior
  1306. geoms.insert(marg_ext)
  1307. if prog_plot:
  1308. self.plot_temp_shapes(margin_poly.exterior)
  1309. for ints in margin_poly.interiors:
  1310. geoms.insert(ints)
  1311. if prog_plot:
  1312. self.plot_temp_shapes(ints)
  1313. if prog_plot:
  1314. self.temp_shapes.redraw()
  1315. # Optimization: Reduce lifts
  1316. if connect:
  1317. # log.debug("Reducing tool lifts...")
  1318. geoms_conn = Geometry.paint_connect(geoms, polygon, tooldia, steps_per_circle)
  1319. if geoms_conn:
  1320. return geoms_conn
  1321. return geoms
  1322. def fill_with_lines(self, line, aperture_size, tooldia, steps_per_circle, overlap=0.15, connect=True, contour=True,
  1323. prog_plot=False):
  1324. """
  1325. Creates geometry of lines inside a polygon for a tool to cover
  1326. the whole area.
  1327. This algorithm draws parallel lines inside the polygon.
  1328. :param line: The target line that create painted polygon.
  1329. :param aperture_size: the size of the aperture that is used to draw the 'line' as a polygon
  1330. :type line: shapely.geometry.LineString or shapely.geometry.MultiLineString
  1331. :param tooldia: Tool diameter.
  1332. :param steps_per_circle: how many linear segments to use to approximate a circle
  1333. :param overlap: Tool path overlap percentage.
  1334. :param connect: Connect lines to avoid tool lifts.
  1335. :param contour: Paint around the edges.
  1336. :param prog_plot: boolean; if to use the progressive plotting
  1337. :return:
  1338. """
  1339. # log.debug("camlib.fill_with_lines()")
  1340. if not isinstance(line, LineString):
  1341. log.debug("camlib.Geometry.fill_with_lines() --> Not a LineString/MultiLineString but %s" % str(type(line)))
  1342. return None
  1343. # ## The toolpaths
  1344. # Index first and last points in paths
  1345. def get_pts(o):
  1346. return [o.coords[0], o.coords[-1]]
  1347. geoms = FlatCAMRTreeStorage()
  1348. geoms.get_points = get_pts
  1349. lines_trimmed = []
  1350. polygon = line.buffer(aperture_size / 2.0, int(steps_per_circle))
  1351. try:
  1352. margin_poly = polygon.buffer(-tooldia / 2.0, int(steps_per_circle))
  1353. except Exception:
  1354. log.debug("camlib.Geometry.fill_with_lines() --> Could not buffer the Polygon, tool diameter too high")
  1355. return None
  1356. # First line
  1357. try:
  1358. delta = 0
  1359. while delta < aperture_size / 2:
  1360. if self.app.abort_flag:
  1361. # graceful abort requested by the user
  1362. raise grace
  1363. # provide the app with a way to process the GUI events when in a blocking loop
  1364. QtWidgets.QApplication.processEvents()
  1365. new_line = line.parallel_offset(distance=delta, side='left', resolution=int(steps_per_circle))
  1366. new_line = new_line.intersection(margin_poly)
  1367. lines_trimmed.append(new_line)
  1368. new_line = line.parallel_offset(distance=delta, side='right', resolution=int(steps_per_circle))
  1369. new_line = new_line.intersection(margin_poly)
  1370. lines_trimmed.append(new_line)
  1371. delta += tooldia * (1 - overlap)
  1372. if prog_plot:
  1373. self.plot_temp_shapes(new_line)
  1374. self.temp_shapes.redraw()
  1375. # Last line
  1376. delta = (aperture_size / 2) - (tooldia / 2.00000001)
  1377. new_line = line.parallel_offset(distance=delta, side='left', resolution=int(steps_per_circle))
  1378. new_line = new_line.intersection(margin_poly)
  1379. except Exception as e:
  1380. log.debug('camlib.Geometry.fill_with_lines() Processing poly --> %s' % str(e))
  1381. return None
  1382. try:
  1383. for ll in new_line:
  1384. lines_trimmed.append(ll)
  1385. if prog_plot:
  1386. self.plot_temp_shapes(ll)
  1387. except TypeError:
  1388. lines_trimmed.append(new_line)
  1389. if prog_plot:
  1390. self.plot_temp_shapes(new_line)
  1391. new_line = line.parallel_offset(distance=delta, side='right', resolution=int(steps_per_circle))
  1392. new_line = new_line.intersection(margin_poly)
  1393. try:
  1394. for ll in new_line:
  1395. lines_trimmed.append(ll)
  1396. if prog_plot:
  1397. self.plot_temp_shapes(ll)
  1398. except TypeError:
  1399. lines_trimmed.append(new_line)
  1400. if prog_plot:
  1401. self.plot_temp_shapes(new_line)
  1402. if prog_plot:
  1403. self.temp_shapes.redraw()
  1404. lines_trimmed = unary_union(lines_trimmed)
  1405. # Add lines to storage
  1406. try:
  1407. for line in lines_trimmed:
  1408. if isinstance(line, LineString) or isinstance(line, LinearRing):
  1409. geoms.insert(line)
  1410. else:
  1411. log.debug("camlib.Geometry.fill_with_lines(). Not a line: %s" % str(type(line)))
  1412. except TypeError:
  1413. # in case lines_trimmed are not iterable (Linestring, LinearRing)
  1414. geoms.insert(lines_trimmed)
  1415. # Add margin (contour) to storage
  1416. if contour:
  1417. try:
  1418. for poly in margin_poly:
  1419. if isinstance(poly, Polygon) and not poly.is_empty:
  1420. geoms.insert(poly.exterior)
  1421. if prog_plot:
  1422. self.plot_temp_shapes(poly.exterior)
  1423. for ints in poly.interiors:
  1424. geoms.insert(ints)
  1425. if prog_plot:
  1426. self.plot_temp_shapes(ints)
  1427. except TypeError:
  1428. if isinstance(margin_poly, Polygon) and not margin_poly.is_empty:
  1429. marg_ext = margin_poly.exterior
  1430. geoms.insert(marg_ext)
  1431. if prog_plot:
  1432. self.plot_temp_shapes(margin_poly.exterior)
  1433. for ints in margin_poly.interiors:
  1434. geoms.insert(ints)
  1435. if prog_plot:
  1436. self.plot_temp_shapes(ints)
  1437. if prog_plot:
  1438. self.temp_shapes.redraw()
  1439. # Optimization: Reduce lifts
  1440. if connect:
  1441. # log.debug("Reducing tool lifts...")
  1442. geoms_conn = Geometry.paint_connect(geoms, polygon, tooldia, steps_per_circle)
  1443. if geoms_conn:
  1444. return geoms_conn
  1445. return geoms
  1446. def scale(self, xfactor, yfactor, point=None):
  1447. """
  1448. Scales all of the object's geometry by a given factor. Override
  1449. this method.
  1450. :param xfactor: Number by which to scale on X axis.
  1451. :type xfactor: float
  1452. :param yfactor: Number by which to scale on Y axis.
  1453. :type yfactor: float
  1454. :param point: point to be used as reference for scaling; a tuple
  1455. :return: None
  1456. :rtype: None
  1457. """
  1458. return
  1459. def offset(self, vect):
  1460. """
  1461. Offset the geometry by the given vector. Override this method.
  1462. :param vect: (x, y) vector by which to offset the object.
  1463. :type vect: tuple
  1464. :return: None
  1465. """
  1466. return
  1467. @staticmethod
  1468. def paint_connect(storage, boundary, tooldia, steps_per_circle, max_walk=None):
  1469. """
  1470. Connects paths that results in a connection segment that is
  1471. within the paint area. This avoids unnecessary tool lifting.
  1472. :param storage: Geometry to be optimized.
  1473. :type storage: FlatCAMRTreeStorage
  1474. :param boundary: Polygon defining the limits of the paintable area.
  1475. :type boundary: Polygon
  1476. :param tooldia: Tool diameter.
  1477. :rtype tooldia: float
  1478. :param steps_per_circle: how many linear segments to use to approximate a circle
  1479. :param max_walk: Maximum allowable distance without lifting tool.
  1480. :type max_walk: float or None
  1481. :return: Optimized geometry.
  1482. :rtype: FlatCAMRTreeStorage
  1483. """
  1484. # If max_walk is not specified, the maximum allowed is
  1485. # 10 times the tool diameter
  1486. max_walk = max_walk or 10 * tooldia
  1487. # Assuming geolist is a flat list of flat elements
  1488. # ## Index first and last points in paths
  1489. def get_pts(o):
  1490. return [o.coords[0], o.coords[-1]]
  1491. # storage = FlatCAMRTreeStorage()
  1492. # storage.get_points = get_pts
  1493. #
  1494. # for shape in geolist:
  1495. # if shape is not None:
  1496. # # Make LlinearRings into linestrings otherwise
  1497. # # When chaining the coordinates path is messed up.
  1498. # storage.insert(LineString(shape))
  1499. # #storage.insert(shape)
  1500. # ## Iterate over geometry paths getting the nearest each time.
  1501. # optimized_paths = []
  1502. optimized_paths = FlatCAMRTreeStorage()
  1503. optimized_paths.get_points = get_pts
  1504. path_count = 0
  1505. current_pt = (0, 0)
  1506. try:
  1507. pt, geo = storage.nearest(current_pt)
  1508. except StopIteration:
  1509. log.debug("camlib.Geometry.paint_connect(). Storage empty")
  1510. return None
  1511. storage.remove(geo)
  1512. geo = LineString(geo)
  1513. current_pt = geo.coords[-1]
  1514. try:
  1515. while True:
  1516. path_count += 1
  1517. # log.debug("Path %d" % path_count)
  1518. pt, candidate = storage.nearest(current_pt)
  1519. storage.remove(candidate)
  1520. candidate = LineString(candidate)
  1521. # If last point in geometry is the nearest
  1522. # then reverse coordinates.
  1523. # but prefer the first one if last == first
  1524. if pt != candidate.coords[0] and pt == candidate.coords[-1]:
  1525. candidate.coords = list(candidate.coords)[::-1]
  1526. # Straight line from current_pt to pt.
  1527. # Is the toolpath inside the geometry?
  1528. walk_path = LineString([current_pt, pt])
  1529. walk_cut = walk_path.buffer(tooldia / 2, int(steps_per_circle))
  1530. if walk_cut.within(boundary) and walk_path.length < max_walk:
  1531. # log.debug("Walk to path #%d is inside. Joining." % path_count)
  1532. # Completely inside. Append...
  1533. geo.coords = list(geo.coords) + list(candidate.coords)
  1534. # try:
  1535. # last = optimized_paths[-1]
  1536. # last.coords = list(last.coords) + list(geo.coords)
  1537. # except IndexError:
  1538. # optimized_paths.append(geo)
  1539. else:
  1540. # Have to lift tool. End path.
  1541. # log.debug("Path #%d not within boundary. Next." % path_count)
  1542. # optimized_paths.append(geo)
  1543. optimized_paths.insert(geo)
  1544. geo = candidate
  1545. current_pt = geo.coords[-1]
  1546. # Next
  1547. # pt, geo = storage.nearest(current_pt)
  1548. except StopIteration: # Nothing left in storage.
  1549. # pass
  1550. optimized_paths.insert(geo)
  1551. return optimized_paths
  1552. @staticmethod
  1553. def path_connect(storage, origin=(0, 0)):
  1554. """
  1555. Simplifies paths in the FlatCAMRTreeStorage storage by
  1556. connecting paths that touch on their endpoints.
  1557. :param storage: Storage containing the initial paths.
  1558. :rtype storage: FlatCAMRTreeStorage
  1559. :param origin: tuple; point from which to calculate the nearest point
  1560. :return: Simplified storage.
  1561. :rtype: FlatCAMRTreeStorage
  1562. """
  1563. log.debug("path_connect()")
  1564. # ## Index first and last points in paths
  1565. def get_pts(o):
  1566. return [o.coords[0], o.coords[-1]]
  1567. #
  1568. # storage = FlatCAMRTreeStorage()
  1569. # storage.get_points = get_pts
  1570. #
  1571. # for shape in pathlist:
  1572. # if shape is not None:
  1573. # storage.insert(shape)
  1574. path_count = 0
  1575. pt, geo = storage.nearest(origin)
  1576. storage.remove(geo)
  1577. # optimized_geometry = [geo]
  1578. optimized_geometry = FlatCAMRTreeStorage()
  1579. optimized_geometry.get_points = get_pts
  1580. # optimized_geometry.insert(geo)
  1581. try:
  1582. while True:
  1583. path_count += 1
  1584. _, left = storage.nearest(geo.coords[0])
  1585. # If left touches geo, remove left from original
  1586. # storage and append to geo.
  1587. if type(left) == LineString:
  1588. if left.coords[0] == geo.coords[0]:
  1589. storage.remove(left)
  1590. geo.coords = list(geo.coords)[::-1] + list(left.coords)
  1591. continue
  1592. if left.coords[-1] == geo.coords[0]:
  1593. storage.remove(left)
  1594. geo.coords = list(left.coords) + list(geo.coords)
  1595. continue
  1596. if left.coords[0] == geo.coords[-1]:
  1597. storage.remove(left)
  1598. geo.coords = list(geo.coords) + list(left.coords)
  1599. continue
  1600. if left.coords[-1] == geo.coords[-1]:
  1601. storage.remove(left)
  1602. geo.coords = list(geo.coords) + list(left.coords)[::-1]
  1603. continue
  1604. _, right = storage.nearest(geo.coords[-1])
  1605. # If right touches geo, remove left from original
  1606. # storage and append to geo.
  1607. if type(right) == LineString:
  1608. if right.coords[0] == geo.coords[-1]:
  1609. storage.remove(right)
  1610. geo.coords = list(geo.coords) + list(right.coords)
  1611. continue
  1612. if right.coords[-1] == geo.coords[-1]:
  1613. storage.remove(right)
  1614. geo.coords = list(geo.coords) + list(right.coords)[::-1]
  1615. continue
  1616. if right.coords[0] == geo.coords[0]:
  1617. storage.remove(right)
  1618. geo.coords = list(geo.coords)[::-1] + list(right.coords)
  1619. continue
  1620. if right.coords[-1] == geo.coords[0]:
  1621. storage.remove(right)
  1622. geo.coords = list(left.coords) + list(geo.coords)
  1623. continue
  1624. # right is either a LinearRing or it does not connect
  1625. # to geo (nothing left to connect to geo), so we continue
  1626. # with right as geo.
  1627. storage.remove(right)
  1628. if type(right) == LinearRing:
  1629. optimized_geometry.insert(right)
  1630. else:
  1631. # Cannot extend geo any further. Put it away.
  1632. optimized_geometry.insert(geo)
  1633. # Continue with right.
  1634. geo = right
  1635. except StopIteration: # Nothing found in storage.
  1636. optimized_geometry.insert(geo)
  1637. # print path_count
  1638. log.debug("path_count = %d" % path_count)
  1639. return optimized_geometry
  1640. def convert_units(self, obj_units):
  1641. """
  1642. Converts the units of the object to ``units`` by scaling all
  1643. the geometry appropriately. This call ``scale()``. Don't call
  1644. it again in descendents.
  1645. :param obj_units: "IN" or "MM"
  1646. :type obj_units: str
  1647. :return: Scaling factor resulting from unit change.
  1648. :rtype: float
  1649. """
  1650. if obj_units.upper() == self.units.upper():
  1651. log.debug("camlib.Geometry.convert_units() --> Factor: 1")
  1652. return 1.0
  1653. if obj_units.upper() == "MM":
  1654. factor = 25.4
  1655. log.debug("camlib.Geometry.convert_units() --> Factor: 25.4")
  1656. elif obj_units.upper() == "IN":
  1657. factor = 1 / 25.4
  1658. log.debug("camlib.Geometry.convert_units() --> Factor: %s" % str(1 / 25.4))
  1659. else:
  1660. log.error("Unsupported units: %s" % str(obj_units))
  1661. log.debug("camlib.Geometry.convert_units() --> Factor: 1")
  1662. return 1.0
  1663. self.units = obj_units
  1664. self.scale(factor, factor)
  1665. self.file_units_factor = factor
  1666. return factor
  1667. def to_dict(self):
  1668. """
  1669. Returns a representation of the object as a dictionary.
  1670. Attributes to include are listed in ``self.ser_attrs``.
  1671. :return: A dictionary-encoded copy of the object.
  1672. :rtype: dict
  1673. """
  1674. d = {}
  1675. for attr in self.ser_attrs:
  1676. d[attr] = getattr(self, attr)
  1677. return d
  1678. def from_dict(self, d):
  1679. """
  1680. Sets object's attributes from a dictionary.
  1681. Attributes to include are listed in ``self.ser_attrs``.
  1682. This method will look only for only and all the
  1683. attributes in ``self.ser_attrs``. They must all
  1684. be present. Use only for deserializing saved
  1685. objects.
  1686. :param d: Dictionary of attributes to set in the object.
  1687. :type d: dict
  1688. :return: None
  1689. """
  1690. for attr in self.ser_attrs:
  1691. setattr(self, attr, d[attr])
  1692. def union(self):
  1693. """
  1694. Runs a cascaded union on the list of objects in
  1695. solid_geometry.
  1696. :return: None
  1697. """
  1698. self.solid_geometry = [cascaded_union(self.solid_geometry)]
  1699. def export_svg(self, scale_stroke_factor=0.00,
  1700. scale_factor_x=None, scale_factor_y=None,
  1701. skew_factor_x=None, skew_factor_y=None,
  1702. skew_reference='center',
  1703. mirror=None):
  1704. """
  1705. Exports the Geometry Object as a SVG Element
  1706. :return: SVG Element
  1707. """
  1708. # Make sure we see a Shapely Geometry class and not a list
  1709. if self.kind.lower() == 'geometry':
  1710. flat_geo = []
  1711. if self.multigeo:
  1712. for tool in self.tools:
  1713. flat_geo += self.flatten(self.tools[tool]['solid_geometry'])
  1714. geom_svg = cascaded_union(flat_geo)
  1715. else:
  1716. geom_svg = cascaded_union(self.flatten())
  1717. else:
  1718. geom_svg = cascaded_union(self.flatten())
  1719. skew_ref = 'center'
  1720. if skew_reference != 'center':
  1721. xmin, ymin, xmax, ymax = geom_svg.bounds
  1722. if skew_reference == 'topleft':
  1723. skew_ref = (xmin, ymax)
  1724. elif skew_reference == 'bottomleft':
  1725. skew_ref = (xmin, ymin)
  1726. elif skew_reference == 'topright':
  1727. skew_ref = (xmax, ymax)
  1728. elif skew_reference == 'bottomright':
  1729. skew_ref = (xmax, ymin)
  1730. geom = geom_svg
  1731. if scale_factor_x:
  1732. geom = affinity.scale(geom_svg, scale_factor_x, 1.0)
  1733. if scale_factor_y:
  1734. geom = affinity.scale(geom_svg, 1.0, scale_factor_y)
  1735. if skew_factor_x:
  1736. geom = affinity.skew(geom_svg, skew_factor_x, 0.0, origin=skew_ref)
  1737. if skew_factor_y:
  1738. geom = affinity.skew(geom_svg, 0.0, skew_factor_y, origin=skew_ref)
  1739. if mirror:
  1740. if mirror == 'x':
  1741. geom = affinity.scale(geom_svg, 1.0, -1.0)
  1742. if mirror == 'y':
  1743. geom = affinity.scale(geom_svg, -1.0, 1.0)
  1744. if mirror == 'both':
  1745. geom = affinity.scale(geom_svg, -1.0, -1.0)
  1746. # scale_factor is a multiplication factor for the SVG stroke-width used within shapely's svg export
  1747. # If 0 or less which is invalid then default to 0.01
  1748. # This value appears to work for zooming, and getting the output svg line width
  1749. # to match that viewed on screen with FlatCam
  1750. # MS: I choose a factor of 0.01 so the scale is right for PCB UV film
  1751. if scale_stroke_factor <= 0:
  1752. scale_stroke_factor = 0.01
  1753. # Convert to a SVG
  1754. svg_elem = geom.svg(scale_factor=scale_stroke_factor)
  1755. return svg_elem
  1756. def mirror(self, axis, point):
  1757. """
  1758. Mirrors the object around a specified axis passign through
  1759. the given point.
  1760. :param axis: "X" or "Y" indicates around which axis to mirror.
  1761. :type axis: str
  1762. :param point: [x, y] point belonging to the mirror axis.
  1763. :type point: list
  1764. :return: None
  1765. """
  1766. log.debug("camlib.Geometry.mirror()")
  1767. px, py = point
  1768. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  1769. def mirror_geom(obj):
  1770. if type(obj) is list:
  1771. new_obj = []
  1772. for g in obj:
  1773. new_obj.append(mirror_geom(g))
  1774. return new_obj
  1775. else:
  1776. try:
  1777. self.el_count += 1
  1778. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  1779. if self.old_disp_number < disp_number <= 100:
  1780. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1781. self.old_disp_number = disp_number
  1782. return affinity.scale(obj, xscale, yscale, origin=(px, py))
  1783. except AttributeError:
  1784. return obj
  1785. try:
  1786. if self.multigeo is True:
  1787. for tool in self.tools:
  1788. # variables to display the percentage of work done
  1789. self.geo_len = 0
  1790. try:
  1791. self.geo_len = len(self.tools[tool]['solid_geometry'])
  1792. except TypeError:
  1793. self.geo_len = 1
  1794. self.old_disp_number = 0
  1795. self.el_count = 0
  1796. self.tools[tool]['solid_geometry'] = mirror_geom(self.tools[tool]['solid_geometry'])
  1797. else:
  1798. # variables to display the percentage of work done
  1799. self.geo_len = 0
  1800. try:
  1801. self.geo_len = len(self.solid_geometry)
  1802. except TypeError:
  1803. self.geo_len = 1
  1804. self.old_disp_number = 0
  1805. self.el_count = 0
  1806. self.solid_geometry = mirror_geom(self.solid_geometry)
  1807. self.app.inform.emit('[success] %s...' % _('Object was mirrored'))
  1808. except AttributeError:
  1809. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Failed to mirror. No object selected"))
  1810. self.app.proc_container.new_text = ''
  1811. def rotate(self, angle, point):
  1812. """
  1813. Rotate an object by an angle (in degrees) around the provided coordinates.
  1814. :param angle:
  1815. The angle of rotation are specified in degrees (default). Positive angles are
  1816. counter-clockwise and negative are clockwise rotations.
  1817. :param point:
  1818. The point of origin can be a keyword 'center' for the bounding box
  1819. center (default), 'centroid' for the geometry's centroid, a Point object
  1820. or a coordinate tuple (x0, y0).
  1821. See shapely manual for more information: http://toblerity.org/shapely/manual.html#affine-transformations
  1822. """
  1823. log.debug("camlib.Geometry.rotate()")
  1824. px, py = point
  1825. def rotate_geom(obj):
  1826. try:
  1827. new_obj = []
  1828. for g in obj:
  1829. new_obj.append(rotate_geom(g))
  1830. return new_obj
  1831. except TypeError:
  1832. try:
  1833. self.el_count += 1
  1834. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  1835. if self.old_disp_number < disp_number <= 100:
  1836. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1837. self.old_disp_number = disp_number
  1838. return affinity.rotate(obj, angle, origin=(px, py))
  1839. except AttributeError:
  1840. return obj
  1841. try:
  1842. if self.multigeo is True:
  1843. for tool in self.tools:
  1844. # variables to display the percentage of work done
  1845. self.geo_len = 0
  1846. try:
  1847. self.geo_len = len(self.tools[tool]['solid_geometry'])
  1848. except TypeError:
  1849. self.geo_len = 1
  1850. self.old_disp_number = 0
  1851. self.el_count = 0
  1852. self.tools[tool]['solid_geometry'] = rotate_geom(self.tools[tool]['solid_geometry'])
  1853. else:
  1854. # variables to display the percentage of work done
  1855. self.geo_len = 0
  1856. try:
  1857. self.geo_len = len(self.solid_geometry)
  1858. except TypeError:
  1859. self.geo_len = 1
  1860. self.old_disp_number = 0
  1861. self.el_count = 0
  1862. self.solid_geometry = rotate_geom(self.solid_geometry)
  1863. self.app.inform.emit('[success] %s...' % _('Object was rotated'))
  1864. except AttributeError:
  1865. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Failed to rotate. No object selected"))
  1866. self.app.proc_container.new_text = ''
  1867. def skew(self, angle_x, angle_y, point):
  1868. """
  1869. Shear/Skew the geometries of an object by angles along x and y dimensions.
  1870. :param angle_x:
  1871. :param angle_y:
  1872. angle_x, angle_y : float, float
  1873. The shear angle(s) for the x and y axes respectively. These can be
  1874. specified in either degrees (default) or radians by setting
  1875. use_radians=True.
  1876. :param point: Origin point for Skew
  1877. point: tuple of coordinates (x,y)
  1878. See shapely manual for more information: http://toblerity.org/shapely/manual.html#affine-transformations
  1879. """
  1880. log.debug("camlib.Geometry.skew()")
  1881. px, py = point
  1882. def skew_geom(obj):
  1883. try:
  1884. new_obj = []
  1885. for g in obj:
  1886. new_obj.append(skew_geom(g))
  1887. return new_obj
  1888. except TypeError:
  1889. try:
  1890. self.el_count += 1
  1891. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  1892. if self.old_disp_number < disp_number <= 100:
  1893. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1894. self.old_disp_number = disp_number
  1895. return affinity.skew(obj, angle_x, angle_y, origin=(px, py))
  1896. except AttributeError:
  1897. return obj
  1898. try:
  1899. if self.multigeo is True:
  1900. for tool in self.tools:
  1901. # variables to display the percentage of work done
  1902. self.geo_len = 0
  1903. try:
  1904. self.geo_len = len(self.tools[tool]['solid_geometry'])
  1905. except TypeError:
  1906. self.geo_len = 1
  1907. self.old_disp_number = 0
  1908. self.el_count = 0
  1909. self.tools[tool]['solid_geometry'] = skew_geom(self.tools[tool]['solid_geometry'])
  1910. else:
  1911. # variables to display the percentage of work done
  1912. self.geo_len = 0
  1913. try:
  1914. self.geo_len = len(self.solid_geometry)
  1915. except TypeError:
  1916. self.geo_len = 1
  1917. self.old_disp_number = 0
  1918. self.el_count = 0
  1919. self.solid_geometry = skew_geom(self.solid_geometry)
  1920. self.app.inform.emit('[success] %s...' % _('Object was skewed'))
  1921. except AttributeError:
  1922. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Failed to skew. No object selected"))
  1923. self.app.proc_container.new_text = ''
  1924. # if type(self.solid_geometry) == list:
  1925. # self.solid_geometry = [affinity.skew(g, angle_x, angle_y, origin=(px, py))
  1926. # for g in self.solid_geometry]
  1927. # else:
  1928. # self.solid_geometry = affinity.skew(self.solid_geometry, angle_x, angle_y,
  1929. # origin=(px, py))
  1930. def buffer(self, distance, join, factor):
  1931. """
  1932. :param distance: if 'factor' is True then distance is the factor
  1933. :param join: The kind of join used by the shapely buffer method: round, square or bevel
  1934. :param factor: True or False (None)
  1935. :return:
  1936. """
  1937. log.debug("camlib.Geometry.buffer()")
  1938. if distance == 0:
  1939. return
  1940. def buffer_geom(obj):
  1941. if type(obj) is list:
  1942. new_obj = []
  1943. for g in obj:
  1944. new_obj.append(buffer_geom(g))
  1945. return new_obj
  1946. else:
  1947. try:
  1948. self.el_count += 1
  1949. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  1950. if self.old_disp_number < disp_number <= 100:
  1951. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1952. self.old_disp_number = disp_number
  1953. if factor is None:
  1954. return obj.buffer(distance, resolution=self.geo_steps_per_circle, join_style=join)
  1955. else:
  1956. return affinity.scale(obj, xfact=distance, yfact=distance, origin='center')
  1957. except AttributeError:
  1958. return obj
  1959. try:
  1960. if self.multigeo is True:
  1961. for tool in self.tools:
  1962. # variables to display the percentage of work done
  1963. self.geo_len = 0
  1964. try:
  1965. self.geo_len += len(self.tools[tool]['solid_geometry'])
  1966. except TypeError:
  1967. self.geo_len += 1
  1968. self.old_disp_number = 0
  1969. self.el_count = 0
  1970. res = buffer_geom(self.tools[tool]['solid_geometry'])
  1971. try:
  1972. __ = iter(res)
  1973. self.tools[tool]['solid_geometry'] = res
  1974. except TypeError:
  1975. self.tools[tool]['solid_geometry'] = [res]
  1976. # variables to display the percentage of work done
  1977. self.geo_len = 0
  1978. try:
  1979. self.geo_len = len(self.solid_geometry)
  1980. except TypeError:
  1981. self.geo_len = 1
  1982. self.old_disp_number = 0
  1983. self.el_count = 0
  1984. self.solid_geometry = buffer_geom(self.solid_geometry)
  1985. self.app.inform.emit('[success] %s...' % _('Object was buffered'))
  1986. except AttributeError:
  1987. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Failed to buffer. No object selected"))
  1988. self.app.proc_container.new_text = ''
  1989. class AttrDict(dict):
  1990. def __init__(self, *args, **kwargs):
  1991. super(AttrDict, self).__init__(*args, **kwargs)
  1992. self.__dict__ = self
  1993. class CNCjob(Geometry):
  1994. """
  1995. Represents work to be done by a CNC machine.
  1996. *ATTRIBUTES*
  1997. * ``gcode_parsed`` (list): Each is a dictionary:
  1998. ===================== =========================================
  1999. Key Value
  2000. ===================== =========================================
  2001. geom (Shapely.LineString) Tool path (XY plane)
  2002. kind (string) "AB", A is "T" (travel) or
  2003. "C" (cut). B is "F" (fast) or "S" (slow).
  2004. ===================== =========================================
  2005. """
  2006. defaults = {
  2007. "global_zdownrate": None,
  2008. "pp_geometry_name": 'default',
  2009. "pp_excellon_name": 'default',
  2010. "excellon_optimization_type": "B",
  2011. }
  2012. settings = QtCore.QSettings("Open Source", "FlatCAM")
  2013. if settings.contains("machinist"):
  2014. machinist_setting = settings.value('machinist', type=int)
  2015. else:
  2016. machinist_setting = 0
  2017. def __init__(self,
  2018. units="in", kind="generic", tooldia=0.0,
  2019. z_cut=-0.002, z_move=0.1,
  2020. feedrate=3.0, feedrate_z=3.0, feedrate_rapid=3.0, feedrate_probe=3.0,
  2021. pp_geometry_name='default', pp_excellon_name='default',
  2022. depthpercut=0.1, z_pdepth=-0.02,
  2023. spindlespeed=None, spindledir='CW', dwell=True, dwelltime=1000,
  2024. toolchangez=0.787402, toolchange_xy='0.0,0.0',
  2025. endz=2.0, endxy='',
  2026. segx=None,
  2027. segy=None,
  2028. steps_per_circle=None):
  2029. self.decimals = self.app.decimals
  2030. # Used when parsing G-code arcs
  2031. self.steps_per_circle = steps_per_circle if steps_per_circle is not None else \
  2032. int(self.app.defaults['cncjob_steps_per_circle'])
  2033. Geometry.__init__(self, geo_steps_per_circle=self.steps_per_circle)
  2034. self.kind = kind
  2035. self.units = units
  2036. self.z_cut = z_cut
  2037. self.z_move = z_move
  2038. self.feedrate = feedrate
  2039. self.z_feedrate = feedrate_z
  2040. self.feedrate_rapid = feedrate_rapid
  2041. self.tooldia = tooldia
  2042. self.toolchange = False
  2043. self.z_toolchange = toolchangez
  2044. self.xy_toolchange = toolchange_xy
  2045. self.toolchange_xy_type = None
  2046. self.toolC = tooldia
  2047. self.startz = None
  2048. self.z_end = endz
  2049. self.xy_end = endxy
  2050. self.multidepth = False
  2051. self.z_depthpercut = depthpercut
  2052. self.extracut_length = None
  2053. # used by the self.generate_from_excellon_by_tool() method
  2054. # but set directly before the actual usage of the method with obj.excellon_optimization_type = value
  2055. self.excellon_optimization_type = 'No'
  2056. # if set True then the GCode generation will use UI; used in Excellon GVode for now
  2057. self.use_ui = False
  2058. self.unitcode = {"IN": "G20", "MM": "G21"}
  2059. self.feedminutecode = "G94"
  2060. # self.absolutecode = "G90"
  2061. # self.incrementalcode = "G91"
  2062. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  2063. self.gcode = ""
  2064. self.gcode_parsed = None
  2065. self.pp_geometry_name = pp_geometry_name
  2066. self.pp_geometry = self.app.preprocessors[self.pp_geometry_name]
  2067. self.pp_excellon_name = pp_excellon_name
  2068. self.pp_excellon = self.app.preprocessors[self.pp_excellon_name]
  2069. self.pp_solderpaste_name = None
  2070. # Controls if the move from Z_Toolchange to Z_Move is done fast with G0 or normally with G1
  2071. self.f_plunge = None
  2072. # Controls if the move from Z_Cutto Z_Move is done fast with G0 or G1 until zero and then G0 to Z_move
  2073. self.f_retract = None
  2074. # how much depth the probe can probe before error
  2075. self.z_pdepth = z_pdepth if z_pdepth else None
  2076. # the feedrate(speed) with which the probel travel while probing
  2077. self.feedrate_probe = feedrate_probe if feedrate_probe else None
  2078. self.spindlespeed = spindlespeed
  2079. self.spindledir = spindledir
  2080. self.dwell = dwell
  2081. self.dwelltime = dwelltime
  2082. self.segx = float(segx) if segx is not None else 0.0
  2083. self.segy = float(segy) if segy is not None else 0.0
  2084. self.input_geometry_bounds = None
  2085. self.oldx = None
  2086. self.oldy = None
  2087. self.tool = 0.0
  2088. # here store the travelled distance
  2089. self.travel_distance = 0.0
  2090. # here store the routing time
  2091. self.routing_time = 0.0
  2092. # store here the Excellon source object tools to be accessible locally
  2093. self.exc_tools = None
  2094. # search for toolchange parameters in the Toolchange Custom Code
  2095. self.re_toolchange_custom = re.compile(r'(%[a-zA-Z0-9\-_]+%)')
  2096. # search for toolchange code: M6
  2097. self.re_toolchange = re.compile(r'^\s*(M6)$')
  2098. # Attributes to be included in serialization
  2099. # Always append to it because it carries contents
  2100. # from Geometry.
  2101. self.ser_attrs += ['kind', 'z_cut', 'z_move', 'z_toolchange', 'feedrate', 'z_feedrate', 'feedrate_rapid',
  2102. 'tooldia', 'gcode', 'input_geometry_bounds', 'gcode_parsed', 'steps_per_circle',
  2103. 'z_depthpercut', 'spindlespeed', 'dwell', 'dwelltime']
  2104. @property
  2105. def postdata(self):
  2106. """
  2107. This will return all the attributes of the class in the form of a dictionary
  2108. :return: Class attributes
  2109. :rtype: dict
  2110. """
  2111. return self.__dict__
  2112. def convert_units(self, units):
  2113. """
  2114. Will convert the parameters in the class that are relevant, from metric to imperial and reverse
  2115. :param units: FlatCAM units
  2116. :type units: str
  2117. :return: conversion factor
  2118. :rtype: float
  2119. """
  2120. log.debug("camlib.CNCJob.convert_units()")
  2121. factor = Geometry.convert_units(self, units)
  2122. self.z_cut = float(self.z_cut) * factor
  2123. self.z_move *= factor
  2124. self.feedrate *= factor
  2125. self.z_feedrate *= factor
  2126. self.feedrate_rapid *= factor
  2127. self.tooldia *= factor
  2128. self.z_toolchange *= factor
  2129. self.z_end *= factor
  2130. self.z_depthpercut = float(self.z_depthpercut) * factor
  2131. return factor
  2132. def doformat(self, fun, **kwargs):
  2133. return self.doformat2(fun, **kwargs) + "\n"
  2134. def doformat2(self, fun, **kwargs):
  2135. """
  2136. This method will call one of the current preprocessor methods having as parameters all the attributes of
  2137. current class to which will add the kwargs parameters
  2138. :param fun: One of the methods inside the preprocessor classes which get loaded here in the 'p' object
  2139. :type fun: class 'function'
  2140. :param kwargs: keyword args which will update attributes of the current class
  2141. :type kwargs: dict
  2142. :return: Gcode line
  2143. :rtype: str
  2144. """
  2145. attributes = AttrDict()
  2146. attributes.update(self.postdata)
  2147. attributes.update(kwargs)
  2148. try:
  2149. returnvalue = fun(attributes)
  2150. return returnvalue
  2151. except Exception:
  2152. self.app.log.error('Exception occurred within a preprocessor: ' + traceback.format_exc())
  2153. return ''
  2154. def parse_custom_toolchange_code(self, data):
  2155. """
  2156. Will parse a text and get a toolchange sequence in text format suitable to be included in a Gcode file.
  2157. The '%' symbol is used to surround class variables name and must be removed in the returned string.
  2158. After that, the class variables (attributes) are replaced with the current values. The result is returned.
  2159. :param data: Toolchange sequence
  2160. :type data: str
  2161. :return: Processed toolchange sequence
  2162. :rtype: str
  2163. """
  2164. text = data
  2165. match_list = self.re_toolchange_custom.findall(text)
  2166. if match_list:
  2167. for match in match_list:
  2168. command = match.strip('%')
  2169. try:
  2170. value = getattr(self, command)
  2171. except AttributeError:
  2172. self.app.inform.emit('[ERROR] %s: %s' %
  2173. (_("There is no such parameter"), str(match)))
  2174. log.debug("CNCJob.parse_custom_toolchange_code() --> AttributeError ")
  2175. return 'fail'
  2176. text = text.replace(match, str(value))
  2177. return text
  2178. # Distance callback
  2179. class CreateDistanceCallback(object):
  2180. """Create callback to calculate distances between points."""
  2181. def __init__(self, locs, manager):
  2182. self.manager = manager
  2183. self.matrix = {}
  2184. if locs:
  2185. size = len(locs)
  2186. for from_node in range(size):
  2187. self.matrix[from_node] = {}
  2188. for to_node in range(size):
  2189. if from_node == to_node:
  2190. self.matrix[from_node][to_node] = 0
  2191. else:
  2192. x1 = locs[from_node][0]
  2193. y1 = locs[from_node][1]
  2194. x2 = locs[to_node][0]
  2195. y2 = locs[to_node][1]
  2196. self.matrix[from_node][to_node] = distance_euclidian(x1, y1, x2, y2)
  2197. # def Distance(self, from_node, to_node):
  2198. # return int(self.matrix[from_node][to_node])
  2199. def Distance(self, from_index, to_index):
  2200. # Convert from routing variable Index to distance matrix NodeIndex.
  2201. from_node = self.manager.IndexToNode(from_index)
  2202. to_node = self.manager.IndexToNode(to_index)
  2203. return self.matrix[from_node][to_node]
  2204. @staticmethod
  2205. def create_tool_data_array(points):
  2206. # Create the data.
  2207. loc_list = []
  2208. for pt in points:
  2209. loc_list.append((pt.coords.xy[0][0], pt.coords.xy[1][0]))
  2210. return loc_list
  2211. def optimized_ortools_meta(self, locations, start=None):
  2212. optimized_path = []
  2213. tsp_size = len(locations)
  2214. num_routes = 1 # The number of routes, which is 1 in the TSP.
  2215. # Nodes are indexed from 0 to tsp_size - 1. The depot is the starting node of the route.
  2216. depot = 0 if start is None else start
  2217. # Create routing model.
  2218. if tsp_size > 0:
  2219. manager = pywrapcp.RoutingIndexManager(tsp_size, num_routes, depot)
  2220. routing = pywrapcp.RoutingModel(manager)
  2221. search_parameters = pywrapcp.DefaultRoutingSearchParameters()
  2222. search_parameters.local_search_metaheuristic = (
  2223. routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH)
  2224. # Set search time limit in milliseconds.
  2225. if float(self.app.defaults["excellon_search_time"]) != 0:
  2226. search_parameters.time_limit.seconds = int(
  2227. float(self.app.defaults["excellon_search_time"]))
  2228. else:
  2229. search_parameters.time_limit.seconds = 3
  2230. # Callback to the distance function. The callback takes two
  2231. # arguments (the from and to node indices) and returns the distance between them.
  2232. dist_between_locations = self.CreateDistanceCallback(locs=locations, manager=manager)
  2233. # if there are no distances then go to the next tool
  2234. if not dist_between_locations:
  2235. return
  2236. dist_callback = dist_between_locations.Distance
  2237. transit_callback_index = routing.RegisterTransitCallback(dist_callback)
  2238. routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)
  2239. # Solve, returns a solution if any.
  2240. assignment = routing.SolveWithParameters(search_parameters)
  2241. if assignment:
  2242. # Solution cost.
  2243. log.info("OR-tools metaheuristics - Total distance: " + str(assignment.ObjectiveValue()))
  2244. # Inspect solution.
  2245. # Only one route here; otherwise iterate from 0 to routing.vehicles() - 1.
  2246. route_number = 0
  2247. node = routing.Start(route_number)
  2248. start_node = node
  2249. while not routing.IsEnd(node):
  2250. if self.app.abort_flag:
  2251. # graceful abort requested by the user
  2252. raise grace
  2253. optimized_path.append(node)
  2254. node = assignment.Value(routing.NextVar(node))
  2255. else:
  2256. log.warning('OR-tools metaheuristics - No solution found.')
  2257. else:
  2258. log.warning('OR-tools metaheuristics - Specify an instance greater than 0.')
  2259. return optimized_path
  2260. # ############################################# ##
  2261. def optimized_ortools_basic(self, locations, start=None):
  2262. optimized_path = []
  2263. tsp_size = len(locations)
  2264. num_routes = 1 # The number of routes, which is 1 in the TSP.
  2265. # Nodes are indexed from 0 to tsp_size - 1. The depot is the starting node of the route.
  2266. depot = 0 if start is None else start
  2267. # Create routing model.
  2268. if tsp_size > 0:
  2269. manager = pywrapcp.RoutingIndexManager(tsp_size, num_routes, depot)
  2270. routing = pywrapcp.RoutingModel(manager)
  2271. search_parameters = pywrapcp.DefaultRoutingSearchParameters()
  2272. # Callback to the distance function. The callback takes two
  2273. # arguments (the from and to node indices) and returns the distance between them.
  2274. dist_between_locations = self.CreateDistanceCallback(locs=locations, manager=manager)
  2275. # if there are no distances then go to the next tool
  2276. if not dist_between_locations:
  2277. return
  2278. dist_callback = dist_between_locations.Distance
  2279. transit_callback_index = routing.RegisterTransitCallback(dist_callback)
  2280. routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)
  2281. # Solve, returns a solution if any.
  2282. assignment = routing.SolveWithParameters(search_parameters)
  2283. if assignment:
  2284. # Solution cost.
  2285. log.info("Total distance: " + str(assignment.ObjectiveValue()))
  2286. # Inspect solution.
  2287. # Only one route here; otherwise iterate from 0 to routing.vehicles() - 1.
  2288. route_number = 0
  2289. node = routing.Start(route_number)
  2290. start_node = node
  2291. while not routing.IsEnd(node):
  2292. optimized_path.append(node)
  2293. node = assignment.Value(routing.NextVar(node))
  2294. else:
  2295. log.warning('No solution found.')
  2296. else:
  2297. log.warning('Specify an instance greater than 0.')
  2298. return optimized_path
  2299. # ############################################# ##
  2300. def optimized_travelling_salesman(self, points, start=None):
  2301. """
  2302. As solving the problem in the brute force way is too slow,
  2303. this function implements a simple heuristic: always
  2304. go to the nearest city.
  2305. Even if this algorithm is extremely simple, it works pretty well
  2306. giving a solution only about 25%% longer than the optimal one (cit. Wikipedia),
  2307. and runs very fast in O(N^2) time complexity.
  2308. >>> optimized_travelling_salesman([[i,j] for i in range(5) for j in range(5)])
  2309. [[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],
  2310. [2, 3], [2, 4], [3, 4], [3, 3], [3, 2], [3, 1], [3, 0], [4, 0], [4, 1], [4, 2], [4, 3], [4, 4]]
  2311. >>> optimized_travelling_salesman([[0,0],[10,0],[6,0]])
  2312. [[0, 0], [6, 0], [10, 0]]
  2313. :param points: List of tuples with x, y coordinates
  2314. :type points: list
  2315. :param start: a tuple with a x,y coordinates of the start point
  2316. :type start: tuple
  2317. :return: List of points ordered in a optimized way
  2318. :rtype: list
  2319. """
  2320. if start is None:
  2321. start = points[0]
  2322. must_visit = points
  2323. path = [start]
  2324. # must_visit.remove(start)
  2325. while must_visit:
  2326. nearest = min(must_visit, key=lambda x: distance(path[-1], x))
  2327. path.append(nearest)
  2328. must_visit.remove(nearest)
  2329. return path
  2330. def check_zcut(self, zcut):
  2331. if zcut > 0:
  2332. self.app.inform.emit('[WARNING] %s' %
  2333. _("The Cut Z parameter has positive value. "
  2334. "It is the depth value to drill into material.\n"
  2335. "The Cut Z parameter needs to have a negative value, assuming it is a typo "
  2336. "therefore the app will convert the value to negative. "
  2337. "Check the resulting CNC code (Gcode etc)."))
  2338. return -zcut
  2339. elif zcut == 0:
  2340. self.app.inform.emit('[WARNING] %s.' % _("The Cut Z parameter is zero. There will be no cut, aborting"))
  2341. return 'fail'
  2342. def generate_from_excellon_by_tool(self, exobj, tools="all", order='fwd', use_ui=False):
  2343. """
  2344. Creates Gcode for this object from an Excellon object
  2345. for the specified tools.
  2346. :param exobj: Excellon object to process
  2347. :type exobj: Excellon
  2348. :param tools: Comma separated tool names
  2349. :type tools: str
  2350. :param order: order of tools processing: "fwd", "rev" or "no"
  2351. :type order: str
  2352. :param use_ui: if True the method will use parameters set in UI
  2353. :type use_ui: bool
  2354. :return: None
  2355. :rtype: None
  2356. """
  2357. # #############################################################################################################
  2358. # #############################################################################################################
  2359. # create a local copy of the exobj.tools so it can be used for creating drill CCode geometry
  2360. # #############################################################################################################
  2361. # #############################################################################################################
  2362. self.exc_tools = deepcopy(exobj.tools)
  2363. # the Excellon GCode preprocessor will use this info in the start_code() method
  2364. self.use_ui = True if use_ui else False
  2365. # Z_cut parameter
  2366. if self.machinist_setting == 0:
  2367. self.z_cut = self.check_zcut(zcut=self.z_cut)
  2368. if self.z_cut == 'fail':
  2369. return 'fail'
  2370. # multidepth use this
  2371. old_zcut = deepcopy(self.z_cut)
  2372. # XY_toolchange parameter
  2373. try:
  2374. if self.xy_toolchange == '':
  2375. self.xy_toolchange = None
  2376. else:
  2377. self.xy_toolchange = re.sub('[()\[\]]', '', str(self.xy_toolchange)) if self.xy_toolchange else None
  2378. if self.xy_toolchange:
  2379. self.xy_toolchange = [float(eval(a)) for a in self.xy_toolchange.split(",")]
  2380. if self.xy_toolchange and len(self.xy_toolchange) != 2:
  2381. self.app.inform.emit('[ERROR]%s' %
  2382. _("The Toolchange X,Y field in Edit -> Preferences has to be "
  2383. "in the format (x, y) \nbut now there is only one value, not two. "))
  2384. return 'fail'
  2385. except Exception as e:
  2386. log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> %s" % str(e))
  2387. pass
  2388. # XY_end parameter
  2389. self.xy_end = re.sub('[()\[\]]', '', str(self.xy_end)) if self.xy_end else None
  2390. if self.xy_end and self.xy_end != '':
  2391. self.xy_end = [float(eval(a)) for a in self.xy_end.split(",")]
  2392. if self.xy_end and len(self.xy_end) < 2:
  2393. self.app.inform.emit('[ERROR] %s' % _("The End Move X,Y field in Edit -> Preferences has to be "
  2394. "in the format (x, y) but now there is only one value, not two."))
  2395. return 'fail'
  2396. # Prepprocessor
  2397. self.pp_excellon = self.app.preprocessors[self.pp_excellon_name]
  2398. p = self.pp_excellon
  2399. log.debug("Creating CNC Job from Excellon...")
  2400. # #############################################################################################################
  2401. # #############################################################################################################
  2402. # TOOLS
  2403. # sort the tools list by the second item in tuple (here we have a dict with diameter of the tool)
  2404. # so we actually are sorting the tools by diameter
  2405. # #############################################################################################################
  2406. # #############################################################################################################
  2407. all_tools = []
  2408. for tool_as_key, v in list(self.exc_tools.items()):
  2409. all_tools.append((int(tool_as_key), float(v['tooldia'])))
  2410. if order == 'fwd':
  2411. sorted_tools = sorted(all_tools, key=lambda t1: t1[1])
  2412. elif order == 'rev':
  2413. sorted_tools = sorted(all_tools, key=lambda t1: t1[1], reverse=True)
  2414. else:
  2415. sorted_tools = all_tools
  2416. if tools == "all":
  2417. selected_tools = [i[0] for i in all_tools] # we get a array of ordered tools
  2418. else:
  2419. selected_tools = eval(tools)
  2420. # Create a sorted list of selected tools from the sorted_tools list
  2421. tools = [i for i, j in sorted_tools for k in selected_tools if i == k]
  2422. log.debug("Tools sorted are: %s" % str(tools))
  2423. # #############################################################################################################
  2424. # #############################################################################################################
  2425. # build a self.options['Tools_in_use'] list from scratch if we don't have one like in the case of
  2426. # running this method from a Tcl Command
  2427. # #############################################################################################################
  2428. # #############################################################################################################
  2429. build_tools_in_use_list = False
  2430. if 'Tools_in_use' not in self.options:
  2431. self.options['Tools_in_use'] = []
  2432. # if the list is empty (either we just added the key or it was already there but empty) signal to build it
  2433. if not self.options['Tools_in_use']:
  2434. build_tools_in_use_list = True
  2435. # #############################################################################################################
  2436. # #############################################################################################################
  2437. # fill the data into the self.exc_cnc_tools dictionary
  2438. # #############################################################################################################
  2439. # #############################################################################################################
  2440. for it in all_tools:
  2441. for to_ol in tools:
  2442. if to_ol == it[0]:
  2443. sol_geo = []
  2444. drill_no = 0
  2445. if 'drills' in exobj.tools[to_ol]:
  2446. drill_no = len(exobj.tools[to_ol]['drills'])
  2447. for drill in exobj.tools[to_ol]['drills']:
  2448. sol_geo.append(drill.buffer((it[1] / 2.0), resolution=self.geo_steps_per_circle))
  2449. slot_no = 0
  2450. if 'slots' in exobj.tools[to_ol]:
  2451. slot_no = len(exobj.tools[to_ol]['slots'])
  2452. for slot in exobj.tools[to_ol]['slots']:
  2453. start = (slot[0].x, slot[0].y)
  2454. stop = (slot[1].x, slot[1].y)
  2455. sol_geo.append(
  2456. LineString([start, stop]).buffer((it[1] / 2.0), resolution=self.geo_steps_per_circle)
  2457. )
  2458. if self.use_ui:
  2459. try:
  2460. z_off = float(exobj.tools[it[0]]['data']['offset']) * (-1)
  2461. except KeyError:
  2462. z_off = 0
  2463. else:
  2464. z_off = 0
  2465. default_data = {}
  2466. for k, v in list(self.options.items()):
  2467. default_data[k] = deepcopy(v)
  2468. self.exc_cnc_tools[it[1]] = {}
  2469. self.exc_cnc_tools[it[1]]['tool'] = it[0]
  2470. self.exc_cnc_tools[it[1]]['nr_drills'] = drill_no
  2471. self.exc_cnc_tools[it[1]]['nr_slots'] = slot_no
  2472. self.exc_cnc_tools[it[1]]['offset_z'] = z_off
  2473. self.exc_cnc_tools[it[1]]['data'] = default_data
  2474. self.exc_cnc_tools[it[1]]['solid_geometry'] = deepcopy(sol_geo)
  2475. # build a self.options['Tools_in_use'] list from scratch if we don't have one like in the case of
  2476. # running this method from a Tcl Command
  2477. if build_tools_in_use_list is True:
  2478. self.options['Tools_in_use'].append(
  2479. [it[0], it[1], drill_no, slot_no]
  2480. )
  2481. self.app.inform.emit(_("Creating a list of points to drill..."))
  2482. # #############################################################################################################
  2483. # #############################################################################################################
  2484. # Points (Group by tool): a dictionary of shapely Point geo elements grouped by tool number
  2485. # #############################################################################################################
  2486. # #############################################################################################################
  2487. points = {}
  2488. for tool, tool_dict in self.exc_tools.items():
  2489. if tool in tools:
  2490. if self.app.abort_flag:
  2491. # graceful abort requested by the user
  2492. raise grace
  2493. if 'drills' in tool_dict and tool_dict['drills']:
  2494. for drill_pt in tool_dict['drills']:
  2495. try:
  2496. points[tool].append(drill_pt)
  2497. except KeyError:
  2498. points[tool] = [drill_pt]
  2499. log.debug("Found %d TOOLS with drills." % len(points))
  2500. # check if there are drill points in the exclusion areas.
  2501. # If we find any within the exclusion areas return 'fail'
  2502. for tool in points:
  2503. for pt in points[tool]:
  2504. for area in self.app.exc_areas.exclusion_areas_storage:
  2505. pt_buf = pt.buffer(self.exc_tools[tool]['tooldia'] / 2.0)
  2506. if pt_buf.within(area['shape']) or pt_buf.intersects(area['shape']):
  2507. self.app.inform.emit("[ERROR_NOTCL] %s" % _("Failed. Drill points inside the exclusion zones."))
  2508. return 'fail'
  2509. # this holds the resulting GCode
  2510. self.gcode = []
  2511. self.f_plunge = self.app.defaults["excellon_f_plunge"]
  2512. self.f_retract = self.app.defaults["excellon_f_retract"]
  2513. # #############################################################################################################
  2514. # #############################################################################################################
  2515. # Initialization
  2516. # #############################################################################################################
  2517. # #############################################################################################################
  2518. gcode = self.doformat(p.start_code)
  2519. if use_ui is False:
  2520. gcode += self.doformat(p.z_feedrate_code)
  2521. if self.toolchange is False:
  2522. if self.xy_toolchange is not None:
  2523. gcode += self.doformat(p.lift_code, x=self.xy_toolchange[0], y=self.xy_toolchange[1])
  2524. gcode += self.doformat(p.startz_code, x=self.xy_toolchange[0], y=self.xy_toolchange[1])
  2525. else:
  2526. gcode += self.doformat(p.lift_code, x=0.0, y=0.0)
  2527. gcode += self.doformat(p.startz_code, x=0.0, y=0.0)
  2528. if self.xy_toolchange is not None:
  2529. self.oldx = self.xy_toolchange[0]
  2530. self.oldy = self.xy_toolchange[1]
  2531. else:
  2532. self.oldx = 0.0
  2533. self.oldy = 0.0
  2534. measured_distance = 0.0
  2535. measured_down_distance = 0.0
  2536. measured_up_to_zero_distance = 0.0
  2537. measured_lift_distance = 0.0
  2538. # #############################################################################################################
  2539. # #############################################################################################################
  2540. # GCODE creation
  2541. # #############################################################################################################
  2542. # #############################################################################################################
  2543. self.app.inform.emit('%s...' % _("Starting G-Code"))
  2544. has_drills = None
  2545. for tool, tool_dict in self.exc_tools.items():
  2546. if 'drills' in tool_dict and tool_dict['drills']:
  2547. has_drills = True
  2548. break
  2549. if not has_drills:
  2550. log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> "
  2551. "The loaded Excellon file has no drills ...")
  2552. self.app.inform.emit('[ERROR_NOTCL] %s...' % _('The loaded Excellon file has no drills'))
  2553. return 'fail'
  2554. current_platform = platform.architecture()[0]
  2555. if current_platform == '64bit':
  2556. used_excellon_optimization_type = self.excellon_optimization_type
  2557. else:
  2558. used_excellon_optimization_type = 'T'
  2559. # #############################################################################################################
  2560. # #############################################################################################################
  2561. # ################################## DRILLING !!! #########################################################
  2562. # #############################################################################################################
  2563. # #############################################################################################################
  2564. if used_excellon_optimization_type == 'M':
  2565. log.debug("Using OR-Tools Metaheuristic Guided Local Search drill path optimization.")
  2566. elif used_excellon_optimization_type == 'B':
  2567. log.debug("Using OR-Tools Basic drill path optimization.")
  2568. elif used_excellon_optimization_type == 'T':
  2569. log.debug("Using Travelling Salesman drill path optimization.")
  2570. else:
  2571. log.debug("Using no path optimization.")
  2572. if self.toolchange is True:
  2573. for tool in tools:
  2574. # check if it has drills
  2575. if not self.exc_tools[tool]['drills']:
  2576. continue
  2577. if self.app.abort_flag:
  2578. # graceful abort requested by the user
  2579. raise grace
  2580. self.tool = tool
  2581. self.tooldia = self.exc_tools[tool]["tooldia"]
  2582. self.postdata['toolC'] = self.tooldia
  2583. if self.use_ui:
  2584. self.z_feedrate = self.exc_tools[tool]['data']['feedrate_z']
  2585. self.feedrate = self.exc_tools[tool]['data']['feedrate']
  2586. self.z_cut = self.exc_tools[tool]['data']['cutz']
  2587. gcode += self.doformat(p.z_feedrate_code)
  2588. if self.machinist_setting == 0:
  2589. if self.z_cut > 0:
  2590. self.app.inform.emit('[WARNING] %s' %
  2591. _("The Cut Z parameter has positive value. "
  2592. "It is the depth value to drill into material.\n"
  2593. "The Cut Z parameter needs to have a negative value, "
  2594. "assuming it is a typo "
  2595. "therefore the app will convert the value to negative. "
  2596. "Check the resulting CNC code (Gcode etc)."))
  2597. self.z_cut = -self.z_cut
  2598. elif self.z_cut == 0:
  2599. self.app.inform.emit('[WARNING] %s: %s' %
  2600. (_(
  2601. "The Cut Z parameter is zero. There will be no cut, "
  2602. "skipping file"),
  2603. exobj.options['name']))
  2604. return 'fail'
  2605. old_zcut = deepcopy(self.z_cut)
  2606. self.z_move = self.exc_tools[tool]['data']['travelz']
  2607. self.spindlespeed = self.exc_tools[tool]['data']['spindlespeed']
  2608. self.dwell = self.exc_tools[tool]['data']['dwell']
  2609. self.dwelltime = self.exc_tools[tool]['data']['dwelltime']
  2610. self.multidepth = self.exc_tools[tool]['data']['multidepth']
  2611. self.z_depthpercut = self.exc_tools[tool]['data']['depthperpass']
  2612. else:
  2613. old_zcut = deepcopy(self.z_cut)
  2614. # #########################################################################################################
  2615. # ############ Create the data. #################
  2616. # #########################################################################################################
  2617. locations = []
  2618. altPoints = []
  2619. optimized_path = []
  2620. if used_excellon_optimization_type == 'M':
  2621. if tool in points:
  2622. locations = self.create_tool_data_array(points=points[tool])
  2623. # if there are no locations then go to the next tool
  2624. if not locations:
  2625. continue
  2626. optimized_path = self.optimized_ortools_meta(locations=locations)
  2627. elif used_excellon_optimization_type == 'B':
  2628. if tool in points:
  2629. locations = self.create_tool_data_array(points=points[tool])
  2630. # if there are no locations then go to the next tool
  2631. if not locations:
  2632. continue
  2633. optimized_path = self.optimized_ortools_basic(locations=locations)
  2634. elif used_excellon_optimization_type == 'T':
  2635. for point in points[tool]:
  2636. altPoints.append((point.coords.xy[0][0], point.coords.xy[1][0]))
  2637. optimized_path = self.optimized_travelling_salesman(altPoints)
  2638. else:
  2639. # it's actually not optimized path but here we build a list of (x,y) coordinates
  2640. # out of the tool's drills
  2641. for drill in self.exc_tools[tool]['drills']:
  2642. unoptimized_coords = (
  2643. drill.x,
  2644. drill.y
  2645. )
  2646. optimized_path.append(unoptimized_coords)
  2647. # #########################################################################################################
  2648. # #########################################################################################################
  2649. # Only if there are locations to drill
  2650. if not optimized_path:
  2651. continue
  2652. if self.app.abort_flag:
  2653. # graceful abort requested by the user
  2654. raise grace
  2655. # Tool change sequence (optional)
  2656. if self.toolchange:
  2657. gcode += self.doformat(p.toolchange_code, toolchangexy=(self.oldx, self.oldy))
  2658. # Spindle start
  2659. gcode += self.doformat(p.spindle_code)
  2660. # Dwell time
  2661. if self.dwell is True:
  2662. gcode += self.doformat(p.dwell_code)
  2663. current_tooldia = float('%.*f' % (self.decimals, float(self.exc_tools[tool]["tooldia"])))
  2664. self.app.inform.emit(
  2665. '%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  2666. str(current_tooldia),
  2667. str(self.units))
  2668. )
  2669. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  2670. # APPLY Offset only when using the appGUI, for TclCommand this will create an error
  2671. # because the values for Z offset are created in build_ui()
  2672. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  2673. try:
  2674. z_offset = float(self.exc_tools[tool]['data']['offset']) * (-1)
  2675. except KeyError:
  2676. z_offset = 0
  2677. self.z_cut = z_offset + old_zcut
  2678. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  2679. if self.coordinates_type == "G90":
  2680. # Drillling! for Absolute coordinates type G90
  2681. # variables to display the percentage of work done
  2682. geo_len = len(optimized_path)
  2683. old_disp_number = 0
  2684. log.warning("Number of drills for which to generate GCode: %s" % str(geo_len))
  2685. loc_nr = 0
  2686. for point in optimized_path:
  2687. if self.app.abort_flag:
  2688. # graceful abort requested by the user
  2689. raise grace
  2690. if used_excellon_optimization_type == 'T':
  2691. locx = point[0]
  2692. locy = point[1]
  2693. else:
  2694. locx = locations[point][0]
  2695. locy = locations[point][1]
  2696. travels = self.app.exc_areas.travel_coordinates(start_point=(self.oldx, self.oldy),
  2697. end_point=(locx, locy),
  2698. tooldia=current_tooldia)
  2699. prev_z = None
  2700. for travel in travels:
  2701. locx = travel[1][0]
  2702. locy = travel[1][1]
  2703. if travel[0] is not None:
  2704. # move to next point
  2705. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  2706. # raise to safe Z (travel[0]) each time because safe Z may be different
  2707. self.z_move = travel[0]
  2708. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  2709. # restore z_move
  2710. self.z_move = self.exc_tools[tool]['data']['travelz']
  2711. else:
  2712. if prev_z is not None:
  2713. # move to next point
  2714. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  2715. # we assume that previously the z_move was altered therefore raise to
  2716. # the travel_z (z_move)
  2717. self.z_move = self.exc_tools[tool]['data']['travelz']
  2718. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  2719. else:
  2720. # move to next point
  2721. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  2722. # store prev_z
  2723. prev_z = travel[0]
  2724. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  2725. if self.multidepth and abs(self.z_cut) > abs(self.z_depthpercut):
  2726. doc = deepcopy(self.z_cut)
  2727. self.z_cut = 0.0
  2728. while abs(self.z_cut) < abs(doc):
  2729. self.z_cut -= self.z_depthpercut
  2730. if abs(doc) < abs(self.z_cut) < (abs(doc) + self.z_depthpercut):
  2731. self.z_cut = doc
  2732. gcode += self.doformat(p.down_code, x=locx, y=locy)
  2733. measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  2734. if self.f_retract is False:
  2735. gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  2736. measured_up_to_zero_distance += abs(self.z_cut)
  2737. measured_lift_distance += abs(self.z_move)
  2738. else:
  2739. measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  2740. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  2741. else:
  2742. gcode += self.doformat(p.down_code, x=locx, y=locy)
  2743. measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  2744. if self.f_retract is False:
  2745. gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  2746. measured_up_to_zero_distance += abs(self.z_cut)
  2747. measured_lift_distance += abs(self.z_move)
  2748. else:
  2749. measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  2750. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  2751. measured_distance += abs(distance_euclidian(locx, locy, self.oldx, self.oldy))
  2752. self.oldx = locx
  2753. self.oldy = locy
  2754. loc_nr += 1
  2755. disp_number = int(np.interp(loc_nr, [0, geo_len], [0, 100]))
  2756. if old_disp_number < disp_number <= 100:
  2757. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  2758. old_disp_number = disp_number
  2759. else:
  2760. self.app.inform.emit('[ERROR_NOTCL] %s...' % _('G91 coordinates not implemented'))
  2761. return 'fail'
  2762. self.z_cut = deepcopy(old_zcut)
  2763. else:
  2764. # We are not using Toolchange therefore we need to decide which tool properties to use
  2765. one_tool = 1
  2766. all_points = []
  2767. for tool in points:
  2768. # check if it has drills
  2769. if not points[tool]:
  2770. continue
  2771. all_points += points[tool]
  2772. if self.app.abort_flag:
  2773. # graceful abort requested by the user
  2774. raise grace
  2775. self.tool = one_tool
  2776. self.tooldia = self.exc_tools[one_tool]["tooldia"]
  2777. self.postdata['toolC'] = self.tooldia
  2778. if self.use_ui:
  2779. self.z_feedrate = self.exc_tools[one_tool]['data']['feedrate_z']
  2780. self.feedrate = self.exc_tools[one_tool]['data']['feedrate']
  2781. self.z_cut = self.exc_tools[one_tool]['data']['cutz']
  2782. gcode += self.doformat(p.z_feedrate_code)
  2783. if self.machinist_setting == 0:
  2784. if self.z_cut > 0:
  2785. self.app.inform.emit('[WARNING] %s' %
  2786. _("The Cut Z parameter has positive value. "
  2787. "It is the depth value to drill into material.\n"
  2788. "The Cut Z parameter needs to have a negative value, "
  2789. "assuming it is a typo "
  2790. "therefore the app will convert the value to negative. "
  2791. "Check the resulting CNC code (Gcode etc)."))
  2792. self.z_cut = -self.z_cut
  2793. elif self.z_cut == 0:
  2794. self.app.inform.emit('[WARNING] %s: %s' %
  2795. (_(
  2796. "The Cut Z parameter is zero. There will be no cut, "
  2797. "skipping file"),
  2798. exobj.options['name']))
  2799. return 'fail'
  2800. old_zcut = deepcopy(self.z_cut)
  2801. self.z_move = self.exc_tools[one_tool]['data']['travelz']
  2802. self.spindlespeed = self.exc_tools[one_tool]['data']['spindlespeed']
  2803. self.dwell = self.exc_tools[one_tool]['data']['dwell']
  2804. self.dwelltime = self.exc_tools[one_tool]['data']['dwelltime']
  2805. self.multidepth = self.exc_tools[one_tool]['data']['multidepth']
  2806. self.z_depthpercut = self.exc_tools[one_tool]['data']['depthperpass']
  2807. else:
  2808. old_zcut = deepcopy(self.z_cut)
  2809. # #########################################################################################################
  2810. # ############ Create the data. #################
  2811. # #########################################################################################################
  2812. locations = []
  2813. altPoints = []
  2814. optimized_path = []
  2815. if used_excellon_optimization_type == 'M':
  2816. if all_points:
  2817. locations = self.create_tool_data_array(points=all_points)
  2818. # if there are no locations then go to the next tool
  2819. if not locations:
  2820. return 'fail'
  2821. optimized_path = self.optimized_ortools_meta(locations=locations)
  2822. elif used_excellon_optimization_type == 'B':
  2823. if all_points:
  2824. locations = self.create_tool_data_array(points=all_points)
  2825. # if there are no locations then go to the next tool
  2826. if not locations:
  2827. return 'fail'
  2828. optimized_path = self.optimized_ortools_basic(locations=locations)
  2829. elif used_excellon_optimization_type == 'T':
  2830. for point in all_points:
  2831. altPoints.append((point.coords.xy[0][0], point.coords.xy[1][0]))
  2832. optimized_path = self.optimized_travelling_salesman(altPoints)
  2833. else:
  2834. # it's actually not optimized path but here we build a list of (x,y) coordinates
  2835. # out of the tool's drills
  2836. for pt in all_points:
  2837. unoptimized_coords = (
  2838. pt.x,
  2839. pt.y
  2840. )
  2841. optimized_path.append(unoptimized_coords)
  2842. # #########################################################################################################
  2843. # #########################################################################################################
  2844. # Only if there are locations to drill
  2845. if not optimized_path:
  2846. return 'fail'
  2847. if self.app.abort_flag:
  2848. # graceful abort requested by the user
  2849. raise grace
  2850. # Spindle start
  2851. gcode += self.doformat(p.spindle_code)
  2852. # Dwell time
  2853. if self.dwell is True:
  2854. gcode += self.doformat(p.dwell_code)
  2855. current_tooldia = float('%.*f' % (self.decimals, float(self.exc_tools[one_tool]["tooldia"])))
  2856. self.app.inform.emit(
  2857. '%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  2858. str(current_tooldia),
  2859. str(self.units))
  2860. )
  2861. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  2862. # APPLY Offset only when using the appGUI, for TclCommand this will create an error
  2863. # because the values for Z offset are created in build_ui()
  2864. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  2865. try:
  2866. z_offset = float(self.exc_tools[one_tool]['data']['offset']) * (-1)
  2867. except KeyError:
  2868. z_offset = 0
  2869. self.z_cut = z_offset + old_zcut
  2870. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  2871. if self.coordinates_type == "G90":
  2872. # Drillling! for Absolute coordinates type G90
  2873. # variables to display the percentage of work done
  2874. geo_len = len(optimized_path)
  2875. old_disp_number = 0
  2876. log.warning("Number of drills for which to generate GCode: %s" % str(geo_len))
  2877. loc_nr = 0
  2878. for point in optimized_path:
  2879. if self.app.abort_flag:
  2880. # graceful abort requested by the user
  2881. raise grace
  2882. if used_excellon_optimization_type == 'T':
  2883. locx = point[0]
  2884. locy = point[1]
  2885. else:
  2886. locx = locations[point][0]
  2887. locy = locations[point][1]
  2888. travels = self.app.exc_areas.travel_coordinates(start_point=(self.oldx, self.oldy),
  2889. end_point=(locx, locy),
  2890. tooldia=current_tooldia)
  2891. prev_z = None
  2892. for travel in travels:
  2893. locx = travel[1][0]
  2894. locy = travel[1][1]
  2895. if travel[0] is not None:
  2896. # move to next point
  2897. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  2898. # raise to safe Z (travel[0]) each time because safe Z may be different
  2899. self.z_move = travel[0]
  2900. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  2901. # restore z_move
  2902. self.z_move = self.exc_tools[one_tool]['data']['travelz']
  2903. else:
  2904. if prev_z is not None:
  2905. # move to next point
  2906. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  2907. # we assume that previously the z_move was altered therefore raise to
  2908. # the travel_z (z_move)
  2909. self.z_move = self.exc_tools[one_tool]['data']['travelz']
  2910. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  2911. else:
  2912. # move to next point
  2913. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  2914. # store prev_z
  2915. prev_z = travel[0]
  2916. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  2917. if self.multidepth and abs(self.z_cut) > abs(self.z_depthpercut):
  2918. doc = deepcopy(self.z_cut)
  2919. self.z_cut = 0.0
  2920. while abs(self.z_cut) < abs(doc):
  2921. self.z_cut -= self.z_depthpercut
  2922. if abs(doc) < abs(self.z_cut) < (abs(doc) + self.z_depthpercut):
  2923. self.z_cut = doc
  2924. gcode += self.doformat(p.down_code, x=locx, y=locy)
  2925. measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  2926. if self.f_retract is False:
  2927. gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  2928. measured_up_to_zero_distance += abs(self.z_cut)
  2929. measured_lift_distance += abs(self.z_move)
  2930. else:
  2931. measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  2932. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  2933. else:
  2934. gcode += self.doformat(p.down_code, x=locx, y=locy)
  2935. measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  2936. if self.f_retract is False:
  2937. gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  2938. measured_up_to_zero_distance += abs(self.z_cut)
  2939. measured_lift_distance += abs(self.z_move)
  2940. else:
  2941. measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  2942. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  2943. measured_distance += abs(distance_euclidian(locx, locy, self.oldx, self.oldy))
  2944. self.oldx = locx
  2945. self.oldy = locy
  2946. loc_nr += 1
  2947. disp_number = int(np.interp(loc_nr, [0, geo_len], [0, 100]))
  2948. if old_disp_number < disp_number <= 100:
  2949. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  2950. old_disp_number = disp_number
  2951. else:
  2952. self.app.inform.emit('[ERROR_NOTCL] %s...' % _('G91 coordinates not implemented'))
  2953. return 'fail'
  2954. self.z_cut = deepcopy(old_zcut)
  2955. if used_excellon_optimization_type == 'M':
  2956. log.debug("The total travel distance with OR-TOOLS Metaheuristics is: %s" % str(measured_distance))
  2957. elif used_excellon_optimization_type == 'B':
  2958. log.debug("The total travel distance with OR-TOOLS Basic Algorithm is: %s" % str(measured_distance))
  2959. elif used_excellon_optimization_type == 'T':
  2960. log.debug("The total travel distance with Travelling Salesman Algorithm is: %s" % str(measured_distance))
  2961. else:
  2962. log.debug("The total travel distance with with no optimization is: %s" % str(measured_distance))
  2963. # if used_excellon_optimization_type == 'M':
  2964. # log.debug("Using OR-Tools Metaheuristic Guided Local Search drill path optimization.")
  2965. #
  2966. # if has_drills:
  2967. # for tool in tools:
  2968. # if self.app.abort_flag:
  2969. # # graceful abort requested by the user
  2970. # raise grace
  2971. #
  2972. # self.tool = tool
  2973. # self.tooldia = self.exc_tools[tool]["tooldia"]
  2974. # self.postdata['toolC'] = self.tooldia
  2975. #
  2976. # if self.use_ui:
  2977. # self.z_feedrate = self.exc_tools[tool]['data']['feedrate_z']
  2978. # self.feedrate = self.exc_tools[tool]['data']['feedrate']
  2979. # gcode += self.doformat(p.z_feedrate_code)
  2980. # self.z_cut = self.exc_tools[tool]['data']['cutz']
  2981. #
  2982. # if self.machinist_setting == 0:
  2983. # if self.z_cut > 0:
  2984. # self.app.inform.emit('[WARNING] %s' %
  2985. # _("The Cut Z parameter has positive value. "
  2986. # "It is the depth value to drill into material.\n"
  2987. # "The Cut Z parameter needs to have a negative value, "
  2988. # "assuming it is a typo "
  2989. # "therefore the app will convert the value to negative. "
  2990. # "Check the resulting CNC code (Gcode etc)."))
  2991. # self.z_cut = -self.z_cut
  2992. # elif self.z_cut == 0:
  2993. # self.app.inform.emit('[WARNING] %s: %s' %
  2994. # (_(
  2995. # "The Cut Z parameter is zero. There will be no cut, "
  2996. # "skipping file"),
  2997. # exobj.options['name']))
  2998. # return 'fail'
  2999. #
  3000. # old_zcut = deepcopy(self.z_cut)
  3001. #
  3002. # self.z_move = self.exc_tools[tool]['data']['travelz']
  3003. # self.spindlespeed = self.exc_tools[tool]['data']['spindlespeed']
  3004. # self.dwell = self.exc_tools[tool]['data']['dwell']
  3005. # self.dwelltime = self.exc_tools[tool]['data']['dwelltime']
  3006. # self.multidepth = self.exc_tools[tool]['data']['multidepth']
  3007. # self.z_depthpercut = self.exc_tools[tool]['data']['depthperpass']
  3008. # else:
  3009. # old_zcut = deepcopy(self.z_cut)
  3010. #
  3011. # # ###############################################
  3012. # # ############ Create the data. #################
  3013. # # ###############################################
  3014. # locations = self.create_tool_data_array(tool=tool, points=points)
  3015. # # if there are no locations then go to the next tool
  3016. # if not locations:
  3017. # continue
  3018. # optimized_path = self.optimized_ortools_meta(locations=locations)
  3019. #
  3020. # # Only if tool has points.
  3021. # if tool in points:
  3022. # if self.app.abort_flag:
  3023. # # graceful abort requested by the user
  3024. # raise grace
  3025. #
  3026. # # Tool change sequence (optional)
  3027. # if self.toolchange:
  3028. # gcode += self.doformat(p.toolchange_code, toolchangexy=(self.oldx, self.oldy))
  3029. # # Spindle start
  3030. # gcode += self.doformat(p.spindle_code)
  3031. # # Dwell time
  3032. # if self.dwell is True:
  3033. # gcode += self.doformat(p.dwell_code)
  3034. #
  3035. # current_tooldia = float('%.*f' % (self.decimals, float(self.exc_tools[tool]["tooldia"])))
  3036. #
  3037. # self.app.inform.emit(
  3038. # '%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  3039. # str(current_tooldia),
  3040. # str(self.units))
  3041. # )
  3042. #
  3043. # # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  3044. # # APPLY Offset only when using the appGUI, for TclCommand this will create an error
  3045. # # because the values for Z offset are created in build_ui()
  3046. # # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  3047. # try:
  3048. # z_offset = float(self.exc_tools[tool]['data']['offset']) * (-1)
  3049. # except KeyError:
  3050. # z_offset = 0
  3051. # self.z_cut = z_offset + old_zcut
  3052. #
  3053. # self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  3054. # if self.coordinates_type == "G90":
  3055. # # Drillling! for Absolute coordinates type G90
  3056. # # variables to display the percentage of work done
  3057. # geo_len = len(optimized_path)
  3058. #
  3059. # old_disp_number = 0
  3060. # log.warning("Number of drills for which to generate GCode: %s" % str(geo_len))
  3061. #
  3062. # loc_nr = 0
  3063. # for k in optimized_path:
  3064. # if self.app.abort_flag:
  3065. # # graceful abort requested by the user
  3066. # raise grace
  3067. #
  3068. # locx = locations[k][0]
  3069. # locy = locations[k][1]
  3070. #
  3071. # travels = self.app.exc_areas.travel_coordinates(start_point=(self.oldx, self.oldy),
  3072. # end_point=(locx, locy),
  3073. # tooldia=current_tooldia)
  3074. # prev_z = None
  3075. # for travel in travels:
  3076. # locx = travel[1][0]
  3077. # locy = travel[1][1]
  3078. #
  3079. # if travel[0] is not None:
  3080. # # move to next point
  3081. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3082. #
  3083. # # raise to safe Z (travel[0]) each time because safe Z may be different
  3084. # self.z_move = travel[0]
  3085. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3086. #
  3087. # # restore z_move
  3088. # self.z_move = self.exc_tools[tool]['data']['travelz']
  3089. # else:
  3090. # if prev_z is not None:
  3091. # # move to next point
  3092. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3093. #
  3094. # # we assume that previously the z_move was altered therefore raise to
  3095. # # the travel_z (z_move)
  3096. # self.z_move = self.exc_tools[tool]['data']['travelz']
  3097. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3098. # else:
  3099. # # move to next point
  3100. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3101. #
  3102. # # store prev_z
  3103. # prev_z = travel[0]
  3104. #
  3105. # # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3106. #
  3107. # if self.multidepth and abs(self.z_cut) > abs(self.z_depthpercut):
  3108. # doc = deepcopy(self.z_cut)
  3109. # self.z_cut = 0.0
  3110. #
  3111. # while abs(self.z_cut) < abs(doc):
  3112. #
  3113. # self.z_cut -= self.z_depthpercut
  3114. # if abs(doc) < abs(self.z_cut) < (abs(doc) + self.z_depthpercut):
  3115. # self.z_cut = doc
  3116. # gcode += self.doformat(p.down_code, x=locx, y=locy)
  3117. #
  3118. # measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  3119. #
  3120. # if self.f_retract is False:
  3121. # gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  3122. # measured_up_to_zero_distance += abs(self.z_cut)
  3123. # measured_lift_distance += abs(self.z_move)
  3124. # else:
  3125. # measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  3126. #
  3127. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3128. #
  3129. # else:
  3130. # gcode += self.doformat(p.down_code, x=locx, y=locy)
  3131. #
  3132. # measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  3133. #
  3134. # if self.f_retract is False:
  3135. # gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  3136. # measured_up_to_zero_distance += abs(self.z_cut)
  3137. # measured_lift_distance += abs(self.z_move)
  3138. # else:
  3139. # measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  3140. #
  3141. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3142. #
  3143. # measured_distance += abs(distance_euclidian(locx, locy, self.oldx, self.oldy))
  3144. # self.oldx = locx
  3145. # self.oldy = locy
  3146. #
  3147. # loc_nr += 1
  3148. # disp_number = int(np.interp(loc_nr, [0, geo_len], [0, 100]))
  3149. #
  3150. # if old_disp_number < disp_number <= 100:
  3151. # self.app.proc_container.update_view_text(' %d%%' % disp_number)
  3152. # old_disp_number = disp_number
  3153. #
  3154. # else:
  3155. # self.app.inform.emit('[ERROR_NOTCL] %s...' % _('G91 coordinates not implemented'))
  3156. # return 'fail'
  3157. # self.z_cut = deepcopy(old_zcut)
  3158. # else:
  3159. # log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> "
  3160. # "The loaded Excellon file has no drills ...")
  3161. # self.app.inform.emit('[ERROR_NOTCL] %s...' % _('The loaded Excellon file has no drills'))
  3162. # return 'fail'
  3163. #
  3164. # log.debug("The total travel distance with OR-TOOLS Metaheuristics is: %s" % str(measured_distance))
  3165. #
  3166. # elif used_excellon_optimization_type == 'B':
  3167. # log.debug("Using OR-Tools Basic drill path optimization.")
  3168. #
  3169. # if has_drills:
  3170. # for tool in tools:
  3171. # if self.app.abort_flag:
  3172. # # graceful abort requested by the user
  3173. # raise grace
  3174. #
  3175. # self.tool = tool
  3176. # self.tooldia = self.exc_tools[tool]["tooldia"]
  3177. # self.postdata['toolC'] = self.tooldia
  3178. #
  3179. # if self.use_ui:
  3180. # self.z_feedrate = self.exc_tools[tool]['data']['feedrate_z']
  3181. # self.feedrate = self.exc_tools[tool]['data']['feedrate']
  3182. # gcode += self.doformat(p.z_feedrate_code)
  3183. # self.z_cut = self.exc_tools[tool]['data']['cutz']
  3184. #
  3185. # if self.machinist_setting == 0:
  3186. # if self.z_cut > 0:
  3187. # self.app.inform.emit('[WARNING] %s' %
  3188. # _("The Cut Z parameter has positive value. "
  3189. # "It is the depth value to drill into material.\n"
  3190. # "The Cut Z parameter needs to have a negative value, "
  3191. # "assuming it is a typo "
  3192. # "therefore the app will convert the value to negative. "
  3193. # "Check the resulting CNC code (Gcode etc)."))
  3194. # self.z_cut = -self.z_cut
  3195. # elif self.z_cut == 0:
  3196. # self.app.inform.emit('[WARNING] %s: %s' %
  3197. # (_(
  3198. # "The Cut Z parameter is zero. There will be no cut, "
  3199. # "skipping file"),
  3200. # exobj.options['name']))
  3201. # return 'fail'
  3202. #
  3203. # old_zcut = deepcopy(self.z_cut)
  3204. #
  3205. # self.z_move = self.exc_tools[tool]['data']['travelz']
  3206. #
  3207. # self.spindlespeed = self.exc_tools[tool]['data']['spindlespeed']
  3208. # self.dwell = self.exc_tools[tool]['data']['dwell']
  3209. # self.dwelltime = self.exc_tools[tool]['data']['dwelltime']
  3210. # self.multidepth = self.exc_tools[tool]['data']['multidepth']
  3211. # self.z_depthpercut = self.exc_tools[tool]['data']['depthperpass']
  3212. # else:
  3213. # old_zcut = deepcopy(self.z_cut)
  3214. #
  3215. # # ###############################################
  3216. # # ############ Create the data. #################
  3217. # # ###############################################
  3218. # locations = self.create_tool_data_array(tool=tool, points=points)
  3219. # # if there are no locations then go to the next tool
  3220. # if not locations:
  3221. # continue
  3222. # optimized_path = self.optimized_ortools_basic(locations=locations)
  3223. #
  3224. # # Only if tool has points.
  3225. # if tool in points:
  3226. # if self.app.abort_flag:
  3227. # # graceful abort requested by the user
  3228. # raise grace
  3229. #
  3230. # # Tool change sequence (optional)
  3231. # if self.toolchange:
  3232. # gcode += self.doformat(p.toolchange_code, toolchangexy=(self.oldx, self.oldy))
  3233. # gcode += self.doformat(p.spindle_code) # Spindle start)
  3234. # if self.dwell is True:
  3235. # gcode += self.doformat(p.dwell_code) # Dwell time
  3236. # else:
  3237. # gcode += self.doformat(p.spindle_code)
  3238. # if self.dwell is True:
  3239. # gcode += self.doformat(p.dwell_code) # Dwell time
  3240. #
  3241. # current_tooldia = float('%.*f' % (self.decimals, float(self.exc_tools[tool]["tooldia"])))
  3242. #
  3243. # self.app.inform.emit(
  3244. # '%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  3245. # str(current_tooldia),
  3246. # str(self.units))
  3247. # )
  3248. #
  3249. # # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  3250. # # APPLY Offset only when using the appGUI, for TclCommand this will create an error
  3251. # # because the values for Z offset are created in build_ui()
  3252. # # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  3253. # try:
  3254. # z_offset = float(self.exc_tools[tool]['data']['offset']) * (-1)
  3255. # except KeyError:
  3256. # z_offset = 0
  3257. # self.z_cut = z_offset + old_zcut
  3258. #
  3259. # self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  3260. # if self.coordinates_type == "G90":
  3261. # # Drillling! for Absolute coordinates type G90
  3262. # # variables to display the percentage of work done
  3263. # geo_len = len(optimized_path)
  3264. # old_disp_number = 0
  3265. # log.warning("Number of drills for which to generate GCode: %s" % str(geo_len))
  3266. #
  3267. # loc_nr = 0
  3268. # for k in optimized_path:
  3269. # if self.app.abort_flag:
  3270. # # graceful abort requested by the user
  3271. # raise grace
  3272. #
  3273. # locx = locations[k][0]
  3274. # locy = locations[k][1]
  3275. #
  3276. # travels = self.app.exc_areas.travel_coordinates(start_point=(self.oldx, self.oldy),
  3277. # end_point=(locx, locy),
  3278. # tooldia=current_tooldia)
  3279. # prev_z = None
  3280. # for travel in travels:
  3281. # locx = travel[1][0]
  3282. # locy = travel[1][1]
  3283. #
  3284. # if travel[0] is not None:
  3285. # # move to next point
  3286. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3287. #
  3288. # # raise to safe Z (travel[0]) each time because safe Z may be different
  3289. # self.z_move = travel[0]
  3290. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3291. #
  3292. # # restore z_move
  3293. # self.z_move = self.exc_tools[tool]['data']['travelz']
  3294. # else:
  3295. # if prev_z is not None:
  3296. # # move to next point
  3297. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3298. #
  3299. # # we assume that previously the z_move was altered therefore raise to
  3300. # # the travel_z (z_move)
  3301. # self.z_move = self.exc_tools[tool]['data']['travelz']
  3302. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3303. # else:
  3304. # # move to next point
  3305. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3306. #
  3307. # # store prev_z
  3308. # prev_z = travel[0]
  3309. #
  3310. # # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3311. #
  3312. # if self.multidepth and abs(self.z_cut) > abs(self.z_depthpercut):
  3313. # doc = deepcopy(self.z_cut)
  3314. # self.z_cut = 0.0
  3315. #
  3316. # while abs(self.z_cut) < abs(doc):
  3317. #
  3318. # self.z_cut -= self.z_depthpercut
  3319. # if abs(doc) < abs(self.z_cut) < (abs(doc) + self.z_depthpercut):
  3320. # self.z_cut = doc
  3321. # gcode += self.doformat(p.down_code, x=locx, y=locy)
  3322. #
  3323. # measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  3324. #
  3325. # if self.f_retract is False:
  3326. # gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  3327. # measured_up_to_zero_distance += abs(self.z_cut)
  3328. # measured_lift_distance += abs(self.z_move)
  3329. # else:
  3330. # measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  3331. #
  3332. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3333. #
  3334. # else:
  3335. # gcode += self.doformat(p.down_code, x=locx, y=locy)
  3336. #
  3337. # measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  3338. #
  3339. # if self.f_retract is False:
  3340. # gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  3341. # measured_up_to_zero_distance += abs(self.z_cut)
  3342. # measured_lift_distance += abs(self.z_move)
  3343. # else:
  3344. # measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  3345. #
  3346. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3347. #
  3348. # measured_distance += abs(distance_euclidian(locx, locy, self.oldx, self.oldy))
  3349. # self.oldx = locx
  3350. # self.oldy = locy
  3351. #
  3352. # loc_nr += 1
  3353. # disp_number = int(np.interp(loc_nr, [0, geo_len], [0, 100]))
  3354. #
  3355. # if old_disp_number < disp_number <= 100:
  3356. # self.app.proc_container.update_view_text(' %d%%' % disp_number)
  3357. # old_disp_number = disp_number
  3358. #
  3359. # else:
  3360. # self.app.inform.emit('[ERROR_NOTCL] %s...' % _('G91 coordinates not implemented'))
  3361. # return 'fail'
  3362. # self.z_cut = deepcopy(old_zcut)
  3363. # else:
  3364. # log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> "
  3365. # "The loaded Excellon file has no drills ...")
  3366. # self.app.inform.emit('[ERROR_NOTCL] %s...' % _('The loaded Excellon file has no drills'))
  3367. # return 'fail'
  3368. #
  3369. # log.debug("The total travel distance with OR-TOOLS Basic Algorithm is: %s" % str(measured_distance))
  3370. #
  3371. # elif used_excellon_optimization_type == 'T':
  3372. # log.debug("Using Travelling Salesman drill path optimization.")
  3373. #
  3374. # for tool in tools:
  3375. # if self.app.abort_flag:
  3376. # # graceful abort requested by the user
  3377. # raise grace
  3378. #
  3379. # if has_drills:
  3380. # self.tool = tool
  3381. # self.tooldia = self.exc_tools[tool]["tooldia"]
  3382. # self.postdata['toolC'] = self.tooldia
  3383. #
  3384. # if self.use_ui:
  3385. # self.z_feedrate = self.exc_tools[tool]['data']['feedrate_z']
  3386. # self.feedrate = self.exc_tools[tool]['data']['feedrate']
  3387. # gcode += self.doformat(p.z_feedrate_code)
  3388. #
  3389. # self.z_cut = self.exc_tools[tool]['data']['cutz']
  3390. #
  3391. # if self.machinist_setting == 0:
  3392. # if self.z_cut > 0:
  3393. # self.app.inform.emit('[WARNING] %s' %
  3394. # _("The Cut Z parameter has positive value. "
  3395. # "It is the depth value to drill into material.\n"
  3396. # "The Cut Z parameter needs to have a negative value, "
  3397. # "assuming it is a typo "
  3398. # "therefore the app will convert the value to negative. "
  3399. # "Check the resulting CNC code (Gcode etc)."))
  3400. # self.z_cut = -self.z_cut
  3401. # elif self.z_cut == 0:
  3402. # self.app.inform.emit('[WARNING] %s: %s' %
  3403. # (_(
  3404. # "The Cut Z parameter is zero. There will be no cut, "
  3405. # "skipping file"),
  3406. # exobj.options['name']))
  3407. # return 'fail'
  3408. #
  3409. # old_zcut = deepcopy(self.z_cut)
  3410. #
  3411. # self.z_move = self.exc_tools[tool]['data']['travelz']
  3412. # self.spindlespeed = self.exc_tools[tool]['data']['spindlespeed']
  3413. # self.dwell = self.exc_tools[tool]['data']['dwell']
  3414. # self.dwelltime = self.exc_tools[tool]['data']['dwelltime']
  3415. # self.multidepth = self.exc_tools[tool]['data']['multidepth']
  3416. # self.z_depthpercut = self.exc_tools[tool]['data']['depthperpass']
  3417. # else:
  3418. # old_zcut = deepcopy(self.z_cut)
  3419. #
  3420. # # ###############################################
  3421. # # ############ Create the data. #################
  3422. # # ###############################################
  3423. # altPoints = []
  3424. # for point in points[tool]:
  3425. # altPoints.append((point.coords.xy[0][0], point.coords.xy[1][0]))
  3426. # optimized_path = self.optimized_travelling_salesman(altPoints)
  3427. #
  3428. # # Only if tool has points.
  3429. # if tool in points:
  3430. # if self.app.abort_flag:
  3431. # # graceful abort requested by the user
  3432. # raise grace
  3433. #
  3434. # # Tool change sequence (optional)
  3435. # if self.toolchange:
  3436. # gcode += self.doformat(p.toolchange_code, toolchangexy=(self.oldx, self.oldy))
  3437. # gcode += self.doformat(p.spindle_code) # Spindle start)
  3438. # if self.dwell is True:
  3439. # gcode += self.doformat(p.dwell_code) # Dwell time
  3440. # else:
  3441. # gcode += self.doformat(p.spindle_code)
  3442. # if self.dwell is True:
  3443. # gcode += self.doformat(p.dwell_code) # Dwell time
  3444. #
  3445. # current_tooldia = float('%.*f' % (self.decimals, float(self.exc_tools[tool]["tooldia"])))
  3446. #
  3447. # self.app.inform.emit(
  3448. # '%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  3449. # str(current_tooldia),
  3450. # str(self.units))
  3451. # )
  3452. #
  3453. # # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  3454. # # APPLY Offset only when using the appGUI, for TclCommand this will create an error
  3455. # # because the values for Z offset are created in build_ui()
  3456. # # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  3457. # try:
  3458. # z_offset = float(self.exc_tools[tool]['data']['offset']) * (-1)
  3459. # except KeyError:
  3460. # z_offset = 0
  3461. # self.z_cut = z_offset + old_zcut
  3462. #
  3463. # self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  3464. # if self.coordinates_type == "G90":
  3465. # # Drillling! for Absolute coordinates type G90
  3466. # # variables to display the percentage of work done
  3467. # geo_len = len(optimized_path)
  3468. # old_disp_number = 0
  3469. # log.warning("Number of drills for which to generate GCode: %s" % str(geo_len))
  3470. #
  3471. # loc_nr = 0
  3472. # for point in optimized_path:
  3473. # if self.app.abort_flag:
  3474. # # graceful abort requested by the user
  3475. # raise grace
  3476. #
  3477. # locx = point[0]
  3478. # locy = point[1]
  3479. #
  3480. # travels = self.app.exc_areas.travel_coordinates(start_point=(self.oldx, self.oldy),
  3481. # end_point=(locx, locy),
  3482. # tooldia=current_tooldia)
  3483. # prev_z = None
  3484. # for travel in travels:
  3485. # locx = travel[1][0]
  3486. # locy = travel[1][1]
  3487. #
  3488. # if travel[0] is not None:
  3489. # # move to next point
  3490. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3491. #
  3492. # # raise to safe Z (travel[0]) each time because safe Z may be different
  3493. # self.z_move = travel[0]
  3494. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3495. #
  3496. # # restore z_move
  3497. # self.z_move = self.exc_tools[tool]['data']['travelz']
  3498. # else:
  3499. # if prev_z is not None:
  3500. # # move to next point
  3501. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3502. #
  3503. # # we assume that previously the z_move was altered therefore raise to
  3504. # # the travel_z (z_move)
  3505. # self.z_move = self.exc_tools[tool]['data']['travelz']
  3506. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3507. # else:
  3508. # # move to next point
  3509. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3510. #
  3511. # # store prev_z
  3512. # prev_z = travel[0]
  3513. #
  3514. # # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3515. #
  3516. # if self.multidepth and abs(self.z_cut) > abs(self.z_depthpercut):
  3517. # doc = deepcopy(self.z_cut)
  3518. # self.z_cut = 0.0
  3519. #
  3520. # while abs(self.z_cut) < abs(doc):
  3521. #
  3522. # self.z_cut -= self.z_depthpercut
  3523. # if abs(doc) < abs(self.z_cut) < (abs(doc) + self.z_depthpercut):
  3524. # self.z_cut = doc
  3525. # gcode += self.doformat(p.down_code, x=locx, y=locy)
  3526. #
  3527. # measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  3528. #
  3529. # if self.f_retract is False:
  3530. # gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  3531. # measured_up_to_zero_distance += abs(self.z_cut)
  3532. # measured_lift_distance += abs(self.z_move)
  3533. # else:
  3534. # measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  3535. #
  3536. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3537. #
  3538. # else:
  3539. # gcode += self.doformat(p.down_code, x=locx, y=locy)
  3540. #
  3541. # measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  3542. #
  3543. # if self.f_retract is False:
  3544. # gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  3545. # measured_up_to_zero_distance += abs(self.z_cut)
  3546. # measured_lift_distance += abs(self.z_move)
  3547. # else:
  3548. # measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  3549. #
  3550. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3551. #
  3552. # measured_distance += abs(distance_euclidian(locx, locy, self.oldx, self.oldy))
  3553. # self.oldx = locx
  3554. # self.oldy = locy
  3555. #
  3556. # loc_nr += 1
  3557. # disp_number = int(np.interp(loc_nr, [0, geo_len], [0, 100]))
  3558. #
  3559. # if old_disp_number < disp_number <= 100:
  3560. # self.app.proc_container.update_view_text(' %d%%' % disp_number)
  3561. # old_disp_number = disp_number
  3562. # else:
  3563. # self.app.inform.emit('[ERROR_NOTCL] %s...' % _('G91 coordinates not implemented'))
  3564. # return 'fail'
  3565. # else:
  3566. # log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> "
  3567. # "The loaded Excellon file has no drills ...")
  3568. # self.app.inform.emit('[ERROR_NOTCL] %s...' % _('The loaded Excellon file has no drills'))
  3569. # return 'fail'
  3570. # self.z_cut = deepcopy(old_zcut)
  3571. # log.debug("The total travel distance with Travelling Salesman Algorithm is: %s" % str(measured_distance))
  3572. #
  3573. # else:
  3574. # log.debug("camlib.CNCJob.generate_from_excellon_by_tool(): Chosen drill optimization doesn't exist.")
  3575. # return 'fail'
  3576. # Spindle stop
  3577. gcode += self.doformat(p.spindle_stop_code)
  3578. # Move to End position
  3579. gcode += self.doformat(p.end_code, x=0, y=0)
  3580. # #############################################################################################################
  3581. # ############################# Calculate DISTANCE and ESTIMATED TIME #########################################
  3582. # #############################################################################################################
  3583. measured_distance += abs(distance_euclidian(self.oldx, self.oldy, 0, 0))
  3584. log.debug("The total travel distance including travel to end position is: %s" %
  3585. str(measured_distance) + '\n')
  3586. self.travel_distance = measured_distance
  3587. # I use the value of self.feedrate_rapid for the feadrate in case of the measure_lift_distance and for
  3588. # traveled_time because it is not always possible to determine the feedrate that the CNC machine uses
  3589. # for G0 move (the fastest speed available to the CNC router). Although self.feedrate_rapids is used only with
  3590. # Marlin preprocessor and derivatives.
  3591. self.routing_time = (measured_down_distance + measured_up_to_zero_distance) / self.feedrate
  3592. lift_time = measured_lift_distance / self.feedrate_rapid
  3593. traveled_time = measured_distance / self.feedrate_rapid
  3594. self.routing_time += lift_time + traveled_time
  3595. # #############################################################################################################
  3596. # ############################# Store the GCODE for further usage ############################################
  3597. # #############################################################################################################
  3598. self.gcode = gcode
  3599. self.app.inform.emit(_("Finished G-Code generation..."))
  3600. return 'OK'
  3601. def generate_from_multitool_geometry(self, geometry, append=True, tooldia=None, offset=0.0, tolerance=0, z_cut=1.0,
  3602. z_move=2.0, feedrate=2.0, feedrate_z=2.0, feedrate_rapid=30,
  3603. spindlespeed=None, spindledir='CW', dwell=False, dwelltime=1.0,
  3604. multidepth=False, depthpercut=None, toolchange=False, toolchangez=1.0,
  3605. toolchangexy="0.0, 0.0", extracut=False, extracut_length=0.2,
  3606. startz=None, endz=2.0, endxy='', pp_geometry_name=None, tool_no=1):
  3607. """
  3608. Algorithm to generate from multitool Geometry.
  3609. Algorithm description:
  3610. ----------------------
  3611. Uses RTree to find the nearest path to follow.
  3612. :param geometry:
  3613. :param append:
  3614. :param tooldia:
  3615. :param offset:
  3616. :param tolerance:
  3617. :param z_cut:
  3618. :param z_move:
  3619. :param feedrate:
  3620. :param feedrate_z:
  3621. :param feedrate_rapid:
  3622. :param spindlespeed:
  3623. :param spindledir: Direction of rotation for the spindle. If using GRBL laser mode will
  3624. adjust the laser mode
  3625. :param dwell:
  3626. :param dwelltime:
  3627. :param multidepth: If True, use multiple passes to reach the desired depth.
  3628. :param depthpercut: Maximum depth in each pass.
  3629. :param toolchange:
  3630. :param toolchangez:
  3631. :param toolchangexy:
  3632. :param extracut: Adds (or not) an extra cut at the end of each path overlapping the
  3633. first point in path to ensure complete copper removal
  3634. :param extracut_length: Extra cut legth at the end of the path
  3635. :param startz:
  3636. :param endz:
  3637. :param endxy:
  3638. :param pp_geometry_name:
  3639. :param tool_no:
  3640. :return: GCode - string
  3641. """
  3642. log.debug("Generate_from_multitool_geometry()")
  3643. temp_solid_geometry = []
  3644. if offset != 0.0:
  3645. for it in geometry:
  3646. # if the geometry is a closed shape then create a Polygon out of it
  3647. if isinstance(it, LineString):
  3648. c = it.coords
  3649. if c[0] == c[-1]:
  3650. it = Polygon(it)
  3651. temp_solid_geometry.append(it.buffer(offset, join_style=2))
  3652. else:
  3653. temp_solid_geometry = geometry
  3654. # ## Flatten the geometry. Only linear elements (no polygons) remain.
  3655. flat_geometry = self.flatten(temp_solid_geometry, pathonly=True)
  3656. log.debug("%d paths" % len(flat_geometry))
  3657. try:
  3658. self.tooldia = float(tooldia)
  3659. except Exception as e:
  3660. self.app.inform.emit('[ERROR] %s\n%s' % (_("Failed."), str(e)))
  3661. return 'fail'
  3662. self.z_cut = float(z_cut) if z_cut else None
  3663. self.z_move = float(z_move) if z_move is not None else None
  3664. self.feedrate = float(feedrate) if feedrate else self.app.defaults["geometry_feedrate"]
  3665. self.z_feedrate = float(feedrate_z) if feedrate_z is not None else self.app.defaults["geometry_feedrate_z"]
  3666. self.feedrate_rapid = float(feedrate_rapid) if feedrate_rapid else self.app.defaults["geometry_feedrate_rapid"]
  3667. self.spindlespeed = int(spindlespeed) if spindlespeed != 0 else None
  3668. self.spindledir = spindledir
  3669. self.dwell = dwell
  3670. self.dwelltime = float(dwelltime) if dwelltime else self.app.defaults["geometry_dwelltime"]
  3671. self.startz = float(startz) if startz is not None else self.app.defaults["geometry_startz"]
  3672. self.z_end = float(endz) if endz is not None else self.app.defaults["geometry_endz"]
  3673. self.xy_end = re.sub('[()\[\]]', '', str(endxy)) if endxy else self.app.defaults["geometry_endxy"]
  3674. if self.xy_end and self.xy_end != '':
  3675. self.xy_end = [float(eval(a)) for a in self.xy_end.split(",")]
  3676. if self.xy_end and len(self.xy_end) < 2:
  3677. self.app.inform.emit('[ERROR] %s' % _("The End Move X,Y field in Edit -> Preferences has to be "
  3678. "in the format (x, y) but now there is only one value, not two."))
  3679. return 'fail'
  3680. self.z_depthpercut = float(depthpercut) if depthpercut else self.app.defaults["geometry_depthperpass"]
  3681. self.multidepth = multidepth
  3682. self.z_toolchange = float(toolchangez) if toolchangez is not None else self.app.defaults["geometry_toolchangez"]
  3683. # it servers in the preprocessor file
  3684. self.tool = tool_no
  3685. try:
  3686. if toolchangexy == '':
  3687. self.xy_toolchange = None
  3688. else:
  3689. self.xy_toolchange = re.sub('[()\[\]]', '', str(toolchangexy)) \
  3690. if toolchangexy else self.app.defaults["geometry_toolchangexy"]
  3691. if self.xy_toolchange and self.xy_toolchange != '':
  3692. self.xy_toolchange = [float(eval(a)) for a in self.xy_toolchange.split(",")]
  3693. if len(self.xy_toolchange) < 2:
  3694. self.app.inform.emit('[ERROR] %s' % _("The Toolchange X,Y field in Edit -> Preferences has to be "
  3695. "in the format (x, y) \n"
  3696. "but now there is only one value, not two."))
  3697. return 'fail'
  3698. except Exception as e:
  3699. log.debug("camlib.CNCJob.generate_from_multitool_geometry() --> %s" % str(e))
  3700. pass
  3701. self.pp_geometry_name = pp_geometry_name if pp_geometry_name else 'default'
  3702. self.f_plunge = self.app.defaults["geometry_f_plunge"]
  3703. if self.z_cut is None:
  3704. if 'laser' not in self.pp_geometry_name:
  3705. self.app.inform.emit(
  3706. '[ERROR_NOTCL] %s' % _("Cut_Z parameter is None or zero. Most likely a bad combinations of "
  3707. "other parameters."))
  3708. return 'fail'
  3709. else:
  3710. self.z_cut = 0
  3711. if self.machinist_setting == 0:
  3712. if self.z_cut > 0:
  3713. self.app.inform.emit('[WARNING] %s' %
  3714. _("The Cut Z parameter has positive value. "
  3715. "It is the depth value to cut into material.\n"
  3716. "The Cut Z parameter needs to have a negative value, assuming it is a typo "
  3717. "therefore the app will convert the value to negative."
  3718. "Check the resulting CNC code (Gcode etc)."))
  3719. self.z_cut = -self.z_cut
  3720. elif self.z_cut == 0 and 'laser' not in self.pp_geometry_name:
  3721. self.app.inform.emit('[WARNING] %s: %s' %
  3722. (_("The Cut Z parameter is zero. There will be no cut, skipping file"),
  3723. self.options['name']))
  3724. return 'fail'
  3725. if self.z_move is None:
  3726. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Travel Z parameter is None or zero."))
  3727. return 'fail'
  3728. if self.z_move < 0:
  3729. self.app.inform.emit('[WARNING] %s' %
  3730. _("The Travel Z parameter has negative value. "
  3731. "It is the height value to travel between cuts.\n"
  3732. "The Z Travel parameter needs to have a positive value, assuming it is a typo "
  3733. "therefore the app will convert the value to positive."
  3734. "Check the resulting CNC code (Gcode etc)."))
  3735. self.z_move = -self.z_move
  3736. elif self.z_move == 0:
  3737. self.app.inform.emit('[WARNING] %s: %s' %
  3738. (_("The Z Travel parameter is zero. This is dangerous, skipping file"),
  3739. self.options['name']))
  3740. return 'fail'
  3741. # made sure that depth_per_cut is no more then the z_cut
  3742. if abs(self.z_cut) < self.z_depthpercut:
  3743. self.z_depthpercut = abs(self.z_cut)
  3744. # ## Index first and last points in paths
  3745. # What points to index.
  3746. def get_pts(o):
  3747. return [o.coords[0], o.coords[-1]]
  3748. # Create the indexed storage.
  3749. storage = FlatCAMRTreeStorage()
  3750. storage.get_points = get_pts
  3751. # Store the geometry
  3752. log.debug("Indexing geometry before generating G-Code...")
  3753. self.app.inform.emit(_("Indexing geometry before generating G-Code..."))
  3754. for geo_shape in flat_geometry:
  3755. if self.app.abort_flag:
  3756. # graceful abort requested by the user
  3757. raise grace
  3758. if geo_shape is not None:
  3759. storage.insert(geo_shape)
  3760. # self.input_geometry_bounds = geometry.bounds()
  3761. if not append:
  3762. self.gcode = ""
  3763. # tell preprocessor the number of tool (for toolchange)
  3764. self.tool = tool_no
  3765. # this is the tool diameter, it is used as such to accommodate the preprocessor who need the tool diameter
  3766. # given under the name 'toolC'
  3767. self.postdata['toolC'] = self.tooldia
  3768. # Initial G-Code
  3769. self.pp_geometry = self.app.preprocessors[self.pp_geometry_name]
  3770. p = self.pp_geometry
  3771. self.gcode = self.doformat(p.start_code)
  3772. self.gcode += self.doformat(p.feedrate_code) # sets the feed rate
  3773. if toolchange is False:
  3774. self.gcode += self.doformat(p.lift_code, x=0, y=0) # Move (up) to travel height
  3775. self.gcode += self.doformat(p.startz_code, x=0, y=0)
  3776. if toolchange:
  3777. # if "line_xyz" in self.pp_geometry_name:
  3778. # self.gcode += self.doformat(p.toolchange_code, x=self.xy_toolchange[0], y=self.xy_toolchange[1])
  3779. # else:
  3780. # self.gcode += self.doformat(p.toolchange_code)
  3781. self.gcode += self.doformat(p.toolchange_code)
  3782. if 'laser' not in self.pp_geometry_name:
  3783. self.gcode += self.doformat(p.spindle_code) # Spindle start
  3784. else:
  3785. # for laser this will disable the laser
  3786. self.gcode += self.doformat(p.lift_code, x=self.oldx, y=self.oldy) # Move (up) to travel height
  3787. if self.dwell is True:
  3788. self.gcode += self.doformat(p.dwell_code) # Dwell time
  3789. else:
  3790. if 'laser' not in self.pp_geometry_name:
  3791. self.gcode += self.doformat(p.spindle_code) # Spindle start
  3792. if self.dwell is True:
  3793. self.gcode += self.doformat(p.dwell_code) # Dwell time
  3794. total_travel = 0.0
  3795. total_cut = 0.0
  3796. # ## Iterate over geometry paths getting the nearest each time.
  3797. log.debug("Starting G-Code...")
  3798. self.app.inform.emit('%s...' % _("Starting G-Code"))
  3799. path_count = 0
  3800. current_pt = (0, 0)
  3801. # variables to display the percentage of work done
  3802. geo_len = len(flat_geometry)
  3803. old_disp_number = 0
  3804. log.warning("Number of paths for which to generate GCode: %s" % str(geo_len))
  3805. current_tooldia = float('%.*f' % (self.decimals, float(self.tooldia)))
  3806. self.app.inform.emit('%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  3807. str(current_tooldia),
  3808. str(self.units)))
  3809. pt, geo = storage.nearest(current_pt)
  3810. try:
  3811. while True:
  3812. if self.app.abort_flag:
  3813. # graceful abort requested by the user
  3814. raise grace
  3815. path_count += 1
  3816. # Remove before modifying, otherwise deletion will fail.
  3817. storage.remove(geo)
  3818. # If last point in geometry is the nearest but prefer the first one if last point == first point
  3819. # then reverse coordinates.
  3820. if pt != geo.coords[0] and pt == geo.coords[-1]:
  3821. geo.coords = list(geo.coords)[::-1]
  3822. # ---------- Single depth/pass --------
  3823. if not multidepth:
  3824. # calculate the cut distance
  3825. total_cut = total_cut + geo.length
  3826. self.gcode += self.create_gcode_single_pass(geo, current_tooldia, extracut, extracut_length,
  3827. tolerance, z_move=z_move, old_point=current_pt)
  3828. # --------- Multi-pass ---------
  3829. else:
  3830. # calculate the cut distance
  3831. # due of the number of cuts (multi depth) it has to multiplied by the number of cuts
  3832. nr_cuts = 0
  3833. depth = abs(self.z_cut)
  3834. while depth > 0:
  3835. nr_cuts += 1
  3836. depth -= float(self.z_depthpercut)
  3837. total_cut += (geo.length * nr_cuts)
  3838. self.gcode += self.create_gcode_multi_pass(geo, current_tooldia, extracut, extracut_length,
  3839. tolerance, z_move=z_move, postproc=p,
  3840. old_point=current_pt)
  3841. # calculate the total distance
  3842. total_travel = total_travel + abs(distance(pt1=current_pt, pt2=pt))
  3843. current_pt = geo.coords[-1]
  3844. pt, geo = storage.nearest(current_pt) # Next
  3845. disp_number = int(np.interp(path_count, [0, geo_len], [0, 100]))
  3846. if old_disp_number < disp_number <= 100:
  3847. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  3848. old_disp_number = disp_number
  3849. except StopIteration: # Nothing found in storage.
  3850. pass
  3851. log.debug("Finished G-Code... %s paths traced." % path_count)
  3852. # add move to end position
  3853. total_travel += abs(distance_euclidian(current_pt[0], current_pt[1], 0, 0))
  3854. self.travel_distance += total_travel + total_cut
  3855. self.routing_time += total_cut / self.feedrate
  3856. # Finish
  3857. self.gcode += self.doformat(p.spindle_stop_code)
  3858. self.gcode += self.doformat(p.lift_code, x=current_pt[0], y=current_pt[1])
  3859. self.gcode += self.doformat(p.end_code, x=0, y=0)
  3860. self.app.inform.emit(
  3861. '%s... %s %s.' % (_("Finished G-Code generation"), str(path_count), _("paths traced"))
  3862. )
  3863. return self.gcode
  3864. def generate_from_geometry_2(self, geometry, append=True, tooldia=None, offset=0.0, tolerance=0, z_cut=None,
  3865. z_move=None, feedrate=None, feedrate_z=None, feedrate_rapid=None, spindlespeed=None,
  3866. spindledir='CW', dwell=False, dwelltime=None, multidepth=False, depthpercut=None,
  3867. toolchange=False, toolchangez=None, toolchangexy="0.0, 0.0", extracut=False,
  3868. extracut_length=None, startz=None, endz=None, endxy='', pp_geometry_name=None,
  3869. tool_no=1):
  3870. """
  3871. Second algorithm to generate from Geometry.
  3872. Algorithm description:
  3873. ----------------------
  3874. Uses RTree to find the nearest path to follow.
  3875. :param geometry:
  3876. :param append:
  3877. :param tooldia:
  3878. :param offset:
  3879. :param tolerance:
  3880. :param z_cut:
  3881. :param z_move:
  3882. :param feedrate:
  3883. :param feedrate_z:
  3884. :param feedrate_rapid:
  3885. :param spindlespeed:
  3886. :param spindledir:
  3887. :param dwell:
  3888. :param dwelltime:
  3889. :param multidepth: If True, use multiple passes to reach the desired depth.
  3890. :param depthpercut: Maximum depth in each pass.
  3891. :param toolchange:
  3892. :param toolchangez:
  3893. :param toolchangexy:
  3894. :param extracut: Adds (or not) an extra cut at the end of each path overlapping the first point in
  3895. path to ensure complete copper removal
  3896. :param extracut_length: The extra cut length
  3897. :param startz:
  3898. :param endz:
  3899. :param endxy:
  3900. :param pp_geometry_name:
  3901. :param tool_no:
  3902. :return: None
  3903. """
  3904. if not isinstance(geometry, Geometry):
  3905. self.app.inform.emit('[ERROR] %s: %s' % (_("Expected a Geometry, got"), type(geometry)))
  3906. return 'fail'
  3907. log.debug("Executing camlib.CNCJob.generate_from_geometry_2()")
  3908. # if solid_geometry is empty raise an exception
  3909. if not geometry.solid_geometry:
  3910. self.app.inform.emit(
  3911. '[ERROR_NOTCL] %s' % _("Trying to generate a CNC Job from a Geometry object without solid_geometry.")
  3912. )
  3913. temp_solid_geometry = []
  3914. def bounds_rec(obj):
  3915. if type(obj) is list:
  3916. minx = np.Inf
  3917. miny = np.Inf
  3918. maxx = -np.Inf
  3919. maxy = -np.Inf
  3920. for k in obj:
  3921. if type(k) is dict:
  3922. for key in k:
  3923. minx_, miny_, maxx_, maxy_ = bounds_rec(k[key])
  3924. minx = min(minx, minx_)
  3925. miny = min(miny, miny_)
  3926. maxx = max(maxx, maxx_)
  3927. maxy = max(maxy, maxy_)
  3928. else:
  3929. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  3930. minx = min(minx, minx_)
  3931. miny = min(miny, miny_)
  3932. maxx = max(maxx, maxx_)
  3933. maxy = max(maxy, maxy_)
  3934. return minx, miny, maxx, maxy
  3935. else:
  3936. # it's a Shapely object, return it's bounds
  3937. return obj.bounds
  3938. if offset != 0.0:
  3939. offset_for_use = offset
  3940. if offset < 0:
  3941. a, b, c, d = bounds_rec(geometry.solid_geometry)
  3942. # if the offset is less than half of the total length or less than half of the total width of the
  3943. # solid geometry it's obvious we can't do the offset
  3944. if -offset > ((c - a) / 2) or -offset > ((d - b) / 2):
  3945. self.app.inform.emit(
  3946. '[ERROR_NOTCL] %s' %
  3947. _("The Tool Offset value is too negative to use for the current_geometry.\n"
  3948. "Raise the value (in module) and try again.")
  3949. )
  3950. return 'fail'
  3951. # hack: make offset smaller by 0.0000000001 which is insignificant difference but allow the job
  3952. # to continue
  3953. elif -offset == ((c - a) / 2) or -offset == ((d - b) / 2):
  3954. offset_for_use = offset - 0.0000000001
  3955. for it in geometry.solid_geometry:
  3956. # if the geometry is a closed shape then create a Polygon out of it
  3957. if isinstance(it, LineString):
  3958. c = it.coords
  3959. if c[0] == c[-1]:
  3960. it = Polygon(it)
  3961. temp_solid_geometry.append(it.buffer(offset_for_use, join_style=2))
  3962. else:
  3963. temp_solid_geometry = geometry.solid_geometry
  3964. # ## Flatten the geometry. Only linear elements (no polygons) remain.
  3965. flat_geometry = self.flatten(temp_solid_geometry, pathonly=True)
  3966. log.debug("%d paths" % len(flat_geometry))
  3967. default_dia = None
  3968. if isinstance(self.app.defaults["geometry_cnctooldia"], float):
  3969. default_dia = self.app.defaults["geometry_cnctooldia"]
  3970. else:
  3971. try:
  3972. tools_string = self.app.defaults["geometry_cnctooldia"].split(",")
  3973. tools_diameters = [eval(a) for a in tools_string if a != '']
  3974. default_dia = tools_diameters[0] if tools_diameters else 0.0
  3975. except Exception as e:
  3976. self.app.log.debug("camlib.CNCJob.generate_from_geometry_2() --> %s" % str(e))
  3977. try:
  3978. self.tooldia = float(tooldia) if tooldia else default_dia
  3979. except ValueError:
  3980. self.tooldia = [float(el) for el in tooldia.split(',') if el != ''] if tooldia is not None else default_dia
  3981. if self.tooldia is None:
  3982. self.app.inform.emit('[ERROR] %s' % _("Failed."))
  3983. return 'fail'
  3984. self.z_cut = float(z_cut) if z_cut is not None else self.app.defaults["geometry_cutz"]
  3985. self.z_move = float(z_move) if z_move is not None else self.app.defaults["geometry_travelz"]
  3986. self.feedrate = float(feedrate) if feedrate is not None else self.app.defaults["geometry_feedrate"]
  3987. self.z_feedrate = float(feedrate_z) if feedrate_z is not None else self.app.defaults["geometry_feedrate_z"]
  3988. self.feedrate_rapid = float(feedrate_rapid) if feedrate_rapid is not None else \
  3989. self.app.defaults["geometry_feedrate_rapid"]
  3990. self.spindlespeed = int(spindlespeed) if spindlespeed != 0 and spindlespeed is not None else None
  3991. self.spindledir = spindledir
  3992. self.dwell = dwell
  3993. self.dwelltime = float(dwelltime) if dwelltime is not None else self.app.defaults["geometry_dwelltime"]
  3994. self.startz = float(startz) if startz is not None and startz != '' else self.app.defaults["geometry_startz"]
  3995. self.z_end = float(endz) if endz is not None else self.app.defaults["geometry_endz"]
  3996. self.xy_end = endxy if endxy != '' and endxy else self.app.defaults["geometry_endxy"]
  3997. self.xy_end = re.sub('[()\[\]]', '', str(self.xy_end)) if self.xy_end else None
  3998. if self.xy_end is not None and self.xy_end != '':
  3999. self.xy_end = [float(eval(a)) for a in self.xy_end.split(",")]
  4000. if self.xy_end and len(self.xy_end) < 2:
  4001. self.app.inform.emit('[ERROR] %s' % _("The End Move X,Y field in Edit -> Preferences has to be "
  4002. "in the format (x, y) but now there is only one value, not two."))
  4003. return 'fail'
  4004. self.z_depthpercut = float(depthpercut) if depthpercut is not None and depthpercut != 0 else abs(self.z_cut)
  4005. self.multidepth = multidepth
  4006. self.z_toolchange = float(toolchangez) if toolchangez is not None else self.app.defaults["geometry_toolchangez"]
  4007. self.extracut_length = float(extracut_length) if extracut_length is not None else \
  4008. self.app.defaults["geometry_extracut_length"]
  4009. try:
  4010. if toolchangexy == '':
  4011. self.xy_toolchange = None
  4012. else:
  4013. self.xy_toolchange = re.sub('[()\[\]]', '', str(toolchangexy)) if self.xy_toolchange else None
  4014. if self.xy_toolchange and self.xy_toolchange != '':
  4015. self.xy_toolchange = [float(eval(a)) for a in self.xy_toolchange.split(",")]
  4016. if len(self.xy_toolchange) < 2:
  4017. msg = _("The Toolchange X,Y field in Edit -> Preferences has to be in the format (x, y)\n"
  4018. "but now there is only one value, not two.")
  4019. self.app.inform.emit('[ERROR] %s' % msg)
  4020. return 'fail'
  4021. except Exception as e:
  4022. log.debug("camlib.CNCJob.generate_from_geometry_2() --> %s" % str(e))
  4023. pass
  4024. self.pp_geometry_name = pp_geometry_name if pp_geometry_name else 'default'
  4025. self.f_plunge = self.app.defaults["geometry_f_plunge"]
  4026. if self.machinist_setting == 0:
  4027. if self.z_cut is None:
  4028. if 'laser' not in self.pp_geometry_name:
  4029. self.app.inform.emit(
  4030. '[ERROR_NOTCL] %s' % _("Cut_Z parameter is None or zero. Most likely a bad combinations of "
  4031. "other parameters.")
  4032. )
  4033. return 'fail'
  4034. else:
  4035. self.z_cut = 0.0
  4036. if self.z_cut > 0:
  4037. self.app.inform.emit('[WARNING] %s' %
  4038. _("The Cut Z parameter has positive value. "
  4039. "It is the depth value to cut into material.\n"
  4040. "The Cut Z parameter needs to have a negative value, assuming it is a typo "
  4041. "therefore the app will convert the value to negative."
  4042. "Check the resulting CNC code (Gcode etc)."))
  4043. self.z_cut = -self.z_cut
  4044. elif self.z_cut == 0 and 'laser' not in self.pp_geometry_name:
  4045. self.app.inform.emit(
  4046. '[WARNING] %s: %s' % (_("The Cut Z parameter is zero. There will be no cut, skipping file"),
  4047. geometry.options['name'])
  4048. )
  4049. return 'fail'
  4050. if self.z_move is None:
  4051. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Travel Z parameter is None or zero."))
  4052. return 'fail'
  4053. if self.z_move < 0:
  4054. self.app.inform.emit('[WARNING] %s' %
  4055. _("The Travel Z parameter has negative value. "
  4056. "It is the height value to travel between cuts.\n"
  4057. "The Z Travel parameter needs to have a positive value, assuming it is a typo "
  4058. "therefore the app will convert the value to positive."
  4059. "Check the resulting CNC code (Gcode etc)."))
  4060. self.z_move = -self.z_move
  4061. elif self.z_move == 0:
  4062. self.app.inform.emit(
  4063. '[WARNING] %s: %s' % (_("The Z Travel parameter is zero. This is dangerous, skipping file"),
  4064. self.options['name'])
  4065. )
  4066. return 'fail'
  4067. # made sure that depth_per_cut is no more then the z_cut
  4068. try:
  4069. if abs(self.z_cut) < self.z_depthpercut:
  4070. self.z_depthpercut = abs(self.z_cut)
  4071. except TypeError:
  4072. self.z_depthpercut = abs(self.z_cut)
  4073. # ## Index first and last points in paths
  4074. # What points to index.
  4075. def get_pts(o):
  4076. return [o.coords[0], o.coords[-1]]
  4077. # Create the indexed storage.
  4078. storage = FlatCAMRTreeStorage()
  4079. storage.get_points = get_pts
  4080. # Store the geometry
  4081. log.debug("Indexing geometry before generating G-Code...")
  4082. self.app.inform.emit(_("Indexing geometry before generating G-Code..."))
  4083. for geo_shape in flat_geometry:
  4084. if self.app.abort_flag:
  4085. # graceful abort requested by the user
  4086. raise grace
  4087. if geo_shape is not None:
  4088. storage.insert(geo_shape)
  4089. if not append:
  4090. self.gcode = ""
  4091. # tell preprocessor the number of tool (for toolchange)
  4092. self.tool = tool_no
  4093. # this is the tool diameter, it is used as such to accommodate the preprocessor who need the tool diameter
  4094. # given under the name 'toolC'
  4095. # this is a fancy way of adding a class attribute (which should be added in the __init__ method) without doing
  4096. # it there :)
  4097. self.postdata['toolC'] = self.tooldia
  4098. # Initial G-Code
  4099. self.pp_geometry = self.app.preprocessors[self.pp_geometry_name]
  4100. # the 'p' local attribute is a reference to the current preprocessor class
  4101. p = self.pp_geometry
  4102. self.oldx = 0.0
  4103. self.oldy = 0.0
  4104. self.gcode = self.doformat(p.start_code)
  4105. self.gcode += self.doformat(p.feedrate_code) # sets the feed rate
  4106. if toolchange is False:
  4107. # all the x and y parameters in self.doformat() are used only by some preprocessors not by all
  4108. self.gcode += self.doformat(p.lift_code, x=self.oldx, y=self.oldy) # Move (up) to travel height
  4109. self.gcode += self.doformat(p.startz_code, x=self.oldx, y=self.oldy)
  4110. if toolchange:
  4111. # if "line_xyz" in self.pp_geometry_name:
  4112. # self.gcode += self.doformat(p.toolchange_code, x=self.xy_toolchange[0], y=self.xy_toolchange[1])
  4113. # else:
  4114. # self.gcode += self.doformat(p.toolchange_code)
  4115. self.gcode += self.doformat(p.toolchange_code)
  4116. if 'laser' not in self.pp_geometry_name:
  4117. self.gcode += self.doformat(p.spindle_code) # Spindle start
  4118. else:
  4119. # for laser this will disable the laser
  4120. self.gcode += self.doformat(p.lift_code, x=self.oldx, y=self.oldy) # Move (up) to travel height
  4121. if self.dwell is True:
  4122. self.gcode += self.doformat(p.dwell_code) # Dwell time
  4123. else:
  4124. if 'laser' not in self.pp_geometry_name:
  4125. self.gcode += self.doformat(p.spindle_code) # Spindle start
  4126. if self.dwell is True:
  4127. self.gcode += self.doformat(p.dwell_code) # Dwell time
  4128. total_travel = 0.0
  4129. total_cut = 0.0
  4130. # Iterate over geometry paths getting the nearest each time.
  4131. log.debug("Starting G-Code...")
  4132. self.app.inform.emit('%s...' % _("Starting G-Code"))
  4133. # variables to display the percentage of work done
  4134. geo_len = len(flat_geometry)
  4135. old_disp_number = 0
  4136. log.warning("Number of paths for which to generate GCode: %s" % str(geo_len))
  4137. current_tooldia = float('%.*f' % (self.decimals, float(self.tooldia)))
  4138. self.app.inform.emit(
  4139. '%s: %s%s.' % (_("Starting G-Code for tool with diameter"), str(current_tooldia), str(self.units))
  4140. )
  4141. path_count = 0
  4142. current_pt = (0, 0)
  4143. pt, geo = storage.nearest(current_pt)
  4144. # when nothing is left in the storage a StopIteration exception will be raised therefore stopping
  4145. # the whole process including the infinite loop while True below.
  4146. try:
  4147. while True:
  4148. if self.app.abort_flag:
  4149. # graceful abort requested by the user
  4150. raise grace
  4151. path_count += 1
  4152. # Remove before modifying, otherwise deletion will fail.
  4153. storage.remove(geo)
  4154. # If last point in geometry is the nearest but prefer the first one if last point == first point
  4155. # then reverse coordinates.
  4156. if pt != geo.coords[0] and pt == geo.coords[-1]:
  4157. geo.coords = list(geo.coords)[::-1]
  4158. # ---------- Single depth/pass --------
  4159. if not multidepth:
  4160. # calculate the cut distance
  4161. total_cut += geo.length
  4162. self.gcode += self.create_gcode_single_pass(geo, current_tooldia, extracut, self.extracut_length,
  4163. tolerance, z_move=z_move, old_point=current_pt)
  4164. # --------- Multi-pass ---------
  4165. else:
  4166. # calculate the cut distance
  4167. # due of the number of cuts (multi depth) it has to multiplied by the number of cuts
  4168. nr_cuts = 0
  4169. depth = abs(self.z_cut)
  4170. while depth > 0:
  4171. nr_cuts += 1
  4172. depth -= float(self.z_depthpercut)
  4173. total_cut += (geo.length * nr_cuts)
  4174. self.gcode += self.create_gcode_multi_pass(geo, current_tooldia, extracut, self.extracut_length,
  4175. tolerance, z_move=z_move, postproc=p,
  4176. old_point=current_pt)
  4177. # calculate the travel distance
  4178. total_travel += abs(distance(pt1=current_pt, pt2=pt))
  4179. current_pt = geo.coords[-1]
  4180. pt, geo = storage.nearest(current_pt) # Next
  4181. # update the activity counter (lower left side of the app, status bar)
  4182. disp_number = int(np.interp(path_count, [0, geo_len], [0, 100]))
  4183. if old_disp_number < disp_number <= 100:
  4184. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  4185. old_disp_number = disp_number
  4186. except StopIteration: # Nothing found in storage.
  4187. pass
  4188. log.debug("Finishing G-Code... %s paths traced." % path_count)
  4189. # add move to end position
  4190. total_travel += abs(distance_euclidian(current_pt[0], current_pt[1], 0, 0))
  4191. self.travel_distance += total_travel + total_cut
  4192. self.routing_time += total_cut / self.feedrate
  4193. # Finish
  4194. self.gcode += self.doformat(p.spindle_stop_code)
  4195. self.gcode += self.doformat(p.lift_code, x=current_pt[0], y=current_pt[1])
  4196. self.gcode += self.doformat(p.end_code, x=0, y=0)
  4197. self.app.inform.emit(
  4198. '%s... %s %s' % (_("Finished G-Code generation"), str(path_count), _(" paths traced."))
  4199. )
  4200. return self.gcode
  4201. def generate_gcode_from_solderpaste_geo(self, **kwargs):
  4202. """
  4203. Algorithm to generate from multitool Geometry.
  4204. Algorithm description:
  4205. ----------------------
  4206. Uses RTree to find the nearest path to follow.
  4207. :return: Gcode string
  4208. """
  4209. log.debug("Generate_from_solderpaste_geometry()")
  4210. # ## Index first and last points in paths
  4211. # What points to index.
  4212. def get_pts(o):
  4213. return [o.coords[0], o.coords[-1]]
  4214. self.gcode = ""
  4215. if not kwargs:
  4216. log.debug("camlib.generate_from_solderpaste_geo() --> No tool in the solderpaste geometry.")
  4217. self.app.inform.emit('[ERROR_NOTCL] %s' %
  4218. _("There is no tool data in the SolderPaste geometry."))
  4219. # this is the tool diameter, it is used as such to accommodate the preprocessor who need the tool diameter
  4220. # given under the name 'toolC'
  4221. self.postdata['z_start'] = kwargs['data']['tools_solderpaste_z_start']
  4222. self.postdata['z_dispense'] = kwargs['data']['tools_solderpaste_z_dispense']
  4223. self.postdata['z_stop'] = kwargs['data']['tools_solderpaste_z_stop']
  4224. self.postdata['z_travel'] = kwargs['data']['tools_solderpaste_z_travel']
  4225. self.postdata['z_toolchange'] = kwargs['data']['tools_solderpaste_z_toolchange']
  4226. self.postdata['xy_toolchange'] = kwargs['data']['tools_solderpaste_xy_toolchange']
  4227. self.postdata['frxy'] = kwargs['data']['tools_solderpaste_frxy']
  4228. self.postdata['frz'] = kwargs['data']['tools_solderpaste_frz']
  4229. self.postdata['frz_dispense'] = kwargs['data']['tools_solderpaste_frz_dispense']
  4230. self.postdata['speedfwd'] = kwargs['data']['tools_solderpaste_speedfwd']
  4231. self.postdata['dwellfwd'] = kwargs['data']['tools_solderpaste_dwellfwd']
  4232. self.postdata['speedrev'] = kwargs['data']['tools_solderpaste_speedrev']
  4233. self.postdata['dwellrev'] = kwargs['data']['tools_solderpaste_dwellrev']
  4234. self.postdata['pp_solderpaste_name'] = kwargs['data']['tools_solderpaste_pp']
  4235. self.postdata['toolC'] = kwargs['tooldia']
  4236. self.pp_solderpaste_name = kwargs['data']['tools_solderpaste_pp'] if kwargs['data']['tools_solderpaste_pp'] \
  4237. else self.app.defaults['tools_solderpaste_pp']
  4238. p = self.app.preprocessors[self.pp_solderpaste_name]
  4239. # ## Flatten the geometry. Only linear elements (no polygons) remain.
  4240. flat_geometry = self.flatten(kwargs['solid_geometry'], pathonly=True)
  4241. log.debug("%d paths" % len(flat_geometry))
  4242. # Create the indexed storage.
  4243. storage = FlatCAMRTreeStorage()
  4244. storage.get_points = get_pts
  4245. # Store the geometry
  4246. log.debug("Indexing geometry before generating G-Code...")
  4247. for geo_shape in flat_geometry:
  4248. if self.app.abort_flag:
  4249. # graceful abort requested by the user
  4250. raise grace
  4251. if geo_shape is not None:
  4252. storage.insert(geo_shape)
  4253. # Initial G-Code
  4254. self.gcode = self.doformat(p.start_code)
  4255. self.gcode += self.doformat(p.spindle_off_code)
  4256. self.gcode += self.doformat(p.toolchange_code)
  4257. # ## Iterate over geometry paths getting the nearest each time.
  4258. log.debug("Starting SolderPaste G-Code...")
  4259. path_count = 0
  4260. current_pt = (0, 0)
  4261. # variables to display the percentage of work done
  4262. geo_len = len(flat_geometry)
  4263. old_disp_number = 0
  4264. pt, geo = storage.nearest(current_pt)
  4265. try:
  4266. while True:
  4267. if self.app.abort_flag:
  4268. # graceful abort requested by the user
  4269. raise grace
  4270. path_count += 1
  4271. # Remove before modifying, otherwise deletion will fail.
  4272. storage.remove(geo)
  4273. # If last point in geometry is the nearest but prefer the first one if last point == first point
  4274. # then reverse coordinates.
  4275. if pt != geo.coords[0] and pt == geo.coords[-1]:
  4276. geo.coords = list(geo.coords)[::-1]
  4277. self.gcode += self.create_soldepaste_gcode(geo, p=p, old_point=current_pt)
  4278. current_pt = geo.coords[-1]
  4279. pt, geo = storage.nearest(current_pt) # Next
  4280. disp_number = int(np.interp(path_count, [0, geo_len], [0, 100]))
  4281. if old_disp_number < disp_number <= 100:
  4282. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  4283. old_disp_number = disp_number
  4284. except StopIteration: # Nothing found in storage.
  4285. pass
  4286. log.debug("Finishing SolderPste G-Code... %s paths traced." % path_count)
  4287. self.app.inform.emit(
  4288. '%s... %s %s' % (_("Finished SolderPaste G-Code generation"), str(path_count), _("paths traced."))
  4289. )
  4290. # Finish
  4291. self.gcode += self.doformat(p.lift_code)
  4292. self.gcode += self.doformat(p.end_code)
  4293. return self.gcode
  4294. def create_soldepaste_gcode(self, geometry, p, old_point=(0, 0)):
  4295. gcode = ''
  4296. path = geometry.coords
  4297. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  4298. if self.coordinates_type == "G90":
  4299. # For Absolute coordinates type G90
  4300. first_x = path[0][0]
  4301. first_y = path[0][1]
  4302. else:
  4303. # For Incremental coordinates type G91
  4304. first_x = path[0][0] - old_point[0]
  4305. first_y = path[0][1] - old_point[1]
  4306. if type(geometry) == LineString or type(geometry) == LinearRing:
  4307. # Move fast to 1st point
  4308. gcode += self.doformat(p.rapid_code, x=first_x, y=first_y) # Move to first point
  4309. # Move down to cutting depth
  4310. gcode += self.doformat(p.z_feedrate_code)
  4311. gcode += self.doformat(p.down_z_start_code)
  4312. gcode += self.doformat(p.spindle_fwd_code) # Start dispensing
  4313. gcode += self.doformat(p.dwell_fwd_code)
  4314. gcode += self.doformat(p.feedrate_z_dispense_code)
  4315. gcode += self.doformat(p.lift_z_dispense_code)
  4316. gcode += self.doformat(p.feedrate_xy_code)
  4317. # Cutting...
  4318. prev_x = first_x
  4319. prev_y = first_y
  4320. for pt in path[1:]:
  4321. if self.coordinates_type == "G90":
  4322. # For Absolute coordinates type G90
  4323. next_x = pt[0]
  4324. next_y = pt[1]
  4325. else:
  4326. # For Incremental coordinates type G91
  4327. next_x = pt[0] - prev_x
  4328. next_y = pt[1] - prev_y
  4329. gcode += self.doformat(p.linear_code, x=next_x, y=next_y) # Linear motion to point
  4330. prev_x = next_x
  4331. prev_y = next_y
  4332. # Up to travelling height.
  4333. gcode += self.doformat(p.spindle_off_code) # Stop dispensing
  4334. gcode += self.doformat(p.spindle_rev_code)
  4335. gcode += self.doformat(p.down_z_stop_code)
  4336. gcode += self.doformat(p.spindle_off_code)
  4337. gcode += self.doformat(p.dwell_rev_code)
  4338. gcode += self.doformat(p.z_feedrate_code)
  4339. gcode += self.doformat(p.lift_code)
  4340. elif type(geometry) == Point:
  4341. gcode += self.doformat(p.linear_code, x=first_x, y=first_y) # Move to first point
  4342. gcode += self.doformat(p.feedrate_z_dispense_code)
  4343. gcode += self.doformat(p.down_z_start_code)
  4344. gcode += self.doformat(p.spindle_fwd_code) # Start dispensing
  4345. gcode += self.doformat(p.dwell_fwd_code)
  4346. gcode += self.doformat(p.lift_z_dispense_code)
  4347. gcode += self.doformat(p.spindle_off_code) # Stop dispensing
  4348. gcode += self.doformat(p.spindle_rev_code)
  4349. gcode += self.doformat(p.spindle_off_code)
  4350. gcode += self.doformat(p.down_z_stop_code)
  4351. gcode += self.doformat(p.dwell_rev_code)
  4352. gcode += self.doformat(p.z_feedrate_code)
  4353. gcode += self.doformat(p.lift_code)
  4354. return gcode
  4355. def create_gcode_single_pass(self, geometry, cdia, extracut, extracut_length, tolerance, z_move, old_point=(0, 0)):
  4356. """
  4357. # G-code. Note: self.linear2gcode() and self.point2gcode() will lower and raise the tool every time.
  4358. :param geometry: A Shapely Geometry (LineString or LinearRing) which is the path to be cut
  4359. :type geometry: LineString, LinearRing
  4360. :param cdia: Tool diameter
  4361. :type cdia: float
  4362. :param extracut: Will add an extra cut over the point where start of the cut is met with the end cut
  4363. :type extracut: bool
  4364. :param extracut_length: The length of the extra cut: half before the meeting point, half after
  4365. :type extracut_length: float
  4366. :param tolerance: Tolerance used to simplify the paths (making them mre rough)
  4367. :type tolerance: float
  4368. :param z_move: Travel Z
  4369. :type z_move: float
  4370. :param old_point: Previous point
  4371. :type old_point: tuple
  4372. :return: Gcode
  4373. :rtype: str
  4374. """
  4375. # p = postproc
  4376. if type(geometry) == LineString or type(geometry) == LinearRing:
  4377. if extracut is False or not geometry.is_ring:
  4378. gcode_single_pass = self.linear2gcode(geometry, cdia, z_move=z_move, tolerance=tolerance,
  4379. old_point=old_point)
  4380. else:
  4381. gcode_single_pass = self.linear2gcode_extra(geometry, cdia, extracut_length, tolerance=tolerance,
  4382. z_move=z_move, old_point=old_point)
  4383. elif type(geometry) == Point:
  4384. gcode_single_pass = self.point2gcode(geometry, cdia, z_move=z_move, old_point=old_point)
  4385. else:
  4386. log.warning("G-code generation not implemented for %s" % (str(type(geometry))))
  4387. return
  4388. return gcode_single_pass
  4389. def create_gcode_multi_pass(self, geometry, cdia, extracut, extracut_length, tolerance, postproc, z_move,
  4390. old_point=(0, 0)):
  4391. """
  4392. :param geometry: A Shapely Geometry (LineString or LinearRing) which is the path to be cut
  4393. :type geometry: LineString, LinearRing
  4394. :param cdia: Tool diameter
  4395. :type cdia: float
  4396. :param extracut: Will add an extra cut over the point where start of the cut is met with the end cut
  4397. :type extracut: bool
  4398. :param extracut_length: The length of the extra cut: half before the meeting point, half after
  4399. :type extracut_length: float
  4400. :param tolerance: Tolerance used to simplify the paths (making them mre rough)
  4401. :type tolerance: float
  4402. :param postproc: Preprocessor class
  4403. :type postproc: class
  4404. :param z_move: Travel Z
  4405. :type z_move: float
  4406. :param old_point: Previous point
  4407. :type old_point: tuple
  4408. :return: Gcode
  4409. :rtype: str
  4410. """
  4411. p = postproc
  4412. gcode_multi_pass = ''
  4413. if isinstance(self.z_cut, Decimal):
  4414. z_cut = self.z_cut
  4415. else:
  4416. z_cut = Decimal(self.z_cut).quantize(Decimal('0.000000001'))
  4417. if self.z_depthpercut is None:
  4418. self.z_depthpercut = z_cut
  4419. elif not isinstance(self.z_depthpercut, Decimal):
  4420. self.z_depthpercut = Decimal(self.z_depthpercut).quantize(Decimal('0.000000001'))
  4421. depth = 0
  4422. reverse = False
  4423. while depth > z_cut:
  4424. # Increase depth. Limit to z_cut.
  4425. depth -= self.z_depthpercut
  4426. if depth < z_cut:
  4427. depth = z_cut
  4428. # Cut at specific depth and do not lift the tool.
  4429. # Note: linear2gcode() will use G00 to move to the first point in the path, but it should be already
  4430. # at the first point if the tool is down (in the material). So, an extra G00 should show up but
  4431. # is inconsequential.
  4432. if type(geometry) == LineString or type(geometry) == LinearRing:
  4433. if extracut is False or not geometry.is_ring:
  4434. gcode_multi_pass += self.linear2gcode(geometry, cdia, tolerance=tolerance, z_cut=depth, up=False,
  4435. z_move=z_move, old_point=old_point)
  4436. else:
  4437. gcode_multi_pass += self.linear2gcode_extra(geometry, cdia, extracut_length, tolerance=tolerance,
  4438. z_move=z_move, z_cut=depth, up=False,
  4439. old_point=old_point)
  4440. # Ignore multi-pass for points.
  4441. elif type(geometry) == Point:
  4442. gcode_multi_pass += self.point2gcode(geometry, cdia, z_move=z_move, old_point=old_point)
  4443. break # Ignoring ...
  4444. else:
  4445. log.warning("G-code generation not implemented for %s" % (str(type(geometry))))
  4446. # Reverse coordinates if not a loop so we can continue cutting without returning to the beginning.
  4447. if type(geometry) == LineString:
  4448. geometry.coords = list(geometry.coords)[::-1]
  4449. reverse = True
  4450. # If geometry is reversed, revert.
  4451. if reverse:
  4452. if type(geometry) == LineString:
  4453. geometry.coords = list(geometry.coords)[::-1]
  4454. # Lift the tool
  4455. gcode_multi_pass += self.doformat(p.lift_code, x=old_point[0], y=old_point[1])
  4456. return gcode_multi_pass
  4457. def codes_split(self, gline):
  4458. """
  4459. Parses a line of G-Code such as "G01 X1234 Y987" into
  4460. a dictionary: {'G': 1.0, 'X': 1234.0, 'Y': 987.0}
  4461. :param gline: G-Code line string
  4462. :type gline: str
  4463. :return: Dictionary with parsed line.
  4464. :rtype: dict
  4465. """
  4466. command = {}
  4467. if 'Roland' in self.pp_excellon_name or 'Roland' in self.pp_geometry_name:
  4468. match_z = re.search(r"^Z(\s*-?\d+\.\d+?),(\s*\s*-?\d+\.\d+?),(\s*\s*-?\d+\.\d+?)*;$", gline)
  4469. if match_z:
  4470. command['G'] = 0
  4471. command['X'] = float(match_z.group(1).replace(" ", "")) * 0.025
  4472. command['Y'] = float(match_z.group(2).replace(" ", "")) * 0.025
  4473. command['Z'] = float(match_z.group(3).replace(" ", "")) * 0.025
  4474. elif 'hpgl' in self.pp_excellon_name or 'hpgl' in self.pp_geometry_name:
  4475. match_pa = re.search(r"^PA(\s*-?\d+\.\d+?),(\s*\s*-?\d+\.\d+?)*;$", gline)
  4476. if match_pa:
  4477. command['G'] = 0
  4478. command['X'] = float(match_pa.group(1).replace(" ", "")) / 40
  4479. command['Y'] = float(match_pa.group(2).replace(" ", "")) / 40
  4480. match_pen = re.search(r"^(P[U|D])", gline)
  4481. if match_pen:
  4482. if match_pen.group(1) == 'PU':
  4483. # the value does not matter, only that it is positive so the gcode_parse() know it is > 0,
  4484. # therefore the move is of kind T (travel)
  4485. command['Z'] = 1
  4486. else:
  4487. command['Z'] = 0
  4488. elif 'laser' in self.pp_excellon_name.lower() or 'laser' in self.pp_geometry_name.lower() or \
  4489. (self.pp_solderpaste_name is not None and 'paste' in self.pp_solderpaste_name.lower()):
  4490. match_lsr = re.search(r"X([\+-]?\d+.[\+-]?\d+)\s*Y([\+-]?\d+.[\+-]?\d+)", gline)
  4491. if match_lsr:
  4492. command['X'] = float(match_lsr.group(1).replace(" ", ""))
  4493. command['Y'] = float(match_lsr.group(2).replace(" ", ""))
  4494. match_lsr_pos = re.search(r"^(M0?[3-5])", gline)
  4495. if match_lsr_pos:
  4496. if 'M05' in match_lsr_pos.group(1) or 'M5' in match_lsr_pos.group(1):
  4497. # the value does not matter, only that it is positive so the gcode_parse() know it is > 0,
  4498. # therefore the move is of kind T (travel)
  4499. command['Z'] = 1
  4500. else:
  4501. command['Z'] = 0
  4502. match_lsr_pos_2 = re.search(r"^(M10[6|7])", gline)
  4503. if match_lsr_pos_2:
  4504. if 'M107' in match_lsr_pos_2.group(1):
  4505. command['Z'] = 1
  4506. else:
  4507. command['Z'] = 0
  4508. elif self.pp_solderpaste_name is not None:
  4509. if 'Paste' in self.pp_solderpaste_name:
  4510. match_paste = re.search(r"X([\+-]?\d+.[\+-]?\d+)\s*Y([\+-]?\d+.[\+-]?\d+)", gline)
  4511. if match_paste:
  4512. command['X'] = float(match_paste.group(1).replace(" ", ""))
  4513. command['Y'] = float(match_paste.group(2).replace(" ", ""))
  4514. else:
  4515. match = re.search(r'^\s*([A-Z])\s*([\+\-\.\d\s]+)', gline)
  4516. while match:
  4517. command[match.group(1)] = float(match.group(2).replace(" ", ""))
  4518. gline = gline[match.end():]
  4519. match = re.search(r'^\s*([A-Z])\s*([\+\-\.\d\s]+)', gline)
  4520. return command
  4521. def gcode_parse(self, force_parsing=None):
  4522. """
  4523. G-Code parser (from self.gcode). Generates dictionary with
  4524. single-segment LineString's and "kind" indicating cut or travel,
  4525. fast or feedrate speed.
  4526. Will return a dict in the format:
  4527. {
  4528. "geom": LineString(path),
  4529. "kind": kind
  4530. }
  4531. where kind can be either ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  4532. :param force_parsing:
  4533. :type force_parsing:
  4534. :return:
  4535. :rtype: dict
  4536. """
  4537. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  4538. # Results go here
  4539. geometry = []
  4540. # Last known instruction
  4541. current = {'X': 0.0, 'Y': 0.0, 'Z': 0.0, 'G': 0}
  4542. # Current path: temporary storage until tool is
  4543. # lifted or lowered.
  4544. if self.toolchange_xy_type == "excellon":
  4545. if self.app.defaults["excellon_toolchangexy"] == '' or self.app.defaults["excellon_toolchangexy"] is None:
  4546. pos_xy = (0, 0)
  4547. else:
  4548. pos_xy = self.app.defaults["excellon_toolchangexy"]
  4549. try:
  4550. pos_xy = [float(eval(a)) for a in pos_xy.split(",")]
  4551. except Exception:
  4552. if len(pos_xy) != 2:
  4553. pos_xy = (0, 0)
  4554. else:
  4555. if self.app.defaults["geometry_toolchangexy"] == '' or self.app.defaults["geometry_toolchangexy"] is None:
  4556. pos_xy = (0, 0)
  4557. else:
  4558. pos_xy = self.app.defaults["geometry_toolchangexy"]
  4559. try:
  4560. pos_xy = [float(eval(a)) for a in pos_xy.split(",")]
  4561. except Exception:
  4562. if len(pos_xy) != 2:
  4563. pos_xy = (0, 0)
  4564. path = [pos_xy]
  4565. # path = [(0, 0)]
  4566. gcode_lines_list = self.gcode.splitlines()
  4567. self.app.inform.emit('%s: %d' % (_("Parsing GCode file. Number of lines"), len(gcode_lines_list)))
  4568. # Process every instruction
  4569. for line in gcode_lines_list:
  4570. if force_parsing is False or force_parsing is None:
  4571. if '%MO' in line or '%' in line or 'MOIN' in line or 'MOMM' in line:
  4572. return "fail"
  4573. gobj = self.codes_split(line)
  4574. # ## Units
  4575. if 'G' in gobj and (gobj['G'] == 20.0 or gobj['G'] == 21.0):
  4576. self.units = {20.0: "IN", 21.0: "MM"}[gobj['G']]
  4577. continue
  4578. # TODO take into consideration the tools and update the travel line thickness
  4579. if 'T' in gobj:
  4580. pass
  4581. # ## Changing height
  4582. if 'Z' in gobj:
  4583. if 'Roland' in self.pp_excellon_name or 'Roland' in self.pp_geometry_name:
  4584. pass
  4585. elif 'hpgl' in self.pp_excellon_name or 'hpgl' in self.pp_geometry_name:
  4586. pass
  4587. elif 'laser' in self.pp_excellon_name or 'laser' in self.pp_geometry_name:
  4588. pass
  4589. elif ('X' in gobj or 'Y' in gobj) and gobj['Z'] != current['Z']:
  4590. if self.pp_geometry_name == 'line_xyz' or self.pp_excellon_name == 'line_xyz':
  4591. pass
  4592. else:
  4593. log.warning("Non-orthogonal motion: From %s" % str(current))
  4594. log.warning(" To: %s" % str(gobj))
  4595. current['Z'] = gobj['Z']
  4596. # Store the path into geometry and reset path
  4597. if len(path) > 1:
  4598. geometry.append({"geom": LineString(path),
  4599. "kind": kind})
  4600. path = [path[-1]] # Start with the last point of last path.
  4601. # create the geometry for the holes created when drilling Excellon drills
  4602. if self.origin_kind == 'excellon':
  4603. if current['Z'] < 0:
  4604. current_drill_point_coords = (
  4605. float('%.*f' % (self.decimals, current['X'])),
  4606. float('%.*f' % (self.decimals, current['Y']))
  4607. )
  4608. # find the drill diameter knowing the drill coordinates
  4609. break_loop = False
  4610. for tool, tool_dict in self.exc_tools.items():
  4611. if 'drills' in tool_dict:
  4612. for drill_pt in tool_dict['drills']:
  4613. point_in_dict_coords = (
  4614. float('%.*f' % (self.decimals, drill_pt.x)),
  4615. float('%.*f' % (self.decimals, drill_pt.y))
  4616. )
  4617. if point_in_dict_coords == current_drill_point_coords:
  4618. dia = self.exc_tools[tool]['tooldia']
  4619. kind = ['C', 'F']
  4620. geometry.append(
  4621. {
  4622. "geom": Point(current_drill_point_coords).buffer(dia / 2.0).exterior,
  4623. "kind": kind
  4624. }
  4625. )
  4626. break_loop = True
  4627. break
  4628. if break_loop:
  4629. break
  4630. if 'G' in gobj:
  4631. current['G'] = int(gobj['G'])
  4632. if 'X' in gobj or 'Y' in gobj:
  4633. if 'X' in gobj:
  4634. x = gobj['X']
  4635. # current['X'] = x
  4636. else:
  4637. x = current['X']
  4638. if 'Y' in gobj:
  4639. y = gobj['Y']
  4640. else:
  4641. y = current['Y']
  4642. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  4643. if current['Z'] > 0:
  4644. kind[0] = 'T'
  4645. if current['G'] > 0:
  4646. kind[1] = 'S'
  4647. if current['G'] in [0, 1]: # line
  4648. path.append((x, y))
  4649. arcdir = [None, None, "cw", "ccw"]
  4650. if current['G'] in [2, 3]: # arc
  4651. center = [gobj['I'] + current['X'], gobj['J'] + current['Y']]
  4652. radius = np.sqrt(gobj['I'] ** 2 + gobj['J'] ** 2)
  4653. start = np.arctan2(-gobj['J'], -gobj['I'])
  4654. stop = np.arctan2(-center[1] + y, -center[0] + x)
  4655. path += arc(center, radius, start, stop, arcdir[current['G']], int(self.steps_per_circle))
  4656. current['X'] = x
  4657. current['Y'] = y
  4658. # Update current instruction
  4659. for code in gobj:
  4660. current[code] = gobj[code]
  4661. self.app.inform.emit('%s...' % _("Creating Geometry from the parsed GCode file. "))
  4662. # There might not be a change in height at the
  4663. # end, therefore, see here too if there is
  4664. # a final path.
  4665. if len(path) > 1:
  4666. geometry.append(
  4667. {
  4668. "geom": LineString(path),
  4669. "kind": kind
  4670. }
  4671. )
  4672. self.gcode_parsed = geometry
  4673. return geometry
  4674. # def plot(self, tooldia=None, dpi=75, margin=0.1,
  4675. # color={"T": ["#F0E24D", "#B5AB3A"], "C": ["#5E6CFF", "#4650BD"]},
  4676. # alpha={"T": 0.3, "C": 1.0}):
  4677. # """
  4678. # Creates a Matplotlib figure with a plot of the
  4679. # G-code job.
  4680. # """
  4681. # if tooldia is None:
  4682. # tooldia = self.tooldia
  4683. #
  4684. # fig = Figure(dpi=dpi)
  4685. # ax = fig.add_subplot(111)
  4686. # ax.set_aspect(1)
  4687. # xmin, ymin, xmax, ymax = self.input_geometry_bounds
  4688. # ax.set_xlim(xmin-margin, xmax+margin)
  4689. # ax.set_ylim(ymin-margin, ymax+margin)
  4690. #
  4691. # if tooldia == 0:
  4692. # for geo in self.gcode_parsed:
  4693. # linespec = '--'
  4694. # linecolor = color[geo['kind'][0]][1]
  4695. # if geo['kind'][0] == 'C':
  4696. # linespec = 'k-'
  4697. # x, y = geo['geom'].coords.xy
  4698. # ax.plot(x, y, linespec, color=linecolor)
  4699. # else:
  4700. # for geo in self.gcode_parsed:
  4701. # poly = geo['geom'].buffer(tooldia/2.0)
  4702. # patch = PolygonPatch(poly, facecolor=color[geo['kind'][0]][0],
  4703. # edgecolor=color[geo['kind'][0]][1],
  4704. # alpha=alpha[geo['kind'][0]], zorder=2)
  4705. # ax.add_patch(patch)
  4706. #
  4707. # return fig
  4708. def plot2(self, tooldia=None, dpi=75, margin=0.1, gcode_parsed=None,
  4709. color=None, alpha={"T": 0.3, "C": 1.0}, tool_tolerance=0.0005, obj=None, visible=False, kind='all'):
  4710. """
  4711. Plots the G-code job onto the given axes.
  4712. :param tooldia: Tool diameter.
  4713. :type tooldia: float
  4714. :param dpi: Not used!
  4715. :type dpi: float
  4716. :param margin: Not used!
  4717. :type margin: float
  4718. :param gcode_parsed: Parsed Gcode
  4719. :type gcode_parsed: str
  4720. :param color: Color specification.
  4721. :type color: str
  4722. :param alpha: Transparency specification.
  4723. :type alpha: dict
  4724. :param tool_tolerance: Tolerance when drawing the toolshape.
  4725. :type tool_tolerance: float
  4726. :param obj: The object for whih to plot
  4727. :type obj: class
  4728. :param visible: Visibility status
  4729. :type visible: bool
  4730. :param kind: Can be: "travel", "cut", "all"
  4731. :type kind: str
  4732. :return: None
  4733. :rtype:
  4734. """
  4735. # units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4736. if color is None:
  4737. color = {
  4738. "T": [self.app.defaults["cncjob_travel_fill"], self.app.defaults["cncjob_travel_line"]],
  4739. "C": [self.app.defaults["cncjob_plot_fill"], self.app.defaults["cncjob_plot_line"]]
  4740. }
  4741. gcode_parsed = gcode_parsed if gcode_parsed else self.gcode_parsed
  4742. path_num = 0
  4743. if tooldia is None:
  4744. tooldia = self.tooldia
  4745. # this should be unlikely unless when upstream the tooldia is a tuple made by one dia and a comma like (2.4,)
  4746. if isinstance(tooldia, list):
  4747. tooldia = tooldia[0] if tooldia[0] is not None else self.tooldia
  4748. if tooldia == 0:
  4749. for geo in gcode_parsed:
  4750. if kind == 'all':
  4751. obj.add_shape(shape=geo['geom'], color=color[geo['kind'][0]][1], visible=visible)
  4752. elif kind == 'travel':
  4753. if geo['kind'][0] == 'T':
  4754. obj.add_shape(shape=geo['geom'], color=color['T'][1], visible=visible)
  4755. elif kind == 'cut':
  4756. if geo['kind'][0] == 'C':
  4757. obj.add_shape(shape=geo['geom'], color=color['C'][1], visible=visible)
  4758. else:
  4759. text = []
  4760. pos = []
  4761. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  4762. if self.coordinates_type == "G90":
  4763. # For Absolute coordinates type G90
  4764. for geo in gcode_parsed:
  4765. if geo['kind'][0] == 'T':
  4766. current_position = geo['geom'].coords[0]
  4767. if current_position not in pos:
  4768. pos.append(current_position)
  4769. path_num += 1
  4770. text.append(str(path_num))
  4771. current_position = geo['geom'].coords[-1]
  4772. if current_position not in pos:
  4773. pos.append(current_position)
  4774. path_num += 1
  4775. text.append(str(path_num))
  4776. # plot the geometry of Excellon objects
  4777. if self.origin_kind == 'excellon':
  4778. try:
  4779. if geo['kind'][0] == 'T':
  4780. # if the geos are travel lines it will enter into Exception
  4781. poly = geo['geom'].buffer(distance=(tooldia / 1.99999999),
  4782. resolution=self.steps_per_circle)
  4783. else:
  4784. poly = Polygon(geo['geom'])
  4785. poly = poly.simplify(tool_tolerance)
  4786. except Exception:
  4787. # deal here with unexpected plot errors due of LineStrings not valid
  4788. continue
  4789. # try:
  4790. # poly = Polygon(geo['geom'])
  4791. # except ValueError:
  4792. # # if the geos are travel lines it will enter into Exception
  4793. # poly = geo['geom'].buffer(distance=(tooldia / 1.99999999), resolution=self.steps_per_circle)
  4794. # poly = poly.simplify(tool_tolerance)
  4795. # except Exception:
  4796. # # deal here with unexpected plot errors due of LineStrings not valid
  4797. # continue
  4798. else:
  4799. # plot the geometry of any objects other than Excellon
  4800. poly = geo['geom'].buffer(distance=(tooldia / 1.99999999), resolution=self.steps_per_circle)
  4801. poly = poly.simplify(tool_tolerance)
  4802. if kind == 'all':
  4803. obj.add_shape(shape=poly, color=color[geo['kind'][0]][1], face_color=color[geo['kind'][0]][0],
  4804. visible=visible, layer=1 if geo['kind'][0] == 'C' else 2)
  4805. elif kind == 'travel':
  4806. if geo['kind'][0] == 'T':
  4807. obj.add_shape(shape=poly, color=color['T'][1], face_color=color['T'][0],
  4808. visible=visible, layer=2)
  4809. elif kind == 'cut':
  4810. if geo['kind'][0] == 'C':
  4811. obj.add_shape(shape=poly, color=color['C'][1], face_color=color['C'][0],
  4812. visible=visible, layer=1)
  4813. else:
  4814. # For Incremental coordinates type G91
  4815. self.app.inform.emit('[ERROR_NOTCL] %s' % _('G91 coordinates not implemented ...'))
  4816. for geo in gcode_parsed:
  4817. if geo['kind'][0] == 'T':
  4818. current_position = geo['geom'].coords[0]
  4819. if current_position not in pos:
  4820. pos.append(current_position)
  4821. path_num += 1
  4822. text.append(str(path_num))
  4823. current_position = geo['geom'].coords[-1]
  4824. if current_position not in pos:
  4825. pos.append(current_position)
  4826. path_num += 1
  4827. text.append(str(path_num))
  4828. # plot the geometry of Excellon objects
  4829. if self.origin_kind == 'excellon':
  4830. try:
  4831. poly = Polygon(geo['geom'])
  4832. except ValueError:
  4833. # if the geos are travel lines it will enter into Exception
  4834. poly = geo['geom'].buffer(distance=(tooldia / 1.99999999), resolution=self.steps_per_circle)
  4835. poly = poly.simplify(tool_tolerance)
  4836. else:
  4837. # plot the geometry of any objects other than Excellon
  4838. poly = geo['geom'].buffer(distance=(tooldia / 1.99999999), resolution=self.steps_per_circle)
  4839. poly = poly.simplify(tool_tolerance)
  4840. if kind == 'all':
  4841. obj.add_shape(shape=poly, color=color[geo['kind'][0]][1], face_color=color[geo['kind'][0]][0],
  4842. visible=visible, layer=1 if geo['kind'][0] == 'C' else 2)
  4843. elif kind == 'travel':
  4844. if geo['kind'][0] == 'T':
  4845. obj.add_shape(shape=poly, color=color['T'][1], face_color=color['T'][0],
  4846. visible=visible, layer=2)
  4847. elif kind == 'cut':
  4848. if geo['kind'][0] == 'C':
  4849. obj.add_shape(shape=poly, color=color['C'][1], face_color=color['C'][0],
  4850. visible=visible, layer=1)
  4851. try:
  4852. if self.app.defaults['global_theme'] == 'white':
  4853. obj.annotation.set(text=text, pos=pos, visible=obj.options['plot'],
  4854. font_size=self.app.defaults["cncjob_annotation_fontsize"],
  4855. color=self.app.defaults["cncjob_annotation_fontcolor"])
  4856. else:
  4857. # invert the color
  4858. old_color = self.app.defaults["cncjob_annotation_fontcolor"].lower()
  4859. new_color = ''
  4860. code = {}
  4861. l1 = "#;0123456789abcdef"
  4862. l2 = "#;fedcba9876543210"
  4863. for i in range(len(l1)):
  4864. code[l1[i]] = l2[i]
  4865. for x in range(len(old_color)):
  4866. new_color += code[old_color[x]]
  4867. obj.annotation.set(text=text, pos=pos, visible=obj.options['plot'],
  4868. font_size=self.app.defaults["cncjob_annotation_fontsize"],
  4869. color=new_color)
  4870. except Exception as e:
  4871. log.debug("CNCJob.plot2() --> annotations --> %s" % str(e))
  4872. def create_geometry(self):
  4873. """
  4874. It is used by the Excellon objects. Will create the solid_geometry which will be an attribute of the
  4875. Excellon object class.
  4876. :return: List of Shapely geometry elements
  4877. :rtype: list
  4878. """
  4879. # TODO: This takes forever. Too much data?
  4880. # self.app.inform.emit('%s: %s' % (_("Unifying Geometry from parsed Geometry segments"),
  4881. # str(len(self.gcode_parsed))))
  4882. # self.solid_geometry = cascaded_union([geo['geom'] for geo in self.gcode_parsed])
  4883. # This is much faster but not so nice to look at as you can see different segments of the geometry
  4884. self.solid_geometry = [geo['geom'] for geo in self.gcode_parsed]
  4885. return self.solid_geometry
  4886. def segment(self, coords):
  4887. """
  4888. Break long linear lines to make it more auto level friendly.
  4889. Code snippet added by Lei Zheng in a rejected pull request on FlatCAM https://bitbucket.org/realthunder/
  4890. :param coords: List of coordinates tuples
  4891. :type coords: list
  4892. :return: A path; list with the multiple coordinates breaking a line.
  4893. :rtype: list
  4894. """
  4895. if len(coords) < 2 or self.segx <= 0 and self.segy <= 0:
  4896. return list(coords)
  4897. path = [coords[0]]
  4898. # break the line in either x or y dimension only
  4899. def linebreak_single(line, dim, dmax):
  4900. if dmax <= 0:
  4901. return None
  4902. if line[1][dim] > line[0][dim]:
  4903. sign = 1.0
  4904. d = line[1][dim] - line[0][dim]
  4905. else:
  4906. sign = -1.0
  4907. d = line[0][dim] - line[1][dim]
  4908. if d > dmax:
  4909. # make sure we don't make any new lines too short
  4910. if d > dmax * 2:
  4911. dd = dmax
  4912. else:
  4913. dd = d / 2
  4914. other = dim ^ 1
  4915. return (line[0][dim] + dd * sign, line[0][other] + \
  4916. dd * (line[1][other] - line[0][other]) / d)
  4917. return None
  4918. # recursively breaks down a given line until it is within the
  4919. # required step size
  4920. def linebreak(line):
  4921. pt_new = linebreak_single(line, 0, self.segx)
  4922. if pt_new is None:
  4923. pt_new2 = linebreak_single(line, 1, self.segy)
  4924. else:
  4925. pt_new2 = linebreak_single((line[0], pt_new), 1, self.segy)
  4926. if pt_new2 is not None:
  4927. pt_new = pt_new2[::-1]
  4928. if pt_new is None:
  4929. path.append(line[1])
  4930. else:
  4931. path.append(pt_new)
  4932. linebreak((pt_new, line[1]))
  4933. for pt in coords[1:]:
  4934. linebreak((path[-1], pt))
  4935. return path
  4936. def linear2gcode(self, linear, dia, tolerance=0, down=True, up=True, z_cut=None, z_move=None, zdownrate=None,
  4937. feedrate=None, feedrate_z=None, feedrate_rapid=None, cont=False, old_point=(0, 0)):
  4938. """
  4939. Generates G-code to cut along the linear feature.
  4940. :param linear: The path to cut along.
  4941. :type: Shapely.LinearRing or Shapely.Linear String
  4942. :param dia: The tool diameter that is going on the path
  4943. :type dia: float
  4944. :param tolerance: All points in the simplified object will be within the
  4945. tolerance distance of the original geometry.
  4946. :type tolerance: float
  4947. :param down:
  4948. :param up:
  4949. :param z_cut:
  4950. :param z_move:
  4951. :param zdownrate:
  4952. :param feedrate: speed for cut on X - Y plane
  4953. :param feedrate_z: speed for cut on Z plane
  4954. :param feedrate_rapid: speed to move between cuts; usually is G0 but some CNC require to specify it
  4955. :param cont:
  4956. :param old_point:
  4957. :return: G-code to cut along the linear feature.
  4958. """
  4959. if z_cut is None:
  4960. z_cut = self.z_cut
  4961. if z_move is None:
  4962. z_move = self.z_move
  4963. #
  4964. # if zdownrate is None:
  4965. # zdownrate = self.zdownrate
  4966. if feedrate is None:
  4967. feedrate = self.feedrate
  4968. if feedrate_z is None:
  4969. feedrate_z = self.z_feedrate
  4970. if feedrate_rapid is None:
  4971. feedrate_rapid = self.feedrate_rapid
  4972. # Simplify paths?
  4973. if tolerance > 0:
  4974. target_linear = linear.simplify(tolerance)
  4975. else:
  4976. target_linear = linear
  4977. gcode = ""
  4978. # path = list(target_linear.coords)
  4979. path = self.segment(target_linear.coords)
  4980. p = self.pp_geometry
  4981. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  4982. if self.coordinates_type == "G90":
  4983. # For Absolute coordinates type G90
  4984. first_x = path[0][0]
  4985. first_y = path[0][1]
  4986. else:
  4987. # For Incremental coordinates type G91
  4988. first_x = path[0][0] - old_point[0]
  4989. first_y = path[0][1] - old_point[1]
  4990. # Move fast to 1st point
  4991. if not cont:
  4992. current_tooldia = dia
  4993. travels = self.app.exc_areas.travel_coordinates(start_point=(old_point[0], old_point[1]),
  4994. end_point=(first_x, first_y),
  4995. tooldia=current_tooldia)
  4996. prev_z = None
  4997. for travel in travels:
  4998. locx = travel[1][0]
  4999. locy = travel[1][1]
  5000. if travel[0] is not None:
  5001. # move to next point
  5002. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  5003. # raise to safe Z (travel[0]) each time because safe Z may be different
  5004. self.z_move = travel[0]
  5005. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  5006. # restore z_move
  5007. self.z_move = z_move
  5008. else:
  5009. if prev_z is not None:
  5010. # move to next point
  5011. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  5012. # we assume that previously the z_move was altered therefore raise to
  5013. # the travel_z (z_move)
  5014. self.z_move = z_move
  5015. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  5016. else:
  5017. # move to next point
  5018. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  5019. # store prev_z
  5020. prev_z = travel[0]
  5021. # gcode += self.doformat(p.rapid_code, x=first_x, y=first_y) # Move to first point
  5022. # Move down to cutting depth
  5023. if down:
  5024. # Different feedrate for vertical cut?
  5025. gcode += self.doformat(p.z_feedrate_code)
  5026. # gcode += self.doformat(p.feedrate_code)
  5027. gcode += self.doformat(p.down_code, x=first_x, y=first_y, z_cut=z_cut)
  5028. gcode += self.doformat(p.feedrate_code, feedrate=feedrate)
  5029. # Cutting...
  5030. prev_x = first_x
  5031. prev_y = first_y
  5032. for pt in path[1:]:
  5033. if self.app.abort_flag:
  5034. # graceful abort requested by the user
  5035. raise grace
  5036. if self.coordinates_type == "G90":
  5037. # For Absolute coordinates type G90
  5038. next_x = pt[0]
  5039. next_y = pt[1]
  5040. else:
  5041. # For Incremental coordinates type G91
  5042. # next_x = pt[0] - prev_x
  5043. # next_y = pt[1] - prev_y
  5044. self.app.inform.emit('[ERROR_NOTCL] %s' % _('G91 coordinates not implemented ...'))
  5045. next_x = pt[0]
  5046. next_y = pt[1]
  5047. gcode += self.doformat(p.linear_code, x=next_x, y=next_y, z=z_cut) # Linear motion to point
  5048. prev_x = pt[0]
  5049. prev_y = pt[1]
  5050. # Up to travelling height.
  5051. if up:
  5052. gcode += self.doformat(p.lift_code, x=prev_x, y=prev_y, z_move=z_move) # Stop cutting
  5053. return gcode
  5054. def linear2gcode_extra(self, linear, dia, extracut_length, tolerance=0, down=True, up=True,
  5055. z_cut=None, z_move=None, zdownrate=None,
  5056. feedrate=None, feedrate_z=None, feedrate_rapid=None, cont=False, old_point=(0, 0)):
  5057. """
  5058. Generates G-code to cut along the linear feature.
  5059. :param linear: The path to cut along.
  5060. :type: Shapely.LinearRing or Shapely.Linear String
  5061. :param dia: The tool diameter that is going on the path
  5062. :type dia: float
  5063. :param extracut_length: how much to cut extra over the first point at the end of the path
  5064. :param tolerance: All points in the simplified object will be within the
  5065. tolerance distance of the original geometry.
  5066. :type tolerance: float
  5067. :param down:
  5068. :param up:
  5069. :param z_cut:
  5070. :param z_move:
  5071. :param zdownrate:
  5072. :param feedrate: speed for cut on X - Y plane
  5073. :param feedrate_z: speed for cut on Z plane
  5074. :param feedrate_rapid: speed to move between cuts; usually is G0 but some CNC require to specify it
  5075. :param cont:
  5076. :param old_point:
  5077. :return: G-code to cut along the linear feature.
  5078. :rtype: str
  5079. """
  5080. if z_cut is None:
  5081. z_cut = self.z_cut
  5082. if z_move is None:
  5083. z_move = self.z_move
  5084. #
  5085. # if zdownrate is None:
  5086. # zdownrate = self.zdownrate
  5087. if feedrate is None:
  5088. feedrate = self.feedrate
  5089. if feedrate_z is None:
  5090. feedrate_z = self.z_feedrate
  5091. if feedrate_rapid is None:
  5092. feedrate_rapid = self.feedrate_rapid
  5093. # Simplify paths?
  5094. if tolerance > 0:
  5095. target_linear = linear.simplify(tolerance)
  5096. else:
  5097. target_linear = linear
  5098. gcode = ""
  5099. path = list(target_linear.coords)
  5100. p = self.pp_geometry
  5101. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  5102. if self.coordinates_type == "G90":
  5103. # For Absolute coordinates type G90
  5104. first_x = path[0][0]
  5105. first_y = path[0][1]
  5106. else:
  5107. # For Incremental coordinates type G91
  5108. first_x = path[0][0] - old_point[0]
  5109. first_y = path[0][1] - old_point[1]
  5110. # Move fast to 1st point
  5111. if not cont:
  5112. current_tooldia = dia
  5113. travels = self.app.exc_areas.travel_coordinates(start_point=(old_point[0], old_point[1]),
  5114. end_point=(first_x, first_y),
  5115. tooldia=current_tooldia)
  5116. prev_z = None
  5117. for travel in travels:
  5118. locx = travel[1][0]
  5119. locy = travel[1][1]
  5120. if travel[0] is not None:
  5121. # move to next point
  5122. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  5123. # raise to safe Z (travel[0]) each time because safe Z may be different
  5124. self.z_move = travel[0]
  5125. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  5126. # restore z_move
  5127. self.z_move = z_move
  5128. else:
  5129. if prev_z is not None:
  5130. # move to next point
  5131. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  5132. # we assume that previously the z_move was altered therefore raise to
  5133. # the travel_z (z_move)
  5134. self.z_move = z_move
  5135. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  5136. else:
  5137. # move to next point
  5138. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  5139. # store prev_z
  5140. prev_z = travel[0]
  5141. # gcode += self.doformat(p.rapid_code, x=first_x, y=first_y) # Move to first point
  5142. # Move down to cutting depth
  5143. if down:
  5144. # Different feedrate for vertical cut?
  5145. if self.z_feedrate is not None:
  5146. gcode += self.doformat(p.z_feedrate_code)
  5147. # gcode += self.doformat(p.feedrate_code)
  5148. gcode += self.doformat(p.down_code, x=first_x, y=first_y, z_cut=z_cut)
  5149. gcode += self.doformat(p.feedrate_code, feedrate=feedrate)
  5150. else:
  5151. gcode += self.doformat(p.down_code, x=first_x, y=first_y, z_cut=z_cut) # Start cutting
  5152. # Cutting...
  5153. prev_x = first_x
  5154. prev_y = first_y
  5155. for pt in path[1:]:
  5156. if self.app.abort_flag:
  5157. # graceful abort requested by the user
  5158. raise grace
  5159. if self.coordinates_type == "G90":
  5160. # For Absolute coordinates type G90
  5161. next_x = pt[0]
  5162. next_y = pt[1]
  5163. else:
  5164. # For Incremental coordinates type G91
  5165. # For Incremental coordinates type G91
  5166. # next_x = pt[0] - prev_x
  5167. # next_y = pt[1] - prev_y
  5168. self.app.inform.emit('[ERROR_NOTCL] %s' % _('G91 coordinates not implemented ...'))
  5169. next_x = pt[0]
  5170. next_y = pt[1]
  5171. gcode += self.doformat(p.linear_code, x=next_x, y=next_y, z=z_cut) # Linear motion to point
  5172. prev_x = next_x
  5173. prev_y = next_y
  5174. # this line is added to create an extra cut over the first point in patch
  5175. # to make sure that we remove the copper leftovers
  5176. # Linear motion to the 1st point in the cut path
  5177. # if self.coordinates_type == "G90":
  5178. # # For Absolute coordinates type G90
  5179. # last_x = path[1][0]
  5180. # last_y = path[1][1]
  5181. # else:
  5182. # # For Incremental coordinates type G91
  5183. # last_x = path[1][0] - first_x
  5184. # last_y = path[1][1] - first_y
  5185. # gcode += self.doformat(p.linear_code, x=last_x, y=last_y)
  5186. # the first point for extracut is always mandatory if the extracut is enabled. But if the length of distance
  5187. # between point 0 and point 1 is more than the distance we set for the extra cut then make an interpolation
  5188. # along the path and find the point at the distance extracut_length
  5189. if extracut_length == 0.0:
  5190. extra_path = [path[-1], path[0], path[1]]
  5191. new_x = extra_path[0][0]
  5192. new_y = extra_path[0][1]
  5193. # this is an extra line therefore lift the milling bit
  5194. gcode += self.doformat(p.lift_code, x=prev_x, y=prev_y, z_move=z_move) # lift
  5195. # move fast to the new first point
  5196. gcode += self.doformat(p.rapid_code, x=new_x, y=new_y)
  5197. # lower the milling bit
  5198. # Different feedrate for vertical cut?
  5199. if self.z_feedrate is not None:
  5200. gcode += self.doformat(p.z_feedrate_code)
  5201. gcode += self.doformat(p.down_code, x=new_x, y=new_y, z_cut=z_cut)
  5202. gcode += self.doformat(p.feedrate_code, feedrate=feedrate)
  5203. else:
  5204. gcode += self.doformat(p.down_code, x=new_x, y=new_y, z_cut=z_cut) # Start cutting
  5205. # start cutting the extra line
  5206. last_pt = extra_path[0]
  5207. for pt in extra_path[1:]:
  5208. gcode += self.doformat(p.linear_code, x=pt[0], y=pt[1])
  5209. last_pt = pt
  5210. # go back to the original point
  5211. gcode += self.doformat(p.linear_code, x=path[0][0], y=path[0][1])
  5212. last_pt = path[0]
  5213. else:
  5214. # go to the point that is 5% in length before the end (therefore 95% length from start of the line),
  5215. # along the line to be cut
  5216. if extracut_length >= target_linear.length:
  5217. extracut_length = target_linear.length
  5218. # ---------------------------------------------
  5219. # first half
  5220. # ---------------------------------------------
  5221. start_length = target_linear.length - (extracut_length * 0.5)
  5222. extra_line = substring(target_linear, start_length, target_linear.length)
  5223. extra_path = list(extra_line.coords)
  5224. new_x = extra_path[0][0]
  5225. new_y = extra_path[0][1]
  5226. # this is an extra line therefore lift the milling bit
  5227. gcode += self.doformat(p.lift_code, x=prev_x, y=prev_y, z_move=z_move) # lift
  5228. # move fast to the new first point
  5229. gcode += self.doformat(p.rapid_code, x=new_x, y=new_y)
  5230. # lower the milling bit
  5231. # Different feedrate for vertical cut?
  5232. if self.z_feedrate is not None:
  5233. gcode += self.doformat(p.z_feedrate_code)
  5234. gcode += self.doformat(p.down_code, x=new_x, y=new_y, z_cut=z_cut)
  5235. gcode += self.doformat(p.feedrate_code, feedrate=feedrate)
  5236. else:
  5237. gcode += self.doformat(p.down_code, x=new_x, y=new_y, z_cut=z_cut) # Start cutting
  5238. # start cutting the extra line
  5239. for pt in extra_path[1:]:
  5240. gcode += self.doformat(p.linear_code, x=pt[0], y=pt[1])
  5241. # ---------------------------------------------
  5242. # second half
  5243. # ---------------------------------------------
  5244. extra_line = substring(target_linear, 0, (extracut_length * 0.5))
  5245. extra_path = list(extra_line.coords)
  5246. # start cutting the extra line
  5247. last_pt = extra_path[0]
  5248. for pt in extra_path[1:]:
  5249. gcode += self.doformat(p.linear_code, x=pt[0], y=pt[1])
  5250. last_pt = pt
  5251. # ---------------------------------------------
  5252. # back to original start point, cutting
  5253. # ---------------------------------------------
  5254. extra_line = substring(target_linear, 0, (extracut_length * 0.5))
  5255. extra_path = list(extra_line.coords)[::-1]
  5256. # start cutting the extra line
  5257. last_pt = extra_path[0]
  5258. for pt in extra_path[1:]:
  5259. gcode += self.doformat(p.linear_code, x=pt[0], y=pt[1])
  5260. last_pt = pt
  5261. # if extracut_length == 0.0:
  5262. # gcode += self.doformat(p.linear_code, x=path[1][0], y=path[1][1])
  5263. # last_pt = path[1]
  5264. # else:
  5265. # if abs(distance(path[1], path[0])) > extracut_length:
  5266. # i_point = LineString([path[0], path[1]]).interpolate(extracut_length)
  5267. # gcode += self.doformat(p.linear_code, x=i_point.x, y=i_point.y)
  5268. # last_pt = (i_point.x, i_point.y)
  5269. # else:
  5270. # last_pt = path[0]
  5271. # for pt in path[1:]:
  5272. # extracut_distance = abs(distance(pt, last_pt))
  5273. # if extracut_distance <= extracut_length:
  5274. # gcode += self.doformat(p.linear_code, x=pt[0], y=pt[1])
  5275. # last_pt = pt
  5276. # else:
  5277. # break
  5278. # Up to travelling height.
  5279. if up:
  5280. gcode += self.doformat(p.lift_code, x=last_pt[0], y=last_pt[1], z_move=z_move) # Stop cutting
  5281. return gcode
  5282. def point2gcode(self, point, dia, z_move=None, old_point=(0, 0)):
  5283. """
  5284. :param point: A Shapely Point
  5285. :type point: Point
  5286. :param dia: The tool diameter that is going on the path
  5287. :type dia: float
  5288. :param z_move: Travel Z
  5289. :type z_move: float
  5290. :param old_point: Old point coordinates from which we moved to the 'point'
  5291. :type old_point: tuple
  5292. :return: G-code to cut on the Point feature.
  5293. :rtype: str
  5294. """
  5295. gcode = ""
  5296. if self.app.abort_flag:
  5297. # graceful abort requested by the user
  5298. raise grace
  5299. path = list(point.coords)
  5300. p = self.pp_geometry
  5301. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  5302. if self.coordinates_type == "G90":
  5303. # For Absolute coordinates type G90
  5304. first_x = path[0][0]
  5305. first_y = path[0][1]
  5306. else:
  5307. # For Incremental coordinates type G91
  5308. # first_x = path[0][0] - old_point[0]
  5309. # first_y = path[0][1] - old_point[1]
  5310. self.app.inform.emit('[ERROR_NOTCL] %s' %
  5311. _('G91 coordinates not implemented ...'))
  5312. first_x = path[0][0]
  5313. first_y = path[0][1]
  5314. current_tooldia = dia
  5315. travels = self.app.exc_areas.travel_coordinates(start_point=(old_point[0], old_point[1]),
  5316. end_point=(first_x, first_y),
  5317. tooldia=current_tooldia)
  5318. prev_z = None
  5319. for travel in travels:
  5320. locx = travel[1][0]
  5321. locy = travel[1][1]
  5322. if travel[0] is not None:
  5323. # move to next point
  5324. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  5325. # raise to safe Z (travel[0]) each time because safe Z may be different
  5326. self.z_move = travel[0]
  5327. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  5328. # restore z_move
  5329. self.z_move = z_move
  5330. else:
  5331. if prev_z is not None:
  5332. # move to next point
  5333. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  5334. # we assume that previously the z_move was altered therefore raise to
  5335. # the travel_z (z_move)
  5336. self.z_move = z_move
  5337. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  5338. else:
  5339. # move to next point
  5340. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  5341. # store prev_z
  5342. prev_z = travel[0]
  5343. # gcode += self.doformat(p.linear_code, x=first_x, y=first_y) # Move to first point
  5344. if self.z_feedrate is not None:
  5345. gcode += self.doformat(p.z_feedrate_code)
  5346. gcode += self.doformat(p.down_code, x=first_x, y=first_y, z_cut=self.z_cut)
  5347. gcode += self.doformat(p.feedrate_code)
  5348. else:
  5349. gcode += self.doformat(p.down_code, x=first_x, y=first_y, z_cut=self.z_cut) # Start cutting
  5350. gcode += self.doformat(p.lift_code, x=first_x, y=first_y) # Stop cutting
  5351. return gcode
  5352. def export_svg(self, scale_stroke_factor=0.00):
  5353. """
  5354. Exports the CNC Job as a SVG Element
  5355. :param scale_stroke_factor: A factor to scale the SVG geometry
  5356. :type scale_stroke_factor: float
  5357. :return: SVG Element string
  5358. :rtype: str
  5359. """
  5360. # scale_factor is a multiplication factor for the SVG stroke-width used within shapely's svg export
  5361. # If not specified then try and use the tool diameter
  5362. # This way what is on screen will match what is outputed for the svg
  5363. # This is quite a useful feature for svg's used with visicut
  5364. if scale_stroke_factor <= 0:
  5365. scale_stroke_factor = self.options['tooldia'] / 2
  5366. # If still 0 then default to 0.05
  5367. # This value appears to work for zooming, and getting the output svg line width
  5368. # to match that viewed on screen with FlatCam
  5369. if scale_stroke_factor == 0:
  5370. scale_stroke_factor = 0.01
  5371. # Separate the list of cuts and travels into 2 distinct lists
  5372. # This way we can add different formatting / colors to both
  5373. cuts = []
  5374. travels = []
  5375. cutsgeom = ''
  5376. travelsgeom = ''
  5377. for g in self.gcode_parsed:
  5378. if self.app.abort_flag:
  5379. # graceful abort requested by the user
  5380. raise grace
  5381. if g['kind'][0] == 'C':
  5382. cuts.append(g)
  5383. if g['kind'][0] == 'T':
  5384. travels.append(g)
  5385. # Used to determine the overall board size
  5386. self.solid_geometry = cascaded_union([geo['geom'] for geo in self.gcode_parsed])
  5387. # Convert the cuts and travels into single geometry objects we can render as svg xml
  5388. if travels:
  5389. travelsgeom = cascaded_union([geo['geom'] for geo in travels])
  5390. if self.app.abort_flag:
  5391. # graceful abort requested by the user
  5392. raise grace
  5393. if cuts:
  5394. cutsgeom = cascaded_union([geo['geom'] for geo in cuts])
  5395. # Render the SVG Xml
  5396. # The scale factor affects the size of the lines, and the stroke color adds different formatting for each set
  5397. # It's better to have the travels sitting underneath the cuts for visicut
  5398. svg_elem = ""
  5399. if travels:
  5400. svg_elem = travelsgeom.svg(scale_factor=scale_stroke_factor, stroke_color="#F0E24D")
  5401. if cuts:
  5402. svg_elem += cutsgeom.svg(scale_factor=scale_stroke_factor, stroke_color="#5E6CFF")
  5403. return svg_elem
  5404. def bounds(self, flatten=None):
  5405. """
  5406. Returns coordinates of rectangular bounds of geometry: (xmin, ymin, xmax, ymax).
  5407. :param flatten: Not used, it is here for compatibility with base class method
  5408. :type flatten: bool
  5409. :return: Bounding values in format (xmin, ymin, xmax, ymax)
  5410. :rtype: tuple
  5411. """
  5412. log.debug("camlib.CNCJob.bounds()")
  5413. def bounds_rec(obj):
  5414. if type(obj) is list:
  5415. cminx = np.Inf
  5416. cminy = np.Inf
  5417. cmaxx = -np.Inf
  5418. cmaxy = -np.Inf
  5419. for k in obj:
  5420. if type(k) is dict:
  5421. for key in k:
  5422. minx_, miny_, maxx_, maxy_ = bounds_rec(k[key])
  5423. cminx = min(cminx, minx_)
  5424. cminy = min(cminy, miny_)
  5425. cmaxx = max(cmaxx, maxx_)
  5426. cmaxy = max(cmaxy, maxy_)
  5427. else:
  5428. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  5429. cminx = min(cminx, minx_)
  5430. cminy = min(cminy, miny_)
  5431. cmaxx = max(cmaxx, maxx_)
  5432. cmaxy = max(cmaxy, maxy_)
  5433. return cminx, cminy, cmaxx, cmaxy
  5434. else:
  5435. # it's a Shapely object, return it's bounds
  5436. return obj.bounds
  5437. if self.multitool is False:
  5438. log.debug("CNCJob->bounds()")
  5439. if self.solid_geometry is None:
  5440. log.debug("solid_geometry is None")
  5441. return 0, 0, 0, 0
  5442. bounds_coords = bounds_rec(self.solid_geometry)
  5443. else:
  5444. minx = np.Inf
  5445. miny = np.Inf
  5446. maxx = -np.Inf
  5447. maxy = -np.Inf
  5448. for k, v in self.cnc_tools.items():
  5449. minx = np.Inf
  5450. miny = np.Inf
  5451. maxx = -np.Inf
  5452. maxy = -np.Inf
  5453. try:
  5454. for k in v['solid_geometry']:
  5455. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  5456. minx = min(minx, minx_)
  5457. miny = min(miny, miny_)
  5458. maxx = max(maxx, maxx_)
  5459. maxy = max(maxy, maxy_)
  5460. except TypeError:
  5461. minx_, miny_, maxx_, maxy_ = bounds_rec(v['solid_geometry'])
  5462. minx = min(minx, minx_)
  5463. miny = min(miny, miny_)
  5464. maxx = max(maxx, maxx_)
  5465. maxy = max(maxy, maxy_)
  5466. bounds_coords = minx, miny, maxx, maxy
  5467. return bounds_coords
  5468. # TODO This function should be replaced at some point with a "real" function. Until then it's an ugly hack ...
  5469. def scale(self, xfactor, yfactor=None, point=None):
  5470. """
  5471. Scales all the geometry on the XY plane in the object by the
  5472. given factor. Tool sizes, feedrates, or Z-axis dimensions are
  5473. not altered.
  5474. :param factor: Number by which to scale the object.
  5475. :type factor: float
  5476. :param point: the (x,y) coords for the point of origin of scale
  5477. :type tuple of floats
  5478. :return: None
  5479. :rtype: None
  5480. """
  5481. log.debug("camlib.CNCJob.scale()")
  5482. if yfactor is None:
  5483. yfactor = xfactor
  5484. if point is None:
  5485. px = 0
  5486. py = 0
  5487. else:
  5488. px, py = point
  5489. def scale_g(g):
  5490. """
  5491. :param g: 'g' parameter it's a gcode string
  5492. :return: scaled gcode string
  5493. """
  5494. temp_gcode = ''
  5495. header_start = False
  5496. header_stop = False
  5497. units = self.app.defaults['units'].upper()
  5498. lines = StringIO(g)
  5499. for line in lines:
  5500. # this changes the GCODE header ---- UGLY HACK
  5501. if "TOOL DIAMETER" in line or "Feedrate:" in line:
  5502. header_start = True
  5503. if "G20" in line or "G21" in line:
  5504. header_start = False
  5505. header_stop = True
  5506. if header_start is True:
  5507. header_stop = False
  5508. if "in" in line:
  5509. if units == 'MM':
  5510. line = line.replace("in", "mm")
  5511. if "mm" in line:
  5512. if units == 'IN':
  5513. line = line.replace("mm", "in")
  5514. # find any float number in header (even multiple on the same line) and convert it
  5515. numbers_in_header = re.findall(self.g_nr_re, line)
  5516. if numbers_in_header:
  5517. for nr in numbers_in_header:
  5518. new_nr = float(nr) * xfactor
  5519. # replace the updated string
  5520. line = line.replace(nr, ('%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_nr))
  5521. )
  5522. # this scales all the X and Y and Z and F values and also the Tool Dia in the toolchange message
  5523. if header_stop is True:
  5524. if "G20" in line:
  5525. if units == 'MM':
  5526. line = line.replace("G20", "G21")
  5527. if "G21" in line:
  5528. if units == 'IN':
  5529. line = line.replace("G21", "G20")
  5530. # find the X group
  5531. match_x = self.g_x_re.search(line)
  5532. if match_x:
  5533. if match_x.group(1) is not None:
  5534. new_x = float(match_x.group(1)[1:]) * xfactor
  5535. # replace the updated string
  5536. line = line.replace(
  5537. match_x.group(1),
  5538. 'X%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_x)
  5539. )
  5540. # find the Y group
  5541. match_y = self.g_y_re.search(line)
  5542. if match_y:
  5543. if match_y.group(1) is not None:
  5544. new_y = float(match_y.group(1)[1:]) * yfactor
  5545. line = line.replace(
  5546. match_y.group(1),
  5547. 'Y%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_y)
  5548. )
  5549. # find the Z group
  5550. match_z = self.g_z_re.search(line)
  5551. if match_z:
  5552. if match_z.group(1) is not None:
  5553. new_z = float(match_z.group(1)[1:]) * xfactor
  5554. line = line.replace(
  5555. match_z.group(1),
  5556. 'Z%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_z)
  5557. )
  5558. # find the F group
  5559. match_f = self.g_f_re.search(line)
  5560. if match_f:
  5561. if match_f.group(1) is not None:
  5562. new_f = float(match_f.group(1)[1:]) * xfactor
  5563. line = line.replace(
  5564. match_f.group(1),
  5565. 'F%.*f' % (self.app.defaults["cncjob_fr_decimals"], new_f)
  5566. )
  5567. # find the T group (tool dia on toolchange)
  5568. match_t = self.g_t_re.search(line)
  5569. if match_t:
  5570. if match_t.group(1) is not None:
  5571. new_t = float(match_t.group(1)[1:]) * xfactor
  5572. line = line.replace(
  5573. match_t.group(1),
  5574. '= %.*f' % (self.app.defaults["cncjob_coords_decimals"], new_t)
  5575. )
  5576. temp_gcode += line
  5577. lines.close()
  5578. header_stop = False
  5579. return temp_gcode
  5580. if self.multitool is False:
  5581. # offset Gcode
  5582. self.gcode = scale_g(self.gcode)
  5583. # variables to display the percentage of work done
  5584. self.geo_len = 0
  5585. try:
  5586. self.geo_len = len(self.gcode_parsed)
  5587. except TypeError:
  5588. self.geo_len = 1
  5589. self.old_disp_number = 0
  5590. self.el_count = 0
  5591. # scale geometry
  5592. for g in self.gcode_parsed:
  5593. try:
  5594. g['geom'] = affinity.scale(g['geom'], xfactor, yfactor, origin=(px, py))
  5595. except AttributeError:
  5596. return g['geom']
  5597. self.el_count += 1
  5598. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  5599. if self.old_disp_number < disp_number <= 100:
  5600. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  5601. self.old_disp_number = disp_number
  5602. self.create_geometry()
  5603. else:
  5604. for k, v in self.cnc_tools.items():
  5605. # scale Gcode
  5606. v['gcode'] = scale_g(v['gcode'])
  5607. # variables to display the percentage of work done
  5608. self.geo_len = 0
  5609. try:
  5610. self.geo_len = len(v['gcode_parsed'])
  5611. except TypeError:
  5612. self.geo_len = 1
  5613. self.old_disp_number = 0
  5614. self.el_count = 0
  5615. # scale gcode_parsed
  5616. for g in v['gcode_parsed']:
  5617. try:
  5618. g['geom'] = affinity.scale(g['geom'], xfactor, yfactor, origin=(px, py))
  5619. except AttributeError:
  5620. return g['geom']
  5621. self.el_count += 1
  5622. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  5623. if self.old_disp_number < disp_number <= 100:
  5624. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  5625. self.old_disp_number = disp_number
  5626. v['solid_geometry'] = cascaded_union([geo['geom'] for geo in v['gcode_parsed']])
  5627. self.create_geometry()
  5628. self.app.proc_container.new_text = ''
  5629. def offset(self, vect):
  5630. """
  5631. Offsets all the geometry on the XY plane in the object by the
  5632. given vector.
  5633. Offsets all the GCODE on the XY plane in the object by the
  5634. given vector.
  5635. g_offsetx_re, g_offsety_re, multitool, cnnc_tools are attributes of FlatCAMCNCJob class in camlib
  5636. :param vect: (x, y) offset vector.
  5637. :type vect: tuple
  5638. :return: None
  5639. """
  5640. log.debug("camlib.CNCJob.offset()")
  5641. dx, dy = vect
  5642. def offset_g(g):
  5643. """
  5644. :param g: 'g' parameter it's a gcode string
  5645. :return: offseted gcode string
  5646. """
  5647. temp_gcode = ''
  5648. lines = StringIO(g)
  5649. for line in lines:
  5650. # find the X group
  5651. match_x = self.g_x_re.search(line)
  5652. if match_x:
  5653. if match_x.group(1) is not None:
  5654. # get the coordinate and add X offset
  5655. new_x = float(match_x.group(1)[1:]) + dx
  5656. # replace the updated string
  5657. line = line.replace(
  5658. match_x.group(1),
  5659. 'X%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_x)
  5660. )
  5661. match_y = self.g_y_re.search(line)
  5662. if match_y:
  5663. if match_y.group(1) is not None:
  5664. new_y = float(match_y.group(1)[1:]) + dy
  5665. line = line.replace(
  5666. match_y.group(1),
  5667. 'Y%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_y)
  5668. )
  5669. temp_gcode += line
  5670. lines.close()
  5671. return temp_gcode
  5672. if self.multitool is False:
  5673. # offset Gcode
  5674. self.gcode = offset_g(self.gcode)
  5675. # variables to display the percentage of work done
  5676. self.geo_len = 0
  5677. try:
  5678. self.geo_len = len(self.gcode_parsed)
  5679. except TypeError:
  5680. self.geo_len = 1
  5681. self.old_disp_number = 0
  5682. self.el_count = 0
  5683. # offset geometry
  5684. for g in self.gcode_parsed:
  5685. try:
  5686. g['geom'] = affinity.translate(g['geom'], xoff=dx, yoff=dy)
  5687. except AttributeError:
  5688. return g['geom']
  5689. self.el_count += 1
  5690. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  5691. if self.old_disp_number < disp_number <= 100:
  5692. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  5693. self.old_disp_number = disp_number
  5694. self.create_geometry()
  5695. else:
  5696. for k, v in self.cnc_tools.items():
  5697. # offset Gcode
  5698. v['gcode'] = offset_g(v['gcode'])
  5699. # variables to display the percentage of work done
  5700. self.geo_len = 0
  5701. try:
  5702. self.geo_len = len(v['gcode_parsed'])
  5703. except TypeError:
  5704. self.geo_len = 1
  5705. self.old_disp_number = 0
  5706. self.el_count = 0
  5707. # offset gcode_parsed
  5708. for g in v['gcode_parsed']:
  5709. try:
  5710. g['geom'] = affinity.translate(g['geom'], xoff=dx, yoff=dy)
  5711. except AttributeError:
  5712. return g['geom']
  5713. self.el_count += 1
  5714. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  5715. if self.old_disp_number < disp_number <= 100:
  5716. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  5717. self.old_disp_number = disp_number
  5718. # for the bounding box
  5719. v['solid_geometry'] = cascaded_union([geo['geom'] for geo in v['gcode_parsed']])
  5720. self.app.proc_container.new_text = ''
  5721. def mirror(self, axis, point):
  5722. """
  5723. Mirror the geometry of an object by an given axis around the coordinates of the 'point'
  5724. :param axis: Axis for Mirror
  5725. :param point: tuple of coordinates (x,y). Point of origin for Mirror
  5726. :return:
  5727. """
  5728. log.debug("camlib.CNCJob.mirror()")
  5729. px, py = point
  5730. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  5731. # variables to display the percentage of work done
  5732. self.geo_len = 0
  5733. try:
  5734. self.geo_len = len(self.gcode_parsed)
  5735. except TypeError:
  5736. self.geo_len = 1
  5737. self.old_disp_number = 0
  5738. self.el_count = 0
  5739. for g in self.gcode_parsed:
  5740. try:
  5741. g['geom'] = affinity.scale(g['geom'], xscale, yscale, origin=(px, py))
  5742. except AttributeError:
  5743. return g['geom']
  5744. self.el_count += 1
  5745. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  5746. if self.old_disp_number < disp_number <= 100:
  5747. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  5748. self.old_disp_number = disp_number
  5749. self.create_geometry()
  5750. self.app.proc_container.new_text = ''
  5751. def skew(self, angle_x, angle_y, point):
  5752. """
  5753. Shear/Skew the geometries of an object by angles along x and y dimensions.
  5754. :param angle_x:
  5755. :param angle_y:
  5756. angle_x, angle_y : float, float
  5757. The shear angle(s) for the x and y axes respectively. These can be
  5758. specified in either degrees (default) or radians by setting
  5759. use_radians=True.
  5760. :param point: tupple of coordinates (x,y)
  5761. See shapely manual for more information: http://toblerity.org/shapely/manual.html#affine-transformations
  5762. """
  5763. log.debug("camlib.CNCJob.skew()")
  5764. px, py = point
  5765. # variables to display the percentage of work done
  5766. self.geo_len = 0
  5767. try:
  5768. self.geo_len = len(self.gcode_parsed)
  5769. except TypeError:
  5770. self.geo_len = 1
  5771. self.old_disp_number = 0
  5772. self.el_count = 0
  5773. for g in self.gcode_parsed:
  5774. try:
  5775. g['geom'] = affinity.skew(g['geom'], angle_x, angle_y, origin=(px, py))
  5776. except AttributeError:
  5777. return g['geom']
  5778. self.el_count += 1
  5779. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  5780. if self.old_disp_number < disp_number <= 100:
  5781. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  5782. self.old_disp_number = disp_number
  5783. self.create_geometry()
  5784. self.app.proc_container.new_text = ''
  5785. def rotate(self, angle, point):
  5786. """
  5787. Rotate the geometry of an object by an given angle around the coordinates of the 'point'
  5788. :param angle: Angle of Rotation
  5789. :param point: tuple of coordinates (x,y). Origin point for Rotation
  5790. :return:
  5791. """
  5792. log.debug("camlib.CNCJob.rotate()")
  5793. px, py = point
  5794. # variables to display the percentage of work done
  5795. self.geo_len = 0
  5796. try:
  5797. self.geo_len = len(self.gcode_parsed)
  5798. except TypeError:
  5799. self.geo_len = 1
  5800. self.old_disp_number = 0
  5801. self.el_count = 0
  5802. for g in self.gcode_parsed:
  5803. try:
  5804. g['geom'] = affinity.rotate(g['geom'], angle, origin=(px, py))
  5805. except AttributeError:
  5806. return g['geom']
  5807. self.el_count += 1
  5808. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  5809. if self.old_disp_number < disp_number <= 100:
  5810. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  5811. self.old_disp_number = disp_number
  5812. self.create_geometry()
  5813. self.app.proc_container.new_text = ''
  5814. def get_bounds(geometry_list):
  5815. """
  5816. Will return limit values for a list of geometries
  5817. :param geometry_list: List of geometries for which to calculate the bounds limits
  5818. :return:
  5819. """
  5820. xmin = np.Inf
  5821. ymin = np.Inf
  5822. xmax = -np.Inf
  5823. ymax = -np.Inf
  5824. for gs in geometry_list:
  5825. try:
  5826. gxmin, gymin, gxmax, gymax = gs.bounds()
  5827. xmin = min([xmin, gxmin])
  5828. ymin = min([ymin, gymin])
  5829. xmax = max([xmax, gxmax])
  5830. ymax = max([ymax, gymax])
  5831. except Exception:
  5832. log.warning("DEVELOPMENT: Tried to get bounds of empty geometry.")
  5833. return [xmin, ymin, xmax, ymax]
  5834. def arc(center, radius, start, stop, direction, steps_per_circ):
  5835. """
  5836. Creates a list of point along the specified arc.
  5837. :param center: Coordinates of the center [x, y]
  5838. :type center: list
  5839. :param radius: Radius of the arc.
  5840. :type radius: float
  5841. :param start: Starting angle in radians
  5842. :type start: float
  5843. :param stop: End angle in radians
  5844. :type stop: float
  5845. :param direction: Orientation of the arc, "CW" or "CCW"
  5846. :type direction: string
  5847. :param steps_per_circ: Number of straight line segments to
  5848. represent a circle.
  5849. :type steps_per_circ: int
  5850. :return: The desired arc, as list of tuples
  5851. :rtype: list
  5852. """
  5853. # TODO: Resolution should be established by maximum error from the exact arc.
  5854. da_sign = {"cw": -1.0, "ccw": 1.0}
  5855. points = []
  5856. if direction == "ccw" and stop <= start:
  5857. stop += 2 * np.pi
  5858. if direction == "cw" and stop >= start:
  5859. stop -= 2 * np.pi
  5860. angle = abs(stop - start)
  5861. # angle = stop-start
  5862. steps = max([int(np.ceil(angle / (2 * np.pi) * steps_per_circ)), 2])
  5863. delta_angle = da_sign[direction] * angle * 1.0 / steps
  5864. for i in range(steps + 1):
  5865. theta = start + delta_angle * i
  5866. points.append((center[0] + radius * np.cos(theta), center[1] + radius * np.sin(theta)))
  5867. return points
  5868. def arc2(p1, p2, center, direction, steps_per_circ):
  5869. r = np.sqrt((center[0] - p1[0]) ** 2 + (center[1] - p1[1]) ** 2)
  5870. start = np.arctan2(p1[1] - center[1], p1[0] - center[0])
  5871. stop = np.arctan2(p2[1] - center[1], p2[0] - center[0])
  5872. return arc(center, r, start, stop, direction, steps_per_circ)
  5873. def arc_angle(start, stop, direction):
  5874. if direction == "ccw" and stop <= start:
  5875. stop += 2 * np.pi
  5876. if direction == "cw" and stop >= start:
  5877. stop -= 2 * np.pi
  5878. angle = abs(stop - start)
  5879. return angle
  5880. # def find_polygon(poly, point):
  5881. # """
  5882. # Find an object that object.contains(Point(point)) in
  5883. # poly, which can can be iterable, contain iterable of, or
  5884. # be itself an implementer of .contains().
  5885. #
  5886. # :param poly: See description
  5887. # :return: Polygon containing point or None.
  5888. # """
  5889. #
  5890. # if poly is None:
  5891. # return None
  5892. #
  5893. # try:
  5894. # for sub_poly in poly:
  5895. # p = find_polygon(sub_poly, point)
  5896. # if p is not None:
  5897. # return p
  5898. # except TypeError:
  5899. # try:
  5900. # if poly.contains(Point(point)):
  5901. # return poly
  5902. # except AttributeError:
  5903. # return None
  5904. #
  5905. # return None
  5906. def to_dict(obj):
  5907. """
  5908. Makes the following types into serializable form:
  5909. * ApertureMacro
  5910. * BaseGeometry
  5911. :param obj: Shapely geometry.
  5912. :type obj: BaseGeometry
  5913. :return: Dictionary with serializable form if ``obj`` was
  5914. BaseGeometry or ApertureMacro, otherwise returns ``obj``.
  5915. """
  5916. if isinstance(obj, ApertureMacro):
  5917. return {
  5918. "__class__": "ApertureMacro",
  5919. "__inst__": obj.to_dict()
  5920. }
  5921. if isinstance(obj, BaseGeometry):
  5922. return {
  5923. "__class__": "Shply",
  5924. "__inst__": sdumps(obj)
  5925. }
  5926. return obj
  5927. def dict2obj(d):
  5928. """
  5929. Default deserializer.
  5930. :param d: Serializable dictionary representation of an object
  5931. to be reconstructed.
  5932. :return: Reconstructed object.
  5933. """
  5934. if '__class__' in d and '__inst__' in d:
  5935. if d['__class__'] == "Shply":
  5936. return sloads(d['__inst__'])
  5937. if d['__class__'] == "ApertureMacro":
  5938. am = ApertureMacro()
  5939. am.from_dict(d['__inst__'])
  5940. return am
  5941. return d
  5942. else:
  5943. return d
  5944. # def plotg(geo, solid_poly=False, color="black"):
  5945. # try:
  5946. # __ = iter(geo)
  5947. # except:
  5948. # geo = [geo]
  5949. #
  5950. # for g in geo:
  5951. # if type(g) == Polygon:
  5952. # if solid_poly:
  5953. # patch = PolygonPatch(g,
  5954. # facecolor="#BBF268",
  5955. # edgecolor="#006E20",
  5956. # alpha=0.75,
  5957. # zorder=2)
  5958. # ax = subplot(111)
  5959. # ax.add_patch(patch)
  5960. # else:
  5961. # x, y = g.exterior.coords.xy
  5962. # plot(x, y, color=color)
  5963. # for ints in g.interiors:
  5964. # x, y = ints.coords.xy
  5965. # plot(x, y, color=color)
  5966. # continue
  5967. #
  5968. # if type(g) == LineString or type(g) == LinearRing:
  5969. # x, y = g.coords.xy
  5970. # plot(x, y, color=color)
  5971. # continue
  5972. #
  5973. # if type(g) == Point:
  5974. # x, y = g.coords.xy
  5975. # plot(x, y, 'o')
  5976. # continue
  5977. #
  5978. # try:
  5979. # __ = iter(g)
  5980. # plotg(g, color=color)
  5981. # except:
  5982. # log.error("Cannot plot: " + str(type(g)))
  5983. # continue
  5984. # def alpha_shape(points, alpha):
  5985. # """
  5986. # Compute the alpha shape (concave hull) of a set of points.
  5987. #
  5988. # @param points: Iterable container of points.
  5989. # @param alpha: alpha value to influence the gooeyness of the border. Smaller
  5990. # numbers don't fall inward as much as larger numbers. Too large,
  5991. # and you lose everything!
  5992. # """
  5993. # if len(points) < 4:
  5994. # # When you have a triangle, there is no sense in computing an alpha
  5995. # # shape.
  5996. # return MultiPoint(list(points)).convex_hull
  5997. #
  5998. # def add_edge(edges, edge_points, coords, i, j):
  5999. # """Add a line between the i-th and j-th points, if not in the list already"""
  6000. # if (i, j) in edges or (j, i) in edges:
  6001. # # already added
  6002. # return
  6003. # edges.add( (i, j) )
  6004. # edge_points.append(coords[ [i, j] ])
  6005. #
  6006. # coords = np.array([point.coords[0] for point in points])
  6007. #
  6008. # tri = Delaunay(coords)
  6009. # edges = set()
  6010. # edge_points = []
  6011. # # loop over triangles:
  6012. # # ia, ib, ic = indices of corner points of the triangle
  6013. # for ia, ib, ic in tri.vertices:
  6014. # pa = coords[ia]
  6015. # pb = coords[ib]
  6016. # pc = coords[ic]
  6017. #
  6018. # # Lengths of sides of triangle
  6019. # a = math.sqrt((pa[0]-pb[0])**2 + (pa[1]-pb[1])**2)
  6020. # b = math.sqrt((pb[0]-pc[0])**2 + (pb[1]-pc[1])**2)
  6021. # c = math.sqrt((pc[0]-pa[0])**2 + (pc[1]-pa[1])**2)
  6022. #
  6023. # # Semiperimeter of triangle
  6024. # s = (a + b + c)/2.0
  6025. #
  6026. # # Area of triangle by Heron's formula
  6027. # area = math.sqrt(s*(s-a)*(s-b)*(s-c))
  6028. # circum_r = a*b*c/(4.0*area)
  6029. #
  6030. # # Here's the radius filter.
  6031. # #print circum_r
  6032. # if circum_r < 1.0/alpha:
  6033. # add_edge(edges, edge_points, coords, ia, ib)
  6034. # add_edge(edges, edge_points, coords, ib, ic)
  6035. # add_edge(edges, edge_points, coords, ic, ia)
  6036. #
  6037. # m = MultiLineString(edge_points)
  6038. # triangles = list(polygonize(m))
  6039. # return cascaded_union(triangles), edge_points
  6040. # def voronoi(P):
  6041. # """
  6042. # Returns a list of all edges of the voronoi diagram for the given input points.
  6043. # """
  6044. # delauny = Delaunay(P)
  6045. # triangles = delauny.points[delauny.vertices]
  6046. #
  6047. # circum_centers = np.array([triangle_csc(tri) for tri in triangles])
  6048. # long_lines_endpoints = []
  6049. #
  6050. # lineIndices = []
  6051. # for i, triangle in enumerate(triangles):
  6052. # circum_center = circum_centers[i]
  6053. # for j, neighbor in enumerate(delauny.neighbors[i]):
  6054. # if neighbor != -1:
  6055. # lineIndices.append((i, neighbor))
  6056. # else:
  6057. # ps = triangle[(j+1)%3] - triangle[(j-1)%3]
  6058. # ps = np.array((ps[1], -ps[0]))
  6059. #
  6060. # middle = (triangle[(j+1)%3] + triangle[(j-1)%3]) * 0.5
  6061. # di = middle - triangle[j]
  6062. #
  6063. # ps /= np.linalg.norm(ps)
  6064. # di /= np.linalg.norm(di)
  6065. #
  6066. # if np.dot(di, ps) < 0.0:
  6067. # ps *= -1000.0
  6068. # else:
  6069. # ps *= 1000.0
  6070. #
  6071. # long_lines_endpoints.append(circum_center + ps)
  6072. # lineIndices.append((i, len(circum_centers) + len(long_lines_endpoints)-1))
  6073. #
  6074. # vertices = np.vstack((circum_centers, long_lines_endpoints))
  6075. #
  6076. # # filter out any duplicate lines
  6077. # lineIndicesSorted = np.sort(lineIndices) # make (1,2) and (2,1) both (1,2)
  6078. # lineIndicesTupled = [tuple(row) for row in lineIndicesSorted]
  6079. # lineIndicesUnique = np.unique(lineIndicesTupled)
  6080. #
  6081. # return vertices, lineIndicesUnique
  6082. #
  6083. #
  6084. # def triangle_csc(pts):
  6085. # rows, cols = pts.shape
  6086. #
  6087. # A = np.bmat([[2 * np.dot(pts, pts.T), np.ones((rows, 1))],
  6088. # [np.ones((1, rows)), np.zeros((1, 1))]])
  6089. #
  6090. # b = np.hstack((np.sum(pts * pts, axis=1), np.ones((1))))
  6091. # x = np.linalg.solve(A,b)
  6092. # bary_coords = x[:-1]
  6093. # return np.sum(pts * np.tile(bary_coords.reshape((pts.shape[0], 1)), (1, pts.shape[1])), axis=0)
  6094. #
  6095. #
  6096. # def voronoi_cell_lines(points, vertices, lineIndices):
  6097. # """
  6098. # Returns a mapping from a voronoi cell to its edges.
  6099. #
  6100. # :param points: shape (m,2)
  6101. # :param vertices: shape (n,2)
  6102. # :param lineIndices: shape (o,2)
  6103. # :rtype: dict point index -> list of shape (n,2) with vertex indices
  6104. # """
  6105. # kd = KDTree(points)
  6106. #
  6107. # cells = collections.defaultdict(list)
  6108. # for i1, i2 in lineIndices:
  6109. # v1, v2 = vertices[i1], vertices[i2]
  6110. # mid = (v1+v2)/2
  6111. # _, (p1Idx, p2Idx) = kd.query(mid, 2)
  6112. # cells[p1Idx].append((i1, i2))
  6113. # cells[p2Idx].append((i1, i2))
  6114. #
  6115. # return cells
  6116. #
  6117. #
  6118. # def voronoi_edges2polygons(cells):
  6119. # """
  6120. # Transforms cell edges into polygons.
  6121. #
  6122. # :param cells: as returned from voronoi_cell_lines
  6123. # :rtype: dict point index -> list of vertex indices which form a polygon
  6124. # """
  6125. #
  6126. # # first, close the outer cells
  6127. # for pIdx, lineIndices_ in cells.items():
  6128. # dangling_lines = []
  6129. # for i1, i2 in lineIndices_:
  6130. # p = (i1, i2)
  6131. # connections = filter(lambda k: p != k and
  6132. # (p[0] == k[0] or p[0] == k[1] or p[1] == k[0] or p[1] == k[1]), lineIndices_)
  6133. # # connections = filter(lambda (i1_, i2_): (i1, i2) != (i1_, i2_) and
  6134. # (i1 == i1_ or i1 == i2_ or i2 == i1_ or i2 == i2_), lineIndices_)
  6135. # assert 1 <= len(connections) <= 2
  6136. # if len(connections) == 1:
  6137. # dangling_lines.append((i1, i2))
  6138. # assert len(dangling_lines) in [0, 2]
  6139. # if len(dangling_lines) == 2:
  6140. # (i11, i12), (i21, i22) = dangling_lines
  6141. # s = (i11, i12)
  6142. # t = (i21, i22)
  6143. #
  6144. # # determine which line ends are unconnected
  6145. # connected = filter(lambda k: k != s and (k[0] == s[0] or k[1] == s[0]), lineIndices_)
  6146. # # connected = filter(lambda (i1,i2): (i1,i2) != (i11,i12) and (i1 == i11 or i2 == i11), lineIndices_)
  6147. # i11Unconnected = len(connected) == 0
  6148. #
  6149. # connected = filter(lambda k: k != t and (k[0] == t[0] or k[1] == t[0]), lineIndices_)
  6150. # # connected = filter(lambda (i1,i2): (i1,i2) != (i21,i22) and (i1 == i21 or i2 == i21), lineIndices_)
  6151. # i21Unconnected = len(connected) == 0
  6152. #
  6153. # startIdx = i11 if i11Unconnected else i12
  6154. # endIdx = i21 if i21Unconnected else i22
  6155. #
  6156. # cells[pIdx].append((startIdx, endIdx))
  6157. #
  6158. # # then, form polygons by storing vertex indices in (counter-)clockwise order
  6159. # polys = {}
  6160. # for pIdx, lineIndices_ in cells.items():
  6161. # # get a directed graph which contains both directions and arbitrarily follow one of both
  6162. # directedGraph = lineIndices_ + [(i2, i1) for (i1, i2) in lineIndices_]
  6163. # directedGraphMap = collections.defaultdict(list)
  6164. # for (i1, i2) in directedGraph:
  6165. # directedGraphMap[i1].append(i2)
  6166. # orderedEdges = []
  6167. # currentEdge = directedGraph[0]
  6168. # while len(orderedEdges) < len(lineIndices_):
  6169. # i1 = currentEdge[1]
  6170. # i2 = directedGraphMap[i1][0] if directedGraphMap[i1][0] != currentEdge[0] else directedGraphMap[i1][1]
  6171. # nextEdge = (i1, i2)
  6172. # orderedEdges.append(nextEdge)
  6173. # currentEdge = nextEdge
  6174. #
  6175. # polys[pIdx] = [i1 for (i1, i2) in orderedEdges]
  6176. #
  6177. # return polys
  6178. #
  6179. #
  6180. # def voronoi_polygons(points):
  6181. # """
  6182. # Returns the voronoi polygon for each input point.
  6183. #
  6184. # :param points: shape (n,2)
  6185. # :rtype: list of n polygons where each polygon is an array of vertices
  6186. # """
  6187. # vertices, lineIndices = voronoi(points)
  6188. # cells = voronoi_cell_lines(points, vertices, lineIndices)
  6189. # polys = voronoi_edges2polygons(cells)
  6190. # polylist = []
  6191. # for i in range(len(points)):
  6192. # poly = vertices[np.asarray(polys[i])]
  6193. # polylist.append(poly)
  6194. # return polylist
  6195. #
  6196. #
  6197. # class Zprofile:
  6198. # def __init__(self):
  6199. #
  6200. # # data contains lists of [x, y, z]
  6201. # self.data = []
  6202. #
  6203. # # Computed voronoi polygons (shapely)
  6204. # self.polygons = []
  6205. # pass
  6206. #
  6207. # # def plot_polygons(self):
  6208. # # axes = plt.subplot(1, 1, 1)
  6209. # #
  6210. # # plt.axis([-0.05, 1.05, -0.05, 1.05])
  6211. # #
  6212. # # for poly in self.polygons:
  6213. # # p = PolygonPatch(poly, facecolor=np.random.rand(3, 1), alpha=0.3)
  6214. # # axes.add_patch(p)
  6215. #
  6216. # def init_from_csv(self, filename):
  6217. # pass
  6218. #
  6219. # def init_from_string(self, zpstring):
  6220. # pass
  6221. #
  6222. # def init_from_list(self, zplist):
  6223. # self.data = zplist
  6224. #
  6225. # def generate_polygons(self):
  6226. # self.polygons = [Polygon(p) for p in voronoi_polygons(array([[x[0], x[1]] for x in self.data]))]
  6227. #
  6228. # def normalize(self, origin):
  6229. # pass
  6230. #
  6231. # def paste(self, path):
  6232. # """
  6233. # Return a list of dictionaries containing the parts of the original
  6234. # path and their z-axis offset.
  6235. # """
  6236. #
  6237. # # At most one region/polygon will contain the path
  6238. # containing = [i for i in range(len(self.polygons)) if self.polygons[i].contains(path)]
  6239. #
  6240. # if len(containing) > 0:
  6241. # return [{"path": path, "z": self.data[containing[0]][2]}]
  6242. #
  6243. # # All region indexes that intersect with the path
  6244. # crossing = [i for i in range(len(self.polygons)) if self.polygons[i].intersects(path)]
  6245. #
  6246. # return [{"path": path.intersection(self.polygons[i]),
  6247. # "z": self.data[i][2]} for i in crossing]
  6248. def autolist(obj):
  6249. try:
  6250. __ = iter(obj)
  6251. return obj
  6252. except TypeError:
  6253. return [obj]
  6254. def three_point_circle(p1, p2, p3):
  6255. """
  6256. Computes the center and radius of a circle from
  6257. 3 points on its circumference.
  6258. :param p1: Point 1
  6259. :param p2: Point 2
  6260. :param p3: Point 3
  6261. :return: center, radius
  6262. """
  6263. # Midpoints
  6264. a1 = (p1 + p2) / 2.0
  6265. a2 = (p2 + p3) / 2.0
  6266. # Normals
  6267. b1 = np.dot((p2 - p1), np.array([[0, -1], [1, 0]], dtype=np.float32))
  6268. b2 = np.dot((p3 - p2), np.array([[0, 1], [-1, 0]], dtype=np.float32))
  6269. # Params
  6270. try:
  6271. T = solve(np.transpose(np.array([-b1, b2])), a1 - a2)
  6272. except Exception as e:
  6273. log.debug("camlib.three_point_circle() --> %s" % str(e))
  6274. return
  6275. # Center
  6276. center = a1 + b1 * T[0]
  6277. # Radius
  6278. radius = np.linalg.norm(center - p1)
  6279. return center, radius, T[0]
  6280. def distance(pt1, pt2):
  6281. return np.sqrt((pt1[0] - pt2[0]) ** 2 + (pt1[1] - pt2[1]) ** 2)
  6282. def distance_euclidian(x1, y1, x2, y2):
  6283. return np.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
  6284. class FlatCAMRTree(object):
  6285. """
  6286. Indexes geometry (Any object with "cooords" property containing
  6287. a list of tuples with x, y values). Objects are indexed by
  6288. all their points by default. To index by arbitrary points,
  6289. override self.points2obj.
  6290. """
  6291. def __init__(self):
  6292. # Python RTree Index
  6293. self.rti = rtindex.Index()
  6294. # ## Track object-point relationship
  6295. # Each is list of points in object.
  6296. self.obj2points = []
  6297. # Index is index in rtree, value is index of
  6298. # object in obj2points.
  6299. self.points2obj = []
  6300. self.get_points = lambda go: go.coords
  6301. def grow_obj2points(self, idx):
  6302. """
  6303. Increases the size of self.obj2points to fit
  6304. idx + 1 items.
  6305. :param idx: Index to fit into list.
  6306. :return: None
  6307. """
  6308. if len(self.obj2points) > idx:
  6309. # len == 2, idx == 1, ok.
  6310. return
  6311. else:
  6312. # len == 2, idx == 2, need 1 more.
  6313. # range(2, 3)
  6314. for i in range(len(self.obj2points), idx + 1):
  6315. self.obj2points.append([])
  6316. def insert(self, objid, obj):
  6317. self.grow_obj2points(objid)
  6318. self.obj2points[objid] = []
  6319. for pt in self.get_points(obj):
  6320. self.rti.insert(len(self.points2obj), (pt[0], pt[1], pt[0], pt[1]), obj=objid)
  6321. self.obj2points[objid].append(len(self.points2obj))
  6322. self.points2obj.append(objid)
  6323. def remove_obj(self, objid, obj):
  6324. # Use all ptids to delete from index
  6325. for i, pt in enumerate(self.get_points(obj)):
  6326. try:
  6327. self.rti.delete(self.obj2points[objid][i], (pt[0], pt[1], pt[0], pt[1]))
  6328. except IndexError:
  6329. pass
  6330. def nearest(self, pt):
  6331. """
  6332. Will raise StopIteration if no items are found.
  6333. :param pt:
  6334. :return:
  6335. """
  6336. return next(self.rti.nearest(pt, objects=True))
  6337. class FlatCAMRTreeStorage(FlatCAMRTree):
  6338. """
  6339. Just like FlatCAMRTree it indexes geometry, but also serves
  6340. as storage for the geometry.
  6341. """
  6342. def __init__(self):
  6343. # super(FlatCAMRTreeStorage, self).__init__()
  6344. super().__init__()
  6345. self.objects = []
  6346. # Optimization attempt!
  6347. self.indexes = {}
  6348. def insert(self, obj):
  6349. self.objects.append(obj)
  6350. idx = len(self.objects) - 1
  6351. # Note: Shapely objects are not hashable any more, although
  6352. # there seem to be plans to re-introduce the feature in
  6353. # version 2.0. For now, we will index using the object's id,
  6354. # but it's important to remember that shapely geometry is
  6355. # mutable, ie. it can be modified to a totally different shape
  6356. # and continue to have the same id.
  6357. # self.indexes[obj] = idx
  6358. self.indexes[id(obj)] = idx
  6359. # super(FlatCAMRTreeStorage, self).insert(idx, obj)
  6360. super().insert(idx, obj)
  6361. # @profile
  6362. def remove(self, obj):
  6363. # See note about self.indexes in insert().
  6364. # objidx = self.indexes[obj]
  6365. objidx = self.indexes[id(obj)]
  6366. # Remove from list
  6367. self.objects[objidx] = None
  6368. # Remove from index
  6369. self.remove_obj(objidx, obj)
  6370. def get_objects(self):
  6371. return (o for o in self.objects if o is not None)
  6372. def nearest(self, pt):
  6373. """
  6374. Returns the nearest matching points and the object
  6375. it belongs to.
  6376. :param pt: Query point.
  6377. :return: (match_x, match_y), Object owner of
  6378. matching point.
  6379. :rtype: tuple
  6380. """
  6381. tidx = super(FlatCAMRTreeStorage, self).nearest(pt)
  6382. return (tidx.bbox[0], tidx.bbox[1]), self.objects[tidx.object]
  6383. # class myO:
  6384. # def __init__(self, coords):
  6385. # self.coords = coords
  6386. #
  6387. #
  6388. # def test_rti():
  6389. #
  6390. # o1 = myO([(0, 0), (0, 1), (1, 1)])
  6391. # o2 = myO([(2, 0), (2, 1), (2, 1)])
  6392. # o3 = myO([(2, 0), (2, 1), (3, 1)])
  6393. #
  6394. # os = [o1, o2]
  6395. #
  6396. # idx = FlatCAMRTree()
  6397. #
  6398. # for o in range(len(os)):
  6399. # idx.insert(o, os[o])
  6400. #
  6401. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  6402. #
  6403. # idx.remove_obj(0, o1)
  6404. #
  6405. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  6406. #
  6407. # idx.remove_obj(1, o2)
  6408. #
  6409. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  6410. #
  6411. #
  6412. # def test_rtis():
  6413. #
  6414. # o1 = myO([(0, 0), (0, 1), (1, 1)])
  6415. # o2 = myO([(2, 0), (2, 1), (2, 1)])
  6416. # o3 = myO([(2, 0), (2, 1), (3, 1)])
  6417. #
  6418. # os = [o1, o2]
  6419. #
  6420. # idx = FlatCAMRTreeStorage()
  6421. #
  6422. # for o in range(len(os)):
  6423. # idx.insert(os[o])
  6424. #
  6425. # #os = None
  6426. # #o1 = None
  6427. # #o2 = None
  6428. #
  6429. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  6430. #
  6431. # idx.remove(idx.nearest((2,0))[1])
  6432. #
  6433. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  6434. #
  6435. # idx.remove(idx.nearest((0,0))[1])
  6436. #
  6437. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]