camlib.py 283 KB

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