camlib.py 268 KB

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