camlib.py 352 KB

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