camlib.py 371 KB

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