camlib.py 317 KB

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