camlib.py 333 KB

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