camlib.py 281 KB

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