camlib.py 356 KB

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