camlib.py 260 KB

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