camlib.py 312 KB

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