camlib.py 356 KB

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