camlib.py 358 KB

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