camlib.py 318 KB

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