camlib.py 288 KB

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