camlib.py 282 KB

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