camlib.py 282 KB

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