camlib.py 360 KB

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