camlib.py 323 KB

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