camlib.py 281 KB

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