camlib.py 263 KB

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