camlib.py 317 KB

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