camlib.py 263 KB

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