camlib.py 370 KB

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