camlib.py 354 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594
  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, Point, LinearRing
  19. from shapely.geometry import box as shply_box
  20. from shapely.ops import cascaded_union, unary_union, substring, linemerge
  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 appCommon.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. # Flattened geometry (list of paths only)
  371. self.flat_geometry = []
  372. # this is the calculated conversion factor when the file units are different than the ones in the app
  373. self.file_units_factor = 1
  374. # Index
  375. self.index = None
  376. self.geo_steps_per_circle = geo_steps_per_circle
  377. # variables to display the percentage of work done
  378. self.geo_len = 0
  379. self.old_disp_number = 0
  380. self.el_count = 0
  381. if self.app.is_legacy is False:
  382. self.temp_shapes = self.app.plotcanvas.new_shape_collection(layers=1)
  383. else:
  384. from appGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  385. self.temp_shapes = ShapeCollectionLegacy(obj=self, app=self.app, name='camlib.geometry')
  386. # Attributes to be included in serialization
  387. self.ser_attrs = ["units", 'solid_geometry', 'follow_geometry', 'tools']
  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, tool=None):
  402. """
  403. Adds a circle to the object.
  404. :param origin: Center of the circle.
  405. :param radius: Radius of the circle.
  406. :param tool: A tool in the Tools dictionary attribute of the object
  407. :return: None
  408. """
  409. if self.solid_geometry is None:
  410. self.solid_geometry = []
  411. new_circle = Point(origin).buffer(radius, int(self.geo_steps_per_circle))
  412. if not new_circle.is_valid:
  413. return "fail"
  414. # add to the solid_geometry
  415. try:
  416. self.solid_geometry.append(new_circle)
  417. except TypeError:
  418. try:
  419. self.solid_geometry = self.solid_geometry.union(new_circle)
  420. except Exception as e:
  421. log.error("Failed to run union on polygons. %s" % str(e))
  422. return "fail"
  423. # add in tools solid_geometry
  424. if tool is None or tool not in self.tools:
  425. tool = 1
  426. self.tools[tool]['solid_geometry'].append(new_circle)
  427. # calculate bounds
  428. try:
  429. xmin, ymin, xmax, ymax = self.bounds()
  430. self.options['xmin'] = xmin
  431. self.options['ymin'] = ymin
  432. self.options['xmax'] = xmax
  433. self.options['ymax'] = ymax
  434. except Exception as e:
  435. log.error("Failed. The object has no bounds properties. %s" % str(e))
  436. def add_polygon(self, points, tool=None):
  437. """
  438. Adds a polygon to the object (by union)
  439. :param points: The vertices of the polygon.
  440. :param tool: A tool in the Tools dictionary attribute of the object
  441. :return: None
  442. """
  443. if self.solid_geometry is None:
  444. self.solid_geometry = []
  445. new_poly = Polygon(points)
  446. if not new_poly.is_valid:
  447. return "fail"
  448. # add to the solid_geometry
  449. if type(self.solid_geometry) is list:
  450. self.solid_geometry.append(new_poly)
  451. else:
  452. try:
  453. self.solid_geometry = self.solid_geometry.union(Polygon(points))
  454. except Exception as e:
  455. log.error("Failed to run union on polygons. %s" % str(e))
  456. return "fail"
  457. # add in tools solid_geometry
  458. if tool is None or tool not in self.tools:
  459. tool = 1
  460. self.tools[tool]['solid_geometry'].append(new_poly)
  461. # calculate bounds
  462. try:
  463. xmin, ymin, xmax, ymax = self.bounds()
  464. self.options['xmin'] = xmin
  465. self.options['ymin'] = ymin
  466. self.options['xmax'] = xmax
  467. self.options['ymax'] = ymax
  468. except Exception as e:
  469. log.error("Failed. The object has no bounds properties. %s" % str(e))
  470. def add_polyline(self, points, tool=None):
  471. """
  472. Adds a polyline to the object (by union)
  473. :param points: The vertices of the polyline.
  474. :param tool: A tool in the Tools dictionary attribute of the object
  475. :return: None
  476. """
  477. if self.solid_geometry is None:
  478. self.solid_geometry = []
  479. new_line = LineString(points)
  480. if not new_line.is_valid:
  481. return "fail"
  482. # add to the solid_geometry
  483. if type(self.solid_geometry) is list:
  484. self.solid_geometry.append(new_line)
  485. else:
  486. try:
  487. self.solid_geometry = self.solid_geometry.union(new_line)
  488. except Exception as e:
  489. log.error("Failed to run union on polylines. %s" % str(e))
  490. return "fail"
  491. # add in tools solid_geometry
  492. if tool is None or tool not in self.tools:
  493. tool = 1
  494. self.tools[tool]['solid_geometry'].append(new_line)
  495. # calculate bounds
  496. try:
  497. xmin, ymin, xmax, ymax = self.bounds()
  498. self.options['xmin'] = xmin
  499. self.options['ymin'] = ymin
  500. self.options['xmax'] = xmax
  501. self.options['ymax'] = ymax
  502. except Exception as e:
  503. log.error("Failed. The object has no bounds properties. %s" % str(e))
  504. def is_empty(self):
  505. if isinstance(self.solid_geometry, BaseGeometry) or isinstance(self.solid_geometry, Polygon) or \
  506. isinstance(self.solid_geometry, MultiPolygon):
  507. return self.solid_geometry.is_empty
  508. if isinstance(self.solid_geometry, list):
  509. return len(self.solid_geometry) == 0
  510. self.app.inform.emit('[ERROR_NOTCL] %s' % _("self.solid_geometry is neither BaseGeometry or list."))
  511. return
  512. def subtract_polygon(self, points):
  513. """
  514. Subtract polygon from the given object. This only operates on the paths in the original geometry,
  515. i.e. it converts polygons into paths.
  516. :param points: The vertices of the polygon.
  517. :return: none
  518. """
  519. if self.solid_geometry is None:
  520. self.solid_geometry = []
  521. # pathonly should be allways True, otherwise polygons are not subtracted
  522. flat_geometry = self.flatten(pathonly=True)
  523. log.debug("%d paths" % len(flat_geometry))
  524. if not isinstance(points, Polygon):
  525. polygon = Polygon(points)
  526. else:
  527. polygon = points
  528. toolgeo = cascaded_union(polygon)
  529. diffs = []
  530. for target in flat_geometry:
  531. if isinstance(target, LineString) or isinstance(target, LineString) or isinstance(target, MultiLineString):
  532. diffs.append(target.difference(toolgeo))
  533. else:
  534. log.warning("Not implemented.")
  535. self.solid_geometry = unary_union(diffs)
  536. def bounds(self, flatten=False):
  537. """
  538. Returns coordinates of rectangular bounds
  539. of geometry: (xmin, ymin, xmax, ymax).
  540. :param flatten: will flatten the solid_geometry if True
  541. :return:
  542. """
  543. # fixed issue of getting bounds only for one level lists of objects
  544. # now it can get bounds for nested lists of objects
  545. log.debug("camlib.Geometry.bounds()")
  546. if self.solid_geometry is None:
  547. log.debug("solid_geometry is None")
  548. return 0, 0, 0, 0
  549. def bounds_rec(obj):
  550. if type(obj) is list:
  551. gminx = np.Inf
  552. gminy = np.Inf
  553. gmaxx = -np.Inf
  554. gmaxy = -np.Inf
  555. for k in obj:
  556. if type(k) is dict:
  557. for key in k:
  558. minx_, miny_, maxx_, maxy_ = bounds_rec(k[key])
  559. gminx = min(gminx, minx_)
  560. gminy = min(gminy, miny_)
  561. gmaxx = max(gmaxx, maxx_)
  562. gmaxy = max(gmaxy, maxy_)
  563. else:
  564. try:
  565. if k.is_empty:
  566. continue
  567. except Exception:
  568. pass
  569. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  570. gminx = min(gminx, minx_)
  571. gminy = min(gminy, miny_)
  572. gmaxx = max(gmaxx, maxx_)
  573. gmaxy = max(gmaxy, maxy_)
  574. return gminx, gminy, gmaxx, gmaxy
  575. else:
  576. # it's a Shapely object, return it's bounds
  577. return obj.bounds
  578. if self.multigeo is True:
  579. minx_list = []
  580. miny_list = []
  581. maxx_list = []
  582. maxy_list = []
  583. for tool in self.tools:
  584. working_geo = self.tools[tool]['solid_geometry']
  585. if flatten:
  586. self.flatten(geometry=working_geo, reset=True)
  587. working_geo = self.flat_geometry
  588. minx, miny, maxx, maxy = bounds_rec(working_geo)
  589. minx_list.append(minx)
  590. miny_list.append(miny)
  591. maxx_list.append(maxx)
  592. maxy_list.append(maxy)
  593. return min(minx_list), min(miny_list), max(maxx_list), max(maxy_list)
  594. else:
  595. if flatten:
  596. self.flatten(reset=True)
  597. self.solid_geometry = self.flat_geometry
  598. bounds_coords = bounds_rec(self.solid_geometry)
  599. return bounds_coords
  600. # try:
  601. # # from here: http://rightfootin.blogspot.com/2006/09/more-on-python-flatten.html
  602. # def flatten(l, ltypes=(list, tuple)):
  603. # ltype = type(l)
  604. # l = list(l)
  605. # i = 0
  606. # while i < len(l):
  607. # while isinstance(l[i], ltypes):
  608. # if not l[i]:
  609. # l.pop(i)
  610. # i -= 1
  611. # break
  612. # else:
  613. # l[i:i + 1] = l[i]
  614. # i += 1
  615. # return ltype(l)
  616. #
  617. # log.debug("Geometry->bounds()")
  618. # if self.solid_geometry is None:
  619. # log.debug("solid_geometry is None")
  620. # return 0, 0, 0, 0
  621. #
  622. # if type(self.solid_geometry) is list:
  623. # if len(self.solid_geometry) == 0:
  624. # log.debug('solid_geometry is empty []')
  625. # return 0, 0, 0, 0
  626. # return cascaded_union(flatten(self.solid_geometry)).bounds
  627. # else:
  628. # return self.solid_geometry.bounds
  629. # except Exception as e:
  630. # self.app.inform.emit("[ERROR_NOTCL] Error cause: %s" % str(e))
  631. # log.debug("Geometry->bounds()")
  632. # if self.solid_geometry is None:
  633. # log.debug("solid_geometry is None")
  634. # return 0, 0, 0, 0
  635. #
  636. # if type(self.solid_geometry) is list:
  637. # if len(self.solid_geometry) == 0:
  638. # log.debug('solid_geometry is empty []')
  639. # return 0, 0, 0, 0
  640. # return cascaded_union(self.solid_geometry).bounds
  641. # else:
  642. # return self.solid_geometry.bounds
  643. def find_polygon(self, point, geoset=None):
  644. """
  645. Find an object that object.contains(Point(point)) in
  646. poly, which can can be iterable, contain iterable of, or
  647. be itself an implementer of .contains().
  648. :param point: See description
  649. :param geoset: a polygon or list of polygons where to find if the param point is contained
  650. :return: Polygon containing point or None.
  651. """
  652. if geoset is None:
  653. geoset = self.solid_geometry
  654. try: # Iterable
  655. for sub_geo in geoset:
  656. p = self.find_polygon(point, geoset=sub_geo)
  657. if p is not None:
  658. return p
  659. except TypeError: # Non-iterable
  660. try: # Implements .contains()
  661. if isinstance(geoset, LinearRing):
  662. geoset = Polygon(geoset)
  663. if geoset.contains(Point(point)):
  664. return geoset
  665. except AttributeError: # Does not implement .contains()
  666. return None
  667. return None
  668. def get_interiors(self, geometry=None):
  669. interiors = []
  670. if geometry is None:
  671. geometry = self.solid_geometry
  672. # ## If iterable, expand recursively.
  673. try:
  674. for geo in geometry:
  675. interiors.extend(self.get_interiors(geometry=geo))
  676. # ## Not iterable, get the interiors if polygon.
  677. except TypeError:
  678. if type(geometry) == Polygon:
  679. interiors.extend(geometry.interiors)
  680. return interiors
  681. def get_exteriors(self, geometry=None):
  682. """
  683. Returns all exteriors of polygons in geometry. Uses
  684. ``self.solid_geometry`` if geometry is not provided.
  685. :param geometry: Shapely type or list or list of list of such.
  686. :return: List of paths constituting the exteriors
  687. of polygons in geometry.
  688. """
  689. exteriors = []
  690. if geometry is None:
  691. geometry = self.solid_geometry
  692. # ## If iterable, expand recursively.
  693. try:
  694. for geo in geometry:
  695. exteriors.extend(self.get_exteriors(geometry=geo))
  696. # ## Not iterable, get the exterior if polygon.
  697. except TypeError:
  698. if type(geometry) == Polygon:
  699. exteriors.append(geometry.exterior)
  700. return exteriors
  701. def flatten(self, geometry=None, reset=True, pathonly=False):
  702. """
  703. Creates a list of non-iterable linear geometry objects.
  704. Polygons are expanded into its exterior and interiors if specified.
  705. Results are placed in self.flat_geometry
  706. :param geometry: Shapely type or list or list of list of such.
  707. :param reset: Clears the contents of self.flat_geometry.
  708. :param pathonly: Expands polygons into linear elements.
  709. """
  710. if geometry is None:
  711. geometry = self.solid_geometry
  712. if reset:
  713. self.flat_geometry = []
  714. # ## If iterable, expand recursively.
  715. try:
  716. for geo in geometry:
  717. if geo is not None:
  718. self.flatten(geometry=geo,
  719. reset=False,
  720. pathonly=pathonly)
  721. # ## Not iterable, do the actual indexing and add.
  722. except TypeError:
  723. if pathonly and type(geometry) == Polygon:
  724. self.flat_geometry.append(geometry.exterior)
  725. self.flatten(geometry=geometry.interiors,
  726. reset=False,
  727. pathonly=True)
  728. else:
  729. self.flat_geometry.append(geometry)
  730. return self.flat_geometry
  731. # def make2Dstorage(self):
  732. #
  733. # self.flatten()
  734. #
  735. # def get_pts(o):
  736. # pts = []
  737. # if type(o) == Polygon:
  738. # g = o.exterior
  739. # pts += list(g.coords)
  740. # for i in o.interiors:
  741. # pts += list(i.coords)
  742. # else:
  743. # pts += list(o.coords)
  744. # return pts
  745. #
  746. # storage = FlatCAMRTreeStorage()
  747. # storage.get_points = get_pts
  748. # for shape in self.flat_geometry:
  749. # storage.insert(shape)
  750. # return storage
  751. # def flatten_to_paths(self, geometry=None, reset=True):
  752. # """
  753. # Creates a list of non-iterable linear geometry elements and
  754. # indexes them in rtree.
  755. #
  756. # :param geometry: Iterable geometry
  757. # :param reset: Wether to clear (True) or append (False) to self.flat_geometry
  758. # :return: self.flat_geometry, self.flat_geometry_rtree
  759. # """
  760. #
  761. # if geometry is None:
  762. # geometry = self.solid_geometry
  763. #
  764. # if reset:
  765. # self.flat_geometry = []
  766. #
  767. # # ## If iterable, expand recursively.
  768. # try:
  769. # for geo in geometry:
  770. # self.flatten_to_paths(geometry=geo, reset=False)
  771. #
  772. # # ## Not iterable, do the actual indexing and add.
  773. # except TypeError:
  774. # if type(geometry) == Polygon:
  775. # g = geometry.exterior
  776. # self.flat_geometry.append(g)
  777. #
  778. # # ## Add first and last points of the path to the index.
  779. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[0])
  780. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[-1])
  781. #
  782. # for interior in geometry.interiors:
  783. # g = interior
  784. # self.flat_geometry.append(g)
  785. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[0])
  786. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[-1])
  787. # else:
  788. # g = geometry
  789. # self.flat_geometry.append(g)
  790. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[0])
  791. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[-1])
  792. #
  793. # return self.flat_geometry, self.flat_geometry_rtree
  794. def isolation_geometry(self, offset, geometry=None, iso_type=2, corner=None, follow=None, passes=0,
  795. prog_plot=False):
  796. """
  797. Creates contours around geometry at a given
  798. offset distance.
  799. :param offset: Offset distance.
  800. :type offset: float
  801. :param geometry The geometry to work with
  802. :param iso_type: type of isolation, can be 0 = exteriors or 1 = interiors or 2 = both (complete)
  803. :param corner: type of corner for the isolation:
  804. 0 = round; 1 = square; 2= beveled (line that connects the ends)
  805. :param follow: whether the geometry to be isolated is a follow_geometry
  806. :param passes: current pass out of possible multiple passes for which the isolation is done
  807. :param prog_plot: type of plotting: "normal" or "progressive"
  808. :return: The buffered geometry.
  809. :rtype: Shapely.MultiPolygon or Shapely.Polygon
  810. """
  811. if self.app.abort_flag:
  812. # graceful abort requested by the user
  813. raise grace
  814. geo_iso = []
  815. if follow:
  816. return geometry
  817. if geometry:
  818. working_geo = geometry
  819. else:
  820. working_geo = self.solid_geometry
  821. try:
  822. geo_len = len(working_geo)
  823. except TypeError:
  824. geo_len = 1
  825. old_disp_number = 0
  826. pol_nr = 0
  827. # yet, it can be done by issuing an unary_union in the end, thus getting rid of the overlapping geo
  828. try:
  829. for pol in working_geo:
  830. if self.app.abort_flag:
  831. # graceful abort requested by the user
  832. raise grace
  833. if offset == 0:
  834. temp_geo = pol
  835. else:
  836. corner_type = 1 if corner is None else corner
  837. temp_geo = pol.buffer(offset, int(self.geo_steps_per_circle), join_style=corner_type)
  838. geo_iso.append(temp_geo)
  839. pol_nr += 1
  840. # activity view update
  841. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  842. if old_disp_number < disp_number <= 100:
  843. self.app.proc_container.update_view_text(' %s %d: %d%%' %
  844. (_("Pass"), int(passes + 1), int(disp_number)))
  845. old_disp_number = disp_number
  846. except TypeError:
  847. # taking care of the case when the self.solid_geometry is just a single Polygon, not a list or a
  848. # MultiPolygon (not an iterable)
  849. if offset == 0:
  850. temp_geo = working_geo
  851. else:
  852. corner_type = 1 if corner is None else corner
  853. temp_geo = working_geo.buffer(offset, int(self.geo_steps_per_circle), join_style=corner_type)
  854. geo_iso.append(temp_geo)
  855. self.app.proc_container.update_view_text(' %s' % _("Buffering"))
  856. geo_iso = unary_union(geo_iso)
  857. self.app.proc_container.update_view_text('')
  858. # end of replaced block
  859. if iso_type == 2:
  860. ret_geo = geo_iso
  861. elif iso_type == 0:
  862. self.app.proc_container.update_view_text(' %s' % _("Get Exteriors"))
  863. ret_geo = self.get_exteriors(geo_iso)
  864. elif iso_type == 1:
  865. self.app.proc_container.update_view_text(' %s' % _("Get Interiors"))
  866. ret_geo = self.get_interiors(geo_iso)
  867. else:
  868. log.debug("Geometry.isolation_geometry() --> Type of isolation not supported")
  869. return "fail"
  870. if prog_plot == 'progressive':
  871. for elem in ret_geo:
  872. self.plot_temp_shapes(elem)
  873. return ret_geo
  874. def flatten_list(self, obj_list):
  875. for item in obj_list:
  876. if isinstance(item, Iterable) and not isinstance(item, (str, bytes)):
  877. yield from self.flatten_list(item)
  878. else:
  879. yield item
  880. def import_svg(self, filename, object_type=None, flip=True, units='MM'):
  881. """
  882. Imports shapes from an SVG file into the object's geometry.
  883. :param filename: Path to the SVG file.
  884. :type filename: str
  885. :param object_type: parameter passed further along
  886. :param flip: Flip the vertically.
  887. :type flip: bool
  888. :param units: FlatCAM units
  889. :return: None
  890. """
  891. log.debug("camlib.Geometry.import_svg()")
  892. # Parse into list of shapely objects
  893. svg_tree = ET.parse(filename)
  894. svg_root = svg_tree.getroot()
  895. # Change origin to bottom left
  896. # h = float(svg_root.get('height'))
  897. # w = float(svg_root.get('width'))
  898. h = svgparselength(svg_root.get('height'))[0] # TODO: No units support yet
  899. geos = getsvggeo(svg_root, object_type)
  900. if flip:
  901. geos = [translate(scale(g, 1.0, -1.0, origin=(0, 0)), yoff=h) for g in geos]
  902. # trying to optimize the resulting geometry by merging contiguous lines
  903. geos = list(self.flatten_list(geos))
  904. geos_polys = []
  905. geos_lines = []
  906. for g in geos:
  907. if isinstance(g, Polygon):
  908. geos_polys.append(g)
  909. else:
  910. geos_lines.append(g)
  911. merged_lines = linemerge(geos_lines)
  912. geos = geos_polys
  913. for l in merged_lines:
  914. geos.append(l)
  915. # Add to object
  916. if self.solid_geometry is None:
  917. self.solid_geometry = []
  918. if type(self.solid_geometry) is list:
  919. if type(geos) is list:
  920. self.solid_geometry += geos
  921. else:
  922. self.solid_geometry.append(geos)
  923. else: # It's shapely geometry
  924. self.solid_geometry = [self.solid_geometry, geos]
  925. # flatten the self.solid_geometry list for import_svg() to import SVG as Gerber
  926. self.solid_geometry = list(self.flatten_list(self.solid_geometry))
  927. geos_text = getsvgtext(svg_root, object_type, units=units)
  928. if geos_text is not None:
  929. geos_text_f = []
  930. if flip:
  931. # Change origin to bottom left
  932. for i in geos_text:
  933. __, minimy, __, maximy = i.bounds
  934. h2 = (maximy - minimy) * 0.5
  935. geos_text_f.append(translate(scale(i, 1.0, -1.0, origin=(0, 0)), yoff=(h + h2)))
  936. if geos_text_f:
  937. self.solid_geometry = self.solid_geometry + geos_text_f
  938. tooldia = float(self.app.defaults["geometry_cnctooldia"])
  939. tooldia = float('%.*f' % (self.decimals, tooldia))
  940. new_data = {k: v for k, v in self.options.items()}
  941. self.tools.update({
  942. 1: {
  943. 'tooldia': tooldia,
  944. 'offset': 'Path',
  945. 'offset_value': 0.0,
  946. 'type': _('Rough'),
  947. 'tool_type': 'C1',
  948. 'data': deepcopy(new_data),
  949. 'solid_geometry': self.solid_geometry
  950. }
  951. })
  952. self.tools[1]['data']['name'] = self.options['name']
  953. def import_dxf_as_geo(self, filename, units='MM'):
  954. """
  955. Imports shapes from an DXF file into the object's geometry.
  956. :param filename: Path to the DXF file.
  957. :type filename: str
  958. :param units: Application units
  959. :return: None
  960. """
  961. log.debug("Parsing DXF file geometry into a Geometry object solid geometry.")
  962. # Parse into list of shapely objects
  963. dxf = ezdxf.readfile(filename)
  964. geos = getdxfgeo(dxf)
  965. # trying to optimize the resulting geometry by merging contiguous lines
  966. geos = list(self.flatten_list(geos))
  967. geos_polys = []
  968. geos_lines = []
  969. for g in geos:
  970. if isinstance(g, Polygon):
  971. geos_polys.append(g)
  972. else:
  973. geos_lines.append(g)
  974. merged_lines = linemerge(geos_lines)
  975. geos = geos_polys
  976. for l in merged_lines:
  977. geos.append(l)
  978. # Add to object
  979. if self.solid_geometry is None:
  980. self.solid_geometry = []
  981. if type(self.solid_geometry) is list:
  982. if type(geos) is list:
  983. self.solid_geometry += geos
  984. else:
  985. self.solid_geometry.append(geos)
  986. else: # It's shapely geometry
  987. self.solid_geometry = [self.solid_geometry, geos]
  988. tooldia = float(self.app.defaults["geometry_cnctooldia"])
  989. tooldia = float('%.*f' % (self.decimals, tooldia))
  990. new_data = {k: v for k, v in self.options.items()}
  991. self.tools.update({
  992. 1: {
  993. 'tooldia': tooldia,
  994. 'offset': 'Path',
  995. 'offset_value': 0.0,
  996. 'type': _('Rough'),
  997. 'tool_type': 'C1',
  998. 'data': deepcopy(new_data),
  999. 'solid_geometry': self.solid_geometry
  1000. }
  1001. })
  1002. self.tools[1]['data']['name'] = self.options['name']
  1003. # commented until this function is ready
  1004. # geos_text = getdxftext(dxf, object_type, units=units)
  1005. # if geos_text is not None:
  1006. # geos_text_f = []
  1007. # self.solid_geometry = [self.solid_geometry, geos_text_f]
  1008. def import_image(self, filename, flip=True, units='MM', dpi=96, mode='black', mask=None):
  1009. """
  1010. Imports shapes from an IMAGE file into the object's geometry.
  1011. :param filename: Path to the IMAGE file.
  1012. :type filename: str
  1013. :param flip: Flip the object vertically.
  1014. :type flip: bool
  1015. :param units: FlatCAM units
  1016. :type units: str
  1017. :param dpi: dots per inch on the imported image
  1018. :param mode: how to import the image: as 'black' or 'color'
  1019. :type mode: str
  1020. :param mask: level of detail for the import
  1021. :return: None
  1022. """
  1023. if mask is None:
  1024. mask = [128, 128, 128, 128]
  1025. scale_factor = 25.4 / dpi if units.lower() == 'mm' else 1 / dpi
  1026. geos = []
  1027. unscaled_geos = []
  1028. with rasterio.open(filename) as src:
  1029. # if filename.lower().rpartition('.')[-1] == 'bmp':
  1030. # red = green = blue = src.read(1)
  1031. # print("BMP")
  1032. # elif filename.lower().rpartition('.')[-1] == 'png':
  1033. # red, green, blue, alpha = src.read()
  1034. # elif filename.lower().rpartition('.')[-1] == 'jpg':
  1035. # red, green, blue = src.read()
  1036. red = green = blue = src.read(1)
  1037. try:
  1038. green = src.read(2)
  1039. except Exception:
  1040. pass
  1041. try:
  1042. blue = src.read(3)
  1043. except Exception:
  1044. pass
  1045. if mode == 'black':
  1046. mask_setting = red <= mask[0]
  1047. total = red
  1048. log.debug("Image import as monochrome.")
  1049. else:
  1050. mask_setting = (red <= mask[1]) + (green <= mask[2]) + (blue <= mask[3])
  1051. total = np.zeros(red.shape, dtype=np.float32)
  1052. for band in red, green, blue:
  1053. total += band
  1054. total /= 3
  1055. log.debug("Image import as colored. Thresholds are: R = %s , G = %s, B = %s" %
  1056. (str(mask[1]), str(mask[2]), str(mask[3])))
  1057. for geom, val in shapes(total, mask=mask_setting):
  1058. unscaled_geos.append(shape(geom))
  1059. for g in unscaled_geos:
  1060. geos.append(scale(g, scale_factor, scale_factor, origin=(0, 0)))
  1061. if flip:
  1062. geos = [translate(scale(g, 1.0, -1.0, origin=(0, 0))) for g in geos]
  1063. # Add to object
  1064. if self.solid_geometry is None:
  1065. self.solid_geometry = []
  1066. if type(self.solid_geometry) is list:
  1067. # self.solid_geometry.append(cascaded_union(geos))
  1068. if type(geos) is list:
  1069. self.solid_geometry += geos
  1070. else:
  1071. self.solid_geometry.append(geos)
  1072. else: # It's shapely geometry
  1073. self.solid_geometry = [self.solid_geometry, geos]
  1074. # flatten the self.solid_geometry list for import_svg() to import SVG as Gerber
  1075. self.solid_geometry = list(self.flatten_list(self.solid_geometry))
  1076. self.solid_geometry = cascaded_union(self.solid_geometry)
  1077. # self.solid_geometry = MultiPolygon(self.solid_geometry)
  1078. # self.solid_geometry = self.solid_geometry.buffer(0.00000001)
  1079. # self.solid_geometry = self.solid_geometry.buffer(-0.00000001)
  1080. def size(self):
  1081. """
  1082. Returns (width, height) of rectangular
  1083. bounds of geometry.
  1084. """
  1085. if self.solid_geometry is None:
  1086. log.warning("Solid_geometry not computed yet.")
  1087. return 0
  1088. bounds = self.bounds()
  1089. return bounds[2] - bounds[0], bounds[3] - bounds[1]
  1090. def get_empty_area(self, boundary=None):
  1091. """
  1092. Returns the complement of self.solid_geometry within
  1093. the given boundary polygon. If not specified, it defaults to
  1094. the rectangular bounding box of self.solid_geometry.
  1095. """
  1096. if boundary is None:
  1097. boundary = self.solid_geometry.envelope
  1098. return boundary.difference(self.solid_geometry)
  1099. def clear_polygon(self, polygon, tooldia, steps_per_circle, overlap=0.15, connect=True, contour=True,
  1100. prog_plot=False):
  1101. """
  1102. Creates geometry inside a polygon for a tool to cover
  1103. the whole area.
  1104. This algorithm shrinks the edges of the polygon and takes
  1105. the resulting edges as toolpaths.
  1106. :param polygon: Polygon to clear.
  1107. :param tooldia: Diameter of the tool.
  1108. :param steps_per_circle: number of linear segments to be used to approximate a circle
  1109. :param overlap: Overlap of toolpasses.
  1110. :param connect: Draw lines between disjoint segments to
  1111. minimize tool lifts.
  1112. :param contour: Paint around the edges. Inconsequential in
  1113. this painting method.
  1114. :param prog_plot: boolean; if Ture use the progressive plotting
  1115. :return:
  1116. """
  1117. # log.debug("camlib.clear_polygon()")
  1118. assert type(polygon) == Polygon or type(polygon) == MultiPolygon, \
  1119. "Expected a Polygon or MultiPolygon, got %s" % type(polygon)
  1120. # ## The toolpaths
  1121. # Index first and last points in paths
  1122. def get_pts(o):
  1123. return [o.coords[0], o.coords[-1]]
  1124. geoms = FlatCAMRTreeStorage()
  1125. geoms.get_points = get_pts
  1126. # Can only result in a Polygon or MultiPolygon
  1127. # NOTE: The resulting polygon can be "empty".
  1128. current = polygon.buffer((-tooldia / 1.999999), int(steps_per_circle))
  1129. if current.area == 0:
  1130. # Otherwise, trying to to insert current.exterior == None
  1131. # into the FlatCAMStorage will fail.
  1132. # print("Area is None")
  1133. return None
  1134. # current can be a MultiPolygon
  1135. try:
  1136. for p in current:
  1137. geoms.insert(p.exterior)
  1138. for i in p.interiors:
  1139. geoms.insert(i)
  1140. # Not a Multipolygon. Must be a Polygon
  1141. except TypeError:
  1142. geoms.insert(current.exterior)
  1143. for i in current.interiors:
  1144. geoms.insert(i)
  1145. while True:
  1146. if self.app.abort_flag:
  1147. # graceful abort requested by the user
  1148. raise grace
  1149. # provide the app with a way to process the GUI events when in a blocking loop
  1150. QtWidgets.QApplication.processEvents()
  1151. # Can only result in a Polygon or MultiPolygon
  1152. current = current.buffer(-tooldia * (1 - overlap), int(steps_per_circle))
  1153. if current.area > 0:
  1154. # current can be a MultiPolygon
  1155. try:
  1156. for p in current:
  1157. geoms.insert(p.exterior)
  1158. for i in p.interiors:
  1159. geoms.insert(i)
  1160. if prog_plot:
  1161. self.plot_temp_shapes(p)
  1162. # Not a Multipolygon. Must be a Polygon
  1163. except TypeError:
  1164. geoms.insert(current.exterior)
  1165. if prog_plot:
  1166. self.plot_temp_shapes(current.exterior)
  1167. for i in current.interiors:
  1168. geoms.insert(i)
  1169. if prog_plot:
  1170. self.plot_temp_shapes(i)
  1171. else:
  1172. log.debug("camlib.Geometry.clear_polygon() --> Current Area is zero")
  1173. break
  1174. if prog_plot:
  1175. self.temp_shapes.redraw()
  1176. # Optimization: Reduce lifts
  1177. if connect:
  1178. # log.debug("Reducing tool lifts...")
  1179. geoms = Geometry.paint_connect(geoms, polygon, tooldia, int(steps_per_circle))
  1180. return geoms
  1181. def clear_polygon2(self, polygon_to_clear, tooldia, steps_per_circle, seedpoint=None, overlap=0.15,
  1182. connect=True, contour=True, prog_plot=False):
  1183. """
  1184. Creates geometry inside a polygon for a tool to cover
  1185. the whole area.
  1186. This algorithm starts with a seed point inside the polygon
  1187. and draws circles around it. Arcs inside the polygons are
  1188. valid cuts. Finalizes by cutting around the inside edge of
  1189. the polygon.
  1190. :param polygon_to_clear: Shapely.geometry.Polygon
  1191. :param steps_per_circle: how many linear segments to use to approximate a circle
  1192. :param tooldia: Diameter of the tool
  1193. :param seedpoint: Shapely.geometry.Point or None
  1194. :param overlap: Tool fraction overlap bewteen passes
  1195. :param connect: Connect disjoint segment to minumize tool lifts
  1196. :param contour: Cut countour inside the polygon.
  1197. :param prog_plot: boolean; if True use the progressive plotting
  1198. :return: List of toolpaths covering polygon.
  1199. :rtype: FlatCAMRTreeStorage | None
  1200. """
  1201. # log.debug("camlib.clear_polygon2()")
  1202. # Current buffer radius
  1203. radius = tooldia / 2 * (1 - overlap)
  1204. # ## The toolpaths
  1205. # Index first and last points in paths
  1206. def get_pts(o):
  1207. return [o.coords[0], o.coords[-1]]
  1208. geoms = FlatCAMRTreeStorage()
  1209. geoms.get_points = get_pts
  1210. # Path margin
  1211. path_margin = polygon_to_clear.buffer(-tooldia / 2, int(steps_per_circle))
  1212. if path_margin.is_empty or path_margin is None:
  1213. return None
  1214. # Estimate good seedpoint if not provided.
  1215. if seedpoint is None:
  1216. seedpoint = path_margin.representative_point()
  1217. # Grow from seed until outside the box. The polygons will
  1218. # never have an interior, so take the exterior LinearRing.
  1219. while True:
  1220. if self.app.abort_flag:
  1221. # graceful abort requested by the user
  1222. raise grace
  1223. # provide the app with a way to process the GUI events when in a blocking loop
  1224. QtWidgets.QApplication.processEvents()
  1225. path = Point(seedpoint).buffer(radius, int(steps_per_circle)).exterior
  1226. path = path.intersection(path_margin)
  1227. # Touches polygon?
  1228. if path.is_empty:
  1229. break
  1230. else:
  1231. # geoms.append(path)
  1232. # geoms.insert(path)
  1233. # path can be a collection of paths.
  1234. try:
  1235. for p in path:
  1236. geoms.insert(p)
  1237. if prog_plot:
  1238. self.plot_temp_shapes(p)
  1239. except TypeError:
  1240. geoms.insert(path)
  1241. if prog_plot:
  1242. self.plot_temp_shapes(path)
  1243. if prog_plot:
  1244. self.temp_shapes.redraw()
  1245. radius += tooldia * (1 - overlap)
  1246. # Clean inside edges (contours) of the original polygon
  1247. if contour:
  1248. buffered_poly = autolist(polygon_to_clear.buffer(-tooldia / 2, int(steps_per_circle)))
  1249. outer_edges = [x.exterior for x in buffered_poly]
  1250. inner_edges = []
  1251. # Over resulting polygons
  1252. for x in buffered_poly:
  1253. for y in x.interiors: # Over interiors of each polygon
  1254. inner_edges.append(y)
  1255. # geoms += outer_edges + inner_edges
  1256. for g in outer_edges + inner_edges:
  1257. if g and not g.is_empty:
  1258. geoms.insert(g)
  1259. if prog_plot:
  1260. self.plot_temp_shapes(g)
  1261. if prog_plot:
  1262. self.temp_shapes.redraw()
  1263. # Optimization connect touching paths
  1264. # log.debug("Connecting paths...")
  1265. # geoms = Geometry.path_connect(geoms)
  1266. # Optimization: Reduce lifts
  1267. if connect:
  1268. # log.debug("Reducing tool lifts...")
  1269. geoms_conn = Geometry.paint_connect(geoms, polygon_to_clear, tooldia, steps_per_circle)
  1270. if geoms_conn:
  1271. return geoms_conn
  1272. return geoms
  1273. def clear_polygon3(self, polygon, tooldia, steps_per_circle, overlap=0.15, connect=True, contour=True,
  1274. prog_plot=False):
  1275. """
  1276. Creates geometry inside a polygon for a tool to cover
  1277. the whole area.
  1278. This algorithm draws horizontal lines inside the polygon.
  1279. :param polygon: The polygon being painted.
  1280. :type polygon: shapely.geometry.Polygon
  1281. :param tooldia: Tool diameter.
  1282. :param steps_per_circle: how many linear segments to use to approximate a circle
  1283. :param overlap: Tool path overlap percentage.
  1284. :param connect: Connect lines to avoid tool lifts.
  1285. :param contour: Paint around the edges.
  1286. :param prog_plot: boolean; if to use the progressive plotting
  1287. :return:
  1288. """
  1289. # log.debug("camlib.clear_polygon3()")
  1290. if not isinstance(polygon, Polygon):
  1291. log.debug("camlib.Geometry.clear_polygon3() --> Not a Polygon but %s" % str(type(polygon)))
  1292. return None
  1293. # ## The toolpaths
  1294. # Index first and last points in paths
  1295. def get_pts(o):
  1296. return [o.coords[0], o.coords[-1]]
  1297. geoms = FlatCAMRTreeStorage()
  1298. geoms.get_points = get_pts
  1299. lines_trimmed = []
  1300. # Bounding box
  1301. left, bot, right, top = polygon.bounds
  1302. try:
  1303. margin_poly = polygon.buffer(-tooldia / 1.99999999, (int(steps_per_circle)))
  1304. except Exception:
  1305. log.debug("camlib.Geometry.clear_polygon3() --> Could not buffer the Polygon")
  1306. return None
  1307. # decide the direction of the lines
  1308. if abs(left - right) >= abs(top - bot):
  1309. # First line
  1310. try:
  1311. y = top - tooldia / 1.99999999
  1312. while y > bot + tooldia / 1.999999999:
  1313. if self.app.abort_flag:
  1314. # graceful abort requested by the user
  1315. raise grace
  1316. # provide the app with a way to process the GUI events when in a blocking loop
  1317. QtWidgets.QApplication.processEvents()
  1318. line = LineString([(left, y), (right, y)])
  1319. line = line.intersection(margin_poly)
  1320. lines_trimmed.append(line)
  1321. y -= tooldia * (1 - overlap)
  1322. if prog_plot:
  1323. self.plot_temp_shapes(line)
  1324. self.temp_shapes.redraw()
  1325. # Last line
  1326. y = bot + tooldia / 2
  1327. line = LineString([(left, y), (right, y)])
  1328. line = line.intersection(margin_poly)
  1329. try:
  1330. for ll in line:
  1331. lines_trimmed.append(ll)
  1332. if prog_plot:
  1333. self.plot_temp_shapes(ll)
  1334. except TypeError:
  1335. lines_trimmed.append(line)
  1336. if prog_plot:
  1337. self.plot_temp_shapes(line)
  1338. except Exception as e:
  1339. log.debug('camlib.Geometry.clear_polygon3() Processing poly --> %s' % str(e))
  1340. return None
  1341. else:
  1342. # First line
  1343. try:
  1344. x = left + tooldia / 1.99999999
  1345. while x < right - tooldia / 1.999999999:
  1346. if self.app.abort_flag:
  1347. # graceful abort requested by the user
  1348. raise grace
  1349. # provide the app with a way to process the GUI events when in a blocking loop
  1350. QtWidgets.QApplication.processEvents()
  1351. line = LineString([(x, top), (x, bot)])
  1352. line = line.intersection(margin_poly)
  1353. lines_trimmed.append(line)
  1354. x += tooldia * (1 - overlap)
  1355. if prog_plot:
  1356. self.plot_temp_shapes(line)
  1357. self.temp_shapes.redraw()
  1358. # Last line
  1359. x = right + tooldia / 2
  1360. line = LineString([(x, top), (x, bot)])
  1361. line = line.intersection(margin_poly)
  1362. try:
  1363. for ll in line:
  1364. lines_trimmed.append(ll)
  1365. if prog_plot:
  1366. self.plot_temp_shapes(ll)
  1367. except TypeError:
  1368. lines_trimmed.append(line)
  1369. if prog_plot:
  1370. self.plot_temp_shapes(line)
  1371. except Exception as e:
  1372. log.debug('camlib.Geometry.clear_polygon3() Processing poly --> %s' % str(e))
  1373. return None
  1374. if prog_plot:
  1375. self.temp_shapes.redraw()
  1376. lines_trimmed = unary_union(lines_trimmed)
  1377. # Add lines to storage
  1378. try:
  1379. for line in lines_trimmed:
  1380. if isinstance(line, LineString) or isinstance(line, LinearRing):
  1381. if not line.is_empty:
  1382. geoms.insert(line)
  1383. else:
  1384. log.debug("camlib.Geometry.clear_polygon3(). Not a line: %s" % str(type(line)))
  1385. except TypeError:
  1386. # in case lines_trimmed are not iterable (Linestring, LinearRing)
  1387. if not lines_trimmed.is_empty:
  1388. geoms.insert(lines_trimmed)
  1389. # Add margin (contour) to storage
  1390. if contour:
  1391. try:
  1392. for poly in margin_poly:
  1393. if isinstance(poly, Polygon) and not poly.is_empty:
  1394. geoms.insert(poly.exterior)
  1395. if prog_plot:
  1396. self.plot_temp_shapes(poly.exterior)
  1397. for ints in poly.interiors:
  1398. geoms.insert(ints)
  1399. if prog_plot:
  1400. self.plot_temp_shapes(ints)
  1401. except TypeError:
  1402. if isinstance(margin_poly, Polygon) and not margin_poly.is_empty:
  1403. marg_ext = margin_poly.exterior
  1404. geoms.insert(marg_ext)
  1405. if prog_plot:
  1406. self.plot_temp_shapes(margin_poly.exterior)
  1407. for ints in margin_poly.interiors:
  1408. geoms.insert(ints)
  1409. if prog_plot:
  1410. self.plot_temp_shapes(ints)
  1411. if prog_plot:
  1412. self.temp_shapes.redraw()
  1413. # Optimization: Reduce lifts
  1414. if connect:
  1415. # log.debug("Reducing tool lifts...")
  1416. geoms_conn = Geometry.paint_connect(geoms, polygon, tooldia, steps_per_circle)
  1417. if geoms_conn:
  1418. return geoms_conn
  1419. return geoms
  1420. def fill_with_lines(self, line, aperture_size, tooldia, steps_per_circle, overlap=0.15, connect=True, contour=True,
  1421. prog_plot=False):
  1422. """
  1423. Creates geometry of lines inside a polygon for a tool to cover
  1424. the whole area.
  1425. This algorithm draws parallel lines inside the polygon.
  1426. :param line: The target line that create painted polygon.
  1427. :param aperture_size: the size of the aperture that is used to draw the 'line' as a polygon
  1428. :type line: shapely.geometry.LineString or shapely.geometry.MultiLineString
  1429. :param tooldia: Tool diameter.
  1430. :param steps_per_circle: how many linear segments to use to approximate a circle
  1431. :param overlap: Tool path overlap percentage.
  1432. :param connect: Connect lines to avoid tool lifts.
  1433. :param contour: Paint around the edges.
  1434. :param prog_plot: boolean; if to use the progressive plotting
  1435. :return:
  1436. """
  1437. # log.debug("camlib.fill_with_lines()")
  1438. if not isinstance(line, LineString):
  1439. log.debug("camlib.Geometry.fill_with_lines() --> Not a LineString/MultiLineString but %s" % str(type(line)))
  1440. return None
  1441. # ## The toolpaths
  1442. # Index first and last points in paths
  1443. def get_pts(o):
  1444. return [o.coords[0], o.coords[-1]]
  1445. geoms = FlatCAMRTreeStorage()
  1446. geoms.get_points = get_pts
  1447. lines_trimmed = []
  1448. polygon = line.buffer(aperture_size / 2.0, int(steps_per_circle))
  1449. try:
  1450. margin_poly = polygon.buffer(-tooldia / 2.0, int(steps_per_circle))
  1451. except Exception:
  1452. log.debug("camlib.Geometry.fill_with_lines() --> Could not buffer the Polygon, tool diameter too high")
  1453. return None
  1454. # First line
  1455. try:
  1456. delta = 0
  1457. while delta < aperture_size / 2:
  1458. if self.app.abort_flag:
  1459. # graceful abort requested by the user
  1460. raise grace
  1461. # provide the app with a way to process the GUI events when in a blocking loop
  1462. QtWidgets.QApplication.processEvents()
  1463. new_line = line.parallel_offset(distance=delta, side='left', resolution=int(steps_per_circle))
  1464. new_line = new_line.intersection(margin_poly)
  1465. lines_trimmed.append(new_line)
  1466. new_line = line.parallel_offset(distance=delta, side='right', resolution=int(steps_per_circle))
  1467. new_line = new_line.intersection(margin_poly)
  1468. lines_trimmed.append(new_line)
  1469. delta += tooldia * (1 - overlap)
  1470. if prog_plot:
  1471. self.plot_temp_shapes(new_line)
  1472. self.temp_shapes.redraw()
  1473. # Last line
  1474. delta = (aperture_size / 2) - (tooldia / 2.00000001)
  1475. new_line = line.parallel_offset(distance=delta, side='left', resolution=int(steps_per_circle))
  1476. new_line = new_line.intersection(margin_poly)
  1477. except Exception as e:
  1478. log.debug('camlib.Geometry.fill_with_lines() Processing poly --> %s' % str(e))
  1479. return None
  1480. try:
  1481. for ll in new_line:
  1482. lines_trimmed.append(ll)
  1483. if prog_plot:
  1484. self.plot_temp_shapes(ll)
  1485. except TypeError:
  1486. lines_trimmed.append(new_line)
  1487. if prog_plot:
  1488. self.plot_temp_shapes(new_line)
  1489. new_line = line.parallel_offset(distance=delta, side='right', resolution=int(steps_per_circle))
  1490. new_line = new_line.intersection(margin_poly)
  1491. try:
  1492. for ll in new_line:
  1493. lines_trimmed.append(ll)
  1494. if prog_plot:
  1495. self.plot_temp_shapes(ll)
  1496. except TypeError:
  1497. lines_trimmed.append(new_line)
  1498. if prog_plot:
  1499. self.plot_temp_shapes(new_line)
  1500. if prog_plot:
  1501. self.temp_shapes.redraw()
  1502. lines_trimmed = unary_union(lines_trimmed)
  1503. # Add lines to storage
  1504. try:
  1505. for line in lines_trimmed:
  1506. if isinstance(line, LineString) or isinstance(line, LinearRing):
  1507. geoms.insert(line)
  1508. else:
  1509. log.debug("camlib.Geometry.fill_with_lines(). Not a line: %s" % str(type(line)))
  1510. except TypeError:
  1511. # in case lines_trimmed are not iterable (Linestring, LinearRing)
  1512. geoms.insert(lines_trimmed)
  1513. # Add margin (contour) to storage
  1514. if contour:
  1515. try:
  1516. for poly in margin_poly:
  1517. if isinstance(poly, Polygon) and not poly.is_empty:
  1518. geoms.insert(poly.exterior)
  1519. if prog_plot:
  1520. self.plot_temp_shapes(poly.exterior)
  1521. for ints in poly.interiors:
  1522. geoms.insert(ints)
  1523. if prog_plot:
  1524. self.plot_temp_shapes(ints)
  1525. except TypeError:
  1526. if isinstance(margin_poly, Polygon) and not margin_poly.is_empty:
  1527. marg_ext = margin_poly.exterior
  1528. geoms.insert(marg_ext)
  1529. if prog_plot:
  1530. self.plot_temp_shapes(margin_poly.exterior)
  1531. for ints in margin_poly.interiors:
  1532. geoms.insert(ints)
  1533. if prog_plot:
  1534. self.plot_temp_shapes(ints)
  1535. if prog_plot:
  1536. self.temp_shapes.redraw()
  1537. # Optimization: Reduce lifts
  1538. if connect:
  1539. # log.debug("Reducing tool lifts...")
  1540. geoms_conn = Geometry.paint_connect(geoms, polygon, tooldia, steps_per_circle)
  1541. if geoms_conn:
  1542. return geoms_conn
  1543. return geoms
  1544. def scale(self, xfactor, yfactor, point=None):
  1545. """
  1546. Scales all of the object's geometry by a given factor. Override
  1547. this method.
  1548. :param xfactor: Number by which to scale on X axis.
  1549. :type xfactor: float
  1550. :param yfactor: Number by which to scale on Y axis.
  1551. :type yfactor: float
  1552. :param point: point to be used as reference for scaling; a tuple
  1553. :return: None
  1554. :rtype: None
  1555. """
  1556. return
  1557. def offset(self, vect):
  1558. """
  1559. Offset the geometry by the given vector. Override this method.
  1560. :param vect: (x, y) vector by which to offset the object.
  1561. :type vect: tuple
  1562. :return: None
  1563. """
  1564. return
  1565. @staticmethod
  1566. def paint_connect(storage, boundary, tooldia, steps_per_circle, max_walk=None):
  1567. """
  1568. Connects paths that results in a connection segment that is
  1569. within the paint area. This avoids unnecessary tool lifting.
  1570. :param storage: Geometry to be optimized.
  1571. :type storage: FlatCAMRTreeStorage
  1572. :param boundary: Polygon defining the limits of the paintable area.
  1573. :type boundary: Polygon
  1574. :param tooldia: Tool diameter.
  1575. :rtype tooldia: float
  1576. :param steps_per_circle: how many linear segments to use to approximate a circle
  1577. :param max_walk: Maximum allowable distance without lifting tool.
  1578. :type max_walk: float or None
  1579. :return: Optimized geometry.
  1580. :rtype: FlatCAMRTreeStorage
  1581. """
  1582. # If max_walk is not specified, the maximum allowed is
  1583. # 10 times the tool diameter
  1584. max_walk = max_walk or 10 * tooldia
  1585. # Assuming geolist is a flat list of flat elements
  1586. # ## Index first and last points in paths
  1587. def get_pts(o):
  1588. return [o.coords[0], o.coords[-1]]
  1589. # storage = FlatCAMRTreeStorage()
  1590. # storage.get_points = get_pts
  1591. #
  1592. # for shape in geolist:
  1593. # if shape is not None:
  1594. # # Make LlinearRings into linestrings otherwise
  1595. # # When chaining the coordinates path is messed up.
  1596. # storage.insert(LineString(shape))
  1597. # #storage.insert(shape)
  1598. # ## Iterate over geometry paths getting the nearest each time.
  1599. # optimized_paths = []
  1600. optimized_paths = FlatCAMRTreeStorage()
  1601. optimized_paths.get_points = get_pts
  1602. path_count = 0
  1603. current_pt = (0, 0)
  1604. try:
  1605. pt, geo = storage.nearest(current_pt)
  1606. except StopIteration:
  1607. log.debug("camlib.Geometry.paint_connect(). Storage empty")
  1608. return None
  1609. storage.remove(geo)
  1610. geo = LineString(geo)
  1611. current_pt = geo.coords[-1]
  1612. try:
  1613. while True:
  1614. path_count += 1
  1615. # log.debug("Path %d" % path_count)
  1616. pt, candidate = storage.nearest(current_pt)
  1617. storage.remove(candidate)
  1618. candidate = LineString(candidate)
  1619. # If last point in geometry is the nearest
  1620. # then reverse coordinates.
  1621. # but prefer the first one if last == first
  1622. if pt != candidate.coords[0] and pt == candidate.coords[-1]:
  1623. # in place coordinates update deprecated in Shapely 2.0
  1624. # candidate.coords = list(candidate.coords)[::-1]
  1625. candidate = LineString(list(candidate.coords)[::-1])
  1626. # Straight line from current_pt to pt.
  1627. # Is the toolpath inside the geometry?
  1628. walk_path = LineString([current_pt, pt])
  1629. walk_cut = walk_path.buffer(tooldia / 2, int(steps_per_circle))
  1630. if walk_cut.within(boundary) and walk_path.length < max_walk:
  1631. # log.debug("Walk to path #%d is inside. Joining." % path_count)
  1632. # Completely inside. Append...
  1633. # in place coordinates update deprecated in Shapely 2.0
  1634. # geo.coords = list(geo.coords) + list(candidate.coords)
  1635. geo = LineString(list(geo.coords) + list(candidate.coords))
  1636. # try:
  1637. # last = optimized_paths[-1]
  1638. # last.coords = list(last.coords) + list(geo.coords)
  1639. # except IndexError:
  1640. # optimized_paths.append(geo)
  1641. else:
  1642. # Have to lift tool. End path.
  1643. # log.debug("Path #%d not within boundary. Next." % path_count)
  1644. # optimized_paths.append(geo)
  1645. optimized_paths.insert(geo)
  1646. geo = candidate
  1647. current_pt = geo.coords[-1]
  1648. # Next
  1649. # pt, geo = storage.nearest(current_pt)
  1650. except StopIteration: # Nothing left in storage.
  1651. # pass
  1652. optimized_paths.insert(geo)
  1653. return optimized_paths
  1654. @staticmethod
  1655. def path_connect(storage, origin=(0, 0)):
  1656. """
  1657. Simplifies paths in the FlatCAMRTreeStorage storage by
  1658. connecting paths that touch on their endpoints.
  1659. :param storage: Storage containing the initial paths.
  1660. :rtype storage: FlatCAMRTreeStorage
  1661. :param origin: tuple; point from which to calculate the nearest point
  1662. :return: Simplified storage.
  1663. :rtype: FlatCAMRTreeStorage
  1664. """
  1665. log.debug("path_connect()")
  1666. # ## Index first and last points in paths
  1667. def get_pts(o):
  1668. return [o.coords[0], o.coords[-1]]
  1669. #
  1670. # storage = FlatCAMRTreeStorage()
  1671. # storage.get_points = get_pts
  1672. #
  1673. # for shape in pathlist:
  1674. # if shape is not None:
  1675. # storage.insert(shape)
  1676. path_count = 0
  1677. pt, geo = storage.nearest(origin)
  1678. storage.remove(geo)
  1679. # optimized_geometry = [geo]
  1680. optimized_geometry = FlatCAMRTreeStorage()
  1681. optimized_geometry.get_points = get_pts
  1682. # optimized_geometry.insert(geo)
  1683. try:
  1684. while True:
  1685. path_count += 1
  1686. _, left = storage.nearest(geo.coords[0])
  1687. # If left touches geo, remove left from original
  1688. # storage and append to geo.
  1689. if type(left) == LineString:
  1690. if left.coords[0] == geo.coords[0]:
  1691. storage.remove(left)
  1692. geo.coords = list(geo.coords)[::-1] + list(left.coords)
  1693. continue
  1694. if left.coords[-1] == geo.coords[0]:
  1695. storage.remove(left)
  1696. geo.coords = list(left.coords) + list(geo.coords)
  1697. continue
  1698. if left.coords[0] == geo.coords[-1]:
  1699. storage.remove(left)
  1700. geo.coords = list(geo.coords) + list(left.coords)
  1701. continue
  1702. if left.coords[-1] == geo.coords[-1]:
  1703. storage.remove(left)
  1704. geo.coords = list(geo.coords) + list(left.coords)[::-1]
  1705. continue
  1706. _, right = storage.nearest(geo.coords[-1])
  1707. # If right touches geo, remove left from original
  1708. # storage and append to geo.
  1709. if type(right) == LineString:
  1710. if right.coords[0] == geo.coords[-1]:
  1711. storage.remove(right)
  1712. geo.coords = list(geo.coords) + list(right.coords)
  1713. continue
  1714. if right.coords[-1] == geo.coords[-1]:
  1715. storage.remove(right)
  1716. geo.coords = list(geo.coords) + list(right.coords)[::-1]
  1717. continue
  1718. if right.coords[0] == geo.coords[0]:
  1719. storage.remove(right)
  1720. geo.coords = list(geo.coords)[::-1] + list(right.coords)
  1721. continue
  1722. if right.coords[-1] == geo.coords[0]:
  1723. storage.remove(right)
  1724. geo.coords = list(left.coords) + list(geo.coords)
  1725. continue
  1726. # right is either a LinearRing or it does not connect
  1727. # to geo (nothing left to connect to geo), so we continue
  1728. # with right as geo.
  1729. storage.remove(right)
  1730. if type(right) == LinearRing:
  1731. optimized_geometry.insert(right)
  1732. else:
  1733. # Cannot extend geo any further. Put it away.
  1734. optimized_geometry.insert(geo)
  1735. # Continue with right.
  1736. geo = right
  1737. except StopIteration: # Nothing found in storage.
  1738. optimized_geometry.insert(geo)
  1739. # print path_count
  1740. log.debug("path_count = %d" % path_count)
  1741. return optimized_geometry
  1742. def convert_units(self, obj_units):
  1743. """
  1744. Converts the units of the object to ``units`` by scaling all
  1745. the geometry appropriately. This call ``scale()``. Don't call
  1746. it again in descendents.
  1747. :param obj_units: "IN" or "MM"
  1748. :type obj_units: str
  1749. :return: Scaling factor resulting from unit change.
  1750. :rtype: float
  1751. """
  1752. if obj_units.upper() == self.units.upper():
  1753. log.debug("camlib.Geometry.convert_units() --> Factor: 1")
  1754. return 1.0
  1755. if obj_units.upper() == "MM":
  1756. factor = 25.4
  1757. log.debug("camlib.Geometry.convert_units() --> Factor: 25.4")
  1758. elif obj_units.upper() == "IN":
  1759. factor = 1 / 25.4
  1760. log.debug("camlib.Geometry.convert_units() --> Factor: %s" % str(1 / 25.4))
  1761. else:
  1762. log.error("Unsupported units: %s" % str(obj_units))
  1763. log.debug("camlib.Geometry.convert_units() --> Factor: 1")
  1764. return 1.0
  1765. self.units = obj_units
  1766. self.scale(factor, factor)
  1767. self.file_units_factor = factor
  1768. return factor
  1769. def to_dict(self):
  1770. """
  1771. Returns a representation of the object as a dictionary.
  1772. Attributes to include are listed in ``self.ser_attrs``.
  1773. :return: A dictionary-encoded copy of the object.
  1774. :rtype: dict
  1775. """
  1776. d = {}
  1777. for attr in self.ser_attrs:
  1778. d[attr] = getattr(self, attr)
  1779. return d
  1780. def from_dict(self, d):
  1781. """
  1782. Sets object's attributes from a dictionary.
  1783. Attributes to include are listed in ``self.ser_attrs``.
  1784. This method will look only for only and all the
  1785. attributes in ``self.ser_attrs``. They must all
  1786. be present. Use only for deserializing saved
  1787. objects.
  1788. :param d: Dictionary of attributes to set in the object.
  1789. :type d: dict
  1790. :return: None
  1791. """
  1792. for attr in self.ser_attrs:
  1793. setattr(self, attr, d[attr])
  1794. def union(self):
  1795. """
  1796. Runs a cascaded union on the list of objects in
  1797. solid_geometry.
  1798. :return: None
  1799. """
  1800. self.solid_geometry = [cascaded_union(self.solid_geometry)]
  1801. def export_svg(self, scale_stroke_factor=0.00,
  1802. scale_factor_x=None, scale_factor_y=None,
  1803. skew_factor_x=None, skew_factor_y=None,
  1804. skew_reference='center',
  1805. mirror=None):
  1806. """
  1807. Exports the Geometry Object as a SVG Element
  1808. :return: SVG Element
  1809. """
  1810. # Make sure we see a Shapely Geometry class and not a list
  1811. if self.kind.lower() == 'geometry':
  1812. flat_geo = []
  1813. if self.multigeo:
  1814. for tool in self.tools:
  1815. flat_geo += self.flatten(self.tools[tool]['solid_geometry'])
  1816. geom_svg = cascaded_union(flat_geo)
  1817. else:
  1818. geom_svg = cascaded_union(self.flatten())
  1819. else:
  1820. geom_svg = cascaded_union(self.flatten())
  1821. skew_ref = 'center'
  1822. if skew_reference != 'center':
  1823. xmin, ymin, xmax, ymax = geom_svg.bounds
  1824. if skew_reference == 'topleft':
  1825. skew_ref = (xmin, ymax)
  1826. elif skew_reference == 'bottomleft':
  1827. skew_ref = (xmin, ymin)
  1828. elif skew_reference == 'topright':
  1829. skew_ref = (xmax, ymax)
  1830. elif skew_reference == 'bottomright':
  1831. skew_ref = (xmax, ymin)
  1832. geom = geom_svg
  1833. if scale_factor_x:
  1834. geom = affinity.scale(geom_svg, scale_factor_x, 1.0)
  1835. if scale_factor_y:
  1836. geom = affinity.scale(geom_svg, 1.0, scale_factor_y)
  1837. if skew_factor_x:
  1838. geom = affinity.skew(geom_svg, skew_factor_x, 0.0, origin=skew_ref)
  1839. if skew_factor_y:
  1840. geom = affinity.skew(geom_svg, 0.0, skew_factor_y, origin=skew_ref)
  1841. if mirror:
  1842. if mirror == 'x':
  1843. geom = affinity.scale(geom_svg, 1.0, -1.0)
  1844. if mirror == 'y':
  1845. geom = affinity.scale(geom_svg, -1.0, 1.0)
  1846. if mirror == 'both':
  1847. geom = affinity.scale(geom_svg, -1.0, -1.0)
  1848. # scale_factor is a multiplication factor for the SVG stroke-width used within shapely's svg export
  1849. # If 0 or less which is invalid then default to 0.01
  1850. # This value appears to work for zooming, and getting the output svg line width
  1851. # to match that viewed on screen with FlatCam
  1852. # MS: I choose a factor of 0.01 so the scale is right for PCB UV film
  1853. if scale_stroke_factor <= 0:
  1854. scale_stroke_factor = 0.01
  1855. # Convert to a SVG
  1856. svg_elem = geom.svg(scale_factor=scale_stroke_factor)
  1857. return svg_elem
  1858. def mirror(self, axis, point):
  1859. """
  1860. Mirrors the object around a specified axis passign through
  1861. the given point.
  1862. :param axis: "X" or "Y" indicates around which axis to mirror.
  1863. :type axis: str
  1864. :param point: [x, y] point belonging to the mirror axis.
  1865. :type point: list
  1866. :return: None
  1867. """
  1868. log.debug("camlib.Geometry.mirror()")
  1869. px, py = point
  1870. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  1871. def mirror_geom(obj):
  1872. if type(obj) is list:
  1873. new_obj = []
  1874. for g in obj:
  1875. new_obj.append(mirror_geom(g))
  1876. return new_obj
  1877. else:
  1878. try:
  1879. self.el_count += 1
  1880. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  1881. if self.old_disp_number < disp_number <= 100:
  1882. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1883. self.old_disp_number = disp_number
  1884. return affinity.scale(obj, xscale, yscale, origin=(px, py))
  1885. except AttributeError:
  1886. return obj
  1887. try:
  1888. if self.multigeo is True:
  1889. for tool in self.tools:
  1890. # variables to display the percentage of work done
  1891. self.geo_len = 0
  1892. try:
  1893. self.geo_len = len(self.tools[tool]['solid_geometry'])
  1894. except TypeError:
  1895. self.geo_len = 1
  1896. self.old_disp_number = 0
  1897. self.el_count = 0
  1898. self.tools[tool]['solid_geometry'] = mirror_geom(self.tools[tool]['solid_geometry'])
  1899. else:
  1900. # variables to display the percentage of work done
  1901. self.geo_len = 0
  1902. try:
  1903. self.geo_len = len(self.solid_geometry)
  1904. except TypeError:
  1905. self.geo_len = 1
  1906. self.old_disp_number = 0
  1907. self.el_count = 0
  1908. self.solid_geometry = mirror_geom(self.solid_geometry)
  1909. self.app.inform.emit('[success] %s...' % _('Object was mirrored'))
  1910. except AttributeError:
  1911. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Failed to mirror. No object selected"))
  1912. self.app.proc_container.new_text = ''
  1913. def rotate(self, angle, point):
  1914. """
  1915. Rotate an object by an angle (in degrees) around the provided coordinates.
  1916. :param angle:
  1917. The angle of rotation are specified in degrees (default). Positive angles are
  1918. counter-clockwise and negative are clockwise rotations.
  1919. :param point:
  1920. The point of origin can be a keyword 'center' for the bounding box
  1921. center (default), 'centroid' for the geometry's centroid, a Point object
  1922. or a coordinate tuple (x0, y0).
  1923. See shapely manual for more information: http://toblerity.org/shapely/manual.html#affine-transformations
  1924. """
  1925. log.debug("camlib.Geometry.rotate()")
  1926. px, py = point
  1927. def rotate_geom(obj):
  1928. try:
  1929. new_obj = []
  1930. for g in obj:
  1931. new_obj.append(rotate_geom(g))
  1932. return new_obj
  1933. except TypeError:
  1934. try:
  1935. self.el_count += 1
  1936. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  1937. if self.old_disp_number < disp_number <= 100:
  1938. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1939. self.old_disp_number = disp_number
  1940. return affinity.rotate(obj, angle, origin=(px, py))
  1941. except AttributeError:
  1942. return obj
  1943. try:
  1944. if self.multigeo is True:
  1945. for tool in self.tools:
  1946. # variables to display the percentage of work done
  1947. self.geo_len = 0
  1948. try:
  1949. self.geo_len = len(self.tools[tool]['solid_geometry'])
  1950. except TypeError:
  1951. self.geo_len = 1
  1952. self.old_disp_number = 0
  1953. self.el_count = 0
  1954. self.tools[tool]['solid_geometry'] = rotate_geom(self.tools[tool]['solid_geometry'])
  1955. else:
  1956. # variables to display the percentage of work done
  1957. self.geo_len = 0
  1958. try:
  1959. self.geo_len = len(self.solid_geometry)
  1960. except TypeError:
  1961. self.geo_len = 1
  1962. self.old_disp_number = 0
  1963. self.el_count = 0
  1964. self.solid_geometry = rotate_geom(self.solid_geometry)
  1965. self.app.inform.emit('[success] %s...' % _('Object was rotated'))
  1966. except AttributeError:
  1967. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Failed to rotate. No object selected"))
  1968. self.app.proc_container.new_text = ''
  1969. def skew(self, angle_x, angle_y, point):
  1970. """
  1971. Shear/Skew the geometries of an object by angles along x and y dimensions.
  1972. :param angle_x:
  1973. :param angle_y:
  1974. angle_x, angle_y : float, float
  1975. The shear angle(s) for the x and y axes respectively. These can be
  1976. specified in either degrees (default) or radians by setting
  1977. use_radians=True.
  1978. :param point: Origin point for Skew
  1979. point: tuple of coordinates (x,y)
  1980. See shapely manual for more information: http://toblerity.org/shapely/manual.html#affine-transformations
  1981. """
  1982. log.debug("camlib.Geometry.skew()")
  1983. px, py = point
  1984. def skew_geom(obj):
  1985. try:
  1986. new_obj = []
  1987. for g in obj:
  1988. new_obj.append(skew_geom(g))
  1989. return new_obj
  1990. except TypeError:
  1991. try:
  1992. self.el_count += 1
  1993. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  1994. if self.old_disp_number < disp_number <= 100:
  1995. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1996. self.old_disp_number = disp_number
  1997. return affinity.skew(obj, angle_x, angle_y, origin=(px, py))
  1998. except AttributeError:
  1999. return obj
  2000. try:
  2001. if self.multigeo is True:
  2002. for tool in self.tools:
  2003. # variables to display the percentage of work done
  2004. self.geo_len = 0
  2005. try:
  2006. self.geo_len = len(self.tools[tool]['solid_geometry'])
  2007. except TypeError:
  2008. self.geo_len = 1
  2009. self.old_disp_number = 0
  2010. self.el_count = 0
  2011. self.tools[tool]['solid_geometry'] = skew_geom(self.tools[tool]['solid_geometry'])
  2012. else:
  2013. # variables to display the percentage of work done
  2014. self.geo_len = 0
  2015. try:
  2016. self.geo_len = len(self.solid_geometry)
  2017. except TypeError:
  2018. self.geo_len = 1
  2019. self.old_disp_number = 0
  2020. self.el_count = 0
  2021. self.solid_geometry = skew_geom(self.solid_geometry)
  2022. self.app.inform.emit('[success] %s...' % _('Object was skewed'))
  2023. except AttributeError:
  2024. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Failed to skew. No object selected"))
  2025. self.app.proc_container.new_text = ''
  2026. # if type(self.solid_geometry) == list:
  2027. # self.solid_geometry = [affinity.skew(g, angle_x, angle_y, origin=(px, py))
  2028. # for g in self.solid_geometry]
  2029. # else:
  2030. # self.solid_geometry = affinity.skew(self.solid_geometry, angle_x, angle_y,
  2031. # origin=(px, py))
  2032. def buffer(self, distance, join, factor):
  2033. """
  2034. :param distance: if 'factor' is True then distance is the factor
  2035. :param join: The kind of join used by the shapely buffer method: round, square or bevel
  2036. :param factor: True or False (None)
  2037. :return:
  2038. """
  2039. log.debug("camlib.Geometry.buffer()")
  2040. if distance == 0:
  2041. return
  2042. def buffer_geom(obj):
  2043. if type(obj) is list:
  2044. new_obj = []
  2045. for g in obj:
  2046. new_obj.append(buffer_geom(g))
  2047. return new_obj
  2048. else:
  2049. try:
  2050. self.el_count += 1
  2051. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  2052. if self.old_disp_number < disp_number <= 100:
  2053. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  2054. self.old_disp_number = disp_number
  2055. if factor is None:
  2056. return obj.buffer(distance, resolution=self.geo_steps_per_circle, join_style=join)
  2057. else:
  2058. return affinity.scale(obj, xfact=distance, yfact=distance, origin='center')
  2059. except AttributeError:
  2060. return obj
  2061. try:
  2062. if self.multigeo is True:
  2063. for tool in self.tools:
  2064. # variables to display the percentage of work done
  2065. self.geo_len = 0
  2066. try:
  2067. self.geo_len += len(self.tools[tool]['solid_geometry'])
  2068. except TypeError:
  2069. self.geo_len += 1
  2070. self.old_disp_number = 0
  2071. self.el_count = 0
  2072. res = buffer_geom(self.tools[tool]['solid_geometry'])
  2073. try:
  2074. __ = iter(res)
  2075. self.tools[tool]['solid_geometry'] = res
  2076. except TypeError:
  2077. self.tools[tool]['solid_geometry'] = [res]
  2078. # variables to display the percentage of work done
  2079. self.geo_len = 0
  2080. try:
  2081. self.geo_len = len(self.solid_geometry)
  2082. except TypeError:
  2083. self.geo_len = 1
  2084. self.old_disp_number = 0
  2085. self.el_count = 0
  2086. self.solid_geometry = buffer_geom(self.solid_geometry)
  2087. self.app.inform.emit('[success] %s...' % _('Object was buffered'))
  2088. except AttributeError:
  2089. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Failed to buffer. No object selected"))
  2090. self.app.proc_container.new_text = ''
  2091. class AttrDict(dict):
  2092. def __init__(self, *args, **kwargs):
  2093. super(AttrDict, self).__init__(*args, **kwargs)
  2094. self.__dict__ = self
  2095. class CNCjob(Geometry):
  2096. """
  2097. Represents work to be done by a CNC machine.
  2098. *ATTRIBUTES*
  2099. * ``gcode_parsed`` (list): Each is a dictionary:
  2100. ===================== =========================================
  2101. Key Value
  2102. ===================== =========================================
  2103. geom (Shapely.LineString) Tool path (XY plane)
  2104. kind (string) "AB", A is "T" (travel) or
  2105. "C" (cut). B is "F" (fast) or "S" (slow).
  2106. ===================== =========================================
  2107. """
  2108. defaults = {
  2109. "global_zdownrate": None,
  2110. "pp_geometry_name": 'default',
  2111. "pp_excellon_name": 'default',
  2112. "excellon_optimization_type": "B",
  2113. }
  2114. settings = QtCore.QSettings("Open Source", "FlatCAM")
  2115. if settings.contains("machinist"):
  2116. machinist_setting = settings.value('machinist', type=int)
  2117. else:
  2118. machinist_setting = 0
  2119. def __init__(self,
  2120. units="in", kind="generic", tooldia=0.0,
  2121. z_cut=-0.002, z_move=0.1,
  2122. feedrate=3.0, feedrate_z=3.0, feedrate_rapid=3.0, feedrate_probe=3.0,
  2123. pp_geometry_name='default', pp_excellon_name='default',
  2124. depthpercut=0.1, z_pdepth=-0.02,
  2125. spindlespeed=None, spindledir='CW', dwell=True, dwelltime=1000,
  2126. toolchangez=0.787402, toolchange_xy='0.0,0.0',
  2127. endz=2.0, endxy='',
  2128. segx=None,
  2129. segy=None,
  2130. steps_per_circle=None):
  2131. self.decimals = self.app.decimals
  2132. # Used when parsing G-code arcs
  2133. self.steps_per_circle = steps_per_circle if steps_per_circle is not None else \
  2134. int(self.app.defaults['cncjob_steps_per_circle'])
  2135. Geometry.__init__(self, geo_steps_per_circle=self.steps_per_circle)
  2136. self.kind = kind
  2137. self.units = units
  2138. self.z_cut = z_cut
  2139. self.multidepth = False
  2140. self.z_depthpercut = depthpercut
  2141. self.z_move = z_move
  2142. self.feedrate = feedrate
  2143. self.z_feedrate = feedrate_z
  2144. self.feedrate_rapid = feedrate_rapid
  2145. self.tooldia = tooldia
  2146. self.toolC = tooldia
  2147. self.toolchange = False
  2148. self.z_toolchange = toolchangez
  2149. self.xy_toolchange = toolchange_xy
  2150. self.toolchange_xy_type = None
  2151. self.startz = None
  2152. self.z_end = endz
  2153. self.xy_end = endxy
  2154. self.extracut = False
  2155. self.extracut_length = None
  2156. self.tolerance = self.drawing_tolerance
  2157. # used by the self.generate_from_excellon_by_tool() method
  2158. # but set directly before the actual usage of the method with obj.excellon_optimization_type = value
  2159. self.excellon_optimization_type = 'No'
  2160. # if set True then the GCode generation will use UI; used in Excellon GVode for now
  2161. self.use_ui = False
  2162. self.unitcode = {"IN": "G20", "MM": "G21"}
  2163. self.feedminutecode = "G94"
  2164. # self.absolutecode = "G90"
  2165. # self.incrementalcode = "G91"
  2166. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  2167. self.gcode = ""
  2168. self.gcode_parsed = None
  2169. self.pp_geometry_name = pp_geometry_name
  2170. self.pp_geometry = self.app.preprocessors[self.pp_geometry_name]
  2171. self.pp_excellon_name = pp_excellon_name
  2172. self.pp_excellon = self.app.preprocessors[self.pp_excellon_name]
  2173. self.pp_solderpaste_name = None
  2174. # Controls if the move from Z_Toolchange to Z_Move is done fast with G0 or normally with G1
  2175. self.f_plunge = None
  2176. # Controls if the move from Z_Cutto Z_Move is done fast with G0 or G1 until zero and then G0 to Z_move
  2177. self.f_retract = None
  2178. # how much depth the probe can probe before error
  2179. self.z_pdepth = z_pdepth if z_pdepth else None
  2180. # the feedrate(speed) with which the probel travel while probing
  2181. self.feedrate_probe = feedrate_probe if feedrate_probe else None
  2182. self.spindlespeed = spindlespeed
  2183. self.spindledir = spindledir
  2184. self.dwell = dwell
  2185. self.dwelltime = dwelltime
  2186. self.segx = float(segx) if segx is not None else 0.0
  2187. self.segy = float(segy) if segy is not None else 0.0
  2188. self.input_geometry_bounds = None
  2189. self.oldx = None
  2190. self.oldy = None
  2191. self.tool = 0.0
  2192. self.measured_distance = 0.0
  2193. self.measured_down_distance = 0.0
  2194. self.measured_up_to_zero_distance = 0.0
  2195. self.measured_lift_distance = 0.0
  2196. # here store the travelled distance
  2197. self.travel_distance = 0.0
  2198. # here store the routing time
  2199. self.routing_time = 0.0
  2200. # store here the Excellon source object tools to be accessible locally
  2201. self.exc_tools = None
  2202. # search for toolchange parameters in the Toolchange Custom Code
  2203. self.re_toolchange_custom = re.compile(r'(%[a-zA-Z0-9\-_]+%)')
  2204. # search for toolchange code: M6
  2205. self.re_toolchange = re.compile(r'^\s*(M6)$')
  2206. # Attributes to be included in serialization
  2207. # Always append to it because it carries contents
  2208. # from Geometry.
  2209. self.ser_attrs += ['kind', 'z_cut', 'z_move', 'z_toolchange', 'feedrate', 'z_feedrate', 'feedrate_rapid',
  2210. 'tooldia', 'gcode', 'input_geometry_bounds', 'gcode_parsed', 'steps_per_circle',
  2211. 'z_depthpercut', 'spindlespeed', 'dwell', 'dwelltime']
  2212. @property
  2213. def postdata(self):
  2214. """
  2215. This will return all the attributes of the class in the form of a dictionary
  2216. :return: Class attributes
  2217. :rtype: dict
  2218. """
  2219. return self.__dict__
  2220. def convert_units(self, units):
  2221. """
  2222. Will convert the parameters in the class that are relevant, from metric to imperial and reverse
  2223. :param units: FlatCAM units
  2224. :type units: str
  2225. :return: conversion factor
  2226. :rtype: float
  2227. """
  2228. log.debug("camlib.CNCJob.convert_units()")
  2229. factor = Geometry.convert_units(self, units)
  2230. self.z_cut = float(self.z_cut) * factor
  2231. self.z_move *= factor
  2232. self.feedrate *= factor
  2233. self.z_feedrate *= factor
  2234. self.feedrate_rapid *= factor
  2235. self.tooldia *= factor
  2236. self.z_toolchange *= factor
  2237. self.z_end *= factor
  2238. self.z_depthpercut = float(self.z_depthpercut) * factor
  2239. return factor
  2240. def doformat(self, fun, **kwargs):
  2241. return self.doformat2(fun, **kwargs) + "\n"
  2242. def doformat2(self, fun, **kwargs):
  2243. """
  2244. This method will call one of the current preprocessor methods having as parameters all the attributes of
  2245. current class to which will add the kwargs parameters
  2246. :param fun: One of the methods inside the preprocessor classes which get loaded here in the 'p' object
  2247. :type fun: class 'function'
  2248. :param kwargs: keyword args which will update attributes of the current class
  2249. :type kwargs: dict
  2250. :return: Gcode line
  2251. :rtype: str
  2252. """
  2253. attributes = AttrDict()
  2254. attributes.update(self.postdata)
  2255. attributes.update(kwargs)
  2256. try:
  2257. returnvalue = fun(attributes)
  2258. return returnvalue
  2259. except Exception:
  2260. self.app.log.error('Exception occurred within a preprocessor: ' + traceback.format_exc())
  2261. return ''
  2262. def parse_custom_toolchange_code(self, data):
  2263. """
  2264. Will parse a text and get a toolchange sequence in text format suitable to be included in a Gcode file.
  2265. The '%' symbol is used to surround class variables name and must be removed in the returned string.
  2266. After that, the class variables (attributes) are replaced with the current values. The result is returned.
  2267. :param data: Toolchange sequence
  2268. :type data: str
  2269. :return: Processed toolchange sequence
  2270. :rtype: str
  2271. """
  2272. text = data
  2273. match_list = self.re_toolchange_custom.findall(text)
  2274. if match_list:
  2275. for match in match_list:
  2276. command = match.strip('%')
  2277. try:
  2278. value = getattr(self, command)
  2279. except AttributeError:
  2280. self.app.inform.emit('[ERROR] %s: %s' %
  2281. (_("There is no such parameter"), str(match)))
  2282. log.debug("CNCJob.parse_custom_toolchange_code() --> AttributeError ")
  2283. return 'fail'
  2284. text = text.replace(match, str(value))
  2285. return text
  2286. # Distance callback
  2287. class CreateDistanceCallback(object):
  2288. """Create callback to calculate distances between points."""
  2289. def __init__(self, locs, manager):
  2290. self.manager = manager
  2291. self.matrix = {}
  2292. if locs:
  2293. size = len(locs)
  2294. for from_node in range(size):
  2295. self.matrix[from_node] = {}
  2296. for to_node in range(size):
  2297. if from_node == to_node:
  2298. self.matrix[from_node][to_node] = 0
  2299. else:
  2300. x1 = locs[from_node][0]
  2301. y1 = locs[from_node][1]
  2302. x2 = locs[to_node][0]
  2303. y2 = locs[to_node][1]
  2304. self.matrix[from_node][to_node] = distance_euclidian(x1, y1, x2, y2)
  2305. # def Distance(self, from_node, to_node):
  2306. # return int(self.matrix[from_node][to_node])
  2307. def Distance(self, from_index, to_index):
  2308. # Convert from routing variable Index to distance matrix NodeIndex.
  2309. from_node = self.manager.IndexToNode(from_index)
  2310. to_node = self.manager.IndexToNode(to_index)
  2311. return self.matrix[from_node][to_node]
  2312. @staticmethod
  2313. def create_tool_data_array(points):
  2314. # Create the data.
  2315. return [(pt.coords.xy[0][0], pt.coords.xy[1][0]) for pt in points]
  2316. def optimized_ortools_meta(self, locations, start=None, opt_time=0):
  2317. optimized_path = []
  2318. tsp_size = len(locations)
  2319. num_routes = 1 # The number of routes, which is 1 in the TSP.
  2320. # Nodes are indexed from 0 to tsp_size - 1. The depot is the starting node of the route.
  2321. depot = 0 if start is None else start
  2322. # Create routing model.
  2323. if tsp_size == 0:
  2324. log.warning('OR-tools metaheuristics - Specify an instance greater than 0.')
  2325. return optimized_path
  2326. manager = pywrapcp.RoutingIndexManager(tsp_size, num_routes, depot)
  2327. routing = pywrapcp.RoutingModel(manager)
  2328. search_parameters = pywrapcp.DefaultRoutingSearchParameters()
  2329. search_parameters.local_search_metaheuristic = (
  2330. routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH)
  2331. # Set search time limit in milliseconds.
  2332. if float(opt_time) != 0:
  2333. search_parameters.time_limit.seconds = int(
  2334. float(opt_time))
  2335. else:
  2336. search_parameters.time_limit.seconds = 3
  2337. # Callback to the distance function. The callback takes two
  2338. # arguments (the from and to node indices) and returns the distance between them.
  2339. dist_between_locations = self.CreateDistanceCallback(locs=locations, manager=manager)
  2340. # if there are no distances then go to the next tool
  2341. if not dist_between_locations:
  2342. return
  2343. dist_callback = dist_between_locations.Distance
  2344. transit_callback_index = routing.RegisterTransitCallback(dist_callback)
  2345. routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)
  2346. # Solve, returns a solution if any.
  2347. assignment = routing.SolveWithParameters(search_parameters)
  2348. if assignment:
  2349. # Solution cost.
  2350. log.info("OR-tools metaheuristics - Total distance: " + str(assignment.ObjectiveValue()))
  2351. # Inspect solution.
  2352. # Only one route here; otherwise iterate from 0 to routing.vehicles() - 1.
  2353. route_number = 0
  2354. node = routing.Start(route_number)
  2355. start_node = node
  2356. while not routing.IsEnd(node):
  2357. if self.app.abort_flag:
  2358. # graceful abort requested by the user
  2359. raise grace
  2360. optimized_path.append(node)
  2361. node = assignment.Value(routing.NextVar(node))
  2362. else:
  2363. log.warning('OR-tools metaheuristics - No solution found.')
  2364. return optimized_path
  2365. # ############################################# ##
  2366. def optimized_ortools_basic(self, locations, start=None):
  2367. optimized_path = []
  2368. tsp_size = len(locations)
  2369. num_routes = 1 # The number of routes, which is 1 in the TSP.
  2370. # Nodes are indexed from 0 to tsp_size - 1. The depot is the starting node of the route.
  2371. depot = 0 if start is None else start
  2372. # Create routing model.
  2373. if tsp_size == 0:
  2374. log.warning('Specify an instance greater than 0.')
  2375. return optimized_path
  2376. manager = pywrapcp.RoutingIndexManager(tsp_size, num_routes, depot)
  2377. routing = pywrapcp.RoutingModel(manager)
  2378. search_parameters = pywrapcp.DefaultRoutingSearchParameters()
  2379. # Callback to the distance function. The callback takes two
  2380. # arguments (the from and to node indices) and returns the distance between them.
  2381. dist_between_locations = self.CreateDistanceCallback(locs=locations, manager=manager)
  2382. # if there are no distances then go to the next tool
  2383. if not dist_between_locations:
  2384. return
  2385. dist_callback = dist_between_locations.Distance
  2386. transit_callback_index = routing.RegisterTransitCallback(dist_callback)
  2387. routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)
  2388. # Solve, returns a solution if any.
  2389. assignment = routing.SolveWithParameters(search_parameters)
  2390. if assignment:
  2391. # Solution cost.
  2392. log.info("Total distance: " + str(assignment.ObjectiveValue()))
  2393. # Inspect solution.
  2394. # Only one route here; otherwise iterate from 0 to routing.vehicles() - 1.
  2395. route_number = 0
  2396. node = routing.Start(route_number)
  2397. start_node = node
  2398. while not routing.IsEnd(node):
  2399. optimized_path.append(node)
  2400. node = assignment.Value(routing.NextVar(node))
  2401. else:
  2402. log.warning('No solution found.')
  2403. return optimized_path
  2404. # ############################################# ##
  2405. def optimized_travelling_salesman(self, points, start=None):
  2406. """
  2407. As solving the problem in the brute force way is too slow,
  2408. this function implements a simple heuristic: always
  2409. go to the nearest city.
  2410. Even if this algorithm is extremely simple, it works pretty well
  2411. giving a solution only about 25%% longer than the optimal one (cit. Wikipedia),
  2412. and runs very fast in O(N^2) time complexity.
  2413. >>> optimized_travelling_salesman([[i,j] for i in range(5) for j in range(5)])
  2414. [[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],
  2415. [2, 3], [2, 4], [3, 4], [3, 3], [3, 2], [3, 1], [3, 0], [4, 0], [4, 1], [4, 2], [4, 3], [4, 4]]
  2416. >>> optimized_travelling_salesman([[0,0],[10,0],[6,0]])
  2417. [[0, 0], [6, 0], [10, 0]]
  2418. :param points: List of tuples with x, y coordinates
  2419. :type points: list
  2420. :param start: a tuple with a x,y coordinates of the start point
  2421. :type start: tuple
  2422. :return: List of points ordered in a optimized way
  2423. :rtype: list
  2424. """
  2425. if start is None:
  2426. start = points[0]
  2427. must_visit = points
  2428. path = [start]
  2429. # must_visit.remove(start)
  2430. while must_visit:
  2431. nearest = min(must_visit, key=lambda x: distance(path[-1], x))
  2432. path.append(nearest)
  2433. must_visit.remove(nearest)
  2434. return path
  2435. def geo_optimized_rtree(self, geometry):
  2436. locations = []
  2437. # ## Index first and last points in paths. What points to index.
  2438. def get_pts(o):
  2439. return [o.coords[0], o.coords[-1]]
  2440. # Create the indexed storage.
  2441. storage = FlatCAMRTreeStorage()
  2442. storage.get_points = get_pts
  2443. # Store the geometry
  2444. log.debug("Indexing geometry before generating G-Code...")
  2445. self.app.inform.emit(_("Indexing geometry before generating G-Code..."))
  2446. for geo_shape in geometry:
  2447. if self.app.abort_flag:
  2448. # graceful abort requested by the user
  2449. raise grace
  2450. if geo_shape is not None:
  2451. storage.insert(geo_shape)
  2452. current_pt = (0, 0)
  2453. pt, geo = storage.nearest(current_pt)
  2454. try:
  2455. while True:
  2456. storage.remove(geo)
  2457. locations.append((pt, geo))
  2458. current_pt = geo.coords[-1]
  2459. pt, geo = storage.nearest(current_pt)
  2460. except StopIteration:
  2461. pass
  2462. # if there are no locations then go to the next tool
  2463. if not locations:
  2464. return 'fail'
  2465. return locations
  2466. def check_zcut(self, zcut):
  2467. if zcut > 0:
  2468. self.app.inform.emit('[WARNING] %s' %
  2469. _("The Cut Z parameter has positive value. "
  2470. "It is the depth value to drill into material.\n"
  2471. "The Cut Z parameter needs to have a negative value, assuming it is a typo "
  2472. "therefore the app will convert the value to negative. "
  2473. "Check the resulting CNC code (Gcode etc)."))
  2474. return -zcut
  2475. elif zcut == 0:
  2476. self.app.inform.emit('[WARNING] %s.' % _("The Cut Z parameter is zero. There will be no cut, aborting"))
  2477. return 'fail'
  2478. def excellon_tool_gcode_gen(self, tool, points, tools, first_pt, is_first=False, is_last=False, opt_type='T',
  2479. toolchange=False):
  2480. """
  2481. Creates Gcode for this object from an Excellon object
  2482. for the specified tools.
  2483. :return: A tuple made from tool_gcode, another tuple holding the coordinates of the last point
  2484. and the start gcode
  2485. :rtype: tuple
  2486. """
  2487. log.debug("Creating CNC Job from Excellon for tool: %s" % str(tool))
  2488. self.exc_tools = deepcopy(tools)
  2489. t_gcode = ''
  2490. # holds the temporary coordinates of the processed drill point
  2491. locx, locy = first_pt
  2492. temp_locx, temp_locy = first_pt
  2493. # #############################################################################################################
  2494. # #############################################################################################################
  2495. # ################################## DRILLING !!! #########################################################
  2496. # #############################################################################################################
  2497. # #############################################################################################################
  2498. if opt_type == 'M':
  2499. log.debug("Using OR-Tools Metaheuristic Guided Local Search drill path optimization.")
  2500. elif opt_type == 'B':
  2501. log.debug("Using OR-Tools Basic drill path optimization.")
  2502. elif opt_type == 'T':
  2503. log.debug("Using Travelling Salesman drill path optimization.")
  2504. else:
  2505. log.debug("Using no path optimization.")
  2506. tool_dict = tools[tool]['data']
  2507. # check if it has drills
  2508. if not points:
  2509. log.debug("Failed. No drills for tool: %s" % str(tool))
  2510. return 'fail'
  2511. if self.app.abort_flag:
  2512. # graceful abort requested by the user
  2513. raise grace
  2514. # #########################################################################################################
  2515. # #########################################################################################################
  2516. # ############# PARAMETERS used in PREPROCESSORS so they need to be updated ###############################
  2517. # #########################################################################################################
  2518. # #########################################################################################################
  2519. self.tool = str(tool)
  2520. # Preprocessor
  2521. p = self.pp_excellon
  2522. # Z_cut parameter
  2523. if self.machinist_setting == 0:
  2524. self.z_cut = self.check_zcut(zcut=tool_dict["tools_drill_cutz"])
  2525. if self.z_cut == 'fail':
  2526. return 'fail'
  2527. # Depth parameters
  2528. self.z_cut = tool_dict['tools_drill_cutz']
  2529. old_zcut = deepcopy(tool_dict["tools_drill_cutz"]) # multidepth use this
  2530. self.multidepth = tool_dict['tools_drill_multidepth']
  2531. self.z_depthpercut = tool_dict['tools_drill_depthperpass']
  2532. self.z_move = tool_dict['tools_drill_travelz']
  2533. self.f_plunge = tool_dict["tools_drill_f_plunge"] # used directly in the preprocessor Toolchange method
  2534. self.f_retract = tool_dict["tools_drill_f_retract"] # used in the current method
  2535. # Feedrate parameters
  2536. self.z_feedrate = tool_dict['tools_drill_feedrate_z']
  2537. self.feedrate = tool_dict['tools_drill_feedrate_z']
  2538. self.feedrate_rapid = tool_dict['tools_drill_feedrate_rapid']
  2539. # Spindle parameters
  2540. self.spindlespeed = tool_dict['tools_drill_spindlespeed']
  2541. self.dwell = tool_dict['tools_drill_dwell']
  2542. self.dwelltime = tool_dict['tools_drill_dwelltime']
  2543. self.spindledir = tool_dict['tools_drill_spindledir']
  2544. self.tooldia = tools[tool]["tooldia"]
  2545. self.postdata['toolC'] = tools[tool]["tooldia"]
  2546. self.toolchange = toolchange
  2547. # Z_toolchange parameter
  2548. self.z_toolchange = tool_dict['tools_drill_toolchangez']
  2549. # XY_toolchange parameter
  2550. self.xy_toolchange = tool_dict["tools_drill_toolchangexy"]
  2551. try:
  2552. if self.xy_toolchange == '':
  2553. self.xy_toolchange = None
  2554. else:
  2555. # either originally it was a string or not, xy_toolchange will be made string
  2556. self.xy_toolchange = re.sub('[()\[\]]', '', str(self.xy_toolchange)) if self.xy_toolchange else None
  2557. # and now, xy_toolchange is made into a list of floats in format [x, y]
  2558. if self.xy_toolchange:
  2559. self.xy_toolchange = [float(eval(a)) for a in self.xy_toolchange.split(",")]
  2560. if self.xy_toolchange and len(self.xy_toolchange) != 2:
  2561. self.app.inform.emit('[ERROR] %s' % _("The Toolchange X,Y format has to be (x, y)."))
  2562. return 'fail'
  2563. except Exception as e:
  2564. log.debug("camlib.CNCJob.generate_from_excellon_by_tool() xy_toolchange --> %s" % str(e))
  2565. self.xy_toolchange = [0, 0]
  2566. # End position parameters
  2567. self.startz = tool_dict["tools_drill_startz"]
  2568. if self.startz == '':
  2569. self.startz = None
  2570. self.z_end = tool_dict["tools_drill_endz"]
  2571. self.xy_end = tool_dict["tools_drill_endxy"]
  2572. try:
  2573. if self.xy_end == '':
  2574. self.xy_end = None
  2575. else:
  2576. # either originally it was a string or not, xy_end will be made string
  2577. self.xy_end = re.sub('[()\[\]]', '', str(self.xy_end)) if self.xy_end else None
  2578. # and now, xy_end is made into a list of floats in format [x, y]
  2579. if self.xy_end:
  2580. self.xy_end = [float(eval(a)) for a in self.xy_end.split(",")]
  2581. if self.xy_end and len(self.xy_end) != 2:
  2582. self.app.inform.emit('[ERROR]%s' % _("The End X,Y format has to be (x, y)."))
  2583. return 'fail'
  2584. except Exception as e:
  2585. log.debug("camlib.CNCJob.generate_from_excellon_by_tool() xy_end --> %s" % str(e))
  2586. self.xy_end = [0, 0]
  2587. # Probe parameters
  2588. self.z_pdepth = tool_dict["tools_drill_z_pdepth"]
  2589. self.feedrate_probe = tool_dict["tools_drill_feedrate_probe"]
  2590. # #########################################################################################################
  2591. # #########################################################################################################
  2592. # #########################################################################################################
  2593. # ############ Create the data. ###########################################################################
  2594. # #########################################################################################################
  2595. locations = []
  2596. optimized_path = []
  2597. if opt_type == 'M':
  2598. locations = self.create_tool_data_array(points=points)
  2599. # if there are no locations then go to the next tool
  2600. if not locations:
  2601. return 'fail'
  2602. opt_time = self.app.defaults["excellon_search_time"]
  2603. optimized_path = self.optimized_ortools_meta(locations=locations, opt_time=opt_time)
  2604. elif opt_type == 'B':
  2605. locations = self.create_tool_data_array(points=points)
  2606. # if there are no locations then go to the next tool
  2607. if not locations:
  2608. return 'fail'
  2609. optimized_path = self.optimized_ortools_basic(locations=locations)
  2610. elif opt_type == 'T':
  2611. locations = self.create_tool_data_array(points=points)
  2612. # if there are no locations then go to the next tool
  2613. if not locations:
  2614. return 'fail'
  2615. optimized_path = self.optimized_travelling_salesman(locations)
  2616. else:
  2617. # it's actually not optimized path but here we build a list of (x,y) coordinates
  2618. # out of the tool's drills
  2619. for drill in tools[tool]['drills']:
  2620. unoptimized_coords = (
  2621. drill.x,
  2622. drill.y
  2623. )
  2624. optimized_path.append(unoptimized_coords)
  2625. # #########################################################################################################
  2626. # #########################################################################################################
  2627. # Only if there are locations to drill
  2628. if not optimized_path:
  2629. log.debug("CNCJob.excellon_tool_gcode_gen() -> Optimized path is empty.")
  2630. return 'fail'
  2631. if self.app.abort_flag:
  2632. # graceful abort requested by the user
  2633. raise grace
  2634. start_gcode = ''
  2635. if is_first:
  2636. start_gcode = self.doformat(p.start_code)
  2637. t_gcode += start_gcode
  2638. # do the ToolChange event
  2639. t_gcode += self.doformat(p.z_feedrate_code)
  2640. t_gcode += self.doformat(p.toolchange_code, toolchangexy=(temp_locx, temp_locy))
  2641. t_gcode += self.doformat(p.z_feedrate_code)
  2642. # Spindle start
  2643. t_gcode += self.doformat(p.spindle_code)
  2644. # Dwell time
  2645. if self.dwell is True:
  2646. t_gcode += self.doformat(p.dwell_code)
  2647. current_tooldia = float('%.*f' % (self.decimals, float(tools[tool]["tooldia"])))
  2648. self.app.inform.emit(
  2649. '%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  2650. str(current_tooldia),
  2651. str(self.units))
  2652. )
  2653. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  2654. # APPLY Offset only when using the appGUI, for TclCommand this will create an error
  2655. # because the values for Z offset are created in build_tool_ui()
  2656. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  2657. try:
  2658. z_offset = float(tool_dict['tools_drill_offset']) * (-1)
  2659. except KeyError:
  2660. z_offset = 0
  2661. self.z_cut = z_offset + old_zcut
  2662. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  2663. if self.coordinates_type == "G90":
  2664. # Drillling! for Absolute coordinates type G90
  2665. # variables to display the percentage of work done
  2666. geo_len = len(optimized_path)
  2667. old_disp_number = 0
  2668. log.warning("Number of drills for which to generate GCode: %s" % str(geo_len))
  2669. loc_nr = 0
  2670. for point in optimized_path:
  2671. if self.app.abort_flag:
  2672. # graceful abort requested by the user
  2673. raise grace
  2674. if opt_type == 'T':
  2675. locx = point[0]
  2676. locy = point[1]
  2677. else:
  2678. locx = locations[point][0]
  2679. locy = locations[point][1]
  2680. travels = self.app.exc_areas.travel_coordinates(start_point=(temp_locx, temp_locy),
  2681. end_point=(locx, locy),
  2682. tooldia=current_tooldia)
  2683. prev_z = None
  2684. for travel in travels:
  2685. locx = travel[1][0]
  2686. locy = travel[1][1]
  2687. if travel[0] is not None:
  2688. # move to next point
  2689. t_gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  2690. # raise to safe Z (travel[0]) each time because safe Z may be different
  2691. self.z_move = travel[0]
  2692. t_gcode += self.doformat(p.lift_code, x=locx, y=locy)
  2693. # restore z_move
  2694. self.z_move = tool_dict['tools_drill_travelz']
  2695. else:
  2696. if prev_z is not None:
  2697. # move to next point
  2698. t_gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  2699. # we assume that previously the z_move was altered therefore raise to
  2700. # the travel_z (z_move)
  2701. self.z_move = tool_dict['tools_drill_travelz']
  2702. t_gcode += self.doformat(p.lift_code, x=locx, y=locy)
  2703. else:
  2704. # move to next point
  2705. t_gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  2706. # store prev_z
  2707. prev_z = travel[0]
  2708. # t_gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  2709. if self.multidepth and abs(self.z_cut) > abs(self.z_depthpercut):
  2710. doc = deepcopy(self.z_cut)
  2711. self.z_cut = 0.0
  2712. while abs(self.z_cut) < abs(doc):
  2713. self.z_cut -= self.z_depthpercut
  2714. if abs(doc) < abs(self.z_cut) < (abs(doc) + self.z_depthpercut):
  2715. self.z_cut = doc
  2716. # Move down the drill bit
  2717. t_gcode += self.doformat(p.down_code, x=locx, y=locy)
  2718. # Update the distance travelled down with the current one
  2719. self.measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  2720. if self.f_retract is False:
  2721. t_gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  2722. self.measured_up_to_zero_distance += abs(self.z_cut)
  2723. self.measured_lift_distance += abs(self.z_move)
  2724. else:
  2725. self.measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  2726. t_gcode += self.doformat(p.lift_code, x=locx, y=locy)
  2727. else:
  2728. t_gcode += self.doformat(p.down_code, x=locx, y=locy)
  2729. self.measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  2730. if self.f_retract is False:
  2731. t_gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  2732. self.measured_up_to_zero_distance += abs(self.z_cut)
  2733. self.measured_lift_distance += abs(self.z_move)
  2734. else:
  2735. self.measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  2736. t_gcode += self.doformat(p.lift_code, x=locx, y=locy)
  2737. self.measured_distance += abs(distance_euclidian(locx, locy, temp_locx, temp_locy))
  2738. temp_locx = locx
  2739. temp_locy = locy
  2740. self.oldx = locx
  2741. self.oldy = locy
  2742. loc_nr += 1
  2743. disp_number = int(np.interp(loc_nr, [0, geo_len], [0, 100]))
  2744. if old_disp_number < disp_number <= 100:
  2745. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  2746. old_disp_number = disp_number
  2747. else:
  2748. self.app.inform.emit('[ERROR_NOTCL] %s...' % _('G91 coordinates not implemented'))
  2749. return 'fail'
  2750. self.z_cut = deepcopy(old_zcut)
  2751. if is_last:
  2752. t_gcode += self.doformat(p.spindle_stop_code)
  2753. # Move to End position
  2754. t_gcode += self.doformat(p.end_code, x=0, y=0)
  2755. self.app.inform.emit(_("Finished G-Code generation for tool: %s" % str(tool)))
  2756. return t_gcode, (locx, locy), start_gcode
  2757. def generate_from_excellon_by_tool(self, exobj, tools="all", order='fwd', use_ui=False):
  2758. """
  2759. Creates Gcode for this object from an Excellon object
  2760. for the specified tools.
  2761. :param exobj: Excellon object to process
  2762. :type exobj: Excellon
  2763. :param tools: Comma separated tool names
  2764. :type tools: str
  2765. :param order: order of tools processing: "fwd", "rev" or "no"
  2766. :type order: str
  2767. :param use_ui: if True the method will use parameters set in UI
  2768. :type use_ui: bool
  2769. :return: None
  2770. :rtype: None
  2771. """
  2772. # #############################################################################################################
  2773. # #############################################################################################################
  2774. # create a local copy of the exobj.tools so it can be used for creating drill CCode geometry
  2775. # #############################################################################################################
  2776. # #############################################################################################################
  2777. self.exc_tools = deepcopy(exobj.tools)
  2778. # the Excellon GCode preprocessor will use this info in the start_code() method
  2779. self.use_ui = True if use_ui else False
  2780. # Z_cut parameter
  2781. if self.machinist_setting == 0:
  2782. self.z_cut = self.check_zcut(zcut=self.z_cut)
  2783. if self.z_cut == 'fail':
  2784. return 'fail'
  2785. # multidepth use this
  2786. old_zcut = deepcopy(self.z_cut)
  2787. # XY_toolchange parameter
  2788. try:
  2789. if self.xy_toolchange == '':
  2790. self.xy_toolchange = None
  2791. else:
  2792. self.xy_toolchange = re.sub('[()\[\]]', '', str(self.xy_toolchange)) if self.xy_toolchange else None
  2793. if self.xy_toolchange:
  2794. self.xy_toolchange = [float(eval(a)) for a in self.xy_toolchange.split(",")]
  2795. if self.xy_toolchange and len(self.xy_toolchange) != 2:
  2796. self.app.inform.emit('[ERROR]%s' %
  2797. _("The Toolchange X,Y field in Edit -> Preferences has to be "
  2798. "in the format (x, y) \nbut now there is only one value, not two. "))
  2799. return 'fail'
  2800. except Exception as e:
  2801. log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> %s" % str(e))
  2802. pass
  2803. # XY_end parameter
  2804. self.xy_end = re.sub('[()\[\]]', '', str(self.xy_end)) if self.xy_end else None
  2805. if self.xy_end and self.xy_end != '':
  2806. self.xy_end = [float(eval(a)) for a in self.xy_end.split(",")]
  2807. if self.xy_end and len(self.xy_end) < 2:
  2808. self.app.inform.emit('[ERROR] %s' % _("The End Move X,Y field in Edit -> Preferences has to be "
  2809. "in the format (x, y) but now there is only one value, not two."))
  2810. return 'fail'
  2811. # Prepprocessor
  2812. self.pp_excellon = self.app.preprocessors[self.pp_excellon_name]
  2813. p = self.pp_excellon
  2814. log.debug("Creating CNC Job from Excellon...")
  2815. # #############################################################################################################
  2816. # #############################################################################################################
  2817. # TOOLS
  2818. # sort the tools list by the second item in tuple (here we have a dict with diameter of the tool)
  2819. # so we actually are sorting the tools by diameter
  2820. # #############################################################################################################
  2821. # #############################################################################################################
  2822. all_tools = []
  2823. for tool_as_key, v in list(self.exc_tools.items()):
  2824. all_tools.append((int(tool_as_key), float(v['tooldia'])))
  2825. if order == 'fwd':
  2826. sorted_tools = sorted(all_tools, key=lambda t1: t1[1])
  2827. elif order == 'rev':
  2828. sorted_tools = sorted(all_tools, key=lambda t1: t1[1], reverse=True)
  2829. else:
  2830. sorted_tools = all_tools
  2831. if tools == "all":
  2832. selected_tools = [i[0] for i in all_tools] # we get a array of ordered tools
  2833. else:
  2834. selected_tools = eval(tools)
  2835. # Create a sorted list of selected tools from the sorted_tools list
  2836. tools = [i for i, j in sorted_tools for k in selected_tools if i == k]
  2837. log.debug("Tools sorted are: %s" % str(tools))
  2838. # #############################################################################################################
  2839. # #############################################################################################################
  2840. # build a self.options['Tools_in_use'] list from scratch if we don't have one like in the case of
  2841. # running this method from a Tcl Command
  2842. # #############################################################################################################
  2843. # #############################################################################################################
  2844. build_tools_in_use_list = False
  2845. if 'Tools_in_use' not in self.options:
  2846. self.options['Tools_in_use'] = []
  2847. # if the list is empty (either we just added the key or it was already there but empty) signal to build it
  2848. if not self.options['Tools_in_use']:
  2849. build_tools_in_use_list = True
  2850. # #############################################################################################################
  2851. # #############################################################################################################
  2852. # fill the data into the self.exc_cnc_tools dictionary
  2853. # #############################################################################################################
  2854. # #############################################################################################################
  2855. for it in all_tools:
  2856. for to_ol in tools:
  2857. if to_ol == it[0]:
  2858. sol_geo = []
  2859. drill_no = 0
  2860. if 'drills' in exobj.tools[to_ol]:
  2861. drill_no = len(exobj.tools[to_ol]['drills'])
  2862. for drill in exobj.tools[to_ol]['drills']:
  2863. sol_geo.append(drill.buffer((it[1] / 2.0), resolution=self.geo_steps_per_circle))
  2864. slot_no = 0
  2865. if 'slots' in exobj.tools[to_ol]:
  2866. slot_no = len(exobj.tools[to_ol]['slots'])
  2867. for slot in exobj.tools[to_ol]['slots']:
  2868. start = (slot[0].x, slot[0].y)
  2869. stop = (slot[1].x, slot[1].y)
  2870. sol_geo.append(
  2871. LineString([start, stop]).buffer((it[1] / 2.0), resolution=self.geo_steps_per_circle)
  2872. )
  2873. if self.use_ui:
  2874. try:
  2875. z_off = float(exobj.tools[it[0]]['data']['tools_drill_offset']) * (-1)
  2876. except KeyError:
  2877. z_off = 0
  2878. else:
  2879. z_off = 0
  2880. default_data = {}
  2881. for k, v in list(self.options.items()):
  2882. default_data[k] = deepcopy(v)
  2883. self.exc_cnc_tools[it[1]] = {}
  2884. self.exc_cnc_tools[it[1]]['tool'] = it[0]
  2885. self.exc_cnc_tools[it[1]]['nr_drills'] = drill_no
  2886. self.exc_cnc_tools[it[1]]['nr_slots'] = slot_no
  2887. self.exc_cnc_tools[it[1]]['offset_z'] = z_off
  2888. self.exc_cnc_tools[it[1]]['data'] = default_data
  2889. self.exc_cnc_tools[it[1]]['solid_geometry'] = deepcopy(sol_geo)
  2890. # build a self.options['Tools_in_use'] list from scratch if we don't have one like in the case of
  2891. # running this method from a Tcl Command
  2892. if build_tools_in_use_list is True:
  2893. self.options['Tools_in_use'].append(
  2894. [it[0], it[1], drill_no, slot_no]
  2895. )
  2896. self.app.inform.emit(_("Creating a list of points to drill..."))
  2897. # #############################################################################################################
  2898. # #############################################################################################################
  2899. # Points (Group by tool): a dictionary of shapely Point geo elements grouped by tool number
  2900. # #############################################################################################################
  2901. # #############################################################################################################
  2902. points = {}
  2903. for tool, tool_dict in self.exc_tools.items():
  2904. if tool in tools:
  2905. if self.app.abort_flag:
  2906. # graceful abort requested by the user
  2907. raise grace
  2908. if 'drills' in tool_dict and tool_dict['drills']:
  2909. for drill_pt in tool_dict['drills']:
  2910. try:
  2911. points[tool].append(drill_pt)
  2912. except KeyError:
  2913. points[tool] = [drill_pt]
  2914. log.debug("Found %d TOOLS with drills." % len(points))
  2915. # check if there are drill points in the exclusion areas.
  2916. # If we find any within the exclusion areas return 'fail'
  2917. for tool in points:
  2918. for pt in points[tool]:
  2919. for area in self.app.exc_areas.exclusion_areas_storage:
  2920. pt_buf = pt.buffer(self.exc_tools[tool]['tooldia'] / 2.0)
  2921. if pt_buf.within(area['shape']) or pt_buf.intersects(area['shape']):
  2922. self.app.inform.emit("[ERROR_NOTCL] %s" % _("Failed. Drill points inside the exclusion zones."))
  2923. return 'fail'
  2924. # this holds the resulting GCode
  2925. self.gcode = []
  2926. # #############################################################################################################
  2927. # #############################################################################################################
  2928. # Initialization
  2929. # #############################################################################################################
  2930. # #############################################################################################################
  2931. gcode = self.doformat(p.start_code)
  2932. if use_ui is False:
  2933. gcode += self.doformat(p.z_feedrate_code)
  2934. if self.toolchange is False:
  2935. if self.xy_toolchange is not None:
  2936. gcode += self.doformat(p.lift_code, x=self.xy_toolchange[0], y=self.xy_toolchange[1])
  2937. gcode += self.doformat(p.startz_code, x=self.xy_toolchange[0], y=self.xy_toolchange[1])
  2938. else:
  2939. gcode += self.doformat(p.lift_code, x=0.0, y=0.0)
  2940. gcode += self.doformat(p.startz_code, x=0.0, y=0.0)
  2941. if self.xy_toolchange is not None:
  2942. self.oldx = self.xy_toolchange[0]
  2943. self.oldy = self.xy_toolchange[1]
  2944. else:
  2945. self.oldx = 0.0
  2946. self.oldy = 0.0
  2947. measured_distance = 0.0
  2948. measured_down_distance = 0.0
  2949. measured_up_to_zero_distance = 0.0
  2950. measured_lift_distance = 0.0
  2951. # #############################################################################################################
  2952. # #############################################################################################################
  2953. # GCODE creation
  2954. # #############################################################################################################
  2955. # #############################################################################################################
  2956. self.app.inform.emit('%s...' % _("Starting G-Code"))
  2957. has_drills = None
  2958. for tool, tool_dict in self.exc_tools.items():
  2959. if 'drills' in tool_dict and tool_dict['drills']:
  2960. has_drills = True
  2961. break
  2962. if not has_drills:
  2963. log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> "
  2964. "The loaded Excellon file has no drills ...")
  2965. self.app.inform.emit('[ERROR_NOTCL] %s...' % _('The loaded Excellon file has no drills'))
  2966. return 'fail'
  2967. current_platform = platform.architecture()[0]
  2968. if current_platform == '64bit':
  2969. used_excellon_optimization_type = self.excellon_optimization_type
  2970. else:
  2971. used_excellon_optimization_type = 'T'
  2972. # #############################################################################################################
  2973. # #############################################################################################################
  2974. # ################################## DRILLING !!! #########################################################
  2975. # #############################################################################################################
  2976. # #############################################################################################################
  2977. if used_excellon_optimization_type == 'M':
  2978. log.debug("Using OR-Tools Metaheuristic Guided Local Search drill path optimization.")
  2979. elif used_excellon_optimization_type == 'B':
  2980. log.debug("Using OR-Tools Basic drill path optimization.")
  2981. elif used_excellon_optimization_type == 'T':
  2982. log.debug("Using Travelling Salesman drill path optimization.")
  2983. else:
  2984. log.debug("Using no path optimization.")
  2985. if self.toolchange is True:
  2986. for tool in tools:
  2987. # check if it has drills
  2988. if not self.exc_tools[tool]['drills']:
  2989. continue
  2990. if self.app.abort_flag:
  2991. # graceful abort requested by the user
  2992. raise grace
  2993. self.tool = tool
  2994. self.tooldia = self.exc_tools[tool]["tooldia"]
  2995. self.postdata['toolC'] = self.tooldia
  2996. if self.use_ui:
  2997. self.z_feedrate = self.exc_tools[tool]['data']['tools_drill_feedrate_z']
  2998. self.feedrate = self.exc_tools[tool]['data']['tools_drill_feedrate_z']
  2999. self.z_cut = self.exc_tools[tool]['data']['tools_drill_cutz']
  3000. gcode += self.doformat(p.z_feedrate_code)
  3001. if self.machinist_setting == 0:
  3002. if self.z_cut > 0:
  3003. self.app.inform.emit('[WARNING] %s' %
  3004. _("The Cut Z parameter has positive value. "
  3005. "It is the depth value to drill into material.\n"
  3006. "The Cut Z parameter needs to have a negative value, "
  3007. "assuming it is a typo "
  3008. "therefore the app will convert the value to negative. "
  3009. "Check the resulting CNC code (Gcode etc)."))
  3010. self.z_cut = -self.z_cut
  3011. elif self.z_cut == 0:
  3012. self.app.inform.emit('[WARNING] %s: %s' %
  3013. (_(
  3014. "The Cut Z parameter is zero. There will be no cut, "
  3015. "skipping file"),
  3016. exobj.options['name']))
  3017. return 'fail'
  3018. old_zcut = deepcopy(self.z_cut)
  3019. self.z_move = self.exc_tools[tool]['data']['tools_drill_travelz']
  3020. self.spindlespeed = self.exc_tools[tool]['data']['tools_drill_spindlespeed']
  3021. self.dwell = self.exc_tools[tool]['data']['tools_drill_dwell']
  3022. self.dwelltime = self.exc_tools[tool]['data']['tools_drill_dwelltime']
  3023. self.multidepth = self.exc_tools[tool]['data']['tools_drill_multidepth']
  3024. self.z_depthpercut = self.exc_tools[tool]['data']['tools_drill_depthperpass']
  3025. else:
  3026. old_zcut = deepcopy(self.z_cut)
  3027. # #########################################################################################################
  3028. # ############ Create the data. #################
  3029. # #########################################################################################################
  3030. locations = []
  3031. altPoints = []
  3032. optimized_path = []
  3033. if used_excellon_optimization_type == 'M':
  3034. if tool in points:
  3035. locations = self.create_tool_data_array(points=points[tool])
  3036. # if there are no locations then go to the next tool
  3037. if not locations:
  3038. continue
  3039. opt_time = self.app.defaults["excellon_search_time"]
  3040. optimized_path = self.optimized_ortools_meta(locations=locations, opt_time=opt_time)
  3041. elif used_excellon_optimization_type == 'B':
  3042. if tool in points:
  3043. locations = self.create_tool_data_array(points=points[tool])
  3044. # if there are no locations then go to the next tool
  3045. if not locations:
  3046. continue
  3047. optimized_path = self.optimized_ortools_basic(locations=locations)
  3048. elif used_excellon_optimization_type == 'T':
  3049. for point in points[tool]:
  3050. altPoints.append((point.coords.xy[0][0], point.coords.xy[1][0]))
  3051. optimized_path = self.optimized_travelling_salesman(altPoints)
  3052. else:
  3053. # it's actually not optimized path but here we build a list of (x,y) coordinates
  3054. # out of the tool's drills
  3055. for drill in self.exc_tools[tool]['drills']:
  3056. unoptimized_coords = (
  3057. drill.x,
  3058. drill.y
  3059. )
  3060. optimized_path.append(unoptimized_coords)
  3061. # #########################################################################################################
  3062. # #########################################################################################################
  3063. # Only if there are locations to drill
  3064. if not optimized_path:
  3065. continue
  3066. if self.app.abort_flag:
  3067. # graceful abort requested by the user
  3068. raise grace
  3069. # Tool change sequence (optional)
  3070. if self.toolchange:
  3071. gcode += self.doformat(p.toolchange_code, toolchangexy=(self.oldx, self.oldy))
  3072. # Spindle start
  3073. gcode += self.doformat(p.spindle_code)
  3074. # Dwell time
  3075. if self.dwell is True:
  3076. gcode += self.doformat(p.dwell_code)
  3077. current_tooldia = float('%.*f' % (self.decimals, float(self.exc_tools[tool]["tooldia"])))
  3078. self.app.inform.emit(
  3079. '%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  3080. str(current_tooldia),
  3081. str(self.units))
  3082. )
  3083. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  3084. # APPLY Offset only when using the appGUI, for TclCommand this will create an error
  3085. # because the values for Z offset are created in build_ui()
  3086. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  3087. try:
  3088. z_offset = float(self.exc_tools[tool]['data']['tools_drill_offset']) * (-1)
  3089. except KeyError:
  3090. z_offset = 0
  3091. self.z_cut = z_offset + old_zcut
  3092. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  3093. if self.coordinates_type == "G90":
  3094. # Drillling! for Absolute coordinates type G90
  3095. # variables to display the percentage of work done
  3096. geo_len = len(optimized_path)
  3097. old_disp_number = 0
  3098. log.warning("Number of drills for which to generate GCode: %s" % str(geo_len))
  3099. loc_nr = 0
  3100. for point in optimized_path:
  3101. if self.app.abort_flag:
  3102. # graceful abort requested by the user
  3103. raise grace
  3104. if used_excellon_optimization_type == 'T':
  3105. locx = point[0]
  3106. locy = point[1]
  3107. else:
  3108. locx = locations[point][0]
  3109. locy = locations[point][1]
  3110. travels = self.app.exc_areas.travel_coordinates(start_point=(self.oldx, self.oldy),
  3111. end_point=(locx, locy),
  3112. tooldia=current_tooldia)
  3113. prev_z = None
  3114. for travel in travels:
  3115. locx = travel[1][0]
  3116. locy = travel[1][1]
  3117. if travel[0] is not None:
  3118. # move to next point
  3119. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3120. # raise to safe Z (travel[0]) each time because safe Z may be different
  3121. self.z_move = travel[0]
  3122. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3123. # restore z_move
  3124. self.z_move = self.exc_tools[tool]['data']['tools_drill_travelz']
  3125. else:
  3126. if prev_z is not None:
  3127. # move to next point
  3128. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3129. # we assume that previously the z_move was altered therefore raise to
  3130. # the travel_z (z_move)
  3131. self.z_move = self.exc_tools[tool]['data']['tools_drill_travelz']
  3132. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3133. else:
  3134. # move to next point
  3135. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3136. # store prev_z
  3137. prev_z = travel[0]
  3138. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3139. if self.multidepth and abs(self.z_cut) > abs(self.z_depthpercut):
  3140. doc = deepcopy(self.z_cut)
  3141. self.z_cut = 0.0
  3142. while abs(self.z_cut) < abs(doc):
  3143. self.z_cut -= self.z_depthpercut
  3144. if abs(doc) < abs(self.z_cut) < (abs(doc) + self.z_depthpercut):
  3145. self.z_cut = doc
  3146. gcode += self.doformat(p.down_code, x=locx, y=locy)
  3147. measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  3148. if self.f_retract is False:
  3149. gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  3150. measured_up_to_zero_distance += abs(self.z_cut)
  3151. measured_lift_distance += abs(self.z_move)
  3152. else:
  3153. measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  3154. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3155. else:
  3156. gcode += self.doformat(p.down_code, x=locx, y=locy)
  3157. measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  3158. if self.f_retract is False:
  3159. gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  3160. measured_up_to_zero_distance += abs(self.z_cut)
  3161. measured_lift_distance += abs(self.z_move)
  3162. else:
  3163. measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  3164. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3165. measured_distance += abs(distance_euclidian(locx, locy, self.oldx, self.oldy))
  3166. self.oldx = locx
  3167. self.oldy = locy
  3168. loc_nr += 1
  3169. disp_number = int(np.interp(loc_nr, [0, geo_len], [0, 100]))
  3170. if old_disp_number < disp_number <= 100:
  3171. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  3172. old_disp_number = disp_number
  3173. else:
  3174. self.app.inform.emit('[ERROR_NOTCL] %s...' % _('G91 coordinates not implemented'))
  3175. return 'fail'
  3176. self.z_cut = deepcopy(old_zcut)
  3177. else:
  3178. # We are not using Toolchange therefore we need to decide which tool properties to use
  3179. one_tool = 1
  3180. all_points = []
  3181. for tool in points:
  3182. # check if it has drills
  3183. if not points[tool]:
  3184. continue
  3185. all_points += points[tool]
  3186. if self.app.abort_flag:
  3187. # graceful abort requested by the user
  3188. raise grace
  3189. self.tool = one_tool
  3190. self.tooldia = self.exc_tools[one_tool]["tooldia"]
  3191. self.postdata['toolC'] = self.tooldia
  3192. if self.use_ui:
  3193. self.z_feedrate = self.exc_tools[one_tool]['data']['tools_drill_feedrate_z']
  3194. self.feedrate = self.exc_tools[one_tool]['data']['tools_drill_feedrate_z']
  3195. self.z_cut = self.exc_tools[one_tool]['data']['tools_drill_cutz']
  3196. gcode += self.doformat(p.z_feedrate_code)
  3197. if self.machinist_setting == 0:
  3198. if self.z_cut > 0:
  3199. self.app.inform.emit('[WARNING] %s' %
  3200. _("The Cut Z parameter has positive value. "
  3201. "It is the depth value to drill into material.\n"
  3202. "The Cut Z parameter needs to have a negative value, "
  3203. "assuming it is a typo "
  3204. "therefore the app will convert the value to negative. "
  3205. "Check the resulting CNC code (Gcode etc)."))
  3206. self.z_cut = -self.z_cut
  3207. elif self.z_cut == 0:
  3208. self.app.inform.emit('[WARNING] %s: %s' %
  3209. (_(
  3210. "The Cut Z parameter is zero. There will be no cut, "
  3211. "skipping file"),
  3212. exobj.options['name']))
  3213. return 'fail'
  3214. old_zcut = deepcopy(self.z_cut)
  3215. self.z_move = self.exc_tools[one_tool]['data']['tools_drill_travelz']
  3216. self.spindlespeed = self.exc_tools[one_tool]['data']['tools_drill_spindlespeed']
  3217. self.dwell = self.exc_tools[one_tool]['data']['tools_drill_dwell']
  3218. self.dwelltime = self.exc_tools[one_tool]['data']['tools_drill_dwelltime']
  3219. self.multidepth = self.exc_tools[one_tool]['data']['tools_drill_multidepth']
  3220. self.z_depthpercut = self.exc_tools[one_tool]['data']['tools_drill_depthperpass']
  3221. else:
  3222. old_zcut = deepcopy(self.z_cut)
  3223. # #########################################################################################################
  3224. # ############ Create the data. #################
  3225. # #########################################################################################################
  3226. locations = []
  3227. altPoints = []
  3228. optimized_path = []
  3229. if used_excellon_optimization_type == 'M':
  3230. if all_points:
  3231. locations = self.create_tool_data_array(points=all_points)
  3232. # if there are no locations then go to the next tool
  3233. if not locations:
  3234. return 'fail'
  3235. opt_time = self.app.defaults["excellon_search_time"]
  3236. optimized_path = self.optimized_ortools_meta(locations=locations, opt_time=opt_time)
  3237. elif used_excellon_optimization_type == 'B':
  3238. if all_points:
  3239. locations = self.create_tool_data_array(points=all_points)
  3240. # if there are no locations then go to the next tool
  3241. if not locations:
  3242. return 'fail'
  3243. optimized_path = self.optimized_ortools_basic(locations=locations)
  3244. elif used_excellon_optimization_type == 'T':
  3245. for point in all_points:
  3246. altPoints.append((point.coords.xy[0][0], point.coords.xy[1][0]))
  3247. optimized_path = self.optimized_travelling_salesman(altPoints)
  3248. else:
  3249. # it's actually not optimized path but here we build a list of (x,y) coordinates
  3250. # out of the tool's drills
  3251. for pt in all_points:
  3252. unoptimized_coords = (
  3253. pt.x,
  3254. pt.y
  3255. )
  3256. optimized_path.append(unoptimized_coords)
  3257. # #########################################################################################################
  3258. # #########################################################################################################
  3259. # Only if there are locations to drill
  3260. if not optimized_path:
  3261. return 'fail'
  3262. if self.app.abort_flag:
  3263. # graceful abort requested by the user
  3264. raise grace
  3265. # Spindle start
  3266. gcode += self.doformat(p.spindle_code)
  3267. # Dwell time
  3268. if self.dwell is True:
  3269. gcode += self.doformat(p.dwell_code)
  3270. current_tooldia = float('%.*f' % (self.decimals, float(self.exc_tools[one_tool]["tooldia"])))
  3271. self.app.inform.emit(
  3272. '%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  3273. str(current_tooldia),
  3274. str(self.units))
  3275. )
  3276. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  3277. # APPLY Offset only when using the appGUI, for TclCommand this will create an error
  3278. # because the values for Z offset are created in build_ui()
  3279. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  3280. try:
  3281. z_offset = float(self.exc_tools[one_tool]['data']['tools_drill_offset']) * (-1)
  3282. except KeyError:
  3283. z_offset = 0
  3284. self.z_cut = z_offset + old_zcut
  3285. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  3286. if self.coordinates_type == "G90":
  3287. # Drillling! for Absolute coordinates type G90
  3288. # variables to display the percentage of work done
  3289. geo_len = len(optimized_path)
  3290. old_disp_number = 0
  3291. log.warning("Number of drills for which to generate GCode: %s" % str(geo_len))
  3292. loc_nr = 0
  3293. for point in optimized_path:
  3294. if self.app.abort_flag:
  3295. # graceful abort requested by the user
  3296. raise grace
  3297. if used_excellon_optimization_type == 'T':
  3298. locx = point[0]
  3299. locy = point[1]
  3300. else:
  3301. locx = locations[point][0]
  3302. locy = locations[point][1]
  3303. travels = self.app.exc_areas.travel_coordinates(start_point=(self.oldx, self.oldy),
  3304. end_point=(locx, locy),
  3305. tooldia=current_tooldia)
  3306. prev_z = None
  3307. for travel in travels:
  3308. locx = travel[1][0]
  3309. locy = travel[1][1]
  3310. if travel[0] is not None:
  3311. # move to next point
  3312. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3313. # raise to safe Z (travel[0]) each time because safe Z may be different
  3314. self.z_move = travel[0]
  3315. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3316. # restore z_move
  3317. self.z_move = self.exc_tools[one_tool]['data']['tools_drill_travelz']
  3318. else:
  3319. if prev_z is not None:
  3320. # move to next point
  3321. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3322. # we assume that previously the z_move was altered therefore raise to
  3323. # the travel_z (z_move)
  3324. self.z_move = self.exc_tools[one_tool]['data']['tools_drill_travelz']
  3325. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3326. else:
  3327. # move to next point
  3328. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3329. # store prev_z
  3330. prev_z = travel[0]
  3331. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3332. if self.multidepth and abs(self.z_cut) > abs(self.z_depthpercut):
  3333. doc = deepcopy(self.z_cut)
  3334. self.z_cut = 0.0
  3335. while abs(self.z_cut) < abs(doc):
  3336. self.z_cut -= self.z_depthpercut
  3337. if abs(doc) < abs(self.z_cut) < (abs(doc) + self.z_depthpercut):
  3338. self.z_cut = doc
  3339. gcode += self.doformat(p.down_code, x=locx, y=locy)
  3340. measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  3341. if self.f_retract is False:
  3342. gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  3343. measured_up_to_zero_distance += abs(self.z_cut)
  3344. measured_lift_distance += abs(self.z_move)
  3345. else:
  3346. measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  3347. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3348. else:
  3349. gcode += self.doformat(p.down_code, x=locx, y=locy)
  3350. measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  3351. if self.f_retract is False:
  3352. gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  3353. measured_up_to_zero_distance += abs(self.z_cut)
  3354. measured_lift_distance += abs(self.z_move)
  3355. else:
  3356. measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  3357. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3358. measured_distance += abs(distance_euclidian(locx, locy, self.oldx, self.oldy))
  3359. self.oldx = locx
  3360. self.oldy = locy
  3361. loc_nr += 1
  3362. disp_number = int(np.interp(loc_nr, [0, geo_len], [0, 100]))
  3363. if old_disp_number < disp_number <= 100:
  3364. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  3365. old_disp_number = disp_number
  3366. else:
  3367. self.app.inform.emit('[ERROR_NOTCL] %s...' % _('G91 coordinates not implemented'))
  3368. return 'fail'
  3369. self.z_cut = deepcopy(old_zcut)
  3370. if used_excellon_optimization_type == 'M':
  3371. log.debug("The total travel distance with OR-TOOLS Metaheuristics is: %s" % str(measured_distance))
  3372. elif used_excellon_optimization_type == 'B':
  3373. log.debug("The total travel distance with OR-TOOLS Basic Algorithm is: %s" % str(measured_distance))
  3374. elif used_excellon_optimization_type == 'T':
  3375. log.debug("The total travel distance with Travelling Salesman Algorithm is: %s" % str(measured_distance))
  3376. else:
  3377. log.debug("The total travel distance with with no optimization is: %s" % str(measured_distance))
  3378. # if used_excellon_optimization_type == 'M':
  3379. # log.debug("Using OR-Tools Metaheuristic Guided Local Search drill path optimization.")
  3380. #
  3381. # if has_drills:
  3382. # for tool in tools:
  3383. # if self.app.abort_flag:
  3384. # # graceful abort requested by the user
  3385. # raise grace
  3386. #
  3387. # self.tool = tool
  3388. # self.tooldia = self.exc_tools[tool]["tooldia"]
  3389. # self.postdata['toolC'] = self.tooldia
  3390. #
  3391. # if self.use_ui:
  3392. # self.z_feedrate = self.exc_tools[tool]['data']['feedrate_z']
  3393. # self.feedrate = self.exc_tools[tool]['data']['feedrate']
  3394. # gcode += self.doformat(p.z_feedrate_code)
  3395. # self.z_cut = self.exc_tools[tool]['data']['cutz']
  3396. #
  3397. # if self.machinist_setting == 0:
  3398. # if self.z_cut > 0:
  3399. # self.app.inform.emit('[WARNING] %s' %
  3400. # _("The Cut Z parameter has positive value. "
  3401. # "It is the depth value to drill into material.\n"
  3402. # "The Cut Z parameter needs to have a negative value, "
  3403. # "assuming it is a typo "
  3404. # "therefore the app will convert the value to negative. "
  3405. # "Check the resulting CNC code (Gcode etc)."))
  3406. # self.z_cut = -self.z_cut
  3407. # elif self.z_cut == 0:
  3408. # self.app.inform.emit('[WARNING] %s: %s' %
  3409. # (_(
  3410. # "The Cut Z parameter is zero. There will be no cut, "
  3411. # "skipping file"),
  3412. # exobj.options['name']))
  3413. # return 'fail'
  3414. #
  3415. # old_zcut = deepcopy(self.z_cut)
  3416. #
  3417. # self.z_move = self.exc_tools[tool]['data']['travelz']
  3418. # self.spindlespeed = self.exc_tools[tool]['data']['spindlespeed']
  3419. # self.dwell = self.exc_tools[tool]['data']['dwell']
  3420. # self.dwelltime = self.exc_tools[tool]['data']['dwelltime']
  3421. # self.multidepth = self.exc_tools[tool]['data']['multidepth']
  3422. # self.z_depthpercut = self.exc_tools[tool]['data']['depthperpass']
  3423. # else:
  3424. # old_zcut = deepcopy(self.z_cut)
  3425. #
  3426. # # ###############################################
  3427. # # ############ Create the data. #################
  3428. # # ###############################################
  3429. # locations = self.create_tool_data_array(tool=tool, points=points)
  3430. # # if there are no locations then go to the next tool
  3431. # if not locations:
  3432. # continue
  3433. # optimized_path = self.optimized_ortools_meta(locations=locations)
  3434. #
  3435. # # Only if tool has points.
  3436. # if tool in points:
  3437. # if self.app.abort_flag:
  3438. # # graceful abort requested by the user
  3439. # raise grace
  3440. #
  3441. # # Tool change sequence (optional)
  3442. # if self.toolchange:
  3443. # gcode += self.doformat(p.toolchange_code, toolchangexy=(self.oldx, self.oldy))
  3444. # # Spindle start
  3445. # gcode += self.doformat(p.spindle_code)
  3446. # # Dwell time
  3447. # if self.dwell is True:
  3448. # gcode += self.doformat(p.dwell_code)
  3449. #
  3450. # current_tooldia = float('%.*f' % (self.decimals, float(self.exc_tools[tool]["tooldia"])))
  3451. #
  3452. # self.app.inform.emit(
  3453. # '%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  3454. # str(current_tooldia),
  3455. # str(self.units))
  3456. # )
  3457. #
  3458. # # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  3459. # # APPLY Offset only when using the appGUI, for TclCommand this will create an error
  3460. # # because the values for Z offset are created in build_ui()
  3461. # # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  3462. # try:
  3463. # z_offset = float(self.exc_tools[tool]['data']['offset']) * (-1)
  3464. # except KeyError:
  3465. # z_offset = 0
  3466. # self.z_cut = z_offset + old_zcut
  3467. #
  3468. # self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  3469. # if self.coordinates_type == "G90":
  3470. # # Drillling! for Absolute coordinates type G90
  3471. # # variables to display the percentage of work done
  3472. # geo_len = len(optimized_path)
  3473. #
  3474. # old_disp_number = 0
  3475. # log.warning("Number of drills for which to generate GCode: %s" % str(geo_len))
  3476. #
  3477. # loc_nr = 0
  3478. # for k in optimized_path:
  3479. # if self.app.abort_flag:
  3480. # # graceful abort requested by the user
  3481. # raise grace
  3482. #
  3483. # locx = locations[k][0]
  3484. # locy = locations[k][1]
  3485. #
  3486. # travels = self.app.exc_areas.travel_coordinates(start_point=(self.oldx, self.oldy),
  3487. # end_point=(locx, locy),
  3488. # tooldia=current_tooldia)
  3489. # prev_z = None
  3490. # for travel in travels:
  3491. # locx = travel[1][0]
  3492. # locy = travel[1][1]
  3493. #
  3494. # if travel[0] is not None:
  3495. # # move to next point
  3496. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3497. #
  3498. # # raise to safe Z (travel[0]) each time because safe Z may be different
  3499. # self.z_move = travel[0]
  3500. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3501. #
  3502. # # restore z_move
  3503. # self.z_move = self.exc_tools[tool]['data']['travelz']
  3504. # else:
  3505. # if prev_z is not None:
  3506. # # move to next point
  3507. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3508. #
  3509. # # we assume that previously the z_move was altered therefore raise to
  3510. # # the travel_z (z_move)
  3511. # self.z_move = self.exc_tools[tool]['data']['travelz']
  3512. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3513. # else:
  3514. # # move to next point
  3515. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3516. #
  3517. # # store prev_z
  3518. # prev_z = travel[0]
  3519. #
  3520. # # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3521. #
  3522. # if self.multidepth and abs(self.z_cut) > abs(self.z_depthpercut):
  3523. # doc = deepcopy(self.z_cut)
  3524. # self.z_cut = 0.0
  3525. #
  3526. # while abs(self.z_cut) < abs(doc):
  3527. #
  3528. # self.z_cut -= self.z_depthpercut
  3529. # if abs(doc) < abs(self.z_cut) < (abs(doc) + self.z_depthpercut):
  3530. # self.z_cut = doc
  3531. # gcode += self.doformat(p.down_code, x=locx, y=locy)
  3532. #
  3533. # measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  3534. #
  3535. # if self.f_retract is False:
  3536. # gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  3537. # measured_up_to_zero_distance += abs(self.z_cut)
  3538. # measured_lift_distance += abs(self.z_move)
  3539. # else:
  3540. # measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  3541. #
  3542. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3543. #
  3544. # else:
  3545. # gcode += self.doformat(p.down_code, x=locx, y=locy)
  3546. #
  3547. # measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  3548. #
  3549. # if self.f_retract is False:
  3550. # gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  3551. # measured_up_to_zero_distance += abs(self.z_cut)
  3552. # measured_lift_distance += abs(self.z_move)
  3553. # else:
  3554. # measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  3555. #
  3556. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3557. #
  3558. # measured_distance += abs(distance_euclidian(locx, locy, self.oldx, self.oldy))
  3559. # self.oldx = locx
  3560. # self.oldy = locy
  3561. #
  3562. # loc_nr += 1
  3563. # disp_number = int(np.interp(loc_nr, [0, geo_len], [0, 100]))
  3564. #
  3565. # if old_disp_number < disp_number <= 100:
  3566. # self.app.proc_container.update_view_text(' %d%%' % disp_number)
  3567. # old_disp_number = disp_number
  3568. #
  3569. # else:
  3570. # self.app.inform.emit('[ERROR_NOTCL] %s...' % _('G91 coordinates not implemented'))
  3571. # return 'fail'
  3572. # self.z_cut = deepcopy(old_zcut)
  3573. # else:
  3574. # log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> "
  3575. # "The loaded Excellon file has no drills ...")
  3576. # self.app.inform.emit('[ERROR_NOTCL] %s...' % _('The loaded Excellon file has no drills'))
  3577. # return 'fail'
  3578. #
  3579. # log.debug("The total travel distance with OR-TOOLS Metaheuristics is: %s" % str(measured_distance))
  3580. #
  3581. # elif used_excellon_optimization_type == 'B':
  3582. # log.debug("Using OR-Tools Basic drill path optimization.")
  3583. #
  3584. # if has_drills:
  3585. # for tool in tools:
  3586. # if self.app.abort_flag:
  3587. # # graceful abort requested by the user
  3588. # raise grace
  3589. #
  3590. # self.tool = tool
  3591. # self.tooldia = self.exc_tools[tool]["tooldia"]
  3592. # self.postdata['toolC'] = self.tooldia
  3593. #
  3594. # if self.use_ui:
  3595. # self.z_feedrate = self.exc_tools[tool]['data']['feedrate_z']
  3596. # self.feedrate = self.exc_tools[tool]['data']['feedrate']
  3597. # gcode += self.doformat(p.z_feedrate_code)
  3598. # self.z_cut = self.exc_tools[tool]['data']['cutz']
  3599. #
  3600. # if self.machinist_setting == 0:
  3601. # if self.z_cut > 0:
  3602. # self.app.inform.emit('[WARNING] %s' %
  3603. # _("The Cut Z parameter has positive value. "
  3604. # "It is the depth value to drill into material.\n"
  3605. # "The Cut Z parameter needs to have a negative value, "
  3606. # "assuming it is a typo "
  3607. # "therefore the app will convert the value to negative. "
  3608. # "Check the resulting CNC code (Gcode etc)."))
  3609. # self.z_cut = -self.z_cut
  3610. # elif self.z_cut == 0:
  3611. # self.app.inform.emit('[WARNING] %s: %s' %
  3612. # (_(
  3613. # "The Cut Z parameter is zero. There will be no cut, "
  3614. # "skipping file"),
  3615. # exobj.options['name']))
  3616. # return 'fail'
  3617. #
  3618. # old_zcut = deepcopy(self.z_cut)
  3619. #
  3620. # self.z_move = self.exc_tools[tool]['data']['travelz']
  3621. #
  3622. # self.spindlespeed = self.exc_tools[tool]['data']['spindlespeed']
  3623. # self.dwell = self.exc_tools[tool]['data']['dwell']
  3624. # self.dwelltime = self.exc_tools[tool]['data']['dwelltime']
  3625. # self.multidepth = self.exc_tools[tool]['data']['multidepth']
  3626. # self.z_depthpercut = self.exc_tools[tool]['data']['depthperpass']
  3627. # else:
  3628. # old_zcut = deepcopy(self.z_cut)
  3629. #
  3630. # # ###############################################
  3631. # # ############ Create the data. #################
  3632. # # ###############################################
  3633. # locations = self.create_tool_data_array(tool=tool, points=points)
  3634. # # if there are no locations then go to the next tool
  3635. # if not locations:
  3636. # continue
  3637. # optimized_path = self.optimized_ortools_basic(locations=locations)
  3638. #
  3639. # # Only if tool has points.
  3640. # if tool in points:
  3641. # if self.app.abort_flag:
  3642. # # graceful abort requested by the user
  3643. # raise grace
  3644. #
  3645. # # Tool change sequence (optional)
  3646. # if self.toolchange:
  3647. # gcode += self.doformat(p.toolchange_code, toolchangexy=(self.oldx, self.oldy))
  3648. # gcode += self.doformat(p.spindle_code) # Spindle start)
  3649. # if self.dwell is True:
  3650. # gcode += self.doformat(p.dwell_code) # Dwell time
  3651. # else:
  3652. # gcode += self.doformat(p.spindle_code)
  3653. # if self.dwell is True:
  3654. # gcode += self.doformat(p.dwell_code) # Dwell time
  3655. #
  3656. # current_tooldia = float('%.*f' % (self.decimals, float(self.exc_tools[tool]["tooldia"])))
  3657. #
  3658. # self.app.inform.emit(
  3659. # '%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  3660. # str(current_tooldia),
  3661. # str(self.units))
  3662. # )
  3663. #
  3664. # # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  3665. # # APPLY Offset only when using the appGUI, for TclCommand this will create an error
  3666. # # because the values for Z offset are created in build_ui()
  3667. # # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  3668. # try:
  3669. # z_offset = float(self.exc_tools[tool]['data']['offset']) * (-1)
  3670. # except KeyError:
  3671. # z_offset = 0
  3672. # self.z_cut = z_offset + old_zcut
  3673. #
  3674. # self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  3675. # if self.coordinates_type == "G90":
  3676. # # Drillling! for Absolute coordinates type G90
  3677. # # variables to display the percentage of work done
  3678. # geo_len = len(optimized_path)
  3679. # old_disp_number = 0
  3680. # log.warning("Number of drills for which to generate GCode: %s" % str(geo_len))
  3681. #
  3682. # loc_nr = 0
  3683. # for k in optimized_path:
  3684. # if self.app.abort_flag:
  3685. # # graceful abort requested by the user
  3686. # raise grace
  3687. #
  3688. # locx = locations[k][0]
  3689. # locy = locations[k][1]
  3690. #
  3691. # travels = self.app.exc_areas.travel_coordinates(start_point=(self.oldx, self.oldy),
  3692. # end_point=(locx, locy),
  3693. # tooldia=current_tooldia)
  3694. # prev_z = None
  3695. # for travel in travels:
  3696. # locx = travel[1][0]
  3697. # locy = travel[1][1]
  3698. #
  3699. # if travel[0] is not None:
  3700. # # move to next point
  3701. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3702. #
  3703. # # raise to safe Z (travel[0]) each time because safe Z may be different
  3704. # self.z_move = travel[0]
  3705. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3706. #
  3707. # # restore z_move
  3708. # self.z_move = self.exc_tools[tool]['data']['travelz']
  3709. # else:
  3710. # if prev_z is not None:
  3711. # # move to next point
  3712. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3713. #
  3714. # # we assume that previously the z_move was altered therefore raise to
  3715. # # the travel_z (z_move)
  3716. # self.z_move = self.exc_tools[tool]['data']['travelz']
  3717. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3718. # else:
  3719. # # move to next point
  3720. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3721. #
  3722. # # store prev_z
  3723. # prev_z = travel[0]
  3724. #
  3725. # # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3726. #
  3727. # if self.multidepth and abs(self.z_cut) > abs(self.z_depthpercut):
  3728. # doc = deepcopy(self.z_cut)
  3729. # self.z_cut = 0.0
  3730. #
  3731. # while abs(self.z_cut) < abs(doc):
  3732. #
  3733. # self.z_cut -= self.z_depthpercut
  3734. # if abs(doc) < abs(self.z_cut) < (abs(doc) + self.z_depthpercut):
  3735. # self.z_cut = doc
  3736. # gcode += self.doformat(p.down_code, x=locx, y=locy)
  3737. #
  3738. # measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  3739. #
  3740. # if self.f_retract is False:
  3741. # gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  3742. # measured_up_to_zero_distance += abs(self.z_cut)
  3743. # measured_lift_distance += abs(self.z_move)
  3744. # else:
  3745. # measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  3746. #
  3747. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3748. #
  3749. # else:
  3750. # gcode += self.doformat(p.down_code, x=locx, y=locy)
  3751. #
  3752. # measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  3753. #
  3754. # if self.f_retract is False:
  3755. # gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  3756. # measured_up_to_zero_distance += abs(self.z_cut)
  3757. # measured_lift_distance += abs(self.z_move)
  3758. # else:
  3759. # measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  3760. #
  3761. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3762. #
  3763. # measured_distance += abs(distance_euclidian(locx, locy, self.oldx, self.oldy))
  3764. # self.oldx = locx
  3765. # self.oldy = locy
  3766. #
  3767. # loc_nr += 1
  3768. # disp_number = int(np.interp(loc_nr, [0, geo_len], [0, 100]))
  3769. #
  3770. # if old_disp_number < disp_number <= 100:
  3771. # self.app.proc_container.update_view_text(' %d%%' % disp_number)
  3772. # old_disp_number = disp_number
  3773. #
  3774. # else:
  3775. # self.app.inform.emit('[ERROR_NOTCL] %s...' % _('G91 coordinates not implemented'))
  3776. # return 'fail'
  3777. # self.z_cut = deepcopy(old_zcut)
  3778. # else:
  3779. # log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> "
  3780. # "The loaded Excellon file has no drills ...")
  3781. # self.app.inform.emit('[ERROR_NOTCL] %s...' % _('The loaded Excellon file has no drills'))
  3782. # return 'fail'
  3783. #
  3784. # log.debug("The total travel distance with OR-TOOLS Basic Algorithm is: %s" % str(measured_distance))
  3785. #
  3786. # elif used_excellon_optimization_type == 'T':
  3787. # log.debug("Using Travelling Salesman drill path optimization.")
  3788. #
  3789. # for tool in tools:
  3790. # if self.app.abort_flag:
  3791. # # graceful abort requested by the user
  3792. # raise grace
  3793. #
  3794. # if has_drills:
  3795. # self.tool = tool
  3796. # self.tooldia = self.exc_tools[tool]["tooldia"]
  3797. # self.postdata['toolC'] = self.tooldia
  3798. #
  3799. # if self.use_ui:
  3800. # self.z_feedrate = self.exc_tools[tool]['data']['feedrate_z']
  3801. # self.feedrate = self.exc_tools[tool]['data']['feedrate']
  3802. # gcode += self.doformat(p.z_feedrate_code)
  3803. #
  3804. # self.z_cut = self.exc_tools[tool]['data']['cutz']
  3805. #
  3806. # if self.machinist_setting == 0:
  3807. # if self.z_cut > 0:
  3808. # self.app.inform.emit('[WARNING] %s' %
  3809. # _("The Cut Z parameter has positive value. "
  3810. # "It is the depth value to drill into material.\n"
  3811. # "The Cut Z parameter needs to have a negative value, "
  3812. # "assuming it is a typo "
  3813. # "therefore the app will convert the value to negative. "
  3814. # "Check the resulting CNC code (Gcode etc)."))
  3815. # self.z_cut = -self.z_cut
  3816. # elif self.z_cut == 0:
  3817. # self.app.inform.emit('[WARNING] %s: %s' %
  3818. # (_(
  3819. # "The Cut Z parameter is zero. There will be no cut, "
  3820. # "skipping file"),
  3821. # exobj.options['name']))
  3822. # return 'fail'
  3823. #
  3824. # old_zcut = deepcopy(self.z_cut)
  3825. #
  3826. # self.z_move = self.exc_tools[tool]['data']['travelz']
  3827. # self.spindlespeed = self.exc_tools[tool]['data']['spindlespeed']
  3828. # self.dwell = self.exc_tools[tool]['data']['dwell']
  3829. # self.dwelltime = self.exc_tools[tool]['data']['dwelltime']
  3830. # self.multidepth = self.exc_tools[tool]['data']['multidepth']
  3831. # self.z_depthpercut = self.exc_tools[tool]['data']['depthperpass']
  3832. # else:
  3833. # old_zcut = deepcopy(self.z_cut)
  3834. #
  3835. # # ###############################################
  3836. # # ############ Create the data. #################
  3837. # # ###############################################
  3838. # altPoints = []
  3839. # for point in points[tool]:
  3840. # altPoints.append((point.coords.xy[0][0], point.coords.xy[1][0]))
  3841. # optimized_path = self.optimized_travelling_salesman(altPoints)
  3842. #
  3843. # # Only if tool has points.
  3844. # if tool in points:
  3845. # if self.app.abort_flag:
  3846. # # graceful abort requested by the user
  3847. # raise grace
  3848. #
  3849. # # Tool change sequence (optional)
  3850. # if self.toolchange:
  3851. # gcode += self.doformat(p.toolchange_code, toolchangexy=(self.oldx, self.oldy))
  3852. # gcode += self.doformat(p.spindle_code) # Spindle start)
  3853. # if self.dwell is True:
  3854. # gcode += self.doformat(p.dwell_code) # Dwell time
  3855. # else:
  3856. # gcode += self.doformat(p.spindle_code)
  3857. # if self.dwell is True:
  3858. # gcode += self.doformat(p.dwell_code) # Dwell time
  3859. #
  3860. # current_tooldia = float('%.*f' % (self.decimals, float(self.exc_tools[tool]["tooldia"])))
  3861. #
  3862. # self.app.inform.emit(
  3863. # '%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  3864. # str(current_tooldia),
  3865. # str(self.units))
  3866. # )
  3867. #
  3868. # # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  3869. # # APPLY Offset only when using the appGUI, for TclCommand this will create an error
  3870. # # because the values for Z offset are created in build_ui()
  3871. # # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  3872. # try:
  3873. # z_offset = float(self.exc_tools[tool]['data']['offset']) * (-1)
  3874. # except KeyError:
  3875. # z_offset = 0
  3876. # self.z_cut = z_offset + old_zcut
  3877. #
  3878. # self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  3879. # if self.coordinates_type == "G90":
  3880. # # Drillling! for Absolute coordinates type G90
  3881. # # variables to display the percentage of work done
  3882. # geo_len = len(optimized_path)
  3883. # old_disp_number = 0
  3884. # log.warning("Number of drills for which to generate GCode: %s" % str(geo_len))
  3885. #
  3886. # loc_nr = 0
  3887. # for point in optimized_path:
  3888. # if self.app.abort_flag:
  3889. # # graceful abort requested by the user
  3890. # raise grace
  3891. #
  3892. # locx = point[0]
  3893. # locy = point[1]
  3894. #
  3895. # travels = self.app.exc_areas.travel_coordinates(start_point=(self.oldx, self.oldy),
  3896. # end_point=(locx, locy),
  3897. # tooldia=current_tooldia)
  3898. # prev_z = None
  3899. # for travel in travels:
  3900. # locx = travel[1][0]
  3901. # locy = travel[1][1]
  3902. #
  3903. # if travel[0] is not None:
  3904. # # move to next point
  3905. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3906. #
  3907. # # raise to safe Z (travel[0]) each time because safe Z may be different
  3908. # self.z_move = travel[0]
  3909. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3910. #
  3911. # # restore z_move
  3912. # self.z_move = self.exc_tools[tool]['data']['travelz']
  3913. # else:
  3914. # if prev_z is not None:
  3915. # # move to next point
  3916. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3917. #
  3918. # # we assume that previously the z_move was altered therefore raise to
  3919. # # the travel_z (z_move)
  3920. # self.z_move = self.exc_tools[tool]['data']['travelz']
  3921. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3922. # else:
  3923. # # move to next point
  3924. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3925. #
  3926. # # store prev_z
  3927. # prev_z = travel[0]
  3928. #
  3929. # # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3930. #
  3931. # if self.multidepth and abs(self.z_cut) > abs(self.z_depthpercut):
  3932. # doc = deepcopy(self.z_cut)
  3933. # self.z_cut = 0.0
  3934. #
  3935. # while abs(self.z_cut) < abs(doc):
  3936. #
  3937. # self.z_cut -= self.z_depthpercut
  3938. # if abs(doc) < abs(self.z_cut) < (abs(doc) + self.z_depthpercut):
  3939. # self.z_cut = doc
  3940. # gcode += self.doformat(p.down_code, x=locx, y=locy)
  3941. #
  3942. # measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  3943. #
  3944. # if self.f_retract is False:
  3945. # gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  3946. # measured_up_to_zero_distance += abs(self.z_cut)
  3947. # measured_lift_distance += abs(self.z_move)
  3948. # else:
  3949. # measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  3950. #
  3951. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3952. #
  3953. # else:
  3954. # gcode += self.doformat(p.down_code, x=locx, y=locy)
  3955. #
  3956. # measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  3957. #
  3958. # if self.f_retract is False:
  3959. # gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  3960. # measured_up_to_zero_distance += abs(self.z_cut)
  3961. # measured_lift_distance += abs(self.z_move)
  3962. # else:
  3963. # measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  3964. #
  3965. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3966. #
  3967. # measured_distance += abs(distance_euclidian(locx, locy, self.oldx, self.oldy))
  3968. # self.oldx = locx
  3969. # self.oldy = locy
  3970. #
  3971. # loc_nr += 1
  3972. # disp_number = int(np.interp(loc_nr, [0, geo_len], [0, 100]))
  3973. #
  3974. # if old_disp_number < disp_number <= 100:
  3975. # self.app.proc_container.update_view_text(' %d%%' % disp_number)
  3976. # old_disp_number = disp_number
  3977. # else:
  3978. # self.app.inform.emit('[ERROR_NOTCL] %s...' % _('G91 coordinates not implemented'))
  3979. # return 'fail'
  3980. # else:
  3981. # log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> "
  3982. # "The loaded Excellon file has no drills ...")
  3983. # self.app.inform.emit('[ERROR_NOTCL] %s...' % _('The loaded Excellon file has no drills'))
  3984. # return 'fail'
  3985. # self.z_cut = deepcopy(old_zcut)
  3986. # log.debug("The total travel distance with Travelling Salesman Algorithm is: %s" % str(measured_distance))
  3987. #
  3988. # else:
  3989. # log.debug("camlib.CNCJob.generate_from_excellon_by_tool(): Chosen drill optimization doesn't exist.")
  3990. # return 'fail'
  3991. # Spindle stop
  3992. gcode += self.doformat(p.spindle_stop_code)
  3993. # Move to End position
  3994. gcode += self.doformat(p.end_code, x=0, y=0)
  3995. # #############################################################################################################
  3996. # ############################# Calculate DISTANCE and ESTIMATED TIME #########################################
  3997. # #############################################################################################################
  3998. measured_distance += abs(distance_euclidian(self.oldx, self.oldy, 0, 0))
  3999. log.debug("The total travel distance including travel to end position is: %s" %
  4000. str(measured_distance) + '\n')
  4001. self.travel_distance = measured_distance
  4002. # I use the value of self.feedrate_rapid for the feadrate in case of the measure_lift_distance and for
  4003. # traveled_time because it is not always possible to determine the feedrate that the CNC machine uses
  4004. # for G0 move (the fastest speed available to the CNC router). Although self.feedrate_rapids is used only with
  4005. # Marlin preprocessor and derivatives.
  4006. self.routing_time = (measured_down_distance + measured_up_to_zero_distance) / self.feedrate
  4007. lift_time = measured_lift_distance / self.feedrate_rapid
  4008. traveled_time = measured_distance / self.feedrate_rapid
  4009. self.routing_time += lift_time + traveled_time
  4010. # #############################################################################################################
  4011. # ############################# Store the GCODE for further usage ############################################
  4012. # #############################################################################################################
  4013. self.gcode = gcode
  4014. self.app.inform.emit(_("Finished G-Code generation..."))
  4015. return 'OK'
  4016. def generate_from_multitool_geometry(self, geometry, append=True, tooldia=None, offset=0.0, tolerance=0, z_cut=1.0,
  4017. z_move=2.0, feedrate=2.0, feedrate_z=2.0, feedrate_rapid=30,
  4018. spindlespeed=None, spindledir='CW', dwell=False, dwelltime=1.0,
  4019. multidepth=False, depthpercut=None, toolchange=False, toolchangez=1.0,
  4020. toolchangexy="0.0, 0.0", extracut=False, extracut_length=0.2,
  4021. startz=None, endz=2.0, endxy='', pp_geometry_name=None, tool_no=1):
  4022. """
  4023. Algorithm to generate from multitool Geometry.
  4024. Algorithm description:
  4025. ----------------------
  4026. Uses RTree to find the nearest path to follow.
  4027. :param geometry:
  4028. :param append:
  4029. :param tooldia:
  4030. :param offset:
  4031. :param tolerance:
  4032. :param z_cut:
  4033. :param z_move:
  4034. :param feedrate:
  4035. :param feedrate_z:
  4036. :param feedrate_rapid:
  4037. :param spindlespeed:
  4038. :param spindledir: Direction of rotation for the spindle. If using GRBL laser mode will
  4039. adjust the laser mode
  4040. :param dwell:
  4041. :param dwelltime:
  4042. :param multidepth: If True, use multiple passes to reach the desired depth.
  4043. :param depthpercut: Maximum depth in each pass.
  4044. :param toolchange:
  4045. :param toolchangez:
  4046. :param toolchangexy:
  4047. :param extracut: Adds (or not) an extra cut at the end of each path overlapping the
  4048. first point in path to ensure complete copper removal
  4049. :param extracut_length: Extra cut legth at the end of the path
  4050. :param startz:
  4051. :param endz:
  4052. :param endxy:
  4053. :param pp_geometry_name:
  4054. :param tool_no:
  4055. :return: GCode - string
  4056. """
  4057. log.debug("Generate_from_multitool_geometry()")
  4058. temp_solid_geometry = []
  4059. if offset != 0.0:
  4060. for it in geometry:
  4061. # if the geometry is a closed shape then create a Polygon out of it
  4062. if isinstance(it, LineString):
  4063. c = it.coords
  4064. if c[0] == c[-1]:
  4065. it = Polygon(it)
  4066. temp_solid_geometry.append(it.buffer(offset, join_style=2))
  4067. else:
  4068. temp_solid_geometry = geometry
  4069. # ## Flatten the geometry. Only linear elements (no polygons) remain.
  4070. flat_geometry = self.flatten(temp_solid_geometry, pathonly=True)
  4071. log.debug("%d paths" % len(flat_geometry))
  4072. try:
  4073. self.tooldia = float(tooldia)
  4074. except Exception as e:
  4075. self.app.inform.emit('[ERROR] %s\n%s' % (_("Failed."), str(e)))
  4076. return 'fail'
  4077. self.z_cut = float(z_cut) if z_cut else None
  4078. self.z_move = float(z_move) if z_move is not None else None
  4079. self.feedrate = float(feedrate) if feedrate else self.app.defaults["geometry_feedrate"]
  4080. self.z_feedrate = float(feedrate_z) if feedrate_z is not None else self.app.defaults["geometry_feedrate_z"]
  4081. self.feedrate_rapid = float(feedrate_rapid) if feedrate_rapid else self.app.defaults["geometry_feedrate_rapid"]
  4082. self.spindlespeed = int(spindlespeed) if spindlespeed != 0 else None
  4083. self.spindledir = spindledir
  4084. self.dwell = dwell
  4085. self.dwelltime = float(dwelltime) if dwelltime else self.app.defaults["geometry_dwelltime"]
  4086. self.startz = float(startz) if startz is not None else self.app.defaults["geometry_startz"]
  4087. self.z_end = float(endz) if endz is not None else self.app.defaults["geometry_endz"]
  4088. self.xy_end = re.sub('[()\[\]]', '', str(endxy)) if endxy else self.app.defaults["geometry_endxy"]
  4089. if self.xy_end and self.xy_end != '':
  4090. self.xy_end = [float(eval(a)) for a in self.xy_end.split(",")]
  4091. if self.xy_end and len(self.xy_end) < 2:
  4092. self.app.inform.emit('[ERROR] %s' % _("The End Move X,Y field in Edit -> Preferences has to be "
  4093. "in the format (x, y) but now there is only one value, not two."))
  4094. return 'fail'
  4095. self.z_depthpercut = float(depthpercut) if depthpercut else self.app.defaults["geometry_depthperpass"]
  4096. self.multidepth = multidepth
  4097. self.z_toolchange = float(toolchangez) if toolchangez is not None else self.app.defaults["geometry_toolchangez"]
  4098. # it servers in the preprocessor file
  4099. self.tool = tool_no
  4100. try:
  4101. if toolchangexy == '':
  4102. self.xy_toolchange = None
  4103. else:
  4104. self.xy_toolchange = re.sub('[()\[\]]', '', str(toolchangexy)) \
  4105. if toolchangexy else self.app.defaults["geometry_toolchangexy"]
  4106. if self.xy_toolchange and self.xy_toolchange != '':
  4107. self.xy_toolchange = [float(eval(a)) for a in self.xy_toolchange.split(",")]
  4108. if len(self.xy_toolchange) < 2:
  4109. self.app.inform.emit('[ERROR] %s' % _("The Toolchange X,Y field in Edit -> Preferences has to be "
  4110. "in the format (x, y) \n"
  4111. "but now there is only one value, not two."))
  4112. return 'fail'
  4113. except Exception as e:
  4114. log.debug("camlib.CNCJob.generate_from_multitool_geometry() --> %s" % str(e))
  4115. pass
  4116. self.pp_geometry_name = pp_geometry_name if pp_geometry_name else 'default'
  4117. self.f_plunge = self.app.defaults["geometry_f_plunge"]
  4118. if self.z_cut is None:
  4119. if 'laser' not in self.pp_geometry_name:
  4120. self.app.inform.emit(
  4121. '[ERROR_NOTCL] %s' % _("Cut_Z parameter is None or zero. Most likely a bad combinations of "
  4122. "other parameters."))
  4123. return 'fail'
  4124. else:
  4125. self.z_cut = 0
  4126. if self.machinist_setting == 0:
  4127. if self.z_cut > 0:
  4128. self.app.inform.emit('[WARNING] %s' %
  4129. _("The Cut Z parameter has positive value. "
  4130. "It is the depth value to cut into material.\n"
  4131. "The Cut Z parameter needs to have a negative value, assuming it is a typo "
  4132. "therefore the app will convert the value to negative."
  4133. "Check the resulting CNC code (Gcode etc)."))
  4134. self.z_cut = -self.z_cut
  4135. elif self.z_cut == 0 and 'laser' not in self.pp_geometry_name:
  4136. self.app.inform.emit('[WARNING] %s: %s' %
  4137. (_("The Cut Z parameter is zero. There will be no cut, skipping file"),
  4138. self.options['name']))
  4139. return 'fail'
  4140. if self.z_move is None:
  4141. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Travel Z parameter is None or zero."))
  4142. return 'fail'
  4143. if self.z_move < 0:
  4144. self.app.inform.emit('[WARNING] %s' %
  4145. _("The Travel Z parameter has negative value. "
  4146. "It is the height value to travel between cuts.\n"
  4147. "The Z Travel parameter needs to have a positive value, assuming it is a typo "
  4148. "therefore the app will convert the value to positive."
  4149. "Check the resulting CNC code (Gcode etc)."))
  4150. self.z_move = -self.z_move
  4151. elif self.z_move == 0:
  4152. self.app.inform.emit('[WARNING] %s: %s' %
  4153. (_("The Z Travel parameter is zero. This is dangerous, skipping file"),
  4154. self.options['name']))
  4155. return 'fail'
  4156. # made sure that depth_per_cut is no more then the z_cut
  4157. if abs(self.z_cut) < self.z_depthpercut:
  4158. self.z_depthpercut = abs(self.z_cut)
  4159. # ## Index first and last points in paths
  4160. # What points to index.
  4161. def get_pts(o):
  4162. return [o.coords[0], o.coords[-1]]
  4163. # Create the indexed storage.
  4164. storage = FlatCAMRTreeStorage()
  4165. storage.get_points = get_pts
  4166. # Store the geometry
  4167. log.debug("Indexing geometry before generating G-Code...")
  4168. self.app.inform.emit(_("Indexing geometry before generating G-Code..."))
  4169. for geo_shape in flat_geometry:
  4170. if self.app.abort_flag:
  4171. # graceful abort requested by the user
  4172. raise grace
  4173. if geo_shape is not None:
  4174. storage.insert(geo_shape)
  4175. # self.input_geometry_bounds = geometry.bounds()
  4176. if not append:
  4177. self.gcode = ""
  4178. # tell preprocessor the number of tool (for toolchange)
  4179. self.tool = tool_no
  4180. # this is the tool diameter, it is used as such to accommodate the preprocessor who need the tool diameter
  4181. # given under the name 'toolC'
  4182. self.postdata['toolC'] = self.tooldia
  4183. # Initial G-Code
  4184. self.pp_geometry = self.app.preprocessors[self.pp_geometry_name]
  4185. p = self.pp_geometry
  4186. self.gcode = self.doformat(p.start_code)
  4187. self.gcode += self.doformat(p.feedrate_code) # sets the feed rate
  4188. if toolchange is False:
  4189. self.gcode += self.doformat(p.lift_code, x=0, y=0) # Move (up) to travel height
  4190. self.gcode += self.doformat(p.startz_code, x=0, y=0)
  4191. if toolchange:
  4192. # if "line_xyz" in self.pp_geometry_name:
  4193. # self.gcode += self.doformat(p.toolchange_code, x=self.xy_toolchange[0], y=self.xy_toolchange[1])
  4194. # else:
  4195. # self.gcode += self.doformat(p.toolchange_code)
  4196. self.gcode += self.doformat(p.toolchange_code)
  4197. if 'laser' not in self.pp_geometry_name:
  4198. self.gcode += self.doformat(p.spindle_code) # Spindle start
  4199. else:
  4200. # for laser this will disable the laser
  4201. self.gcode += self.doformat(p.lift_code, x=self.oldx, y=self.oldy) # Move (up) to travel height
  4202. if self.dwell is True:
  4203. self.gcode += self.doformat(p.dwell_code) # Dwell time
  4204. else:
  4205. if 'laser' not in self.pp_geometry_name:
  4206. self.gcode += self.doformat(p.spindle_code) # Spindle start
  4207. if self.dwell is True:
  4208. self.gcode += self.doformat(p.dwell_code) # Dwell time
  4209. total_travel = 0.0
  4210. total_cut = 0.0
  4211. # ## Iterate over geometry paths getting the nearest each time.
  4212. log.debug("Starting G-Code...")
  4213. self.app.inform.emit('%s...' % _("Starting G-Code"))
  4214. path_count = 0
  4215. current_pt = (0, 0)
  4216. # variables to display the percentage of work done
  4217. geo_len = len(flat_geometry)
  4218. old_disp_number = 0
  4219. log.warning("Number of paths for which to generate GCode: %s" % str(geo_len))
  4220. current_tooldia = float('%.*f' % (self.decimals, float(self.tooldia)))
  4221. self.app.inform.emit('%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  4222. str(current_tooldia),
  4223. str(self.units)))
  4224. pt, geo = storage.nearest(current_pt)
  4225. try:
  4226. while True:
  4227. if self.app.abort_flag:
  4228. # graceful abort requested by the user
  4229. raise grace
  4230. path_count += 1
  4231. # Remove before modifying, otherwise deletion will fail.
  4232. storage.remove(geo)
  4233. # If last point in geometry is the nearest but prefer the first one if last point == first point
  4234. # then reverse coordinates.
  4235. if pt != geo.coords[0] and pt == geo.coords[-1]:
  4236. geo.coords = list(geo.coords)[::-1]
  4237. # ---------- Single depth/pass --------
  4238. if not multidepth:
  4239. # calculate the cut distance
  4240. total_cut = total_cut + geo.length
  4241. self.gcode += self.create_gcode_single_pass(geo, current_tooldia, extracut, extracut_length,
  4242. tolerance, z_move=z_move, old_point=current_pt)
  4243. # --------- Multi-pass ---------
  4244. else:
  4245. # calculate the cut distance
  4246. # due of the number of cuts (multi depth) it has to multiplied by the number of cuts
  4247. nr_cuts = 0
  4248. depth = abs(self.z_cut)
  4249. while depth > 0:
  4250. nr_cuts += 1
  4251. depth -= float(self.z_depthpercut)
  4252. total_cut += (geo.length * nr_cuts)
  4253. self.gcode += self.create_gcode_multi_pass(geo, current_tooldia, extracut, extracut_length,
  4254. tolerance, z_move=z_move, postproc=p,
  4255. old_point=current_pt)
  4256. # calculate the total distance
  4257. total_travel = total_travel + abs(distance(pt1=current_pt, pt2=pt))
  4258. current_pt = geo.coords[-1]
  4259. pt, geo = storage.nearest(current_pt) # Next
  4260. disp_number = int(np.interp(path_count, [0, geo_len], [0, 100]))
  4261. if old_disp_number < disp_number <= 100:
  4262. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  4263. old_disp_number = disp_number
  4264. except StopIteration: # Nothing found in storage.
  4265. pass
  4266. log.debug("Finished G-Code... %s paths traced." % path_count)
  4267. # add move to end position
  4268. total_travel += abs(distance_euclidian(current_pt[0], current_pt[1], 0, 0))
  4269. self.travel_distance += total_travel + total_cut
  4270. self.routing_time += total_cut / self.feedrate
  4271. # Finish
  4272. self.gcode += self.doformat(p.spindle_stop_code)
  4273. self.gcode += self.doformat(p.lift_code, x=current_pt[0], y=current_pt[1])
  4274. self.gcode += self.doformat(p.end_code, x=0, y=0)
  4275. self.app.inform.emit(
  4276. '%s... %s %s.' % (_("Finished G-Code generation"), str(path_count), _("paths traced"))
  4277. )
  4278. return self.gcode
  4279. def geometry_tool_gcode_gen(self, tool, tools, first_pt, tolerance, is_first=False, is_last=False,
  4280. toolchange=False):
  4281. """
  4282. Algorithm to generate GCode from multitool Geometry.
  4283. :param tool: tool number for which to generate GCode
  4284. :type tool: int
  4285. :param tools: a dictionary holding all the tools and data
  4286. :type tools: dict
  4287. :param first_pt: a tuple of coordinates for the first point of the current tool
  4288. :type first_pt: tuple
  4289. :param tolerance: geometry tolerance
  4290. :type tolerance:
  4291. :param is_first: if the current tool is the first tool (for this we need to add start GCode)
  4292. :type is_first: bool
  4293. :param is_last: if the current tool is the last tool (for this we need to add the end GCode)
  4294. :type is_last: bool
  4295. :param toolchange: add toolchange event
  4296. :type toolchange: bool
  4297. :return: GCode
  4298. :rtype: str
  4299. """
  4300. log.debug("Generate_from_multitool_geometry()")
  4301. t_gcode = ''
  4302. temp_solid_geometry = []
  4303. # The Geometry from which we create GCode
  4304. geometry = tools[tool]['solid_geometry']
  4305. # ## Flatten the geometry. Only linear elements (no polygons) remain.
  4306. flat_geometry = self.flatten(geometry, reset=True, pathonly=True)
  4307. log.debug("%d paths" % len(flat_geometry))
  4308. # #########################################################################################################
  4309. # #########################################################################################################
  4310. # ############# PARAMETERS used in PREPROCESSORS so they need to be updated ###############################
  4311. # #########################################################################################################
  4312. # #########################################################################################################
  4313. self.tool = str(tool)
  4314. tool_dict = tools[tool]['data']
  4315. # this is the tool diameter, it is used as such to accommodate the preprocessor who need the tool diameter
  4316. # given under the name 'toolC'
  4317. self.postdata['toolC'] = float(tools[tool]['tooldia'])
  4318. self.tooldia = float(tools[tool]['tooldia'])
  4319. self.use_ui = True
  4320. self.tolerance = tolerance
  4321. # Optimization type. Can be: 'M', 'B', 'T', 'R', 'No'
  4322. opt_type = tool_dict['optimization_type']
  4323. opt_time = tool_dict['search_time'] if 'search_time' in tool_dict else 'R'
  4324. if opt_type == 'M':
  4325. log.debug("Using OR-Tools Metaheuristic Guided Local Search path optimization.")
  4326. elif opt_type == 'B':
  4327. log.debug("Using OR-Tools Basic path optimization.")
  4328. elif opt_type == 'T':
  4329. log.debug("Using Travelling Salesman path optimization.")
  4330. elif opt_type == 'R':
  4331. log.debug("Using RTree path optimization.")
  4332. else:
  4333. log.debug("Using no path optimization.")
  4334. # Preprocessor
  4335. self.pp_geometry_name = tool_dict['ppname_g']
  4336. self.pp_geometry = self.app.preprocessors[self.pp_geometry_name]
  4337. p = self.pp_geometry
  4338. # Offset the Geometry if it is the case
  4339. # FIXME need to test if in ["Path", "In", "Out", "Custom"]. For now only 'Custom' is somehow done
  4340. offset = tools[tool]['offset_value']
  4341. if offset != 0.0:
  4342. for it in flat_geometry:
  4343. # if the geometry is a closed shape then create a Polygon out of it
  4344. if isinstance(it, LineString):
  4345. if it.is_ring:
  4346. it = Polygon(it)
  4347. temp_solid_geometry.append(it.buffer(offset, join_style=2))
  4348. temp_solid_geometry = self.flatten(temp_solid_geometry, reset=True, pathonly=True)
  4349. else:
  4350. temp_solid_geometry = flat_geometry
  4351. if self.z_cut is None:
  4352. if 'laser' not in self.pp_geometry_name:
  4353. self.app.inform.emit(
  4354. '[ERROR_NOTCL] %s' % _("Cut_Z parameter is None or zero. Most likely a bad combinations of "
  4355. "other parameters."))
  4356. return 'fail'
  4357. else:
  4358. self.z_cut = 0
  4359. if self.machinist_setting == 0:
  4360. if self.z_cut > 0:
  4361. self.app.inform.emit('[WARNING] %s' %
  4362. _("The Cut Z parameter has positive value. "
  4363. "It is the depth value to cut into material.\n"
  4364. "The Cut Z parameter needs to have a negative value, assuming it is a typo "
  4365. "therefore the app will convert the value to negative."
  4366. "Check the resulting CNC code (Gcode etc)."))
  4367. self.z_cut = -self.z_cut
  4368. elif self.z_cut == 0 and 'laser' not in self.pp_geometry_name:
  4369. self.app.inform.emit('[WARNING] %s: %s' %
  4370. (_("The Cut Z parameter is zero. There will be no cut, skipping file"),
  4371. self.options['name']))
  4372. return 'fail'
  4373. if self.z_move is None:
  4374. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Travel Z parameter is None or zero."))
  4375. return 'fail'
  4376. if self.z_move < 0:
  4377. self.app.inform.emit('[WARNING] %s' %
  4378. _("The Travel Z parameter has negative value. "
  4379. "It is the height value to travel between cuts.\n"
  4380. "The Z Travel parameter needs to have a positive value, assuming it is a typo "
  4381. "therefore the app will convert the value to positive."
  4382. "Check the resulting CNC code (Gcode etc)."))
  4383. self.z_move = -self.z_move
  4384. elif self.z_move == 0:
  4385. self.app.inform.emit('[WARNING] %s: %s' %
  4386. (_("The Z Travel parameter is zero. This is dangerous, skipping file"),
  4387. self.options['name']))
  4388. return 'fail'
  4389. # made sure that depth_per_cut is no more then the z_cut
  4390. if abs(self.z_cut) < self.z_depthpercut:
  4391. self.z_depthpercut = abs(self.z_cut)
  4392. # Depth parameters
  4393. self.z_cut = float(tool_dict['cutz'])
  4394. self.multidepth = tool_dict['multidepth']
  4395. self.z_depthpercut = float(tool_dict['depthperpass'])
  4396. self.z_move = float(tool_dict['travelz'])
  4397. self.f_plunge = self.app.defaults["geometry_f_plunge"]
  4398. self.feedrate = float(tool_dict['feedrate'])
  4399. self.z_feedrate = float(tool_dict['feedrate_z'])
  4400. self.feedrate_rapid = float(tool_dict['feedrate_rapid'])
  4401. self.spindlespeed = float(tool_dict['spindlespeed'])
  4402. self.spindledir = tool_dict['spindledir']
  4403. self.dwell = tool_dict['dwell']
  4404. self.dwelltime = float(tool_dict['dwelltime'])
  4405. self.startz = float(tool_dict['startz']) if tool_dict['startz'] else None
  4406. if self.startz == '':
  4407. self.startz = None
  4408. self.z_end = float(tool_dict['endz'])
  4409. try:
  4410. if self.xy_end == '':
  4411. self.xy_end = None
  4412. else:
  4413. # either originally it was a string or not, xy_end will be made string
  4414. self.xy_end = re.sub('[()\[\]]', '', str(self.xy_end)) if self.xy_end else None
  4415. # and now, xy_end is made into a list of floats in format [x, y]
  4416. if self.xy_end:
  4417. self.xy_end = [float(eval(a)) for a in self.xy_end.split(",")]
  4418. if self.xy_end and len(self.xy_end) != 2:
  4419. self.app.inform.emit('[ERROR]%s' % _("The End X,Y format has to be (x, y)."))
  4420. return 'fail'
  4421. except Exception as e:
  4422. log.debug("camlib.CNCJob.geometry_from_excellon_by_tool() xy_end --> %s" % str(e))
  4423. self.xy_end = [0, 0]
  4424. self.z_toolchange = tool_dict['toolchangez']
  4425. self.xy_toolchange = tool_dict["toolchangexy"]
  4426. try:
  4427. if self.xy_toolchange == '':
  4428. self.xy_toolchange = None
  4429. else:
  4430. # either originally it was a string or not, xy_toolchange will be made string
  4431. self.xy_toolchange = re.sub('[()\[\]]', '', str(self.xy_toolchange)) if self.xy_toolchange else None
  4432. # and now, xy_toolchange is made into a list of floats in format [x, y]
  4433. if self.xy_toolchange:
  4434. self.xy_toolchange = [float(eval(a)) for a in self.xy_toolchange.split(",")]
  4435. if self.xy_toolchange and len(self.xy_toolchange) != 2:
  4436. self.app.inform.emit('[ERROR] %s' % _("The Toolchange X,Y format has to be (x, y)."))
  4437. return 'fail'
  4438. except Exception as e:
  4439. log.debug("camlib.CNCJob.geometry_from_excellon_by_tool() --> %s" % str(e))
  4440. pass
  4441. self.extracut = tool_dict['extracut']
  4442. self.extracut_length = tool_dict['extracut_length']
  4443. # Probe parameters
  4444. # self.z_pdepth = tool_dict["tools_drill_z_pdepth"]
  4445. # self.feedrate_probe = tool_dict["tools_drill_feedrate_probe"]
  4446. # #########################################################################################################
  4447. # ############ Create the data. ###########################################################################
  4448. # #########################################################################################################
  4449. optimized_path = []
  4450. geo_storage = {}
  4451. for geo in temp_solid_geometry:
  4452. if not geo is None:
  4453. geo_storage[geo.coords[0]] = geo
  4454. locations = list(geo_storage.keys())
  4455. if opt_type == 'M':
  4456. # if there are no locations then go to the next tool
  4457. if not locations:
  4458. return 'fail'
  4459. optimized_locations = self.optimized_ortools_meta(locations=locations, opt_time=opt_time)
  4460. optimized_path = [(locations[loc], geo_storage[locations[loc]]) for loc in optimized_locations]
  4461. elif opt_type == 'B':
  4462. # if there are no locations then go to the next tool
  4463. if not locations:
  4464. return 'fail'
  4465. optimized_locations = self.optimized_ortools_basic(locations=locations)
  4466. optimized_path = [(locations[loc], geo_storage[locations[loc]]) for loc in optimized_locations]
  4467. elif opt_type == 'T':
  4468. # if there are no locations then go to the next tool
  4469. if not locations:
  4470. return 'fail'
  4471. optimized_locations = self.optimized_travelling_salesman(locations)
  4472. optimized_path = [(loc, geo_storage[loc]) for loc in optimized_locations]
  4473. elif opt_type == 'R':
  4474. optimized_path = self.geo_optimized_rtree(temp_solid_geometry)
  4475. if optimized_path == 'fail':
  4476. return 'fail'
  4477. else:
  4478. # it's actually not optimized path but here we build a list of (x,y) coordinates
  4479. # out of the tool's drills
  4480. for geo in temp_solid_geometry:
  4481. optimized_path.append(geo.coords[0])
  4482. # #########################################################################################################
  4483. # #########################################################################################################
  4484. # Only if there are locations to mill
  4485. if not optimized_path:
  4486. log.debug("camlib.CNCJob.geometry_tool_gcode_gen() -> Optimized path is empty.")
  4487. return 'fail'
  4488. if self.app.abort_flag:
  4489. # graceful abort requested by the user
  4490. raise grace
  4491. # #############################################################################################################
  4492. # #############################################################################################################
  4493. # ################# MILLING !!! ##############################################################################
  4494. # #############################################################################################################
  4495. # #############################################################################################################
  4496. log.debug("Starting G-Code...")
  4497. current_tooldia = float('%.*f' % (self.decimals, float(self.tooldia)))
  4498. self.app.inform.emit('%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  4499. str(current_tooldia),
  4500. str(self.units)))
  4501. # Measurements
  4502. total_travel = 0.0
  4503. total_cut = 0.0
  4504. # Start GCode
  4505. start_gcode = ''
  4506. if is_first:
  4507. start_gcode = self.doformat(p.start_code)
  4508. t_gcode += start_gcode
  4509. # Toolchange code
  4510. t_gcode += self.doformat(p.feedrate_code) # sets the feed rate
  4511. if toolchange:
  4512. t_gcode += self.doformat(p.toolchange_code)
  4513. if 'laser' not in self.pp_geometry_name.lower():
  4514. t_gcode += self.doformat(p.spindle_code) # Spindle start
  4515. else:
  4516. # for laser this will disable the laser
  4517. t_gcode += self.doformat(p.lift_code, x=self.oldx, y=self.oldy) # Move (up) to travel height
  4518. if self.dwell:
  4519. t_gcode += self.doformat(p.dwell_code) # Dwell time
  4520. else:
  4521. t_gcode += self.doformat(p.lift_code, x=0, y=0) # Move (up) to travel height
  4522. t_gcode += self.doformat(p.startz_code, x=0, y=0)
  4523. if 'laser' not in self.pp_geometry_name.lower():
  4524. t_gcode += self.doformat(p.spindle_code) # Spindle start
  4525. if self.dwell is True:
  4526. t_gcode += self.doformat(p.dwell_code) # Dwell time
  4527. t_gcode += self.doformat(p.feedrate_code) # sets the feed rate
  4528. # ## Iterate over geometry paths getting the nearest each time.
  4529. path_count = 0
  4530. # variables to display the percentage of work done
  4531. geo_len = len(flat_geometry)
  4532. log.warning("Number of paths for which to generate GCode: %s" % str(geo_len))
  4533. old_disp_number = 0
  4534. current_pt = (0, 0)
  4535. for pt, geo in optimized_path:
  4536. if self.app.abort_flag:
  4537. # graceful abort requested by the user
  4538. raise grace
  4539. path_count += 1
  4540. # If last point in geometry is the nearest but prefer the first one if last point == first point
  4541. # then reverse coordinates.
  4542. if pt != geo.coords[0] and pt == geo.coords[-1]:
  4543. geo.coords = list(geo.coords)[::-1]
  4544. # ---------- Single depth/pass --------
  4545. if not self.multidepth:
  4546. # calculate the cut distance
  4547. total_cut = total_cut + geo.length
  4548. t_gcode += self.create_gcode_single_pass(geo, current_tooldia, self.extracut,
  4549. self.extracut_length, self.tolerance,
  4550. z_move=self.z_move, old_point=current_pt)
  4551. # --------- Multi-pass ---------
  4552. else:
  4553. # calculate the cut distance
  4554. # due of the number of cuts (multi depth) it has to multiplied by the number of cuts
  4555. nr_cuts = 0
  4556. depth = abs(self.z_cut)
  4557. while depth > 0:
  4558. nr_cuts += 1
  4559. depth -= float(self.z_depthpercut)
  4560. total_cut += (geo.length * nr_cuts)
  4561. t_gcode += self.create_gcode_multi_pass(geo, current_tooldia, self.extracut,
  4562. self.extracut_length, self.tolerance,
  4563. z_move=self.z_move, postproc=p, old_point=current_pt)
  4564. # calculate the total distance
  4565. total_travel = total_travel + abs(distance(pt1=current_pt, pt2=pt))
  4566. current_pt = geo.coords[-1]
  4567. disp_number = int(np.interp(path_count, [0, geo_len], [0, 100]))
  4568. if old_disp_number < disp_number <= 100:
  4569. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  4570. old_disp_number = disp_number
  4571. log.debug("Finished G-Code... %s paths traced." % path_count)
  4572. # add move to end position
  4573. total_travel += abs(distance_euclidian(current_pt[0], current_pt[1], 0, 0))
  4574. self.travel_distance += total_travel + total_cut
  4575. self.routing_time += total_cut / self.feedrate
  4576. # Finish
  4577. if is_last:
  4578. t_gcode += self.doformat(p.spindle_stop_code)
  4579. t_gcode += self.doformat(p.lift_code, x=current_pt[0], y=current_pt[1])
  4580. t_gcode += self.doformat(p.end_code, x=0, y=0)
  4581. self.app.inform.emit(
  4582. '%s... %s %s.' % (_("Finished G-Code generation"), str(path_count), _("paths traced"))
  4583. )
  4584. self.gcode = t_gcode
  4585. return self.gcode, start_gcode
  4586. def generate_from_geometry_2(self, geometry, append=True, tooldia=None, offset=0.0, tolerance=0, z_cut=None,
  4587. z_move=None, feedrate=None, feedrate_z=None, feedrate_rapid=None, spindlespeed=None,
  4588. spindledir='CW', dwell=False, dwelltime=None, multidepth=False, depthpercut=None,
  4589. toolchange=False, toolchangez=None, toolchangexy="0.0, 0.0", extracut=False,
  4590. extracut_length=None, startz=None, endz=None, endxy='', pp_geometry_name=None,
  4591. tool_no=1):
  4592. """
  4593. Second algorithm to generate from Geometry.
  4594. Algorithm description:
  4595. ----------------------
  4596. Uses RTree to find the nearest path to follow.
  4597. :param geometry:
  4598. :param append:
  4599. :param tooldia:
  4600. :param offset:
  4601. :param tolerance:
  4602. :param z_cut:
  4603. :param z_move:
  4604. :param feedrate:
  4605. :param feedrate_z:
  4606. :param feedrate_rapid:
  4607. :param spindlespeed:
  4608. :param spindledir:
  4609. :param dwell:
  4610. :param dwelltime:
  4611. :param multidepth: If True, use multiple passes to reach the desired depth.
  4612. :param depthpercut: Maximum depth in each pass.
  4613. :param toolchange:
  4614. :param toolchangez:
  4615. :param toolchangexy:
  4616. :param extracut: Adds (or not) an extra cut at the end of each path overlapping the first point in
  4617. path to ensure complete copper removal
  4618. :param extracut_length: The extra cut length
  4619. :param startz:
  4620. :param endz:
  4621. :param endxy:
  4622. :param pp_geometry_name:
  4623. :param tool_no:
  4624. :return: None
  4625. """
  4626. log.debug("Executing camlib.CNCJob.generate_from_geometry_2()")
  4627. # if solid_geometry is empty raise an exception
  4628. if not geometry.solid_geometry:
  4629. self.app.inform.emit(
  4630. '[ERROR_NOTCL] %s' % _("Trying to generate a CNC Job from a Geometry object without solid_geometry.")
  4631. )
  4632. return 'fail'
  4633. def bounds_rec(obj):
  4634. if type(obj) is list:
  4635. minx = np.Inf
  4636. miny = np.Inf
  4637. maxx = -np.Inf
  4638. maxy = -np.Inf
  4639. for k in obj:
  4640. if type(k) is dict:
  4641. for key in k:
  4642. minx_, miny_, maxx_, maxy_ = bounds_rec(k[key])
  4643. minx = min(minx, minx_)
  4644. miny = min(miny, miny_)
  4645. maxx = max(maxx, maxx_)
  4646. maxy = max(maxy, maxy_)
  4647. else:
  4648. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  4649. minx = min(minx, minx_)
  4650. miny = min(miny, miny_)
  4651. maxx = max(maxx, maxx_)
  4652. maxy = max(maxy, maxy_)
  4653. return minx, miny, maxx, maxy
  4654. else:
  4655. # it's a Shapely object, return it's bounds
  4656. return obj.bounds
  4657. # Create the solid geometry which will be used to generate GCode
  4658. temp_solid_geometry = []
  4659. if offset != 0.0:
  4660. offset_for_use = offset
  4661. if offset < 0:
  4662. a, b, c, d = bounds_rec(geometry.solid_geometry)
  4663. # if the offset is less than half of the total length or less than half of the total width of the
  4664. # solid geometry it's obvious we can't do the offset
  4665. if -offset > ((c - a) / 2) or -offset > ((d - b) / 2):
  4666. self.app.inform.emit(
  4667. '[ERROR_NOTCL] %s' %
  4668. _("The Tool Offset value is too negative to use for the current_geometry.\n"
  4669. "Raise the value (in module) and try again.")
  4670. )
  4671. return 'fail'
  4672. # hack: make offset smaller by 0.0000000001 which is insignificant difference but allow the job
  4673. # to continue
  4674. elif -offset == ((c - a) / 2) or -offset == ((d - b) / 2):
  4675. offset_for_use = offset - 0.0000000001
  4676. for it in geometry.solid_geometry:
  4677. # if the geometry is a closed shape then create a Polygon out of it
  4678. if isinstance(it, LineString):
  4679. c = it.coords
  4680. if c[0] == c[-1]:
  4681. it = Polygon(it)
  4682. temp_solid_geometry.append(it.buffer(offset_for_use, join_style=2))
  4683. else:
  4684. temp_solid_geometry = geometry.solid_geometry
  4685. # ## Flatten the geometry. Only linear elements (no polygons) remain.
  4686. flat_geometry = self.flatten(temp_solid_geometry, pathonly=True)
  4687. log.debug("%d paths" % len(flat_geometry))
  4688. default_dia = None
  4689. if isinstance(self.app.defaults["geometry_cnctooldia"], float):
  4690. default_dia = self.app.defaults["geometry_cnctooldia"]
  4691. else:
  4692. try:
  4693. tools_string = self.app.defaults["geometry_cnctooldia"].split(",")
  4694. tools_diameters = [eval(a) for a in tools_string if a != '']
  4695. default_dia = tools_diameters[0] if tools_diameters else 0.0
  4696. except Exception as e:
  4697. self.app.log.debug("camlib.CNCJob.generate_from_geometry_2() --> %s" % str(e))
  4698. try:
  4699. self.tooldia = float(tooldia) if tooldia else default_dia
  4700. except ValueError:
  4701. self.tooldia = [float(el) for el in tooldia.split(',') if el != ''] if tooldia is not None else default_dia
  4702. if self.tooldia is None:
  4703. self.app.inform.emit('[ERROR] %s' % _("Failed."))
  4704. return 'fail'
  4705. self.z_cut = float(z_cut) if z_cut is not None else self.app.defaults["geometry_cutz"]
  4706. self.z_move = float(z_move) if z_move is not None else self.app.defaults["geometry_travelz"]
  4707. self.feedrate = float(feedrate) if feedrate is not None else self.app.defaults["geometry_feedrate"]
  4708. self.z_feedrate = float(feedrate_z) if feedrate_z is not None else self.app.defaults["geometry_feedrate_z"]
  4709. self.feedrate_rapid = float(feedrate_rapid) if feedrate_rapid is not None else \
  4710. self.app.defaults["geometry_feedrate_rapid"]
  4711. self.spindlespeed = int(spindlespeed) if spindlespeed != 0 and spindlespeed is not None else None
  4712. self.spindledir = spindledir
  4713. self.dwell = dwell
  4714. self.dwelltime = float(dwelltime) if dwelltime is not None else self.app.defaults["geometry_dwelltime"]
  4715. self.startz = float(startz) if startz is not None and startz != '' else self.app.defaults["geometry_startz"]
  4716. self.z_end = float(endz) if endz is not None else self.app.defaults["geometry_endz"]
  4717. self.xy_end = endxy if endxy != '' and endxy else self.app.defaults["geometry_endxy"]
  4718. self.xy_end = re.sub('[()\[\]]', '', str(self.xy_end)) if self.xy_end else None
  4719. if self.xy_end is not None and self.xy_end != '':
  4720. self.xy_end = [float(eval(a)) for a in self.xy_end.split(",")]
  4721. if self.xy_end and len(self.xy_end) < 2:
  4722. self.app.inform.emit('[ERROR] %s' % _("The End Move X,Y field in Edit -> Preferences has to be "
  4723. "in the format (x, y) but now there is only one value, not two."))
  4724. return 'fail'
  4725. self.z_depthpercut = float(depthpercut) if depthpercut is not None and depthpercut != 0 else abs(self.z_cut)
  4726. self.multidepth = multidepth
  4727. self.z_toolchange = float(toolchangez) if toolchangez is not None else self.app.defaults["geometry_toolchangez"]
  4728. self.extracut_length = float(extracut_length) if extracut_length is not None else \
  4729. self.app.defaults["geometry_extracut_length"]
  4730. try:
  4731. if toolchangexy == '':
  4732. self.xy_toolchange = None
  4733. else:
  4734. self.xy_toolchange = re.sub('[()\[\]]', '', str(toolchangexy)) if self.xy_toolchange else None
  4735. if self.xy_toolchange and self.xy_toolchange != '':
  4736. self.xy_toolchange = [float(eval(a)) for a in self.xy_toolchange.split(",")]
  4737. if len(self.xy_toolchange) < 2:
  4738. self.app.inform.emit('[ERROR] %s' % _("The Toolchange X,Y format has to be (x, y)."))
  4739. return 'fail'
  4740. except Exception as e:
  4741. log.debug("camlib.CNCJob.generate_from_geometry_2() --> %s" % str(e))
  4742. pass
  4743. self.pp_geometry_name = pp_geometry_name if pp_geometry_name else 'default'
  4744. self.f_plunge = self.app.defaults["geometry_f_plunge"]
  4745. if self.machinist_setting == 0:
  4746. if self.z_cut is None:
  4747. if 'laser' not in self.pp_geometry_name:
  4748. self.app.inform.emit(
  4749. '[ERROR_NOTCL] %s' % _("Cut_Z parameter is None or zero. Most likely a bad combinations of "
  4750. "other parameters.")
  4751. )
  4752. return 'fail'
  4753. else:
  4754. self.z_cut = 0.0
  4755. if self.z_cut > 0:
  4756. self.app.inform.emit('[WARNING] %s' %
  4757. _("The Cut Z parameter has positive value. "
  4758. "It is the depth value to cut into material.\n"
  4759. "The Cut Z parameter needs to have a negative value, assuming it is a typo "
  4760. "therefore the app will convert the value to negative."
  4761. "Check the resulting CNC code (Gcode etc)."))
  4762. self.z_cut = -self.z_cut
  4763. elif self.z_cut == 0 and 'laser' not in self.pp_geometry_name:
  4764. self.app.inform.emit(
  4765. '[WARNING] %s: %s' % (_("The Cut Z parameter is zero. There will be no cut, skipping file"),
  4766. geometry.options['name'])
  4767. )
  4768. return 'fail'
  4769. if self.z_move is None:
  4770. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Travel Z parameter is None or zero."))
  4771. return 'fail'
  4772. if self.z_move < 0:
  4773. self.app.inform.emit('[WARNING] %s' %
  4774. _("The Travel Z parameter has negative value. "
  4775. "It is the height value to travel between cuts.\n"
  4776. "The Z Travel parameter needs to have a positive value, assuming it is a typo "
  4777. "therefore the app will convert the value to positive."
  4778. "Check the resulting CNC code (Gcode etc)."))
  4779. self.z_move = -self.z_move
  4780. elif self.z_move == 0:
  4781. self.app.inform.emit(
  4782. '[WARNING] %s: %s' % (_("The Z Travel parameter is zero. This is dangerous, skipping file"),
  4783. self.options['name'])
  4784. )
  4785. return 'fail'
  4786. # made sure that depth_per_cut is no more then the z_cut
  4787. try:
  4788. if abs(self.z_cut) < self.z_depthpercut:
  4789. self.z_depthpercut = abs(self.z_cut)
  4790. except TypeError:
  4791. self.z_depthpercut = abs(self.z_cut)
  4792. # ## Index first and last points in paths
  4793. # What points to index.
  4794. def get_pts(o):
  4795. return [o.coords[0], o.coords[-1]]
  4796. # Create the indexed storage.
  4797. storage = FlatCAMRTreeStorage()
  4798. storage.get_points = get_pts
  4799. # Store the geometry
  4800. log.debug("Indexing geometry before generating G-Code...")
  4801. self.app.inform.emit(_("Indexing geometry before generating G-Code..."))
  4802. for geo_shape in flat_geometry:
  4803. if self.app.abort_flag:
  4804. # graceful abort requested by the user
  4805. raise grace
  4806. if geo_shape is not None:
  4807. storage.insert(geo_shape)
  4808. if not append:
  4809. self.gcode = ""
  4810. # tell preprocessor the number of tool (for toolchange)
  4811. self.tool = tool_no
  4812. # this is the tool diameter, it is used as such to accommodate the preprocessor who need the tool diameter
  4813. # given under the name 'toolC'
  4814. # this is a fancy way of adding a class attribute (which should be added in the __init__ method) without doing
  4815. # it there :)
  4816. self.postdata['toolC'] = self.tooldia
  4817. # Initial G-Code
  4818. self.pp_geometry = self.app.preprocessors[self.pp_geometry_name]
  4819. # the 'p' local attribute is a reference to the current preprocessor class
  4820. p = self.pp_geometry
  4821. self.oldx = 0.0
  4822. self.oldy = 0.0
  4823. self.gcode = self.doformat(p.start_code)
  4824. self.gcode += self.doformat(p.feedrate_code) # sets the feed rate
  4825. if toolchange is False:
  4826. # all the x and y parameters in self.doformat() are used only by some preprocessors not by all
  4827. self.gcode += self.doformat(p.lift_code, x=self.oldx, y=self.oldy) # Move (up) to travel height
  4828. self.gcode += self.doformat(p.startz_code, x=self.oldx, y=self.oldy)
  4829. if toolchange:
  4830. # if "line_xyz" in self.pp_geometry_name:
  4831. # self.gcode += self.doformat(p.toolchange_code, x=self.xy_toolchange[0], y=self.xy_toolchange[1])
  4832. # else:
  4833. # self.gcode += self.doformat(p.toolchange_code)
  4834. self.gcode += self.doformat(p.toolchange_code)
  4835. if 'laser' not in self.pp_geometry_name:
  4836. self.gcode += self.doformat(p.spindle_code) # Spindle start
  4837. else:
  4838. # for laser this will disable the laser
  4839. self.gcode += self.doformat(p.lift_code, x=self.oldx, y=self.oldy) # Move (up) to travel height
  4840. if self.dwell is True:
  4841. self.gcode += self.doformat(p.dwell_code) # Dwell time
  4842. else:
  4843. if 'laser' not in self.pp_geometry_name:
  4844. self.gcode += self.doformat(p.spindle_code) # Spindle start
  4845. if self.dwell is True:
  4846. self.gcode += self.doformat(p.dwell_code) # Dwell time
  4847. total_travel = 0.0
  4848. total_cut = 0.0
  4849. # Iterate over geometry paths getting the nearest each time.
  4850. log.debug("Starting G-Code...")
  4851. self.app.inform.emit('%s...' % _("Starting G-Code"))
  4852. # variables to display the percentage of work done
  4853. geo_len = len(flat_geometry)
  4854. old_disp_number = 0
  4855. log.warning("Number of paths for which to generate GCode: %s" % str(geo_len))
  4856. current_tooldia = float('%.*f' % (self.decimals, float(self.tooldia)))
  4857. self.app.inform.emit(
  4858. '%s: %s%s.' % (_("Starting G-Code for tool with diameter"), str(current_tooldia), str(self.units))
  4859. )
  4860. path_count = 0
  4861. current_pt = (0, 0)
  4862. pt, geo = storage.nearest(current_pt)
  4863. # when nothing is left in the storage a StopIteration exception will be raised therefore stopping
  4864. # the whole process including the infinite loop while True below.
  4865. try:
  4866. while True:
  4867. if self.app.abort_flag:
  4868. # graceful abort requested by the user
  4869. raise grace
  4870. path_count += 1
  4871. # Remove before modifying, otherwise deletion will fail.
  4872. storage.remove(geo)
  4873. # If last point in geometry is the nearest but prefer the first one if last point == first point
  4874. # then reverse coordinates.
  4875. if pt != geo.coords[0] and pt == geo.coords[-1]:
  4876. geo.coords = list(geo.coords)[::-1]
  4877. # ---------- Single depth/pass --------
  4878. if not multidepth:
  4879. # calculate the cut distance
  4880. total_cut += geo.length
  4881. self.gcode += self.create_gcode_single_pass(geo, current_tooldia, extracut, self.extracut_length,
  4882. tolerance, z_move=z_move, old_point=current_pt)
  4883. # --------- Multi-pass ---------
  4884. else:
  4885. # calculate the cut distance
  4886. # due of the number of cuts (multi depth) it has to multiplied by the number of cuts
  4887. nr_cuts = 0
  4888. depth = abs(self.z_cut)
  4889. while depth > 0:
  4890. nr_cuts += 1
  4891. depth -= float(self.z_depthpercut)
  4892. total_cut += (geo.length * nr_cuts)
  4893. self.gcode += self.create_gcode_multi_pass(geo, current_tooldia, extracut, self.extracut_length,
  4894. tolerance, z_move=z_move, postproc=p,
  4895. old_point=current_pt)
  4896. # calculate the travel distance
  4897. total_travel += abs(distance(pt1=current_pt, pt2=pt))
  4898. current_pt = geo.coords[-1]
  4899. pt, geo = storage.nearest(current_pt) # Next
  4900. # update the activity counter (lower left side of the app, status bar)
  4901. disp_number = int(np.interp(path_count, [0, geo_len], [0, 100]))
  4902. if old_disp_number < disp_number <= 100:
  4903. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  4904. old_disp_number = disp_number
  4905. except StopIteration: # Nothing found in storage.
  4906. pass
  4907. log.debug("Finishing G-Code... %s paths traced." % path_count)
  4908. # add move to end position
  4909. total_travel += abs(distance_euclidian(current_pt[0], current_pt[1], 0, 0))
  4910. self.travel_distance += total_travel + total_cut
  4911. self.routing_time += total_cut / self.feedrate
  4912. # Finish
  4913. self.gcode += self.doformat(p.spindle_stop_code)
  4914. self.gcode += self.doformat(p.lift_code, x=current_pt[0], y=current_pt[1])
  4915. self.gcode += self.doformat(p.end_code, x=0, y=0)
  4916. self.app.inform.emit(
  4917. '%s... %s %s' % (_("Finished G-Code generation"), str(path_count), _(" paths traced."))
  4918. )
  4919. return self.gcode
  4920. def generate_gcode_from_solderpaste_geo(self, **kwargs):
  4921. """
  4922. Algorithm to generate from multitool Geometry.
  4923. Algorithm description:
  4924. ----------------------
  4925. Uses RTree to find the nearest path to follow.
  4926. :return: Gcode string
  4927. """
  4928. log.debug("Generate_from_solderpaste_geometry()")
  4929. # ## Index first and last points in paths
  4930. # What points to index.
  4931. def get_pts(o):
  4932. return [o.coords[0], o.coords[-1]]
  4933. self.gcode = ""
  4934. if not kwargs:
  4935. log.debug("camlib.generate_from_solderpaste_geo() --> No tool in the solderpaste geometry.")
  4936. self.app.inform.emit('[ERROR_NOTCL] %s' %
  4937. _("There is no tool data in the SolderPaste geometry."))
  4938. # this is the tool diameter, it is used as such to accommodate the preprocessor who need the tool diameter
  4939. # given under the name 'toolC'
  4940. self.postdata['z_start'] = kwargs['data']['tools_solderpaste_z_start']
  4941. self.postdata['z_dispense'] = kwargs['data']['tools_solderpaste_z_dispense']
  4942. self.postdata['z_stop'] = kwargs['data']['tools_solderpaste_z_stop']
  4943. self.postdata['z_travel'] = kwargs['data']['tools_solderpaste_z_travel']
  4944. self.postdata['z_toolchange'] = kwargs['data']['tools_solderpaste_z_toolchange']
  4945. self.postdata['xy_toolchange'] = kwargs['data']['tools_solderpaste_xy_toolchange']
  4946. self.postdata['frxy'] = kwargs['data']['tools_solderpaste_frxy']
  4947. self.postdata['frz'] = kwargs['data']['tools_solderpaste_frz']
  4948. self.postdata['frz_dispense'] = kwargs['data']['tools_solderpaste_frz_dispense']
  4949. self.postdata['speedfwd'] = kwargs['data']['tools_solderpaste_speedfwd']
  4950. self.postdata['dwellfwd'] = kwargs['data']['tools_solderpaste_dwellfwd']
  4951. self.postdata['speedrev'] = kwargs['data']['tools_solderpaste_speedrev']
  4952. self.postdata['dwellrev'] = kwargs['data']['tools_solderpaste_dwellrev']
  4953. self.postdata['pp_solderpaste_name'] = kwargs['data']['tools_solderpaste_pp']
  4954. self.postdata['toolC'] = kwargs['tooldia']
  4955. self.pp_solderpaste_name = kwargs['data']['tools_solderpaste_pp'] if kwargs['data']['tools_solderpaste_pp'] \
  4956. else self.app.defaults['tools_solderpaste_pp']
  4957. p = self.app.preprocessors[self.pp_solderpaste_name]
  4958. # ## Flatten the geometry. Only linear elements (no polygons) remain.
  4959. flat_geometry = self.flatten(kwargs['solid_geometry'], pathonly=True)
  4960. log.debug("%d paths" % len(flat_geometry))
  4961. # Create the indexed storage.
  4962. storage = FlatCAMRTreeStorage()
  4963. storage.get_points = get_pts
  4964. # Store the geometry
  4965. log.debug("Indexing geometry before generating G-Code...")
  4966. for geo_shape in flat_geometry:
  4967. if self.app.abort_flag:
  4968. # graceful abort requested by the user
  4969. raise grace
  4970. if geo_shape is not None:
  4971. storage.insert(geo_shape)
  4972. # Initial G-Code
  4973. self.gcode = self.doformat(p.start_code)
  4974. self.gcode += self.doformat(p.spindle_off_code)
  4975. self.gcode += self.doformat(p.toolchange_code)
  4976. # ## Iterate over geometry paths getting the nearest each time.
  4977. log.debug("Starting SolderPaste G-Code...")
  4978. path_count = 0
  4979. current_pt = (0, 0)
  4980. # variables to display the percentage of work done
  4981. geo_len = len(flat_geometry)
  4982. old_disp_number = 0
  4983. pt, geo = storage.nearest(current_pt)
  4984. try:
  4985. while True:
  4986. if self.app.abort_flag:
  4987. # graceful abort requested by the user
  4988. raise grace
  4989. path_count += 1
  4990. # Remove before modifying, otherwise deletion will fail.
  4991. storage.remove(geo)
  4992. # If last point in geometry is the nearest but prefer the first one if last point == first point
  4993. # then reverse coordinates.
  4994. if pt != geo.coords[0] and pt == geo.coords[-1]:
  4995. geo.coords = list(geo.coords)[::-1]
  4996. self.gcode += self.create_soldepaste_gcode(geo, p=p, old_point=current_pt)
  4997. current_pt = geo.coords[-1]
  4998. pt, geo = storage.nearest(current_pt) # Next
  4999. disp_number = int(np.interp(path_count, [0, geo_len], [0, 100]))
  5000. if old_disp_number < disp_number <= 100:
  5001. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  5002. old_disp_number = disp_number
  5003. except StopIteration: # Nothing found in storage.
  5004. pass
  5005. log.debug("Finishing SolderPste G-Code... %s paths traced." % path_count)
  5006. self.app.inform.emit(
  5007. '%s... %s %s' % (_("Finished SolderPaste G-Code generation"), str(path_count), _("paths traced."))
  5008. )
  5009. # Finish
  5010. self.gcode += self.doformat(p.lift_code)
  5011. self.gcode += self.doformat(p.end_code)
  5012. return self.gcode
  5013. def create_soldepaste_gcode(self, geometry, p, old_point=(0, 0)):
  5014. gcode = ''
  5015. path = geometry.coords
  5016. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  5017. if self.coordinates_type == "G90":
  5018. # For Absolute coordinates type G90
  5019. first_x = path[0][0]
  5020. first_y = path[0][1]
  5021. else:
  5022. # For Incremental coordinates type G91
  5023. first_x = path[0][0] - old_point[0]
  5024. first_y = path[0][1] - old_point[1]
  5025. if type(geometry) == LineString or type(geometry) == LinearRing:
  5026. # Move fast to 1st point
  5027. gcode += self.doformat(p.rapid_code, x=first_x, y=first_y) # Move to first point
  5028. # Move down to cutting depth
  5029. gcode += self.doformat(p.z_feedrate_code)
  5030. gcode += self.doformat(p.down_z_start_code)
  5031. gcode += self.doformat(p.spindle_fwd_code) # Start dispensing
  5032. gcode += self.doformat(p.dwell_fwd_code)
  5033. gcode += self.doformat(p.feedrate_z_dispense_code)
  5034. gcode += self.doformat(p.lift_z_dispense_code)
  5035. gcode += self.doformat(p.feedrate_xy_code)
  5036. # Cutting...
  5037. prev_x = first_x
  5038. prev_y = first_y
  5039. for pt in path[1:]:
  5040. if self.coordinates_type == "G90":
  5041. # For Absolute coordinates type G90
  5042. next_x = pt[0]
  5043. next_y = pt[1]
  5044. else:
  5045. # For Incremental coordinates type G91
  5046. next_x = pt[0] - prev_x
  5047. next_y = pt[1] - prev_y
  5048. gcode += self.doformat(p.linear_code, x=next_x, y=next_y) # Linear motion to point
  5049. prev_x = next_x
  5050. prev_y = next_y
  5051. # Up to travelling height.
  5052. gcode += self.doformat(p.spindle_off_code) # Stop dispensing
  5053. gcode += self.doformat(p.spindle_rev_code)
  5054. gcode += self.doformat(p.down_z_stop_code)
  5055. gcode += self.doformat(p.spindle_off_code)
  5056. gcode += self.doformat(p.dwell_rev_code)
  5057. gcode += self.doformat(p.z_feedrate_code)
  5058. gcode += self.doformat(p.lift_code)
  5059. elif type(geometry) == Point:
  5060. gcode += self.doformat(p.linear_code, x=first_x, y=first_y) # Move to first point
  5061. gcode += self.doformat(p.feedrate_z_dispense_code)
  5062. gcode += self.doformat(p.down_z_start_code)
  5063. gcode += self.doformat(p.spindle_fwd_code) # Start dispensing
  5064. gcode += self.doformat(p.dwell_fwd_code)
  5065. gcode += self.doformat(p.lift_z_dispense_code)
  5066. gcode += self.doformat(p.spindle_off_code) # Stop dispensing
  5067. gcode += self.doformat(p.spindle_rev_code)
  5068. gcode += self.doformat(p.spindle_off_code)
  5069. gcode += self.doformat(p.down_z_stop_code)
  5070. gcode += self.doformat(p.dwell_rev_code)
  5071. gcode += self.doformat(p.z_feedrate_code)
  5072. gcode += self.doformat(p.lift_code)
  5073. return gcode
  5074. def create_gcode_single_pass(self, geometry, cdia, extracut, extracut_length, tolerance, z_move, old_point=(0, 0)):
  5075. """
  5076. # G-code. Note: self.linear2gcode() and self.point2gcode() will lower and raise the tool every time.
  5077. :param geometry: A Shapely Geometry (LineString or LinearRing) which is the path to be cut
  5078. :type geometry: LineString, LinearRing
  5079. :param cdia: Tool diameter
  5080. :type cdia: float
  5081. :param extracut: Will add an extra cut over the point where start of the cut is met with the end cut
  5082. :type extracut: bool
  5083. :param extracut_length: The length of the extra cut: half before the meeting point, half after
  5084. :type extracut_length: float
  5085. :param tolerance: Tolerance used to simplify the paths (making them mre rough)
  5086. :type tolerance: float
  5087. :param z_move: Travel Z
  5088. :type z_move: float
  5089. :param old_point: Previous point
  5090. :type old_point: tuple
  5091. :return: Gcode
  5092. :rtype: str
  5093. """
  5094. # p = postproc
  5095. if type(geometry) == LineString or type(geometry) == LinearRing:
  5096. if extracut is False or not geometry.is_ring:
  5097. gcode_single_pass = self.linear2gcode(geometry, cdia, z_move=z_move, tolerance=tolerance,
  5098. old_point=old_point)
  5099. else:
  5100. gcode_single_pass = self.linear2gcode_extra(geometry, cdia, extracut_length, tolerance=tolerance,
  5101. z_move=z_move, old_point=old_point)
  5102. elif type(geometry) == Point:
  5103. gcode_single_pass = self.point2gcode(geometry, cdia, z_move=z_move, old_point=old_point)
  5104. else:
  5105. log.warning("G-code generation not implemented for %s" % (str(type(geometry))))
  5106. return
  5107. return gcode_single_pass
  5108. def create_gcode_multi_pass(self, geometry, cdia, extracut, extracut_length, tolerance, postproc, z_move,
  5109. old_point=(0, 0)):
  5110. """
  5111. :param geometry: A Shapely Geometry (LineString or LinearRing) which is the path to be cut
  5112. :type geometry: LineString, LinearRing
  5113. :param cdia: Tool diameter
  5114. :type cdia: float
  5115. :param extracut: Will add an extra cut over the point where start of the cut is met with the end cut
  5116. :type extracut: bool
  5117. :param extracut_length: The length of the extra cut: half before the meeting point, half after
  5118. :type extracut_length: float
  5119. :param tolerance: Tolerance used to simplify the paths (making them mre rough)
  5120. :type tolerance: float
  5121. :param postproc: Preprocessor class
  5122. :type postproc: class
  5123. :param z_move: Travel Z
  5124. :type z_move: float
  5125. :param old_point: Previous point
  5126. :type old_point: tuple
  5127. :return: Gcode
  5128. :rtype: str
  5129. """
  5130. p = postproc
  5131. gcode_multi_pass = ''
  5132. if isinstance(self.z_cut, Decimal):
  5133. z_cut = self.z_cut
  5134. else:
  5135. z_cut = Decimal(self.z_cut).quantize(Decimal('0.000000001'))
  5136. if self.z_depthpercut is None:
  5137. self.z_depthpercut = z_cut
  5138. elif not isinstance(self.z_depthpercut, Decimal):
  5139. self.z_depthpercut = Decimal(self.z_depthpercut).quantize(Decimal('0.000000001'))
  5140. depth = 0
  5141. reverse = False
  5142. while depth > z_cut:
  5143. # Increase depth. Limit to z_cut.
  5144. depth -= self.z_depthpercut
  5145. if depth < z_cut:
  5146. depth = z_cut
  5147. # Cut at specific depth and do not lift the tool.
  5148. # Note: linear2gcode() will use G00 to move to the first point in the path, but it should be already
  5149. # at the first point if the tool is down (in the material). So, an extra G00 should show up but
  5150. # is inconsequential.
  5151. if type(geometry) == LineString or type(geometry) == LinearRing:
  5152. if extracut is False or not geometry.is_ring:
  5153. gcode_multi_pass += self.linear2gcode(geometry, cdia, tolerance=tolerance, z_cut=depth, up=False,
  5154. z_move=z_move, old_point=old_point)
  5155. else:
  5156. gcode_multi_pass += self.linear2gcode_extra(geometry, cdia, extracut_length, tolerance=tolerance,
  5157. z_move=z_move, z_cut=depth, up=False,
  5158. old_point=old_point)
  5159. # Ignore multi-pass for points.
  5160. elif type(geometry) == Point:
  5161. gcode_multi_pass += self.point2gcode(geometry, cdia, z_move=z_move, old_point=old_point)
  5162. break # Ignoring ...
  5163. else:
  5164. log.warning("G-code generation not implemented for %s" % (str(type(geometry))))
  5165. # Reverse coordinates if not a loop so we can continue cutting without returning to the beginning.
  5166. if type(geometry) == LineString:
  5167. geometry.coords = list(geometry.coords)[::-1]
  5168. reverse = True
  5169. # If geometry is reversed, revert.
  5170. if reverse:
  5171. if type(geometry) == LineString:
  5172. geometry.coords = list(geometry.coords)[::-1]
  5173. # Lift the tool
  5174. gcode_multi_pass += self.doformat(p.lift_code, x=old_point[0], y=old_point[1])
  5175. return gcode_multi_pass
  5176. def codes_split(self, gline):
  5177. """
  5178. Parses a line of G-Code such as "G01 X1234 Y987" into
  5179. a dictionary: {'G': 1.0, 'X': 1234.0, 'Y': 987.0}
  5180. :param gline: G-Code line string
  5181. :type gline: str
  5182. :return: Dictionary with parsed line.
  5183. :rtype: dict
  5184. """
  5185. command = {}
  5186. if 'Roland' in self.pp_excellon_name or 'Roland' in self.pp_geometry_name:
  5187. match_z = re.search(r"^Z(\s*-?\d+\.\d+?),(\s*\s*-?\d+\.\d+?),(\s*\s*-?\d+\.\d+?)*;$", gline)
  5188. if match_z:
  5189. command['G'] = 0
  5190. command['X'] = float(match_z.group(1).replace(" ", "")) * 0.025
  5191. command['Y'] = float(match_z.group(2).replace(" ", "")) * 0.025
  5192. command['Z'] = float(match_z.group(3).replace(" ", "")) * 0.025
  5193. elif 'hpgl' in self.pp_excellon_name or 'hpgl' in self.pp_geometry_name:
  5194. match_pa = re.search(r"^PA(\s*-?\d+\.\d+?),(\s*\s*-?\d+\.\d+?)*;$", gline)
  5195. if match_pa:
  5196. command['G'] = 0
  5197. command['X'] = float(match_pa.group(1).replace(" ", "")) / 40
  5198. command['Y'] = float(match_pa.group(2).replace(" ", "")) / 40
  5199. match_pen = re.search(r"^(P[U|D])", gline)
  5200. if match_pen:
  5201. if match_pen.group(1) == 'PU':
  5202. # the value does not matter, only that it is positive so the gcode_parse() know it is > 0,
  5203. # therefore the move is of kind T (travel)
  5204. command['Z'] = 1
  5205. else:
  5206. command['Z'] = 0
  5207. elif 'laser' in self.pp_excellon_name.lower() or 'laser' in self.pp_geometry_name.lower() or \
  5208. (self.pp_solderpaste_name is not None and 'paste' in self.pp_solderpaste_name.lower()):
  5209. match_lsr = re.search(r"X([\+-]?\d+.[\+-]?\d+)\s*Y([\+-]?\d+.[\+-]?\d+)", gline)
  5210. if match_lsr:
  5211. command['X'] = float(match_lsr.group(1).replace(" ", ""))
  5212. command['Y'] = float(match_lsr.group(2).replace(" ", ""))
  5213. match_lsr_pos = re.search(r"^(M0?[3-5])", gline)
  5214. if match_lsr_pos:
  5215. if 'M05' in match_lsr_pos.group(1) or 'M5' in match_lsr_pos.group(1):
  5216. # the value does not matter, only that it is positive so the gcode_parse() know it is > 0,
  5217. # therefore the move is of kind T (travel)
  5218. command['Z'] = 1
  5219. else:
  5220. command['Z'] = 0
  5221. match_lsr_pos_2 = re.search(r"^(M10[6|7])", gline)
  5222. if match_lsr_pos_2:
  5223. if 'M107' in match_lsr_pos_2.group(1):
  5224. command['Z'] = 1
  5225. else:
  5226. command['Z'] = 0
  5227. elif self.pp_solderpaste_name is not None:
  5228. if 'Paste' in self.pp_solderpaste_name:
  5229. match_paste = re.search(r"X([\+-]?\d+.[\+-]?\d+)\s*Y([\+-]?\d+.[\+-]?\d+)", gline)
  5230. if match_paste:
  5231. command['X'] = float(match_paste.group(1).replace(" ", ""))
  5232. command['Y'] = float(match_paste.group(2).replace(" ", ""))
  5233. else:
  5234. match = re.search(r'^\s*([A-Z])\s*([\+\-\.\d\s]+)', gline)
  5235. while match:
  5236. command[match.group(1)] = float(match.group(2).replace(" ", ""))
  5237. gline = gline[match.end():]
  5238. match = re.search(r'^\s*([A-Z])\s*([\+\-\.\d\s]+)', gline)
  5239. return command
  5240. def gcode_parse(self, force_parsing=None):
  5241. """
  5242. G-Code parser (from self.gcode). Generates dictionary with
  5243. single-segment LineString's and "kind" indicating cut or travel,
  5244. fast or feedrate speed.
  5245. Will return a list of dict in the format:
  5246. {
  5247. "geom": LineString(path),
  5248. "kind": kind
  5249. }
  5250. where kind can be either ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  5251. :param force_parsing:
  5252. :type force_parsing:
  5253. :return:
  5254. :rtype: dict
  5255. """
  5256. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  5257. # Results go here
  5258. geometry = []
  5259. # Last known instruction
  5260. current = {'X': 0.0, 'Y': 0.0, 'Z': 0.0, 'G': 0}
  5261. # Current path: temporary storage until tool is
  5262. # lifted or lowered.
  5263. if self.toolchange_xy_type == "excellon":
  5264. if self.app.defaults["excellon_toolchangexy"] == '' or self.app.defaults["excellon_toolchangexy"] is None:
  5265. pos_xy = (0, 0)
  5266. else:
  5267. pos_xy = self.app.defaults["excellon_toolchangexy"]
  5268. try:
  5269. pos_xy = [float(eval(a)) for a in pos_xy.split(",")]
  5270. except Exception:
  5271. if len(pos_xy) != 2:
  5272. pos_xy = (0, 0)
  5273. else:
  5274. if self.app.defaults["geometry_toolchangexy"] == '' or self.app.defaults["geometry_toolchangexy"] is None:
  5275. pos_xy = (0, 0)
  5276. else:
  5277. pos_xy = self.app.defaults["geometry_toolchangexy"]
  5278. try:
  5279. pos_xy = [float(eval(a)) for a in pos_xy.split(",")]
  5280. except Exception:
  5281. if len(pos_xy) != 2:
  5282. pos_xy = (0, 0)
  5283. path = [pos_xy]
  5284. # path = [(0, 0)]
  5285. gcode_lines_list = self.gcode.splitlines()
  5286. self.app.inform.emit('%s: %d' % (_("Parsing GCode file. Number of lines"), len(gcode_lines_list)))
  5287. # Process every instruction
  5288. for line in gcode_lines_list:
  5289. if force_parsing is False or force_parsing is None:
  5290. if '%MO' in line or '%' in line or 'MOIN' in line or 'MOMM' in line:
  5291. return "fail"
  5292. gobj = self.codes_split(line)
  5293. # ## Units
  5294. if 'G' in gobj and (gobj['G'] == 20.0 or gobj['G'] == 21.0):
  5295. self.units = {20.0: "IN", 21.0: "MM"}[gobj['G']]
  5296. continue
  5297. # TODO take into consideration the tools and update the travel line thickness
  5298. if 'T' in gobj:
  5299. pass
  5300. # ## Changing height
  5301. if 'Z' in gobj:
  5302. if 'Roland' in self.pp_excellon_name or 'Roland' in self.pp_geometry_name:
  5303. pass
  5304. elif 'hpgl' in self.pp_excellon_name or 'hpgl' in self.pp_geometry_name:
  5305. pass
  5306. elif 'laser' in self.pp_excellon_name or 'laser' in self.pp_geometry_name:
  5307. pass
  5308. elif ('X' in gobj or 'Y' in gobj) and gobj['Z'] != current['Z']:
  5309. if self.pp_geometry_name == 'line_xyz' or self.pp_excellon_name == 'line_xyz':
  5310. pass
  5311. else:
  5312. log.warning("Non-orthogonal motion: From %s" % str(current))
  5313. log.warning(" To: %s" % str(gobj))
  5314. current['Z'] = gobj['Z']
  5315. # Store the path into geometry and reset path
  5316. if len(path) > 1:
  5317. geometry.append({"geom": LineString(path),
  5318. "kind": kind})
  5319. path = [path[-1]] # Start with the last point of last path.
  5320. # create the geometry for the holes created when drilling Excellon drills
  5321. if self.origin_kind == 'excellon':
  5322. if current['Z'] < 0:
  5323. current_drill_point_coords = (
  5324. float('%.*f' % (self.decimals, current['X'])),
  5325. float('%.*f' % (self.decimals, current['Y']))
  5326. )
  5327. # find the drill diameter knowing the drill coordinates
  5328. break_loop = False
  5329. for tool, tool_dict in self.exc_tools.items():
  5330. if 'drills' in tool_dict:
  5331. for drill_pt in tool_dict['drills']:
  5332. point_in_dict_coords = (
  5333. float('%.*f' % (self.decimals, drill_pt.x)),
  5334. float('%.*f' % (self.decimals, drill_pt.y))
  5335. )
  5336. if point_in_dict_coords == current_drill_point_coords:
  5337. dia = self.exc_tools[tool]['tooldia']
  5338. kind = ['C', 'F']
  5339. geometry.append(
  5340. {
  5341. "geom": Point(current_drill_point_coords).buffer(dia / 2.0).exterior,
  5342. "kind": kind
  5343. }
  5344. )
  5345. break_loop = True
  5346. break
  5347. if break_loop:
  5348. break
  5349. if 'G' in gobj:
  5350. current['G'] = int(gobj['G'])
  5351. if 'X' in gobj or 'Y' in gobj:
  5352. if 'X' in gobj:
  5353. x = gobj['X']
  5354. # current['X'] = x
  5355. else:
  5356. x = current['X']
  5357. if 'Y' in gobj:
  5358. y = gobj['Y']
  5359. else:
  5360. y = current['Y']
  5361. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  5362. if current['Z'] > 0:
  5363. kind[0] = 'T'
  5364. if current['G'] > 0:
  5365. kind[1] = 'S'
  5366. if current['G'] in [0, 1]: # line
  5367. path.append((x, y))
  5368. arcdir = [None, None, "cw", "ccw"]
  5369. if current['G'] in [2, 3]: # arc
  5370. center = [gobj['I'] + current['X'], gobj['J'] + current['Y']]
  5371. radius = np.sqrt(gobj['I'] ** 2 + gobj['J'] ** 2)
  5372. start = np.arctan2(-gobj['J'], -gobj['I'])
  5373. stop = np.arctan2(-center[1] + y, -center[0] + x)
  5374. path += arc(center, radius, start, stop, arcdir[current['G']], int(self.steps_per_circle))
  5375. current['X'] = x
  5376. current['Y'] = y
  5377. # Update current instruction
  5378. for code in gobj:
  5379. current[code] = gobj[code]
  5380. self.app.inform.emit('%s...' % _("Creating Geometry from the parsed GCode file. "))
  5381. # There might not be a change in height at the
  5382. # end, therefore, see here too if there is
  5383. # a final path.
  5384. if len(path) > 1:
  5385. geometry.append(
  5386. {
  5387. "geom": LineString(path),
  5388. "kind": kind
  5389. }
  5390. )
  5391. self.gcode_parsed = geometry
  5392. return geometry
  5393. def excellon_tool_gcode_parse(self, dia, gcode, start_pt=(0, 0), force_parsing=None):
  5394. """
  5395. G-Code parser (from self.exc_cnc_tools['tooldia']['gcode']). Generates dictionary with
  5396. single-segment LineString's and "kind" indicating cut or travel,
  5397. fast or feedrate speed.
  5398. Will return the Geometry as a list of dict in the format:
  5399. {
  5400. "geom": LineString(path),
  5401. "kind": kind
  5402. }
  5403. where kind can be either ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  5404. :param dia: the dia is a tool diameter which is the key in self.exc_cnc_tools dict
  5405. :type dia: float
  5406. :param gcode: Gcode to parse
  5407. :type gcode: str
  5408. :param start_pt: the point coordinates from where to start the parsing
  5409. :type start_pt: tuple
  5410. :param force_parsing:
  5411. :type force_parsing: bool
  5412. :return: Geometry as a list of dictionaries
  5413. :rtype: list
  5414. """
  5415. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  5416. # Results go here
  5417. geometry = []
  5418. # Last known instruction
  5419. current = {'X': 0.0, 'Y': 0.0, 'Z': 0.0, 'G': 0}
  5420. # Current path: temporary storage until tool is
  5421. # lifted or lowered.
  5422. pos_xy = start_pt
  5423. path = [pos_xy]
  5424. # path = [(0, 0)]
  5425. gcode_lines_list = gcode.splitlines()
  5426. self.app.inform.emit(
  5427. '%s: %s. %s: %d' % (_("Parsing GCode file for tool diameter"),
  5428. str(dia), _("Number of lines"),
  5429. len(gcode_lines_list))
  5430. )
  5431. # Process every instruction
  5432. for line in gcode_lines_list:
  5433. if force_parsing is False or force_parsing is None:
  5434. if '%MO' in line or '%' in line or 'MOIN' in line or 'MOMM' in line:
  5435. return "fail"
  5436. gobj = self.codes_split(line)
  5437. # ## Units
  5438. if 'G' in gobj and (gobj['G'] == 20.0 or gobj['G'] == 21.0):
  5439. self.units = {20.0: "IN", 21.0: "MM"}[gobj['G']]
  5440. continue
  5441. # TODO take into consideration the tools and update the travel line thickness
  5442. if 'T' in gobj:
  5443. pass
  5444. # ## Changing height
  5445. if 'Z' in gobj:
  5446. if 'Roland' in self.pp_excellon_name or 'Roland' in self.pp_geometry_name:
  5447. pass
  5448. elif 'hpgl' in self.pp_excellon_name or 'hpgl' in self.pp_geometry_name:
  5449. pass
  5450. elif 'laser' in self.pp_excellon_name or 'laser' in self.pp_geometry_name:
  5451. pass
  5452. elif ('X' in gobj or 'Y' in gobj) and gobj['Z'] != current['Z']:
  5453. if self.pp_geometry_name == 'line_xyz' or self.pp_excellon_name == 'line_xyz':
  5454. pass
  5455. else:
  5456. log.warning("Non-orthogonal motion: From %s" % str(current))
  5457. log.warning(" To: %s" % str(gobj))
  5458. current['Z'] = gobj['Z']
  5459. # Store the path into geometry and reset path
  5460. if len(path) > 1:
  5461. geometry.append({"geom": LineString(path),
  5462. "kind": kind})
  5463. path = [path[-1]] # Start with the last point of last path.
  5464. # create the geometry for the holes created when drilling Excellon drills
  5465. if current['Z'] < 0:
  5466. current_drill_point_coords = (
  5467. float('%.*f' % (self.decimals, current['X'])),
  5468. float('%.*f' % (self.decimals, current['Y']))
  5469. )
  5470. kind = ['C', 'F']
  5471. geometry.append(
  5472. {
  5473. "geom": Point(current_drill_point_coords).buffer(dia/2.0).exterior,
  5474. "kind": kind
  5475. }
  5476. )
  5477. if 'G' in gobj:
  5478. current['G'] = int(gobj['G'])
  5479. if 'X' in gobj or 'Y' in gobj:
  5480. x = gobj['X'] if 'X' in gobj else current['X']
  5481. y = gobj['Y'] if 'Y' in gobj else current['Y']
  5482. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  5483. if current['Z'] > 0:
  5484. kind[0] = 'T'
  5485. if current['G'] > 0:
  5486. kind[1] = 'S'
  5487. if current['G'] in [0, 1]: # line
  5488. path.append((x, y))
  5489. arcdir = [None, None, "cw", "ccw"]
  5490. if current['G'] in [2, 3]: # arc
  5491. center = [gobj['I'] + current['X'], gobj['J'] + current['Y']]
  5492. radius = np.sqrt(gobj['I'] ** 2 + gobj['J'] ** 2)
  5493. start = np.arctan2(-gobj['J'], -gobj['I'])
  5494. stop = np.arctan2(-center[1] + y, -center[0] + x)
  5495. path += arc(center, radius, start, stop, arcdir[current['G']], int(self.steps_per_circle))
  5496. current['X'] = x
  5497. current['Y'] = y
  5498. # Update current instruction
  5499. for code in gobj:
  5500. current[code] = gobj[code]
  5501. self.app.inform.emit('%s: %s' % (_("Creating Geometry from the parsed GCode file for tool diameter"), str(dia)))
  5502. # There might not be a change in height at the end, therefore, see here too if there is a final path.
  5503. if len(path) > 1:
  5504. geometry.append(
  5505. {
  5506. "geom": LineString(path),
  5507. "kind": kind
  5508. }
  5509. )
  5510. return geometry
  5511. # def plot(self, tooldia=None, dpi=75, margin=0.1,
  5512. # color={"T": ["#F0E24D", "#B5AB3A"], "C": ["#5E6CFF", "#4650BD"]},
  5513. # alpha={"T": 0.3, "C": 1.0}):
  5514. # """
  5515. # Creates a Matplotlib figure with a plot of the
  5516. # G-code job.
  5517. # """
  5518. # if tooldia is None:
  5519. # tooldia = self.tooldia
  5520. #
  5521. # fig = Figure(dpi=dpi)
  5522. # ax = fig.add_subplot(111)
  5523. # ax.set_aspect(1)
  5524. # xmin, ymin, xmax, ymax = self.input_geometry_bounds
  5525. # ax.set_xlim(xmin-margin, xmax+margin)
  5526. # ax.set_ylim(ymin-margin, ymax+margin)
  5527. #
  5528. # if tooldia == 0:
  5529. # for geo in self.gcode_parsed:
  5530. # linespec = '--'
  5531. # linecolor = color[geo['kind'][0]][1]
  5532. # if geo['kind'][0] == 'C':
  5533. # linespec = 'k-'
  5534. # x, y = geo['geom'].coords.xy
  5535. # ax.plot(x, y, linespec, color=linecolor)
  5536. # else:
  5537. # for geo in self.gcode_parsed:
  5538. # poly = geo['geom'].buffer(tooldia/2.0)
  5539. # patch = PolygonPatch(poly, facecolor=color[geo['kind'][0]][0],
  5540. # edgecolor=color[geo['kind'][0]][1],
  5541. # alpha=alpha[geo['kind'][0]], zorder=2)
  5542. # ax.add_patch(patch)
  5543. #
  5544. # return fig
  5545. def plot2(self, tooldia=None, dpi=75, margin=0.1, gcode_parsed=None,
  5546. color=None, alpha={"T": 0.3, "C": 1.0}, tool_tolerance=0.0005, obj=None, visible=False, kind='all'):
  5547. """
  5548. Plots the G-code job onto the given axes.
  5549. :param tooldia: Tool diameter.
  5550. :type tooldia: float
  5551. :param dpi: Not used!
  5552. :type dpi: float
  5553. :param margin: Not used!
  5554. :type margin: float
  5555. :param gcode_parsed: Parsed Gcode
  5556. :type gcode_parsed: str
  5557. :param color: Color specification.
  5558. :type color: str
  5559. :param alpha: Transparency specification.
  5560. :type alpha: dict
  5561. :param tool_tolerance: Tolerance when drawing the toolshape.
  5562. :type tool_tolerance: float
  5563. :param obj: The object for whih to plot
  5564. :type obj: class
  5565. :param visible: Visibility status
  5566. :type visible: bool
  5567. :param kind: Can be: "travel", "cut", "all"
  5568. :type kind: str
  5569. :return: None
  5570. :rtype:
  5571. """
  5572. # units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5573. if color is None:
  5574. color = {
  5575. "T": [self.app.defaults["cncjob_travel_fill"], self.app.defaults["cncjob_travel_line"]],
  5576. "C": [self.app.defaults["cncjob_plot_fill"], self.app.defaults["cncjob_plot_line"]]
  5577. }
  5578. gcode_parsed = gcode_parsed if gcode_parsed else self.gcode_parsed
  5579. if tooldia is None:
  5580. tooldia = self.tooldia
  5581. # this should be unlikely unless when upstream the tooldia is a tuple made by one dia and a comma like (2.4,)
  5582. if isinstance(tooldia, list):
  5583. tooldia = tooldia[0] if tooldia[0] is not None else self.tooldia
  5584. if tooldia == 0:
  5585. for geo in gcode_parsed:
  5586. if kind == 'all':
  5587. obj.add_shape(shape=geo['geom'], color=color[geo['kind'][0]][1], visible=visible)
  5588. elif kind == 'travel':
  5589. if geo['kind'][0] == 'T':
  5590. obj.add_shape(shape=geo['geom'], color=color['T'][1], visible=visible)
  5591. elif kind == 'cut':
  5592. if geo['kind'][0] == 'C':
  5593. obj.add_shape(shape=geo['geom'], color=color['C'][1], visible=visible)
  5594. else:
  5595. path_num = 0
  5596. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  5597. if self.coordinates_type == "G90":
  5598. # For Absolute coordinates type G90
  5599. for geo in gcode_parsed:
  5600. if geo['kind'][0] == 'T':
  5601. start_position = geo['geom'].coords[0]
  5602. if tooldia not in obj.annotations_dict:
  5603. obj.annotations_dict[tooldia] = {
  5604. 'pos': [],
  5605. 'text': []
  5606. }
  5607. if start_position not in obj.annotations_dict[tooldia]['pos']:
  5608. path_num += 1
  5609. obj.annotations_dict[tooldia]['pos'].append(start_position)
  5610. obj.annotations_dict[tooldia]['text'].append(str(path_num))
  5611. end_position = geo['geom'].coords[-1]
  5612. if tooldia not in obj.annotations_dict:
  5613. obj.annotations_dict[tooldia] = {
  5614. 'pos': [],
  5615. 'text': []
  5616. }
  5617. if end_position not in obj.annotations_dict[tooldia]['pos']:
  5618. path_num += 1
  5619. obj.annotations_dict[tooldia]['pos'].append(end_position)
  5620. obj.annotations_dict[tooldia]['text'].append(str(path_num))
  5621. # plot the geometry of Excellon objects
  5622. if self.origin_kind == 'excellon':
  5623. try:
  5624. # if the geos are travel lines
  5625. if geo['kind'][0] == 'T':
  5626. poly = geo['geom'].buffer(distance=(tooldia / 1.99999999),
  5627. resolution=self.steps_per_circle)
  5628. else:
  5629. poly = Polygon(geo['geom'])
  5630. poly = poly.simplify(tool_tolerance)
  5631. except Exception:
  5632. # deal here with unexpected plot errors due of LineStrings not valid
  5633. continue
  5634. else:
  5635. # plot the geometry of any objects other than Excellon
  5636. poly = geo['geom'].buffer(distance=(tooldia / 1.99999999), resolution=self.steps_per_circle)
  5637. poly = poly.simplify(tool_tolerance)
  5638. if kind == 'all':
  5639. obj.add_shape(shape=poly, color=color[geo['kind'][0]][1], face_color=color[geo['kind'][0]][0],
  5640. visible=visible, layer=1 if geo['kind'][0] == 'C' else 2)
  5641. elif kind == 'travel':
  5642. if geo['kind'][0] == 'T':
  5643. obj.add_shape(shape=poly, color=color['T'][1], face_color=color['T'][0],
  5644. visible=visible, layer=2)
  5645. elif kind == 'cut':
  5646. if geo['kind'][0] == 'C':
  5647. obj.add_shape(shape=poly, color=color['C'][1], face_color=color['C'][0],
  5648. visible=visible, layer=1)
  5649. else:
  5650. self.app.inform.emit('[ERROR_NOTCL] %s...' % _('G91 coordinates not implemented'))
  5651. return 'fail'
  5652. def plot_annotations(self, obj, visible=True):
  5653. """
  5654. Plot annotations.
  5655. :param obj: FlatCAM CNCJob object for which to plot the annotations
  5656. :type obj:
  5657. :param visible: annotaions visibility
  5658. :type visible: bool
  5659. :return: Nothing
  5660. :rtype:
  5661. """
  5662. if not obj.annotations_dict:
  5663. return
  5664. if visible is True:
  5665. obj.text_col.enabled = True
  5666. else:
  5667. obj.text_col.enabled = False
  5668. return
  5669. text = []
  5670. pos = []
  5671. for tooldia in obj.annotations_dict:
  5672. pos += obj.annotations_dict[tooldia]['pos']
  5673. text += obj.annotations_dict[tooldia]['text']
  5674. if not text or not pos:
  5675. return
  5676. try:
  5677. if self.app.defaults['global_theme'] == 'white':
  5678. obj.annotation.set(text=text, pos=pos, visible=obj.options['plot'],
  5679. font_size=self.app.defaults["cncjob_annotation_fontsize"],
  5680. color=self.app.defaults["cncjob_annotation_fontcolor"])
  5681. else:
  5682. # invert the color
  5683. old_color = self.app.defaults["cncjob_annotation_fontcolor"].lower()
  5684. new_color = ''
  5685. code = {}
  5686. l1 = "#;0123456789abcdef"
  5687. l2 = "#;fedcba9876543210"
  5688. for i in range(len(l1)):
  5689. code[l1[i]] = l2[i]
  5690. for x in range(len(old_color)):
  5691. new_color += code[old_color[x]]
  5692. obj.annotation.set(text=text, pos=pos, visible=obj.options['plot'],
  5693. font_size=self.app.defaults["cncjob_annotation_fontsize"],
  5694. color=new_color)
  5695. except Exception as e:
  5696. log.debug("CNCJob.plot2() --> annotations --> %s" % str(e))
  5697. if self.app.is_legacy is False:
  5698. obj.annotation.clear(update=True)
  5699. obj.annotation.redraw()
  5700. def create_geometry(self):
  5701. """
  5702. It is used by the Excellon objects. Will create the solid_geometry which will be an attribute of the
  5703. Excellon object class.
  5704. :return: List of Shapely geometry elements
  5705. :rtype: list
  5706. """
  5707. # TODO: This takes forever. Too much data?
  5708. # self.app.inform.emit('%s: %s' % (_("Unifying Geometry from parsed Geometry segments"),
  5709. # str(len(self.gcode_parsed))))
  5710. # self.solid_geometry = cascaded_union([geo['geom'] for geo in self.gcode_parsed])
  5711. # This is much faster but not so nice to look at as you can see different segments of the geometry
  5712. self.solid_geometry = [geo['geom'] for geo in self.gcode_parsed]
  5713. return self.solid_geometry
  5714. def segment(self, coords):
  5715. """
  5716. Break long linear lines to make it more auto level friendly.
  5717. Code snippet added by Lei Zheng in a rejected pull request on FlatCAM https://bitbucket.org/realthunder/
  5718. :param coords: List of coordinates tuples
  5719. :type coords: list
  5720. :return: A path; list with the multiple coordinates breaking a line.
  5721. :rtype: list
  5722. """
  5723. if len(coords) < 2 or self.segx <= 0 and self.segy <= 0:
  5724. return list(coords)
  5725. path = [coords[0]]
  5726. # break the line in either x or y dimension only
  5727. def linebreak_single(line, dim, dmax):
  5728. if dmax <= 0:
  5729. return None
  5730. if line[1][dim] > line[0][dim]:
  5731. sign = 1.0
  5732. d = line[1][dim] - line[0][dim]
  5733. else:
  5734. sign = -1.0
  5735. d = line[0][dim] - line[1][dim]
  5736. if d > dmax:
  5737. # make sure we don't make any new lines too short
  5738. if d > dmax * 2:
  5739. dd = dmax
  5740. else:
  5741. dd = d / 2
  5742. other = dim ^ 1
  5743. return (line[0][dim] + dd * sign, line[0][other] + \
  5744. dd * (line[1][other] - line[0][other]) / d)
  5745. return None
  5746. # recursively breaks down a given line until it is within the
  5747. # required step size
  5748. def linebreak(line):
  5749. pt_new = linebreak_single(line, 0, self.segx)
  5750. if pt_new is None:
  5751. pt_new2 = linebreak_single(line, 1, self.segy)
  5752. else:
  5753. pt_new2 = linebreak_single((line[0], pt_new), 1, self.segy)
  5754. if pt_new2 is not None:
  5755. pt_new = pt_new2[::-1]
  5756. if pt_new is None:
  5757. path.append(line[1])
  5758. else:
  5759. path.append(pt_new)
  5760. linebreak((pt_new, line[1]))
  5761. for pt in coords[1:]:
  5762. linebreak((path[-1], pt))
  5763. return path
  5764. def linear2gcode(self, linear, dia, tolerance=0, down=True, up=True, z_cut=None, z_move=None, zdownrate=None,
  5765. feedrate=None, feedrate_z=None, feedrate_rapid=None, cont=False, old_point=(0, 0)):
  5766. """
  5767. Generates G-code to cut along the linear feature.
  5768. :param linear: The path to cut along.
  5769. :type: Shapely.LinearRing or Shapely.Linear String
  5770. :param dia: The tool diameter that is going on the path
  5771. :type dia: float
  5772. :param tolerance: All points in the simplified object will be within the
  5773. tolerance distance of the original geometry.
  5774. :type tolerance: float
  5775. :param down:
  5776. :param up:
  5777. :param z_cut:
  5778. :param z_move:
  5779. :param zdownrate:
  5780. :param feedrate: speed for cut on X - Y plane
  5781. :param feedrate_z: speed for cut on Z plane
  5782. :param feedrate_rapid: speed to move between cuts; usually is G0 but some CNC require to specify it
  5783. :param cont:
  5784. :param old_point:
  5785. :return: G-code to cut along the linear feature.
  5786. """
  5787. if z_cut is None:
  5788. z_cut = self.z_cut
  5789. if z_move is None:
  5790. z_move = self.z_move
  5791. #
  5792. # if zdownrate is None:
  5793. # zdownrate = self.zdownrate
  5794. if feedrate is None:
  5795. feedrate = self.feedrate
  5796. if feedrate_z is None:
  5797. feedrate_z = self.z_feedrate
  5798. if feedrate_rapid is None:
  5799. feedrate_rapid = self.feedrate_rapid
  5800. # Simplify paths?
  5801. if tolerance > 0:
  5802. target_linear = linear.simplify(tolerance)
  5803. else:
  5804. target_linear = linear
  5805. gcode = ""
  5806. # path = list(target_linear.coords)
  5807. path = self.segment(target_linear.coords)
  5808. p = self.pp_geometry
  5809. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  5810. if self.coordinates_type == "G90":
  5811. # For Absolute coordinates type G90
  5812. first_x = path[0][0]
  5813. first_y = path[0][1]
  5814. else:
  5815. # For Incremental coordinates type G91
  5816. first_x = path[0][0] - old_point[0]
  5817. first_y = path[0][1] - old_point[1]
  5818. # Move fast to 1st point
  5819. if not cont:
  5820. current_tooldia = dia
  5821. travels = self.app.exc_areas.travel_coordinates(start_point=(old_point[0], old_point[1]),
  5822. end_point=(first_x, first_y),
  5823. tooldia=current_tooldia)
  5824. prev_z = None
  5825. for travel in travels:
  5826. locx = travel[1][0]
  5827. locy = travel[1][1]
  5828. if travel[0] is not None:
  5829. # move to next point
  5830. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  5831. # raise to safe Z (travel[0]) each time because safe Z may be different
  5832. self.z_move = travel[0]
  5833. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  5834. # restore z_move
  5835. self.z_move = z_move
  5836. else:
  5837. if prev_z is not None:
  5838. # move to next point
  5839. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  5840. # we assume that previously the z_move was altered therefore raise to
  5841. # the travel_z (z_move)
  5842. self.z_move = z_move
  5843. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  5844. else:
  5845. # move to next point
  5846. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  5847. # store prev_z
  5848. prev_z = travel[0]
  5849. # gcode += self.doformat(p.rapid_code, x=first_x, y=first_y) # Move to first point
  5850. # Move down to cutting depth
  5851. if down:
  5852. # Different feedrate for vertical cut?
  5853. gcode += self.doformat(p.z_feedrate_code)
  5854. # gcode += self.doformat(p.feedrate_code)
  5855. gcode += self.doformat(p.down_code, x=first_x, y=first_y, z_cut=z_cut)
  5856. gcode += self.doformat(p.feedrate_code, feedrate=feedrate)
  5857. # Cutting...
  5858. prev_x = first_x
  5859. prev_y = first_y
  5860. for pt in path[1:]:
  5861. if self.app.abort_flag:
  5862. # graceful abort requested by the user
  5863. raise grace
  5864. if self.coordinates_type == "G90":
  5865. # For Absolute coordinates type G90
  5866. next_x = pt[0]
  5867. next_y = pt[1]
  5868. else:
  5869. # For Incremental coordinates type G91
  5870. # next_x = pt[0] - prev_x
  5871. # next_y = pt[1] - prev_y
  5872. self.app.inform.emit('[ERROR_NOTCL] %s' % _('G91 coordinates not implemented ...'))
  5873. next_x = pt[0]
  5874. next_y = pt[1]
  5875. gcode += self.doformat(p.linear_code, x=next_x, y=next_y, z=z_cut) # Linear motion to point
  5876. prev_x = pt[0]
  5877. prev_y = pt[1]
  5878. # Up to travelling height.
  5879. if up:
  5880. gcode += self.doformat(p.lift_code, x=prev_x, y=prev_y, z_move=z_move) # Stop cutting
  5881. return gcode
  5882. def linear2gcode_extra(self, linear, dia, extracut_length, tolerance=0, down=True, up=True,
  5883. z_cut=None, z_move=None, zdownrate=None,
  5884. feedrate=None, feedrate_z=None, feedrate_rapid=None, cont=False, old_point=(0, 0)):
  5885. """
  5886. Generates G-code to cut along the linear feature.
  5887. :param linear: The path to cut along.
  5888. :type: Shapely.LinearRing or Shapely.Linear String
  5889. :param dia: The tool diameter that is going on the path
  5890. :type dia: float
  5891. :param extracut_length: how much to cut extra over the first point at the end of the path
  5892. :param tolerance: All points in the simplified object will be within the
  5893. tolerance distance of the original geometry.
  5894. :type tolerance: float
  5895. :param down:
  5896. :param up:
  5897. :param z_cut:
  5898. :param z_move:
  5899. :param zdownrate:
  5900. :param feedrate: speed for cut on X - Y plane
  5901. :param feedrate_z: speed for cut on Z plane
  5902. :param feedrate_rapid: speed to move between cuts; usually is G0 but some CNC require to specify it
  5903. :param cont:
  5904. :param old_point:
  5905. :return: G-code to cut along the linear feature.
  5906. :rtype: str
  5907. """
  5908. if z_cut is None:
  5909. z_cut = self.z_cut
  5910. if z_move is None:
  5911. z_move = self.z_move
  5912. #
  5913. # if zdownrate is None:
  5914. # zdownrate = self.zdownrate
  5915. if feedrate is None:
  5916. feedrate = self.feedrate
  5917. if feedrate_z is None:
  5918. feedrate_z = self.z_feedrate
  5919. if feedrate_rapid is None:
  5920. feedrate_rapid = self.feedrate_rapid
  5921. # Simplify paths?
  5922. if tolerance > 0:
  5923. target_linear = linear.simplify(tolerance)
  5924. else:
  5925. target_linear = linear
  5926. gcode = ""
  5927. path = list(target_linear.coords)
  5928. p = self.pp_geometry
  5929. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  5930. if self.coordinates_type == "G90":
  5931. # For Absolute coordinates type G90
  5932. first_x = path[0][0]
  5933. first_y = path[0][1]
  5934. else:
  5935. # For Incremental coordinates type G91
  5936. first_x = path[0][0] - old_point[0]
  5937. first_y = path[0][1] - old_point[1]
  5938. # Move fast to 1st point
  5939. if not cont:
  5940. current_tooldia = dia
  5941. travels = self.app.exc_areas.travel_coordinates(start_point=(old_point[0], old_point[1]),
  5942. end_point=(first_x, first_y),
  5943. tooldia=current_tooldia)
  5944. prev_z = None
  5945. for travel in travels:
  5946. locx = travel[1][0]
  5947. locy = travel[1][1]
  5948. if travel[0] is not None:
  5949. # move to next point
  5950. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  5951. # raise to safe Z (travel[0]) each time because safe Z may be different
  5952. self.z_move = travel[0]
  5953. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  5954. # restore z_move
  5955. self.z_move = z_move
  5956. else:
  5957. if prev_z is not None:
  5958. # move to next point
  5959. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  5960. # we assume that previously the z_move was altered therefore raise to
  5961. # the travel_z (z_move)
  5962. self.z_move = z_move
  5963. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  5964. else:
  5965. # move to next point
  5966. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  5967. # store prev_z
  5968. prev_z = travel[0]
  5969. # gcode += self.doformat(p.rapid_code, x=first_x, y=first_y) # Move to first point
  5970. # Move down to cutting depth
  5971. if down:
  5972. # Different feedrate for vertical cut?
  5973. if self.z_feedrate is not None:
  5974. gcode += self.doformat(p.z_feedrate_code)
  5975. # gcode += self.doformat(p.feedrate_code)
  5976. gcode += self.doformat(p.down_code, x=first_x, y=first_y, z_cut=z_cut)
  5977. gcode += self.doformat(p.feedrate_code, feedrate=feedrate)
  5978. else:
  5979. gcode += self.doformat(p.down_code, x=first_x, y=first_y, z_cut=z_cut) # Start cutting
  5980. # Cutting...
  5981. prev_x = first_x
  5982. prev_y = first_y
  5983. for pt in path[1:]:
  5984. if self.app.abort_flag:
  5985. # graceful abort requested by the user
  5986. raise grace
  5987. if self.coordinates_type == "G90":
  5988. # For Absolute coordinates type G90
  5989. next_x = pt[0]
  5990. next_y = pt[1]
  5991. else:
  5992. # For Incremental coordinates type G91
  5993. # For Incremental coordinates type G91
  5994. # next_x = pt[0] - prev_x
  5995. # next_y = pt[1] - prev_y
  5996. self.app.inform.emit('[ERROR_NOTCL] %s' % _('G91 coordinates not implemented ...'))
  5997. next_x = pt[0]
  5998. next_y = pt[1]
  5999. gcode += self.doformat(p.linear_code, x=next_x, y=next_y, z=z_cut) # Linear motion to point
  6000. prev_x = next_x
  6001. prev_y = next_y
  6002. # this line is added to create an extra cut over the first point in patch
  6003. # to make sure that we remove the copper leftovers
  6004. # Linear motion to the 1st point in the cut path
  6005. # if self.coordinates_type == "G90":
  6006. # # For Absolute coordinates type G90
  6007. # last_x = path[1][0]
  6008. # last_y = path[1][1]
  6009. # else:
  6010. # # For Incremental coordinates type G91
  6011. # last_x = path[1][0] - first_x
  6012. # last_y = path[1][1] - first_y
  6013. # gcode += self.doformat(p.linear_code, x=last_x, y=last_y)
  6014. # the first point for extracut is always mandatory if the extracut is enabled. But if the length of distance
  6015. # between point 0 and point 1 is more than the distance we set for the extra cut then make an interpolation
  6016. # along the path and find the point at the distance extracut_length
  6017. if extracut_length == 0.0:
  6018. extra_path = [path[-1], path[0], path[1]]
  6019. new_x = extra_path[0][0]
  6020. new_y = extra_path[0][1]
  6021. # this is an extra line therefore lift the milling bit
  6022. gcode += self.doformat(p.lift_code, x=prev_x, y=prev_y, z_move=z_move) # lift
  6023. # move fast to the new first point
  6024. gcode += self.doformat(p.rapid_code, x=new_x, y=new_y)
  6025. # lower the milling bit
  6026. # Different feedrate for vertical cut?
  6027. if self.z_feedrate is not None:
  6028. gcode += self.doformat(p.z_feedrate_code)
  6029. gcode += self.doformat(p.down_code, x=new_x, y=new_y, z_cut=z_cut)
  6030. gcode += self.doformat(p.feedrate_code, feedrate=feedrate)
  6031. else:
  6032. gcode += self.doformat(p.down_code, x=new_x, y=new_y, z_cut=z_cut) # Start cutting
  6033. # start cutting the extra line
  6034. last_pt = extra_path[0]
  6035. for pt in extra_path[1:]:
  6036. gcode += self.doformat(p.linear_code, x=pt[0], y=pt[1])
  6037. last_pt = pt
  6038. # go back to the original point
  6039. gcode += self.doformat(p.linear_code, x=path[0][0], y=path[0][1])
  6040. last_pt = path[0]
  6041. else:
  6042. # go to the point that is 5% in length before the end (therefore 95% length from start of the line),
  6043. # along the line to be cut
  6044. if extracut_length >= target_linear.length:
  6045. extracut_length = target_linear.length
  6046. # ---------------------------------------------
  6047. # first half
  6048. # ---------------------------------------------
  6049. start_length = target_linear.length - (extracut_length * 0.5)
  6050. extra_line = substring(target_linear, start_length, target_linear.length)
  6051. extra_path = list(extra_line.coords)
  6052. new_x = extra_path[0][0]
  6053. new_y = extra_path[0][1]
  6054. # this is an extra line therefore lift the milling bit
  6055. gcode += self.doformat(p.lift_code, x=prev_x, y=prev_y, z_move=z_move) # lift
  6056. # move fast to the new first point
  6057. gcode += self.doformat(p.rapid_code, x=new_x, y=new_y)
  6058. # lower the milling bit
  6059. # Different feedrate for vertical cut?
  6060. if self.z_feedrate is not None:
  6061. gcode += self.doformat(p.z_feedrate_code)
  6062. gcode += self.doformat(p.down_code, x=new_x, y=new_y, z_cut=z_cut)
  6063. gcode += self.doformat(p.feedrate_code, feedrate=feedrate)
  6064. else:
  6065. gcode += self.doformat(p.down_code, x=new_x, y=new_y, z_cut=z_cut) # Start cutting
  6066. # start cutting the extra line
  6067. for pt in extra_path[1:]:
  6068. gcode += self.doformat(p.linear_code, x=pt[0], y=pt[1])
  6069. # ---------------------------------------------
  6070. # second half
  6071. # ---------------------------------------------
  6072. extra_line = substring(target_linear, 0, (extracut_length * 0.5))
  6073. extra_path = list(extra_line.coords)
  6074. # start cutting the extra line
  6075. last_pt = extra_path[0]
  6076. for pt in extra_path[1:]:
  6077. gcode += self.doformat(p.linear_code, x=pt[0], y=pt[1])
  6078. last_pt = pt
  6079. # ---------------------------------------------
  6080. # back to original start point, cutting
  6081. # ---------------------------------------------
  6082. extra_line = substring(target_linear, 0, (extracut_length * 0.5))
  6083. extra_path = list(extra_line.coords)[::-1]
  6084. # start cutting the extra line
  6085. last_pt = extra_path[0]
  6086. for pt in extra_path[1:]:
  6087. gcode += self.doformat(p.linear_code, x=pt[0], y=pt[1])
  6088. last_pt = pt
  6089. # if extracut_length == 0.0:
  6090. # gcode += self.doformat(p.linear_code, x=path[1][0], y=path[1][1])
  6091. # last_pt = path[1]
  6092. # else:
  6093. # if abs(distance(path[1], path[0])) > extracut_length:
  6094. # i_point = LineString([path[0], path[1]]).interpolate(extracut_length)
  6095. # gcode += self.doformat(p.linear_code, x=i_point.x, y=i_point.y)
  6096. # last_pt = (i_point.x, i_point.y)
  6097. # else:
  6098. # last_pt = path[0]
  6099. # for pt in path[1:]:
  6100. # extracut_distance = abs(distance(pt, last_pt))
  6101. # if extracut_distance <= extracut_length:
  6102. # gcode += self.doformat(p.linear_code, x=pt[0], y=pt[1])
  6103. # last_pt = pt
  6104. # else:
  6105. # break
  6106. # Up to travelling height.
  6107. if up:
  6108. gcode += self.doformat(p.lift_code, x=last_pt[0], y=last_pt[1], z_move=z_move) # Stop cutting
  6109. return gcode
  6110. def point2gcode(self, point, dia, z_move=None, old_point=(0, 0)):
  6111. """
  6112. :param point: A Shapely Point
  6113. :type point: Point
  6114. :param dia: The tool diameter that is going on the path
  6115. :type dia: float
  6116. :param z_move: Travel Z
  6117. :type z_move: float
  6118. :param old_point: Old point coordinates from which we moved to the 'point'
  6119. :type old_point: tuple
  6120. :return: G-code to cut on the Point feature.
  6121. :rtype: str
  6122. """
  6123. gcode = ""
  6124. if self.app.abort_flag:
  6125. # graceful abort requested by the user
  6126. raise grace
  6127. path = list(point.coords)
  6128. p = self.pp_geometry
  6129. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  6130. if self.coordinates_type == "G90":
  6131. # For Absolute coordinates type G90
  6132. first_x = path[0][0]
  6133. first_y = path[0][1]
  6134. else:
  6135. # For Incremental coordinates type G91
  6136. # first_x = path[0][0] - old_point[0]
  6137. # first_y = path[0][1] - old_point[1]
  6138. self.app.inform.emit('[ERROR_NOTCL] %s' %
  6139. _('G91 coordinates not implemented ...'))
  6140. first_x = path[0][0]
  6141. first_y = path[0][1]
  6142. current_tooldia = dia
  6143. travels = self.app.exc_areas.travel_coordinates(start_point=(old_point[0], old_point[1]),
  6144. end_point=(first_x, first_y),
  6145. tooldia=current_tooldia)
  6146. prev_z = None
  6147. for travel in travels:
  6148. locx = travel[1][0]
  6149. locy = travel[1][1]
  6150. if travel[0] is not None:
  6151. # move to next point
  6152. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  6153. # raise to safe Z (travel[0]) each time because safe Z may be different
  6154. self.z_move = travel[0]
  6155. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  6156. # restore z_move
  6157. self.z_move = z_move
  6158. else:
  6159. if prev_z is not None:
  6160. # move to next point
  6161. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  6162. # we assume that previously the z_move was altered therefore raise to
  6163. # the travel_z (z_move)
  6164. self.z_move = z_move
  6165. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  6166. else:
  6167. # move to next point
  6168. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  6169. # store prev_z
  6170. prev_z = travel[0]
  6171. # gcode += self.doformat(p.linear_code, x=first_x, y=first_y) # Move to first point
  6172. if self.z_feedrate is not None:
  6173. gcode += self.doformat(p.z_feedrate_code)
  6174. gcode += self.doformat(p.down_code, x=first_x, y=first_y, z_cut=self.z_cut)
  6175. gcode += self.doformat(p.feedrate_code)
  6176. else:
  6177. gcode += self.doformat(p.down_code, x=first_x, y=first_y, z_cut=self.z_cut) # Start cutting
  6178. gcode += self.doformat(p.lift_code, x=first_x, y=first_y) # Stop cutting
  6179. return gcode
  6180. def export_svg(self, scale_stroke_factor=0.00):
  6181. """
  6182. Exports the CNC Job as a SVG Element
  6183. :param scale_stroke_factor: A factor to scale the SVG geometry
  6184. :type scale_stroke_factor: float
  6185. :return: SVG Element string
  6186. :rtype: str
  6187. """
  6188. # scale_factor is a multiplication factor for the SVG stroke-width used within shapely's svg export
  6189. # If not specified then try and use the tool diameter
  6190. # This way what is on screen will match what is outputed for the svg
  6191. # This is quite a useful feature for svg's used with visicut
  6192. if scale_stroke_factor <= 0:
  6193. scale_stroke_factor = self.options['tooldia'] / 2
  6194. # If still 0 then default to 0.05
  6195. # This value appears to work for zooming, and getting the output svg line width
  6196. # to match that viewed on screen with FlatCam
  6197. if scale_stroke_factor == 0:
  6198. scale_stroke_factor = 0.01
  6199. # Separate the list of cuts and travels into 2 distinct lists
  6200. # This way we can add different formatting / colors to both
  6201. cuts = []
  6202. travels = []
  6203. cutsgeom = ''
  6204. travelsgeom = ''
  6205. for g in self.gcode_parsed:
  6206. if self.app.abort_flag:
  6207. # graceful abort requested by the user
  6208. raise grace
  6209. if g['kind'][0] == 'C':
  6210. cuts.append(g)
  6211. if g['kind'][0] == 'T':
  6212. travels.append(g)
  6213. # Used to determine the overall board size
  6214. self.solid_geometry = cascaded_union([geo['geom'] for geo in self.gcode_parsed])
  6215. # Convert the cuts and travels into single geometry objects we can render as svg xml
  6216. if travels:
  6217. travelsgeom = cascaded_union([geo['geom'] for geo in travels])
  6218. if self.app.abort_flag:
  6219. # graceful abort requested by the user
  6220. raise grace
  6221. if cuts:
  6222. cutsgeom = cascaded_union([geo['geom'] for geo in cuts])
  6223. # Render the SVG Xml
  6224. # The scale factor affects the size of the lines, and the stroke color adds different formatting for each set
  6225. # It's better to have the travels sitting underneath the cuts for visicut
  6226. svg_elem = ""
  6227. if travels:
  6228. svg_elem = travelsgeom.svg(scale_factor=scale_stroke_factor, stroke_color="#F0E24D")
  6229. if cuts:
  6230. svg_elem += cutsgeom.svg(scale_factor=scale_stroke_factor, stroke_color="#5E6CFF")
  6231. return svg_elem
  6232. def bounds(self, flatten=None):
  6233. """
  6234. Returns coordinates of rectangular bounds of geometry: (xmin, ymin, xmax, ymax).
  6235. :param flatten: Not used, it is here for compatibility with base class method
  6236. :type flatten: bool
  6237. :return: Bounding values in format (xmin, ymin, xmax, ymax)
  6238. :rtype: tuple
  6239. """
  6240. log.debug("camlib.CNCJob.bounds()")
  6241. def bounds_rec(obj):
  6242. if type(obj) is list:
  6243. cminx = np.Inf
  6244. cminy = np.Inf
  6245. cmaxx = -np.Inf
  6246. cmaxy = -np.Inf
  6247. for k in obj:
  6248. if type(k) is dict:
  6249. for key in k:
  6250. minx_, miny_, maxx_, maxy_ = bounds_rec(k[key])
  6251. cminx = min(cminx, minx_)
  6252. cminy = min(cminy, miny_)
  6253. cmaxx = max(cmaxx, maxx_)
  6254. cmaxy = max(cmaxy, maxy_)
  6255. else:
  6256. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  6257. cminx = min(cminx, minx_)
  6258. cminy = min(cminy, miny_)
  6259. cmaxx = max(cmaxx, maxx_)
  6260. cmaxy = max(cmaxy, maxy_)
  6261. return cminx, cminy, cmaxx, cmaxy
  6262. else:
  6263. # it's a Shapely object, return it's bounds
  6264. return obj.bounds
  6265. if self.multitool is False:
  6266. log.debug("CNCJob->bounds()")
  6267. if self.solid_geometry is None:
  6268. log.debug("solid_geometry is None")
  6269. return 0, 0, 0, 0
  6270. bounds_coords = bounds_rec(self.solid_geometry)
  6271. else:
  6272. minx = np.Inf
  6273. miny = np.Inf
  6274. maxx = -np.Inf
  6275. maxy = -np.Inf
  6276. for k, v in self.cnc_tools.items():
  6277. minx = np.Inf
  6278. miny = np.Inf
  6279. maxx = -np.Inf
  6280. maxy = -np.Inf
  6281. try:
  6282. for k in v['solid_geometry']:
  6283. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  6284. minx = min(minx, minx_)
  6285. miny = min(miny, miny_)
  6286. maxx = max(maxx, maxx_)
  6287. maxy = max(maxy, maxy_)
  6288. except TypeError:
  6289. minx_, miny_, maxx_, maxy_ = bounds_rec(v['solid_geometry'])
  6290. minx = min(minx, minx_)
  6291. miny = min(miny, miny_)
  6292. maxx = max(maxx, maxx_)
  6293. maxy = max(maxy, maxy_)
  6294. bounds_coords = minx, miny, maxx, maxy
  6295. return bounds_coords
  6296. # TODO This function should be replaced at some point with a "real" function. Until then it's an ugly hack ...
  6297. def scale(self, xfactor, yfactor=None, point=None):
  6298. """
  6299. Scales all the geometry on the XY plane in the object by the
  6300. given factor. Tool sizes, feedrates, or Z-axis dimensions are
  6301. not altered.
  6302. :param factor: Number by which to scale the object.
  6303. :type factor: float
  6304. :param point: the (x,y) coords for the point of origin of scale
  6305. :type tuple of floats
  6306. :return: None
  6307. :rtype: None
  6308. """
  6309. log.debug("camlib.CNCJob.scale()")
  6310. if yfactor is None:
  6311. yfactor = xfactor
  6312. if point is None:
  6313. px = 0
  6314. py = 0
  6315. else:
  6316. px, py = point
  6317. def scale_g(g):
  6318. """
  6319. :param g: 'g' parameter it's a gcode string
  6320. :return: scaled gcode string
  6321. """
  6322. temp_gcode = ''
  6323. header_start = False
  6324. header_stop = False
  6325. units = self.app.defaults['units'].upper()
  6326. lines = StringIO(g)
  6327. for line in lines:
  6328. # this changes the GCODE header ---- UGLY HACK
  6329. if "TOOL DIAMETER" in line or "Feedrate:" in line:
  6330. header_start = True
  6331. if "G20" in line or "G21" in line:
  6332. header_start = False
  6333. header_stop = True
  6334. if header_start is True:
  6335. header_stop = False
  6336. if "in" in line:
  6337. if units == 'MM':
  6338. line = line.replace("in", "mm")
  6339. if "mm" in line:
  6340. if units == 'IN':
  6341. line = line.replace("mm", "in")
  6342. # find any float number in header (even multiple on the same line) and convert it
  6343. numbers_in_header = re.findall(self.g_nr_re, line)
  6344. if numbers_in_header:
  6345. for nr in numbers_in_header:
  6346. new_nr = float(nr) * xfactor
  6347. # replace the updated string
  6348. line = line.replace(nr, ('%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_nr))
  6349. )
  6350. # this scales all the X and Y and Z and F values and also the Tool Dia in the toolchange message
  6351. if header_stop is True:
  6352. if "G20" in line:
  6353. if units == 'MM':
  6354. line = line.replace("G20", "G21")
  6355. if "G21" in line:
  6356. if units == 'IN':
  6357. line = line.replace("G21", "G20")
  6358. # find the X group
  6359. match_x = self.g_x_re.search(line)
  6360. if match_x:
  6361. if match_x.group(1) is not None:
  6362. new_x = float(match_x.group(1)[1:]) * xfactor
  6363. # replace the updated string
  6364. line = line.replace(
  6365. match_x.group(1),
  6366. 'X%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_x)
  6367. )
  6368. # find the Y group
  6369. match_y = self.g_y_re.search(line)
  6370. if match_y:
  6371. if match_y.group(1) is not None:
  6372. new_y = float(match_y.group(1)[1:]) * yfactor
  6373. line = line.replace(
  6374. match_y.group(1),
  6375. 'Y%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_y)
  6376. )
  6377. # find the Z group
  6378. match_z = self.g_z_re.search(line)
  6379. if match_z:
  6380. if match_z.group(1) is not None:
  6381. new_z = float(match_z.group(1)[1:]) * xfactor
  6382. line = line.replace(
  6383. match_z.group(1),
  6384. 'Z%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_z)
  6385. )
  6386. # find the F group
  6387. match_f = self.g_f_re.search(line)
  6388. if match_f:
  6389. if match_f.group(1) is not None:
  6390. new_f = float(match_f.group(1)[1:]) * xfactor
  6391. line = line.replace(
  6392. match_f.group(1),
  6393. 'F%.*f' % (self.app.defaults["cncjob_fr_decimals"], new_f)
  6394. )
  6395. # find the T group (tool dia on toolchange)
  6396. match_t = self.g_t_re.search(line)
  6397. if match_t:
  6398. if match_t.group(1) is not None:
  6399. new_t = float(match_t.group(1)[1:]) * xfactor
  6400. line = line.replace(
  6401. match_t.group(1),
  6402. '= %.*f' % (self.app.defaults["cncjob_coords_decimals"], new_t)
  6403. )
  6404. temp_gcode += line
  6405. lines.close()
  6406. header_stop = False
  6407. return temp_gcode
  6408. if self.multitool is False:
  6409. # offset Gcode
  6410. self.gcode = scale_g(self.gcode)
  6411. # variables to display the percentage of work done
  6412. self.geo_len = 0
  6413. try:
  6414. self.geo_len = len(self.gcode_parsed)
  6415. except TypeError:
  6416. self.geo_len = 1
  6417. self.old_disp_number = 0
  6418. self.el_count = 0
  6419. # scale geometry
  6420. for g in self.gcode_parsed:
  6421. try:
  6422. g['geom'] = affinity.scale(g['geom'], xfactor, yfactor, origin=(px, py))
  6423. except AttributeError:
  6424. return g['geom']
  6425. self.el_count += 1
  6426. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  6427. if self.old_disp_number < disp_number <= 100:
  6428. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  6429. self.old_disp_number = disp_number
  6430. self.create_geometry()
  6431. else:
  6432. for k, v in self.cnc_tools.items():
  6433. # scale Gcode
  6434. v['gcode'] = scale_g(v['gcode'])
  6435. # variables to display the percentage of work done
  6436. self.geo_len = 0
  6437. try:
  6438. self.geo_len = len(v['gcode_parsed'])
  6439. except TypeError:
  6440. self.geo_len = 1
  6441. self.old_disp_number = 0
  6442. self.el_count = 0
  6443. # scale gcode_parsed
  6444. for g in v['gcode_parsed']:
  6445. try:
  6446. g['geom'] = affinity.scale(g['geom'], xfactor, yfactor, origin=(px, py))
  6447. except AttributeError:
  6448. return g['geom']
  6449. self.el_count += 1
  6450. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  6451. if self.old_disp_number < disp_number <= 100:
  6452. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  6453. self.old_disp_number = disp_number
  6454. v['solid_geometry'] = cascaded_union([geo['geom'] for geo in v['gcode_parsed']])
  6455. self.create_geometry()
  6456. self.app.proc_container.new_text = ''
  6457. def offset(self, vect):
  6458. """
  6459. Offsets all the geometry on the XY plane in the object by the
  6460. given vector.
  6461. Offsets all the GCODE on the XY plane in the object by the
  6462. given vector.
  6463. g_offsetx_re, g_offsety_re, multitool, cnnc_tools are attributes of FlatCAMCNCJob class in camlib
  6464. :param vect: (x, y) offset vector.
  6465. :type vect: tuple
  6466. :return: None
  6467. """
  6468. log.debug("camlib.CNCJob.offset()")
  6469. dx, dy = vect
  6470. def offset_g(g):
  6471. """
  6472. :param g: 'g' parameter it's a gcode string
  6473. :return: offseted gcode string
  6474. """
  6475. temp_gcode = ''
  6476. lines = StringIO(g)
  6477. for line in lines:
  6478. # find the X group
  6479. match_x = self.g_x_re.search(line)
  6480. if match_x:
  6481. if match_x.group(1) is not None:
  6482. # get the coordinate and add X offset
  6483. new_x = float(match_x.group(1)[1:]) + dx
  6484. # replace the updated string
  6485. line = line.replace(
  6486. match_x.group(1),
  6487. 'X%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_x)
  6488. )
  6489. match_y = self.g_y_re.search(line)
  6490. if match_y:
  6491. if match_y.group(1) is not None:
  6492. new_y = float(match_y.group(1)[1:]) + dy
  6493. line = line.replace(
  6494. match_y.group(1),
  6495. 'Y%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_y)
  6496. )
  6497. temp_gcode += line
  6498. lines.close()
  6499. return temp_gcode
  6500. if self.multitool is False:
  6501. # offset Gcode
  6502. self.gcode = offset_g(self.gcode)
  6503. # variables to display the percentage of work done
  6504. self.geo_len = 0
  6505. try:
  6506. self.geo_len = len(self.gcode_parsed)
  6507. except TypeError:
  6508. self.geo_len = 1
  6509. self.old_disp_number = 0
  6510. self.el_count = 0
  6511. # offset geometry
  6512. for g in self.gcode_parsed:
  6513. try:
  6514. g['geom'] = affinity.translate(g['geom'], xoff=dx, yoff=dy)
  6515. except AttributeError:
  6516. return g['geom']
  6517. self.el_count += 1
  6518. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  6519. if self.old_disp_number < disp_number <= 100:
  6520. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  6521. self.old_disp_number = disp_number
  6522. self.create_geometry()
  6523. else:
  6524. for k, v in self.cnc_tools.items():
  6525. # offset Gcode
  6526. v['gcode'] = offset_g(v['gcode'])
  6527. # variables to display the percentage of work done
  6528. self.geo_len = 0
  6529. try:
  6530. self.geo_len = len(v['gcode_parsed'])
  6531. except TypeError:
  6532. self.geo_len = 1
  6533. self.old_disp_number = 0
  6534. self.el_count = 0
  6535. # offset gcode_parsed
  6536. for g in v['gcode_parsed']:
  6537. try:
  6538. g['geom'] = affinity.translate(g['geom'], xoff=dx, yoff=dy)
  6539. except AttributeError:
  6540. return g['geom']
  6541. self.el_count += 1
  6542. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  6543. if self.old_disp_number < disp_number <= 100:
  6544. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  6545. self.old_disp_number = disp_number
  6546. # for the bounding box
  6547. v['solid_geometry'] = cascaded_union([geo['geom'] for geo in v['gcode_parsed']])
  6548. self.app.proc_container.new_text = ''
  6549. def mirror(self, axis, point):
  6550. """
  6551. Mirror the geometry of an object by an given axis around the coordinates of the 'point'
  6552. :param axis: Axis for Mirror
  6553. :param point: tuple of coordinates (x,y). Point of origin for Mirror
  6554. :return:
  6555. """
  6556. log.debug("camlib.CNCJob.mirror()")
  6557. px, py = point
  6558. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  6559. # variables to display the percentage of work done
  6560. self.geo_len = 0
  6561. try:
  6562. self.geo_len = len(self.gcode_parsed)
  6563. except TypeError:
  6564. self.geo_len = 1
  6565. self.old_disp_number = 0
  6566. self.el_count = 0
  6567. for g in self.gcode_parsed:
  6568. try:
  6569. g['geom'] = affinity.scale(g['geom'], xscale, yscale, origin=(px, py))
  6570. except AttributeError:
  6571. return g['geom']
  6572. self.el_count += 1
  6573. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  6574. if self.old_disp_number < disp_number <= 100:
  6575. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  6576. self.old_disp_number = disp_number
  6577. self.create_geometry()
  6578. self.app.proc_container.new_text = ''
  6579. def skew(self, angle_x, angle_y, point):
  6580. """
  6581. Shear/Skew the geometries of an object by angles along x and y dimensions.
  6582. :param angle_x:
  6583. :param angle_y:
  6584. angle_x, angle_y : float, float
  6585. The shear angle(s) for the x and y axes respectively. These can be
  6586. specified in either degrees (default) or radians by setting
  6587. use_radians=True.
  6588. :param point: tupple of coordinates (x,y)
  6589. See shapely manual for more information: http://toblerity.org/shapely/manual.html#affine-transformations
  6590. """
  6591. log.debug("camlib.CNCJob.skew()")
  6592. px, py = point
  6593. # variables to display the percentage of work done
  6594. self.geo_len = 0
  6595. try:
  6596. self.geo_len = len(self.gcode_parsed)
  6597. except TypeError:
  6598. self.geo_len = 1
  6599. self.old_disp_number = 0
  6600. self.el_count = 0
  6601. for g in self.gcode_parsed:
  6602. try:
  6603. g['geom'] = affinity.skew(g['geom'], angle_x, angle_y, origin=(px, py))
  6604. except AttributeError:
  6605. return g['geom']
  6606. self.el_count += 1
  6607. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  6608. if self.old_disp_number < disp_number <= 100:
  6609. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  6610. self.old_disp_number = disp_number
  6611. self.create_geometry()
  6612. self.app.proc_container.new_text = ''
  6613. def rotate(self, angle, point):
  6614. """
  6615. Rotate the geometry of an object by an given angle around the coordinates of the 'point'
  6616. :param angle: Angle of Rotation
  6617. :param point: tuple of coordinates (x,y). Origin point for Rotation
  6618. :return:
  6619. """
  6620. log.debug("camlib.CNCJob.rotate()")
  6621. px, py = point
  6622. # variables to display the percentage of work done
  6623. self.geo_len = 0
  6624. try:
  6625. self.geo_len = len(self.gcode_parsed)
  6626. except TypeError:
  6627. self.geo_len = 1
  6628. self.old_disp_number = 0
  6629. self.el_count = 0
  6630. for g in self.gcode_parsed:
  6631. try:
  6632. g['geom'] = affinity.rotate(g['geom'], angle, origin=(px, py))
  6633. except AttributeError:
  6634. return g['geom']
  6635. self.el_count += 1
  6636. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  6637. if self.old_disp_number < disp_number <= 100:
  6638. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  6639. self.old_disp_number = disp_number
  6640. self.create_geometry()
  6641. self.app.proc_container.new_text = ''
  6642. def get_bounds(geometry_list):
  6643. """
  6644. Will return limit values for a list of geometries
  6645. :param geometry_list: List of geometries for which to calculate the bounds limits
  6646. :return:
  6647. """
  6648. xmin = np.Inf
  6649. ymin = np.Inf
  6650. xmax = -np.Inf
  6651. ymax = -np.Inf
  6652. for gs in geometry_list:
  6653. try:
  6654. gxmin, gymin, gxmax, gymax = gs.bounds()
  6655. xmin = min([xmin, gxmin])
  6656. ymin = min([ymin, gymin])
  6657. xmax = max([xmax, gxmax])
  6658. ymax = max([ymax, gymax])
  6659. except Exception:
  6660. log.warning("DEVELOPMENT: Tried to get bounds of empty geometry.")
  6661. return [xmin, ymin, xmax, ymax]
  6662. def arc(center, radius, start, stop, direction, steps_per_circ):
  6663. """
  6664. Creates a list of point along the specified arc.
  6665. :param center: Coordinates of the center [x, y]
  6666. :type center: list
  6667. :param radius: Radius of the arc.
  6668. :type radius: float
  6669. :param start: Starting angle in radians
  6670. :type start: float
  6671. :param stop: End angle in radians
  6672. :type stop: float
  6673. :param direction: Orientation of the arc, "CW" or "CCW"
  6674. :type direction: string
  6675. :param steps_per_circ: Number of straight line segments to
  6676. represent a circle.
  6677. :type steps_per_circ: int
  6678. :return: The desired arc, as list of tuples
  6679. :rtype: list
  6680. """
  6681. # TODO: Resolution should be established by maximum error from the exact arc.
  6682. da_sign = {"cw": -1.0, "ccw": 1.0}
  6683. points = []
  6684. if direction == "ccw" and stop <= start:
  6685. stop += 2 * np.pi
  6686. if direction == "cw" and stop >= start:
  6687. stop -= 2 * np.pi
  6688. angle = abs(stop - start)
  6689. # angle = stop-start
  6690. steps = max([int(np.ceil(angle / (2 * np.pi) * steps_per_circ)), 2])
  6691. delta_angle = da_sign[direction] * angle * 1.0 / steps
  6692. for i in range(steps + 1):
  6693. theta = start + delta_angle * i
  6694. points.append((center[0] + radius * np.cos(theta), center[1] + radius * np.sin(theta)))
  6695. return points
  6696. def arc2(p1, p2, center, direction, steps_per_circ):
  6697. r = np.sqrt((center[0] - p1[0]) ** 2 + (center[1] - p1[1]) ** 2)
  6698. start = np.arctan2(p1[1] - center[1], p1[0] - center[0])
  6699. stop = np.arctan2(p2[1] - center[1], p2[0] - center[0])
  6700. return arc(center, r, start, stop, direction, steps_per_circ)
  6701. def arc_angle(start, stop, direction):
  6702. if direction == "ccw" and stop <= start:
  6703. stop += 2 * np.pi
  6704. if direction == "cw" and stop >= start:
  6705. stop -= 2 * np.pi
  6706. angle = abs(stop - start)
  6707. return angle
  6708. # def find_polygon(poly, point):
  6709. # """
  6710. # Find an object that object.contains(Point(point)) in
  6711. # poly, which can can be iterable, contain iterable of, or
  6712. # be itself an implementer of .contains().
  6713. #
  6714. # :param poly: See description
  6715. # :return: Polygon containing point or None.
  6716. # """
  6717. #
  6718. # if poly is None:
  6719. # return None
  6720. #
  6721. # try:
  6722. # for sub_poly in poly:
  6723. # p = find_polygon(sub_poly, point)
  6724. # if p is not None:
  6725. # return p
  6726. # except TypeError:
  6727. # try:
  6728. # if poly.contains(Point(point)):
  6729. # return poly
  6730. # except AttributeError:
  6731. # return None
  6732. #
  6733. # return None
  6734. def to_dict(obj):
  6735. """
  6736. Makes the following types into serializable form:
  6737. * ApertureMacro
  6738. * BaseGeometry
  6739. :param obj: Shapely geometry.
  6740. :type obj: BaseGeometry
  6741. :return: Dictionary with serializable form if ``obj`` was
  6742. BaseGeometry or ApertureMacro, otherwise returns ``obj``.
  6743. """
  6744. if isinstance(obj, ApertureMacro):
  6745. return {
  6746. "__class__": "ApertureMacro",
  6747. "__inst__": obj.to_dict()
  6748. }
  6749. if isinstance(obj, BaseGeometry):
  6750. return {
  6751. "__class__": "Shply",
  6752. "__inst__": sdumps(obj)
  6753. }
  6754. return obj
  6755. def dict2obj(d):
  6756. """
  6757. Default deserializer.
  6758. :param d: Serializable dictionary representation of an object
  6759. to be reconstructed.
  6760. :return: Reconstructed object.
  6761. """
  6762. if '__class__' in d and '__inst__' in d:
  6763. if d['__class__'] == "Shply":
  6764. return sloads(d['__inst__'])
  6765. if d['__class__'] == "ApertureMacro":
  6766. am = ApertureMacro()
  6767. am.from_dict(d['__inst__'])
  6768. return am
  6769. return d
  6770. else:
  6771. return d
  6772. # def plotg(geo, solid_poly=False, color="black"):
  6773. # try:
  6774. # __ = iter(geo)
  6775. # except:
  6776. # geo = [geo]
  6777. #
  6778. # for g in geo:
  6779. # if type(g) == Polygon:
  6780. # if solid_poly:
  6781. # patch = PolygonPatch(g,
  6782. # facecolor="#BBF268",
  6783. # edgecolor="#006E20",
  6784. # alpha=0.75,
  6785. # zorder=2)
  6786. # ax = subplot(111)
  6787. # ax.add_patch(patch)
  6788. # else:
  6789. # x, y = g.exterior.coords.xy
  6790. # plot(x, y, color=color)
  6791. # for ints in g.interiors:
  6792. # x, y = ints.coords.xy
  6793. # plot(x, y, color=color)
  6794. # continue
  6795. #
  6796. # if type(g) == LineString or type(g) == LinearRing:
  6797. # x, y = g.coords.xy
  6798. # plot(x, y, color=color)
  6799. # continue
  6800. #
  6801. # if type(g) == Point:
  6802. # x, y = g.coords.xy
  6803. # plot(x, y, 'o')
  6804. # continue
  6805. #
  6806. # try:
  6807. # __ = iter(g)
  6808. # plotg(g, color=color)
  6809. # except:
  6810. # log.error("Cannot plot: " + str(type(g)))
  6811. # continue
  6812. # def alpha_shape(points, alpha):
  6813. # """
  6814. # Compute the alpha shape (concave hull) of a set of points.
  6815. #
  6816. # @param points: Iterable container of points.
  6817. # @param alpha: alpha value to influence the gooeyness of the border. Smaller
  6818. # numbers don't fall inward as much as larger numbers. Too large,
  6819. # and you lose everything!
  6820. # """
  6821. # if len(points) < 4:
  6822. # # When you have a triangle, there is no sense in computing an alpha
  6823. # # shape.
  6824. # return MultiPoint(list(points)).convex_hull
  6825. #
  6826. # def add_edge(edges, edge_points, coords, i, j):
  6827. # """Add a line between the i-th and j-th points, if not in the list already"""
  6828. # if (i, j) in edges or (j, i) in edges:
  6829. # # already added
  6830. # return
  6831. # edges.add( (i, j) )
  6832. # edge_points.append(coords[ [i, j] ])
  6833. #
  6834. # coords = np.array([point.coords[0] for point in points])
  6835. #
  6836. # tri = Delaunay(coords)
  6837. # edges = set()
  6838. # edge_points = []
  6839. # # loop over triangles:
  6840. # # ia, ib, ic = indices of corner points of the triangle
  6841. # for ia, ib, ic in tri.vertices:
  6842. # pa = coords[ia]
  6843. # pb = coords[ib]
  6844. # pc = coords[ic]
  6845. #
  6846. # # Lengths of sides of triangle
  6847. # a = math.sqrt((pa[0]-pb[0])**2 + (pa[1]-pb[1])**2)
  6848. # b = math.sqrt((pb[0]-pc[0])**2 + (pb[1]-pc[1])**2)
  6849. # c = math.sqrt((pc[0]-pa[0])**2 + (pc[1]-pa[1])**2)
  6850. #
  6851. # # Semiperimeter of triangle
  6852. # s = (a + b + c)/2.0
  6853. #
  6854. # # Area of triangle by Heron's formula
  6855. # area = math.sqrt(s*(s-a)*(s-b)*(s-c))
  6856. # circum_r = a*b*c/(4.0*area)
  6857. #
  6858. # # Here's the radius filter.
  6859. # #print circum_r
  6860. # if circum_r < 1.0/alpha:
  6861. # add_edge(edges, edge_points, coords, ia, ib)
  6862. # add_edge(edges, edge_points, coords, ib, ic)
  6863. # add_edge(edges, edge_points, coords, ic, ia)
  6864. #
  6865. # m = MultiLineString(edge_points)
  6866. # triangles = list(polygonize(m))
  6867. # return cascaded_union(triangles), edge_points
  6868. # def voronoi(P):
  6869. # """
  6870. # Returns a list of all edges of the voronoi diagram for the given input points.
  6871. # """
  6872. # delauny = Delaunay(P)
  6873. # triangles = delauny.points[delauny.vertices]
  6874. #
  6875. # circum_centers = np.array([triangle_csc(tri) for tri in triangles])
  6876. # long_lines_endpoints = []
  6877. #
  6878. # lineIndices = []
  6879. # for i, triangle in enumerate(triangles):
  6880. # circum_center = circum_centers[i]
  6881. # for j, neighbor in enumerate(delauny.neighbors[i]):
  6882. # if neighbor != -1:
  6883. # lineIndices.append((i, neighbor))
  6884. # else:
  6885. # ps = triangle[(j+1)%3] - triangle[(j-1)%3]
  6886. # ps = np.array((ps[1], -ps[0]))
  6887. #
  6888. # middle = (triangle[(j+1)%3] + triangle[(j-1)%3]) * 0.5
  6889. # di = middle - triangle[j]
  6890. #
  6891. # ps /= np.linalg.norm(ps)
  6892. # di /= np.linalg.norm(di)
  6893. #
  6894. # if np.dot(di, ps) < 0.0:
  6895. # ps *= -1000.0
  6896. # else:
  6897. # ps *= 1000.0
  6898. #
  6899. # long_lines_endpoints.append(circum_center + ps)
  6900. # lineIndices.append((i, len(circum_centers) + len(long_lines_endpoints)-1))
  6901. #
  6902. # vertices = np.vstack((circum_centers, long_lines_endpoints))
  6903. #
  6904. # # filter out any duplicate lines
  6905. # lineIndicesSorted = np.sort(lineIndices) # make (1,2) and (2,1) both (1,2)
  6906. # lineIndicesTupled = [tuple(row) for row in lineIndicesSorted]
  6907. # lineIndicesUnique = np.unique(lineIndicesTupled)
  6908. #
  6909. # return vertices, lineIndicesUnique
  6910. #
  6911. #
  6912. # def triangle_csc(pts):
  6913. # rows, cols = pts.shape
  6914. #
  6915. # A = np.bmat([[2 * np.dot(pts, pts.T), np.ones((rows, 1))],
  6916. # [np.ones((1, rows)), np.zeros((1, 1))]])
  6917. #
  6918. # b = np.hstack((np.sum(pts * pts, axis=1), np.ones((1))))
  6919. # x = np.linalg.solve(A,b)
  6920. # bary_coords = x[:-1]
  6921. # return np.sum(pts * np.tile(bary_coords.reshape((pts.shape[0], 1)), (1, pts.shape[1])), axis=0)
  6922. #
  6923. #
  6924. # def voronoi_cell_lines(points, vertices, lineIndices):
  6925. # """
  6926. # Returns a mapping from a voronoi cell to its edges.
  6927. #
  6928. # :param points: shape (m,2)
  6929. # :param vertices: shape (n,2)
  6930. # :param lineIndices: shape (o,2)
  6931. # :rtype: dict point index -> list of shape (n,2) with vertex indices
  6932. # """
  6933. # kd = KDTree(points)
  6934. #
  6935. # cells = collections.defaultdict(list)
  6936. # for i1, i2 in lineIndices:
  6937. # v1, v2 = vertices[i1], vertices[i2]
  6938. # mid = (v1+v2)/2
  6939. # _, (p1Idx, p2Idx) = kd.query(mid, 2)
  6940. # cells[p1Idx].append((i1, i2))
  6941. # cells[p2Idx].append((i1, i2))
  6942. #
  6943. # return cells
  6944. #
  6945. #
  6946. # def voronoi_edges2polygons(cells):
  6947. # """
  6948. # Transforms cell edges into polygons.
  6949. #
  6950. # :param cells: as returned from voronoi_cell_lines
  6951. # :rtype: dict point index -> list of vertex indices which form a polygon
  6952. # """
  6953. #
  6954. # # first, close the outer cells
  6955. # for pIdx, lineIndices_ in cells.items():
  6956. # dangling_lines = []
  6957. # for i1, i2 in lineIndices_:
  6958. # p = (i1, i2)
  6959. # connections = filter(lambda k: p != k and
  6960. # (p[0] == k[0] or p[0] == k[1] or p[1] == k[0] or p[1] == k[1]), lineIndices_)
  6961. # # connections = filter(lambda (i1_, i2_): (i1, i2) != (i1_, i2_) and
  6962. # (i1 == i1_ or i1 == i2_ or i2 == i1_ or i2 == i2_), lineIndices_)
  6963. # assert 1 <= len(connections) <= 2
  6964. # if len(connections) == 1:
  6965. # dangling_lines.append((i1, i2))
  6966. # assert len(dangling_lines) in [0, 2]
  6967. # if len(dangling_lines) == 2:
  6968. # (i11, i12), (i21, i22) = dangling_lines
  6969. # s = (i11, i12)
  6970. # t = (i21, i22)
  6971. #
  6972. # # determine which line ends are unconnected
  6973. # connected = filter(lambda k: k != s and (k[0] == s[0] or k[1] == s[0]), lineIndices_)
  6974. # # connected = filter(lambda (i1,i2): (i1,i2) != (i11,i12) and (i1 == i11 or i2 == i11), lineIndices_)
  6975. # i11Unconnected = len(connected) == 0
  6976. #
  6977. # connected = filter(lambda k: k != t and (k[0] == t[0] or k[1] == t[0]), lineIndices_)
  6978. # # connected = filter(lambda (i1,i2): (i1,i2) != (i21,i22) and (i1 == i21 or i2 == i21), lineIndices_)
  6979. # i21Unconnected = len(connected) == 0
  6980. #
  6981. # startIdx = i11 if i11Unconnected else i12
  6982. # endIdx = i21 if i21Unconnected else i22
  6983. #
  6984. # cells[pIdx].append((startIdx, endIdx))
  6985. #
  6986. # # then, form polygons by storing vertex indices in (counter-)clockwise order
  6987. # polys = {}
  6988. # for pIdx, lineIndices_ in cells.items():
  6989. # # get a directed graph which contains both directions and arbitrarily follow one of both
  6990. # directedGraph = lineIndices_ + [(i2, i1) for (i1, i2) in lineIndices_]
  6991. # directedGraphMap = collections.defaultdict(list)
  6992. # for (i1, i2) in directedGraph:
  6993. # directedGraphMap[i1].append(i2)
  6994. # orderedEdges = []
  6995. # currentEdge = directedGraph[0]
  6996. # while len(orderedEdges) < len(lineIndices_):
  6997. # i1 = currentEdge[1]
  6998. # i2 = directedGraphMap[i1][0] if directedGraphMap[i1][0] != currentEdge[0] else directedGraphMap[i1][1]
  6999. # nextEdge = (i1, i2)
  7000. # orderedEdges.append(nextEdge)
  7001. # currentEdge = nextEdge
  7002. #
  7003. # polys[pIdx] = [i1 for (i1, i2) in orderedEdges]
  7004. #
  7005. # return polys
  7006. #
  7007. #
  7008. # def voronoi_polygons(points):
  7009. # """
  7010. # Returns the voronoi polygon for each input point.
  7011. #
  7012. # :param points: shape (n,2)
  7013. # :rtype: list of n polygons where each polygon is an array of vertices
  7014. # """
  7015. # vertices, lineIndices = voronoi(points)
  7016. # cells = voronoi_cell_lines(points, vertices, lineIndices)
  7017. # polys = voronoi_edges2polygons(cells)
  7018. # polylist = []
  7019. # for i in range(len(points)):
  7020. # poly = vertices[np.asarray(polys[i])]
  7021. # polylist.append(poly)
  7022. # return polylist
  7023. #
  7024. #
  7025. # class Zprofile:
  7026. # def __init__(self):
  7027. #
  7028. # # data contains lists of [x, y, z]
  7029. # self.data = []
  7030. #
  7031. # # Computed voronoi polygons (shapely)
  7032. # self.polygons = []
  7033. # pass
  7034. #
  7035. # # def plot_polygons(self):
  7036. # # axes = plt.subplot(1, 1, 1)
  7037. # #
  7038. # # plt.axis([-0.05, 1.05, -0.05, 1.05])
  7039. # #
  7040. # # for poly in self.polygons:
  7041. # # p = PolygonPatch(poly, facecolor=np.random.rand(3, 1), alpha=0.3)
  7042. # # axes.add_patch(p)
  7043. #
  7044. # def init_from_csv(self, filename):
  7045. # pass
  7046. #
  7047. # def init_from_string(self, zpstring):
  7048. # pass
  7049. #
  7050. # def init_from_list(self, zplist):
  7051. # self.data = zplist
  7052. #
  7053. # def generate_polygons(self):
  7054. # self.polygons = [Polygon(p) for p in voronoi_polygons(array([[x[0], x[1]] for x in self.data]))]
  7055. #
  7056. # def normalize(self, origin):
  7057. # pass
  7058. #
  7059. # def paste(self, path):
  7060. # """
  7061. # Return a list of dictionaries containing the parts of the original
  7062. # path and their z-axis offset.
  7063. # """
  7064. #
  7065. # # At most one region/polygon will contain the path
  7066. # containing = [i for i in range(len(self.polygons)) if self.polygons[i].contains(path)]
  7067. #
  7068. # if len(containing) > 0:
  7069. # return [{"path": path, "z": self.data[containing[0]][2]}]
  7070. #
  7071. # # All region indexes that intersect with the path
  7072. # crossing = [i for i in range(len(self.polygons)) if self.polygons[i].intersects(path)]
  7073. #
  7074. # return [{"path": path.intersection(self.polygons[i]),
  7075. # "z": self.data[i][2]} for i in crossing]
  7076. def autolist(obj):
  7077. try:
  7078. __ = iter(obj)
  7079. return obj
  7080. except TypeError:
  7081. return [obj]
  7082. def three_point_circle(p1, p2, p3):
  7083. """
  7084. Computes the center and radius of a circle from
  7085. 3 points on its circumference.
  7086. :param p1: Point 1
  7087. :param p2: Point 2
  7088. :param p3: Point 3
  7089. :return: center, radius
  7090. """
  7091. # Midpoints
  7092. a1 = (p1 + p2) / 2.0
  7093. a2 = (p2 + p3) / 2.0
  7094. # Normals
  7095. b1 = np.dot((p2 - p1), np.array([[0, -1], [1, 0]], dtype=np.float32))
  7096. b2 = np.dot((p3 - p2), np.array([[0, 1], [-1, 0]], dtype=np.float32))
  7097. # Params
  7098. try:
  7099. T = solve(np.transpose(np.array([-b1, b2])), a1 - a2)
  7100. except Exception as e:
  7101. log.debug("camlib.three_point_circle() --> %s" % str(e))
  7102. return
  7103. # Center
  7104. center = a1 + b1 * T[0]
  7105. # Radius
  7106. radius = np.linalg.norm(center - p1)
  7107. return center, radius, T[0]
  7108. def distance(pt1, pt2):
  7109. return np.sqrt((pt1[0] - pt2[0]) ** 2 + (pt1[1] - pt2[1]) ** 2)
  7110. def distance_euclidian(x1, y1, x2, y2):
  7111. return np.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
  7112. class FlatCAMRTree(object):
  7113. """
  7114. Indexes geometry (Any object with "cooords" property containing
  7115. a list of tuples with x, y values). Objects are indexed by
  7116. all their points by default. To index by arbitrary points,
  7117. override self.points2obj.
  7118. """
  7119. def __init__(self):
  7120. # Python RTree Index
  7121. self.rti = rtindex.Index()
  7122. # ## Track object-point relationship
  7123. # Each is list of points in object.
  7124. self.obj2points = []
  7125. # Index is index in rtree, value is index of
  7126. # object in obj2points.
  7127. self.points2obj = []
  7128. self.get_points = lambda go: go.coords
  7129. def grow_obj2points(self, idx):
  7130. """
  7131. Increases the size of self.obj2points to fit
  7132. idx + 1 items.
  7133. :param idx: Index to fit into list.
  7134. :return: None
  7135. """
  7136. if len(self.obj2points) > idx:
  7137. # len == 2, idx == 1, ok.
  7138. return
  7139. else:
  7140. # len == 2, idx == 2, need 1 more.
  7141. # range(2, 3)
  7142. for i in range(len(self.obj2points), idx + 1):
  7143. self.obj2points.append([])
  7144. def insert(self, objid, obj):
  7145. self.grow_obj2points(objid)
  7146. self.obj2points[objid] = []
  7147. for pt in self.get_points(obj):
  7148. self.rti.insert(len(self.points2obj), (pt[0], pt[1], pt[0], pt[1]), obj=objid)
  7149. self.obj2points[objid].append(len(self.points2obj))
  7150. self.points2obj.append(objid)
  7151. def remove_obj(self, objid, obj):
  7152. # Use all ptids to delete from index
  7153. for i, pt in enumerate(self.get_points(obj)):
  7154. try:
  7155. self.rti.delete(self.obj2points[objid][i], (pt[0], pt[1], pt[0], pt[1]))
  7156. except IndexError:
  7157. pass
  7158. def nearest(self, pt):
  7159. """
  7160. Will raise StopIteration if no items are found.
  7161. :param pt:
  7162. :return:
  7163. """
  7164. return next(self.rti.nearest(pt, objects=True))
  7165. class FlatCAMRTreeStorage(FlatCAMRTree):
  7166. """
  7167. Just like FlatCAMRTree it indexes geometry, but also serves
  7168. as storage for the geometry.
  7169. """
  7170. def __init__(self):
  7171. # super(FlatCAMRTreeStorage, self).__init__()
  7172. super().__init__()
  7173. self.objects = []
  7174. # Optimization attempt!
  7175. self.indexes = {}
  7176. def insert(self, obj):
  7177. self.objects.append(obj)
  7178. idx = len(self.objects) - 1
  7179. # Note: Shapely objects are not hashable any more, although
  7180. # there seem to be plans to re-introduce the feature in
  7181. # version 2.0. For now, we will index using the object's id,
  7182. # but it's important to remember that shapely geometry is
  7183. # mutable, ie. it can be modified to a totally different shape
  7184. # and continue to have the same id.
  7185. # self.indexes[obj] = idx
  7186. self.indexes[id(obj)] = idx
  7187. # super(FlatCAMRTreeStorage, self).insert(idx, obj)
  7188. super().insert(idx, obj)
  7189. # @profile
  7190. def remove(self, obj):
  7191. # See note about self.indexes in insert().
  7192. # objidx = self.indexes[obj]
  7193. objidx = self.indexes[id(obj)]
  7194. # Remove from list
  7195. self.objects[objidx] = None
  7196. # Remove from index
  7197. self.remove_obj(objidx, obj)
  7198. def get_objects(self):
  7199. return (o for o in self.objects if o is not None)
  7200. def nearest(self, pt):
  7201. """
  7202. Returns the nearest matching points and the object
  7203. it belongs to.
  7204. :param pt: Query point.
  7205. :return: (match_x, match_y), Object owner of
  7206. matching point.
  7207. :rtype: tuple
  7208. """
  7209. tidx = super(FlatCAMRTreeStorage, self).nearest(pt)
  7210. return (tidx.bbox[0], tidx.bbox[1]), self.objects[tidx.object]
  7211. # class myO:
  7212. # def __init__(self, coords):
  7213. # self.coords = coords
  7214. #
  7215. #
  7216. # def test_rti():
  7217. #
  7218. # o1 = myO([(0, 0), (0, 1), (1, 1)])
  7219. # o2 = myO([(2, 0), (2, 1), (2, 1)])
  7220. # o3 = myO([(2, 0), (2, 1), (3, 1)])
  7221. #
  7222. # os = [o1, o2]
  7223. #
  7224. # idx = FlatCAMRTree()
  7225. #
  7226. # for o in range(len(os)):
  7227. # idx.insert(o, os[o])
  7228. #
  7229. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  7230. #
  7231. # idx.remove_obj(0, o1)
  7232. #
  7233. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  7234. #
  7235. # idx.remove_obj(1, o2)
  7236. #
  7237. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  7238. #
  7239. #
  7240. # def test_rtis():
  7241. #
  7242. # o1 = myO([(0, 0), (0, 1), (1, 1)])
  7243. # o2 = myO([(2, 0), (2, 1), (2, 1)])
  7244. # o3 = myO([(2, 0), (2, 1), (3, 1)])
  7245. #
  7246. # os = [o1, o2]
  7247. #
  7248. # idx = FlatCAMRTreeStorage()
  7249. #
  7250. # for o in range(len(os)):
  7251. # idx.insert(os[o])
  7252. #
  7253. # #os = None
  7254. # #o1 = None
  7255. # #o2 = None
  7256. #
  7257. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  7258. #
  7259. # idx.remove(idx.nearest((2,0))[1])
  7260. #
  7261. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  7262. #
  7263. # idx.remove(idx.nearest((0,0))[1])
  7264. #
  7265. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]