camlib.py 310 KB

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