camlib.py 295 KB

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