camlib.py 318 KB

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