camlib.py 268 KB

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