camlib.py 375 KB

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