camlib.py 356 KB

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