camlib.py 364 KB

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