camlib.py 281 KB

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