camlib.py 322 KB

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