camlib.py 227 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868
  1. # ########################################################## ##
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # ########################################################## ##
  8. from PyQt5 import QtWidgets, QtCore
  9. from io import StringIO
  10. import numpy as np
  11. from numpy.linalg import solve, norm
  12. import platform
  13. from copy import deepcopy
  14. import traceback
  15. from decimal import Decimal
  16. from rtree import index as rtindex
  17. from lxml import etree as ET
  18. # See: http://toblerity.org/shapely/manual.html
  19. from shapely.geometry import Polygon, LineString, Point, LinearRing, MultiLineString, MultiPoint, MultiPolygon
  20. from shapely.geometry import box as shply_box
  21. from shapely.ops import cascaded_union, unary_union, polygonize
  22. import shapely.affinity as affinity
  23. from shapely.wkt import loads as sloads
  24. from shapely.wkt import dumps as sdumps
  25. from shapely.geometry.base import BaseGeometry
  26. from shapely.geometry import shape
  27. # needed for legacy mode
  28. # Used for solid polygons in Matplotlib
  29. from descartes.patch import PolygonPatch
  30. import collections
  31. from collections import Iterable
  32. import rasterio
  33. from rasterio.features import shapes
  34. import ezdxf
  35. # TODO: Commented for FlatCAM packaging with cx_freeze
  36. # from scipy.spatial import KDTree, Delaunay
  37. # from scipy.spatial import Delaunay
  38. from flatcamParsers.ParseSVG import *
  39. from flatcamParsers.ParseDXF import *
  40. if platform.architecture()[0] == '64bit':
  41. from ortools.constraint_solver import pywrapcp
  42. from ortools.constraint_solver import routing_enums_pb2
  43. import logging
  44. import FlatCAMApp
  45. import gettext
  46. import FlatCAMTranslation as fcTranslate
  47. import builtins
  48. fcTranslate.apply_language('strings')
  49. log = logging.getLogger('base2')
  50. log.setLevel(logging.DEBUG)
  51. formatter = logging.Formatter('[%(levelname)s] %(message)s')
  52. handler = logging.StreamHandler()
  53. handler.setFormatter(formatter)
  54. log.addHandler(handler)
  55. if '_' not in builtins.__dict__:
  56. _ = gettext.gettext
  57. class ParseError(Exception):
  58. pass
  59. class ApertureMacro:
  60. """
  61. Syntax of aperture macros.
  62. <AM command>: AM<Aperture macro name>*<Macro content>
  63. <Macro content>: {{<Variable definition>*}{<Primitive>*}}
  64. <Variable definition>: $K=<Arithmetic expression>
  65. <Primitive>: <Primitive code>,<Modifier>{,<Modifier>}|<Comment>
  66. <Modifier>: $M|< Arithmetic expression>
  67. <Comment>: 0 <Text>
  68. """
  69. # ## Regular expressions
  70. am1_re = re.compile(r'^%AM([^\*]+)\*(.+)?(%)?$')
  71. am2_re = re.compile(r'(.*)%$')
  72. amcomm_re = re.compile(r'^0(.*)')
  73. amprim_re = re.compile(r'^[1-9].*')
  74. amvar_re = re.compile(r'^\$([0-9a-zA-z]+)=(.*)')
  75. def __init__(self, name=None):
  76. self.name = name
  77. self.raw = ""
  78. # ## These below are recomputed for every aperture
  79. # ## definition, in other words, are temporary variables.
  80. self.primitives = []
  81. self.locvars = {}
  82. self.geometry = None
  83. def to_dict(self):
  84. """
  85. Returns the object in a serializable form. Only the name and
  86. raw are required.
  87. :return: Dictionary representing the object. JSON ready.
  88. :rtype: dict
  89. """
  90. return {
  91. 'name': self.name,
  92. 'raw': self.raw
  93. }
  94. def from_dict(self, d):
  95. """
  96. Populates the object from a serial representation created
  97. with ``self.to_dict()``.
  98. :param d: Serial representation of an ApertureMacro object.
  99. :return: None
  100. """
  101. for attr in ['name', 'raw']:
  102. setattr(self, attr, d[attr])
  103. def parse_content(self):
  104. """
  105. Creates numerical lists for all primitives in the aperture
  106. macro (in ``self.raw``) by replacing all variables by their
  107. values iteratively and evaluating expressions. Results
  108. are stored in ``self.primitives``.
  109. :return: None
  110. """
  111. # Cleanup
  112. self.raw = self.raw.replace('\n', '').replace('\r', '').strip(" *")
  113. self.primitives = []
  114. # Separate parts
  115. parts = self.raw.split('*')
  116. # ### Every part in the macro ####
  117. for part in parts:
  118. # ## Comments. Ignored.
  119. match = ApertureMacro.amcomm_re.search(part)
  120. if match:
  121. continue
  122. # ## Variables
  123. # These are variables defined locally inside the macro. They can be
  124. # numerical constant or defined in terms of previously define
  125. # variables, which can be defined locally or in an aperture
  126. # definition. All replacements occur here.
  127. match = ApertureMacro.amvar_re.search(part)
  128. if match:
  129. var = match.group(1)
  130. val = match.group(2)
  131. # Replace variables in value
  132. for v in self.locvars:
  133. # replaced the following line with the next to fix Mentor custom apertures not parsed OK
  134. # val = re.sub((r'\$'+str(v)+r'(?![0-9a-zA-Z])'), str(self.locvars[v]), val)
  135. val = val.replace('$' + str(v), str(self.locvars[v]))
  136. # Make all others 0
  137. val = re.sub(r'\$[0-9a-zA-Z](?![0-9a-zA-Z])', "0", val)
  138. # Change x with *
  139. val = re.sub(r'[xX]', "*", val)
  140. # Eval() and store.
  141. self.locvars[var] = eval(val)
  142. continue
  143. # ## Primitives
  144. # Each is an array. The first identifies the primitive, while the
  145. # rest depend on the primitive. All are strings representing a
  146. # number and may contain variable definition. The values of these
  147. # variables are defined in an aperture definition.
  148. match = ApertureMacro.amprim_re.search(part)
  149. if match:
  150. # ## Replace all variables
  151. for v in self.locvars:
  152. # replaced the following line with the next to fix Mentor custom apertures not parsed OK
  153. # part = re.sub(r'\$' + str(v) + r'(?![0-9a-zA-Z])', str(self.locvars[v]), part)
  154. part = part.replace('$' + str(v), str(self.locvars[v]))
  155. # Make all others 0
  156. part = re.sub(r'\$[0-9a-zA-Z](?![0-9a-zA-Z])', "0", part)
  157. # Change x with *
  158. part = re.sub(r'[xX]', "*", part)
  159. # ## Store
  160. elements = part.split(",")
  161. self.primitives.append([eval(x) for x in elements])
  162. continue
  163. log.warning("Unknown syntax of aperture macro part: %s" % str(part))
  164. def append(self, data):
  165. """
  166. Appends a string to the raw macro.
  167. :param data: Part of the macro.
  168. :type data: str
  169. :return: None
  170. """
  171. self.raw += data
  172. @staticmethod
  173. def default2zero(n, mods):
  174. """
  175. Pads the ``mods`` list with zeros resulting in an
  176. list of length n.
  177. :param n: Length of the resulting list.
  178. :type n: int
  179. :param mods: List to be padded.
  180. :type mods: list
  181. :return: Zero-padded list.
  182. :rtype: list
  183. """
  184. x = [0.0] * n
  185. na = len(mods)
  186. x[0:na] = mods
  187. return x
  188. @staticmethod
  189. def make_circle(mods):
  190. """
  191. :param mods: (Exposure 0/1, Diameter >=0, X-coord, Y-coord)
  192. :return:
  193. """
  194. pol, dia, x, y = ApertureMacro.default2zero(4, mods)
  195. return {"pol": int(pol), "geometry": Point(x, y).buffer(dia/2)}
  196. @staticmethod
  197. def make_vectorline(mods):
  198. """
  199. :param mods: (Exposure 0/1, Line width >= 0, X-start, Y-start, X-end, Y-end,
  200. rotation angle around origin in degrees)
  201. :return:
  202. """
  203. pol, width, xs, ys, xe, ye, angle = ApertureMacro.default2zero(7, mods)
  204. line = LineString([(xs, ys), (xe, ye)])
  205. box = line.buffer(width/2, cap_style=2)
  206. box_rotated = affinity.rotate(box, angle, origin=(0, 0))
  207. return {"pol": int(pol), "geometry": box_rotated}
  208. @staticmethod
  209. def make_centerline(mods):
  210. """
  211. :param mods: (Exposure 0/1, width >=0, height >=0, x-center, y-center,
  212. rotation angle around origin in degrees)
  213. :return:
  214. """
  215. pol, width, height, x, y, angle = ApertureMacro.default2zero(6, mods)
  216. box = shply_box(x-width/2, y-height/2, x+width/2, y+height/2)
  217. box_rotated = affinity.rotate(box, angle, origin=(0, 0))
  218. return {"pol": int(pol), "geometry": box_rotated}
  219. @staticmethod
  220. def make_lowerleftline(mods):
  221. """
  222. :param mods: (exposure 0/1, width >=0, height >=0, x-lowerleft, y-lowerleft,
  223. rotation angle around origin in degrees)
  224. :return:
  225. """
  226. pol, width, height, x, y, angle = ApertureMacro.default2zero(6, mods)
  227. box = shply_box(x, y, x+width, y+height)
  228. box_rotated = affinity.rotate(box, angle, origin=(0, 0))
  229. return {"pol": int(pol), "geometry": box_rotated}
  230. @staticmethod
  231. def make_outline(mods):
  232. """
  233. :param mods:
  234. :return:
  235. """
  236. pol = mods[0]
  237. n = mods[1]
  238. points = [(0, 0)]*(n+1)
  239. for i in range(n+1):
  240. points[i] = mods[2*i + 2:2*i + 4]
  241. angle = mods[2*n + 4]
  242. poly = Polygon(points)
  243. poly_rotated = affinity.rotate(poly, angle, origin=(0, 0))
  244. return {"pol": int(pol), "geometry": poly_rotated}
  245. @staticmethod
  246. def make_polygon(mods):
  247. """
  248. Note: Specs indicate that rotation is only allowed if the center
  249. (x, y) == (0, 0). I will tolerate breaking this rule.
  250. :param mods: (exposure 0/1, n_verts 3<=n<=12, x-center, y-center,
  251. diameter of circumscribed circle >=0, rotation angle around origin)
  252. :return:
  253. """
  254. pol, nverts, x, y, dia, angle = ApertureMacro.default2zero(6, mods)
  255. points = [(0, 0)]*nverts
  256. for i in range(nverts):
  257. points[i] = (x + 0.5 * dia * np.cos(2*np.pi * i/nverts),
  258. y + 0.5 * dia * np.sin(2*np.pi * i/nverts))
  259. poly = Polygon(points)
  260. poly_rotated = affinity.rotate(poly, angle, origin=(0, 0))
  261. return {"pol": int(pol), "geometry": poly_rotated}
  262. @staticmethod
  263. def make_moire(mods):
  264. """
  265. Note: Specs indicate that rotation is only allowed if the center
  266. (x, y) == (0, 0). I will tolerate breaking this rule.
  267. :param mods: (x-center, y-center, outer_dia_outer_ring, ring thickness,
  268. gap, max_rings, crosshair_thickness, crosshair_len, rotation
  269. angle around origin in degrees)
  270. :return:
  271. """
  272. x, y, dia, thickness, gap, nrings, cross_th, cross_len, angle = ApertureMacro.default2zero(9, mods)
  273. r = dia/2 - thickness/2
  274. result = Point((x, y)).buffer(r).exterior.buffer(thickness/2.0)
  275. ring = Point((x, y)).buffer(r).exterior.buffer(thickness/2.0) # Need a copy!
  276. i = 1 # Number of rings created so far
  277. # ## If the ring does not have an interior it means that it is
  278. # ## a disk. Then stop.
  279. while len(ring.interiors) > 0 and i < nrings:
  280. r -= thickness + gap
  281. if r <= 0:
  282. break
  283. ring = Point((x, y)).buffer(r).exterior.buffer(thickness/2.0)
  284. result = cascaded_union([result, ring])
  285. i += 1
  286. # ## Crosshair
  287. hor = LineString([(x - cross_len, y), (x + cross_len, y)]).buffer(cross_th/2.0, cap_style=2)
  288. ver = LineString([(x, y-cross_len), (x, y + cross_len)]).buffer(cross_th/2.0, cap_style=2)
  289. result = cascaded_union([result, hor, ver])
  290. return {"pol": 1, "geometry": result}
  291. @staticmethod
  292. def make_thermal(mods):
  293. """
  294. Note: Specs indicate that rotation is only allowed if the center
  295. (x, y) == (0, 0). I will tolerate breaking this rule.
  296. :param mods: [x-center, y-center, diameter-outside, diameter-inside,
  297. gap-thickness, rotation angle around origin]
  298. :return:
  299. """
  300. x, y, dout, din, t, angle = ApertureMacro.default2zero(6, mods)
  301. ring = Point((x, y)).buffer(dout/2.0).difference(Point((x, y)).buffer(din/2.0))
  302. hline = LineString([(x - dout/2.0, y), (x + dout/2.0, y)]).buffer(t/2.0, cap_style=3)
  303. vline = LineString([(x, y - dout/2.0), (x, y + dout/2.0)]).buffer(t/2.0, cap_style=3)
  304. thermal = ring.difference(hline.union(vline))
  305. return {"pol": 1, "geometry": thermal}
  306. def make_geometry(self, modifiers):
  307. """
  308. Runs the macro for the given modifiers and generates
  309. the corresponding geometry.
  310. :param modifiers: Modifiers (parameters) for this macro
  311. :type modifiers: list
  312. :return: Shapely geometry
  313. :rtype: shapely.geometry.polygon
  314. """
  315. # ## Primitive makers
  316. makers = {
  317. "1": ApertureMacro.make_circle,
  318. "2": ApertureMacro.make_vectorline,
  319. "20": ApertureMacro.make_vectorline,
  320. "21": ApertureMacro.make_centerline,
  321. "22": ApertureMacro.make_lowerleftline,
  322. "4": ApertureMacro.make_outline,
  323. "5": ApertureMacro.make_polygon,
  324. "6": ApertureMacro.make_moire,
  325. "7": ApertureMacro.make_thermal
  326. }
  327. # ## Store modifiers as local variables
  328. modifiers = modifiers or []
  329. modifiers = [float(m) for m in modifiers]
  330. self.locvars = {}
  331. for i in range(0, len(modifiers)):
  332. self.locvars[str(i + 1)] = modifiers[i]
  333. # ## Parse
  334. self.primitives = [] # Cleanup
  335. self.geometry = Polygon()
  336. self.parse_content()
  337. # ## Make the geometry
  338. for primitive in self.primitives:
  339. # Make the primitive
  340. prim_geo = makers[str(int(primitive[0]))](primitive[1:])
  341. # Add it (according to polarity)
  342. # if self.geometry is None and prim_geo['pol'] == 1:
  343. # self.geometry = prim_geo['geometry']
  344. # continue
  345. if prim_geo['pol'] == 1:
  346. self.geometry = self.geometry.union(prim_geo['geometry'])
  347. continue
  348. if prim_geo['pol'] == 0:
  349. self.geometry = self.geometry.difference(prim_geo['geometry'])
  350. continue
  351. return self.geometry
  352. class Geometry(object):
  353. """
  354. Base geometry class.
  355. """
  356. defaults = {
  357. "units": 'in',
  358. "geo_steps_per_circle": 128
  359. }
  360. def __init__(self, geo_steps_per_circle=None):
  361. # Units (in or mm)
  362. self.units = self.app.defaults["units"]
  363. # Final geometry: MultiPolygon or list (of geometry constructs)
  364. self.solid_geometry = None
  365. # Final geometry: MultiLineString or list (of LineString or Points)
  366. self.follow_geometry = None
  367. # Attributes to be included in serialization
  368. self.ser_attrs = ["units", 'solid_geometry', 'follow_geometry']
  369. # Flattened geometry (list of paths only)
  370. self.flat_geometry = []
  371. # this is the calculated conversion factor when the file units are different than the ones in the app
  372. self.file_units_factor = 1
  373. # Index
  374. self.index = None
  375. self.geo_steps_per_circle = geo_steps_per_circle
  376. # variables to display the percentage of work done
  377. self.geo_len = 0
  378. self.old_disp_number = 0
  379. self.el_count = 0
  380. if self.app.is_legacy is False:
  381. self.temp_shapes = self.app.plotcanvas.new_shape_group()
  382. else:
  383. from flatcamGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  384. self.temp_shapes = ShapeCollectionLegacy(obj=self, app=self.app, name='camlib.geometry')
  385. def plot_temp_shapes(self, element, color='red'):
  386. try:
  387. for sub_el in element:
  388. self.plot_temp_shapes(sub_el)
  389. except TypeError: # Element is not iterable...
  390. # self.add_shape(shape=element, color=color, visible=visible, layer=0)
  391. self.temp_shapes.add(tolerance=float(self.app.defaults["global_tolerance"]),
  392. shape=element, color=color, visible=True, layer=0)
  393. def make_index(self):
  394. self.flatten()
  395. self.index = FlatCAMRTree()
  396. for i, g in enumerate(self.flat_geometry):
  397. self.index.insert(i, g)
  398. def add_circle(self, origin, radius):
  399. """
  400. Adds a circle to the object.
  401. :param origin: Center of the circle.
  402. :param radius: Radius of the circle.
  403. :return: None
  404. """
  405. if self.solid_geometry is None:
  406. self.solid_geometry = []
  407. if type(self.solid_geometry) is list:
  408. self.solid_geometry.append(Point(origin).buffer(
  409. radius, int(int(self.geo_steps_per_circle) / 4)))
  410. return
  411. try:
  412. self.solid_geometry = self.solid_geometry.union(Point(origin).buffer(
  413. radius, int(int(self.geo_steps_per_circle) / 4)))
  414. except Exception as e:
  415. log.error("Failed to run union on polygons. %s" % str(e))
  416. return
  417. def add_polygon(self, points):
  418. """
  419. Adds a polygon to the object (by union)
  420. :param points: The vertices of the polygon.
  421. :return: None
  422. """
  423. if self.solid_geometry is None:
  424. self.solid_geometry = []
  425. if type(self.solid_geometry) is list:
  426. self.solid_geometry.append(Polygon(points))
  427. return
  428. try:
  429. self.solid_geometry = self.solid_geometry.union(Polygon(points))
  430. except Exception as e:
  431. log.error("Failed to run union on polygons. %s" % str(e))
  432. return
  433. def add_polyline(self, points):
  434. """
  435. Adds a polyline to the object (by union)
  436. :param points: The vertices of the polyline.
  437. :return: None
  438. """
  439. if self.solid_geometry is None:
  440. self.solid_geometry = []
  441. if type(self.solid_geometry) is list:
  442. self.solid_geometry.append(LineString(points))
  443. return
  444. try:
  445. self.solid_geometry = self.solid_geometry.union(LineString(points))
  446. except Exception as e:
  447. log.error("Failed to run union on polylines. %s" % str(e))
  448. return
  449. def is_empty(self):
  450. if isinstance(self.solid_geometry, BaseGeometry):
  451. return self.solid_geometry.is_empty
  452. if isinstance(self.solid_geometry, list):
  453. return len(self.solid_geometry) == 0
  454. self.app.inform.emit('[ERROR_NOTCL] %s' %
  455. _("self.solid_geometry is neither BaseGeometry or list."))
  456. return
  457. def subtract_polygon(self, points):
  458. """
  459. Subtract polygon from the given object. This only operates on the paths in the original geometry,
  460. i.e. it converts polygons into paths.
  461. :param points: The vertices of the polygon.
  462. :return: none
  463. """
  464. if self.solid_geometry is None:
  465. self.solid_geometry = []
  466. # pathonly should be allways True, otherwise polygons are not subtracted
  467. flat_geometry = self.flatten(pathonly=True)
  468. log.debug("%d paths" % len(flat_geometry))
  469. polygon = Polygon(points)
  470. toolgeo = cascaded_union(polygon)
  471. diffs = []
  472. for target in flat_geometry:
  473. if type(target) == LineString or type(target) == LinearRing:
  474. diffs.append(target.difference(toolgeo))
  475. else:
  476. log.warning("Not implemented.")
  477. self.solid_geometry = cascaded_union(diffs)
  478. def bounds(self):
  479. """
  480. Returns coordinates of rectangular bounds
  481. of geometry: (xmin, ymin, xmax, ymax).
  482. """
  483. # fixed issue of getting bounds only for one level lists of objects
  484. # now it can get bounds for nested lists of objects
  485. log.debug("camlib.Geometry.bounds()")
  486. if self.solid_geometry is None:
  487. log.debug("solid_geometry is None")
  488. return 0, 0, 0, 0
  489. def bounds_rec(obj):
  490. if type(obj) is list:
  491. minx = np.Inf
  492. miny = np.Inf
  493. maxx = -np.Inf
  494. maxy = -np.Inf
  495. for k in obj:
  496. if type(k) is dict:
  497. for key in k:
  498. minx_, miny_, maxx_, maxy_ = bounds_rec(k[key])
  499. minx = min(minx, minx_)
  500. miny = min(miny, miny_)
  501. maxx = max(maxx, maxx_)
  502. maxy = max(maxy, maxy_)
  503. else:
  504. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  505. minx = min(minx, minx_)
  506. miny = min(miny, miny_)
  507. maxx = max(maxx, maxx_)
  508. maxy = max(maxy, maxy_)
  509. return minx, miny, maxx, maxy
  510. else:
  511. # it's a Shapely object, return it's bounds
  512. return obj.bounds
  513. if self.multigeo is True:
  514. minx_list = []
  515. miny_list = []
  516. maxx_list = []
  517. maxy_list = []
  518. for tool in self.tools:
  519. minx, miny, maxx, maxy = bounds_rec(self.tools[tool]['solid_geometry'])
  520. minx_list.append(minx)
  521. miny_list.append(miny)
  522. maxx_list.append(maxx)
  523. maxy_list.append(maxy)
  524. return(min(minx_list), min(miny_list), max(maxx_list), max(maxy_list))
  525. else:
  526. bounds_coords = bounds_rec(self.solid_geometry)
  527. return bounds_coords
  528. # try:
  529. # # from here: http://rightfootin.blogspot.com/2006/09/more-on-python-flatten.html
  530. # def flatten(l, ltypes=(list, tuple)):
  531. # ltype = type(l)
  532. # l = list(l)
  533. # i = 0
  534. # while i < len(l):
  535. # while isinstance(l[i], ltypes):
  536. # if not l[i]:
  537. # l.pop(i)
  538. # i -= 1
  539. # break
  540. # else:
  541. # l[i:i + 1] = l[i]
  542. # i += 1
  543. # return ltype(l)
  544. #
  545. # log.debug("Geometry->bounds()")
  546. # if self.solid_geometry is None:
  547. # log.debug("solid_geometry is None")
  548. # return 0, 0, 0, 0
  549. #
  550. # if type(self.solid_geometry) is list:
  551. # # TODO: This can be done faster. See comment from Shapely mailing lists.
  552. # if len(self.solid_geometry) == 0:
  553. # log.debug('solid_geometry is empty []')
  554. # return 0, 0, 0, 0
  555. # return cascaded_union(flatten(self.solid_geometry)).bounds
  556. # else:
  557. # return self.solid_geometry.bounds
  558. # except Exception as e:
  559. # self.app.inform.emit("[ERROR_NOTCL] Error cause: %s" % str(e))
  560. # log.debug("Geometry->bounds()")
  561. # if self.solid_geometry is None:
  562. # log.debug("solid_geometry is None")
  563. # return 0, 0, 0, 0
  564. #
  565. # if type(self.solid_geometry) is list:
  566. # # TODO: This can be done faster. See comment from Shapely mailing lists.
  567. # if len(self.solid_geometry) == 0:
  568. # log.debug('solid_geometry is empty []')
  569. # return 0, 0, 0, 0
  570. # return cascaded_union(self.solid_geometry).bounds
  571. # else:
  572. # return self.solid_geometry.bounds
  573. def find_polygon(self, point, geoset=None):
  574. """
  575. Find an object that object.contains(Point(point)) in
  576. poly, which can can be iterable, contain iterable of, or
  577. be itself an implementer of .contains().
  578. :param point: See description
  579. :param geoset: a polygon or list of polygons where to find if the param point is contained
  580. :return: Polygon containing point or None.
  581. """
  582. if geoset is None:
  583. geoset = self.solid_geometry
  584. try: # Iterable
  585. for sub_geo in geoset:
  586. p = self.find_polygon(point, geoset=sub_geo)
  587. if p is not None:
  588. return p
  589. except TypeError: # Non-iterable
  590. try: # Implements .contains()
  591. if isinstance(geoset, LinearRing):
  592. geoset = Polygon(geoset)
  593. if geoset.contains(Point(point)):
  594. return geoset
  595. except AttributeError: # Does not implement .contains()
  596. return None
  597. return None
  598. def get_interiors(self, geometry=None):
  599. interiors = []
  600. if geometry is None:
  601. geometry = self.solid_geometry
  602. # ## If iterable, expand recursively.
  603. try:
  604. for geo in geometry:
  605. interiors.extend(self.get_interiors(geometry=geo))
  606. # ## Not iterable, get the interiors if polygon.
  607. except TypeError:
  608. if type(geometry) == Polygon:
  609. interiors.extend(geometry.interiors)
  610. return interiors
  611. def get_exteriors(self, geometry=None):
  612. """
  613. Returns all exteriors of polygons in geometry. Uses
  614. ``self.solid_geometry`` if geometry is not provided.
  615. :param geometry: Shapely type or list or list of list of such.
  616. :return: List of paths constituting the exteriors
  617. of polygons in geometry.
  618. """
  619. exteriors = []
  620. if geometry is None:
  621. geometry = self.solid_geometry
  622. # ## If iterable, expand recursively.
  623. try:
  624. for geo in geometry:
  625. exteriors.extend(self.get_exteriors(geometry=geo))
  626. # ## Not iterable, get the exterior if polygon.
  627. except TypeError:
  628. if type(geometry) == Polygon:
  629. exteriors.append(geometry.exterior)
  630. return exteriors
  631. def flatten(self, geometry=None, reset=True, pathonly=False):
  632. """
  633. Creates a list of non-iterable linear geometry objects.
  634. Polygons are expanded into its exterior and interiors if specified.
  635. Results are placed in self.flat_geometry
  636. :param geometry: Shapely type or list or list of list of such.
  637. :param reset: Clears the contents of self.flat_geometry.
  638. :param pathonly: Expands polygons into linear elements.
  639. """
  640. if geometry is None:
  641. geometry = self.solid_geometry
  642. if reset:
  643. self.flat_geometry = []
  644. # ## If iterable, expand recursively.
  645. try:
  646. for geo in geometry:
  647. if geo is not None:
  648. self.flatten(geometry=geo,
  649. reset=False,
  650. pathonly=pathonly)
  651. # ## Not iterable, do the actual indexing and add.
  652. except TypeError:
  653. if pathonly and type(geometry) == Polygon:
  654. self.flat_geometry.append(geometry.exterior)
  655. self.flatten(geometry=geometry.interiors,
  656. reset=False,
  657. pathonly=True)
  658. else:
  659. self.flat_geometry.append(geometry)
  660. return self.flat_geometry
  661. # def make2Dstorage(self):
  662. #
  663. # self.flatten()
  664. #
  665. # def get_pts(o):
  666. # pts = []
  667. # if type(o) == Polygon:
  668. # g = o.exterior
  669. # pts += list(g.coords)
  670. # for i in o.interiors:
  671. # pts += list(i.coords)
  672. # else:
  673. # pts += list(o.coords)
  674. # return pts
  675. #
  676. # storage = FlatCAMRTreeStorage()
  677. # storage.get_points = get_pts
  678. # for shape in self.flat_geometry:
  679. # storage.insert(shape)
  680. # return storage
  681. # def flatten_to_paths(self, geometry=None, reset=True):
  682. # """
  683. # Creates a list of non-iterable linear geometry elements and
  684. # indexes them in rtree.
  685. #
  686. # :param geometry: Iterable geometry
  687. # :param reset: Wether to clear (True) or append (False) to self.flat_geometry
  688. # :return: self.flat_geometry, self.flat_geometry_rtree
  689. # """
  690. #
  691. # if geometry is None:
  692. # geometry = self.solid_geometry
  693. #
  694. # if reset:
  695. # self.flat_geometry = []
  696. #
  697. # # ## If iterable, expand recursively.
  698. # try:
  699. # for geo in geometry:
  700. # self.flatten_to_paths(geometry=geo, reset=False)
  701. #
  702. # # ## Not iterable, do the actual indexing and add.
  703. # except TypeError:
  704. # if type(geometry) == Polygon:
  705. # g = geometry.exterior
  706. # self.flat_geometry.append(g)
  707. #
  708. # # ## Add first and last points of the path to the index.
  709. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[0])
  710. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[-1])
  711. #
  712. # for interior in geometry.interiors:
  713. # g = interior
  714. # self.flat_geometry.append(g)
  715. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[0])
  716. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[-1])
  717. # else:
  718. # g = geometry
  719. # self.flat_geometry.append(g)
  720. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[0])
  721. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[-1])
  722. #
  723. # return self.flat_geometry, self.flat_geometry_rtree
  724. def isolation_geometry(self, offset, geometry=None, iso_type=2, corner=None, follow=None, passes=0):
  725. """
  726. Creates contours around geometry at a given
  727. offset distance.
  728. :param offset: Offset distance.
  729. :type offset: float
  730. :param iso_type: type of isolation, can be 0 = exteriors or 1 = interiors or 2 = both (complete)
  731. :param corner: type of corner for the isolation: 0 = round; 1 = square; 2= beveled (line that connects the ends)
  732. :param follow: whether the geometry to be isolated is a follow_geometry
  733. :param passes: current pass out of possible multiple passes for which the isolation is done
  734. :return: The buffered geometry.
  735. :rtype: Shapely.MultiPolygon or Shapely.Polygon
  736. """
  737. if self.app.abort_flag:
  738. # graceful abort requested by the user
  739. raise FlatCAMApp.GracefulException
  740. geo_iso = list()
  741. if follow:
  742. return geometry
  743. if geometry:
  744. working_geo = geometry
  745. else:
  746. working_geo = self.solid_geometry
  747. try:
  748. geo_len = len(working_geo)
  749. except TypeError:
  750. geo_len = 1
  751. old_disp_number = 0
  752. pol_nr = 0
  753. # yet, it can be done by issuing an unary_union in the end, thus getting rid of the overlapping geo
  754. try:
  755. for pol in working_geo:
  756. if self.app.abort_flag:
  757. # graceful abort requested by the user
  758. raise FlatCAMApp.GracefulException
  759. if offset == 0:
  760. geo_iso.append(pol)
  761. else:
  762. corner_type = 1 if corner is None else corner
  763. geo_iso.append(pol.buffer(offset, int(int(self.geo_steps_per_circle) / 4), join_style=corner_type))
  764. pol_nr += 1
  765. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  766. if old_disp_number < disp_number <= 100:
  767. self.app.proc_container.update_view_text(' %s %d: %d%%' %
  768. (_("Pass"), int(passes + 1), int(disp_number)))
  769. old_disp_number = disp_number
  770. except TypeError:
  771. # taking care of the case when the self.solid_geometry is just a single Polygon, not a list or a
  772. # MultiPolygon (not an iterable)
  773. if offset == 0:
  774. geo_iso.append(working_geo)
  775. else:
  776. corner_type = 1 if corner is None else corner
  777. geo_iso.append(working_geo.buffer(offset, int(int(self.geo_steps_per_circle) / 4),
  778. join_style=corner_type))
  779. self.app.proc_container.update_view_text(' %s' % _("Buffering"))
  780. geo_iso = unary_union(geo_iso)
  781. self.app.proc_container.update_view_text('')
  782. # end of replaced block
  783. if iso_type == 2:
  784. return geo_iso
  785. elif iso_type == 0:
  786. self.app.proc_container.update_view_text(' %s' % _("Get Exteriors"))
  787. return self.get_exteriors(geo_iso)
  788. elif iso_type == 1:
  789. self.app.proc_container.update_view_text(' %s' % _("Get Interiors"))
  790. return self.get_interiors(geo_iso)
  791. else:
  792. log.debug("Geometry.isolation_geometry() --> Type of isolation not supported")
  793. return "fail"
  794. def flatten_list(self, list):
  795. for item in list:
  796. if isinstance(item, Iterable) and not isinstance(item, (str, bytes)):
  797. yield from self.flatten_list(item)
  798. else:
  799. yield item
  800. def import_svg(self, filename, object_type=None, flip=True, units='MM'):
  801. """
  802. Imports shapes from an SVG file into the object's geometry.
  803. :param filename: Path to the SVG file.
  804. :type filename: str
  805. :param object_type: parameter passed further along
  806. :param flip: Flip the vertically.
  807. :type flip: bool
  808. :param units: FlatCAM units
  809. :return: None
  810. """
  811. log.debug("camlib.Geometry.import_svg()")
  812. # Parse into list of shapely objects
  813. svg_tree = ET.parse(filename)
  814. svg_root = svg_tree.getroot()
  815. # Change origin to bottom left
  816. # h = float(svg_root.get('height'))
  817. # w = float(svg_root.get('width'))
  818. h = svgparselength(svg_root.get('height'))[0] # TODO: No units support yet
  819. geos = getsvggeo(svg_root, object_type)
  820. if flip:
  821. geos = [translate(scale(g, 1.0, -1.0, origin=(0, 0)), yoff=h) for g in geos]
  822. # Add to object
  823. if self.solid_geometry is None:
  824. self.solid_geometry = []
  825. if type(self.solid_geometry) is list:
  826. # self.solid_geometry.append(cascaded_union(geos))
  827. if type(geos) is list:
  828. self.solid_geometry += geos
  829. else:
  830. self.solid_geometry.append(geos)
  831. else: # It's shapely geometry
  832. # self.solid_geometry = cascaded_union([self.solid_geometry,
  833. # cascaded_union(geos)])
  834. self.solid_geometry = [self.solid_geometry, geos]
  835. # flatten the self.solid_geometry list for import_svg() to import SVG as Gerber
  836. self.solid_geometry = list(self.flatten_list(self.solid_geometry))
  837. geos_text = getsvgtext(svg_root, object_type, units=units)
  838. if geos_text is not None:
  839. geos_text_f = []
  840. if flip:
  841. # Change origin to bottom left
  842. for i in geos_text:
  843. _, minimy, _, maximy = i.bounds
  844. h2 = (maximy - minimy) * 0.5
  845. geos_text_f.append(translate(scale(i, 1.0, -1.0, origin=(0, 0)), yoff=(h + h2)))
  846. if geos_text_f:
  847. self.solid_geometry = self.solid_geometry + geos_text_f
  848. def import_dxf(self, filename, object_type=None, units='MM'):
  849. """
  850. Imports shapes from an DXF file into the object's geometry.
  851. :param filename: Path to the DXF file.
  852. :type filename: str
  853. :param units: Application units
  854. :type flip: str
  855. :return: None
  856. """
  857. # Parse into list of shapely objects
  858. dxf = ezdxf.readfile(filename)
  859. geos = getdxfgeo(dxf)
  860. # Add to object
  861. if self.solid_geometry is None:
  862. self.solid_geometry = []
  863. if type(self.solid_geometry) is list:
  864. if type(geos) is list:
  865. self.solid_geometry += geos
  866. else:
  867. self.solid_geometry.append(geos)
  868. else: # It's shapely geometry
  869. self.solid_geometry = [self.solid_geometry, geos]
  870. # flatten the self.solid_geometry list for import_dxf() to import DXF as Gerber
  871. self.solid_geometry = list(self.flatten_list(self.solid_geometry))
  872. if self.solid_geometry is not None:
  873. self.solid_geometry = cascaded_union(self.solid_geometry)
  874. else:
  875. return
  876. # commented until this function is ready
  877. # geos_text = getdxftext(dxf, object_type, units=units)
  878. # if geos_text is not None:
  879. # geos_text_f = []
  880. # self.solid_geometry = [self.solid_geometry, geos_text_f]
  881. def import_image(self, filename, flip=True, units='MM', dpi=96, mode='black', mask=None):
  882. """
  883. Imports shapes from an IMAGE file into the object's geometry.
  884. :param filename: Path to the IMAGE file.
  885. :type filename: str
  886. :param flip: Flip the object vertically.
  887. :type flip: bool
  888. :param units: FlatCAM units
  889. :param dpi: dots per inch on the imported image
  890. :param mode: how to import the image: as 'black' or 'color'
  891. :param mask: level of detail for the import
  892. :return: None
  893. """
  894. if mask is None:
  895. mask = [128, 128, 128, 128]
  896. scale_factor = 25.4 / dpi if units.lower() == 'mm' else 1 / dpi
  897. geos = list()
  898. unscaled_geos = list()
  899. with rasterio.open(filename) as src:
  900. # if filename.lower().rpartition('.')[-1] == 'bmp':
  901. # red = green = blue = src.read(1)
  902. # print("BMP")
  903. # elif filename.lower().rpartition('.')[-1] == 'png':
  904. # red, green, blue, alpha = src.read()
  905. # elif filename.lower().rpartition('.')[-1] == 'jpg':
  906. # red, green, blue = src.read()
  907. red = green = blue = src.read(1)
  908. try:
  909. green = src.read(2)
  910. except Exception:
  911. pass
  912. try:
  913. blue = src.read(3)
  914. except Exception:
  915. pass
  916. if mode == 'black':
  917. mask_setting = red <= mask[0]
  918. total = red
  919. log.debug("Image import as monochrome.")
  920. else:
  921. mask_setting = (red <= mask[1]) + (green <= mask[2]) + (blue <= mask[3])
  922. total = np.zeros(red.shape, dtype=np.float32)
  923. for band in red, green, blue:
  924. total += band
  925. total /= 3
  926. log.debug("Image import as colored. Thresholds are: R = %s , G = %s, B = %s" %
  927. (str(mask[1]), str(mask[2]), str(mask[3])))
  928. for geom, val in shapes(total, mask=mask_setting):
  929. unscaled_geos.append(shape(geom))
  930. for g in unscaled_geos:
  931. geos.append(scale(g, scale_factor, scale_factor, origin=(0, 0)))
  932. if flip:
  933. geos = [translate(scale(g, 1.0, -1.0, origin=(0, 0))) for g in geos]
  934. # Add to object
  935. if self.solid_geometry is None:
  936. self.solid_geometry = list()
  937. if type(self.solid_geometry) is list:
  938. # self.solid_geometry.append(cascaded_union(geos))
  939. if type(geos) is list:
  940. self.solid_geometry += geos
  941. else:
  942. self.solid_geometry.append(geos)
  943. else: # It's shapely geometry
  944. self.solid_geometry = [self.solid_geometry, geos]
  945. # flatten the self.solid_geometry list for import_svg() to import SVG as Gerber
  946. self.solid_geometry = list(self.flatten_list(self.solid_geometry))
  947. self.solid_geometry = cascaded_union(self.solid_geometry)
  948. # self.solid_geometry = MultiPolygon(self.solid_geometry)
  949. # self.solid_geometry = self.solid_geometry.buffer(0.00000001)
  950. # self.solid_geometry = self.solid_geometry.buffer(-0.00000001)
  951. def size(self):
  952. """
  953. Returns (width, height) of rectangular
  954. bounds of geometry.
  955. """
  956. if self.solid_geometry is None:
  957. log.warning("Solid_geometry not computed yet.")
  958. return 0
  959. bounds = self.bounds()
  960. return bounds[2] - bounds[0], bounds[3] - bounds[1]
  961. def get_empty_area(self, boundary=None):
  962. """
  963. Returns the complement of self.solid_geometry within
  964. the given boundary polygon. If not specified, it defaults to
  965. the rectangular bounding box of self.solid_geometry.
  966. """
  967. if boundary is None:
  968. boundary = self.solid_geometry.envelope
  969. return boundary.difference(self.solid_geometry)
  970. def clear_polygon(self, polygon, tooldia, steps_per_circle, overlap=0.15, connect=True, contour=True,
  971. prog_plot=False):
  972. """
  973. Creates geometry inside a polygon for a tool to cover
  974. the whole area.
  975. This algorithm shrinks the edges of the polygon and takes
  976. the resulting edges as toolpaths.
  977. :param polygon: Polygon to clear.
  978. :param tooldia: Diameter of the tool.
  979. :param steps_per_circle: number of linear segments to be used to approximate a circle
  980. :param overlap: Overlap of toolpasses.
  981. :param connect: Draw lines between disjoint segments to
  982. minimize tool lifts.
  983. :param contour: Paint around the edges. Inconsequential in
  984. this painting method.
  985. :param prog_plot: boolean; if Ture use the progressive plotting
  986. :return:
  987. """
  988. # log.debug("camlib.clear_polygon()")
  989. assert type(polygon) == Polygon or type(polygon) == MultiPolygon, \
  990. "Expected a Polygon or MultiPolygon, got %s" % type(polygon)
  991. # ## The toolpaths
  992. # Index first and last points in paths
  993. def get_pts(o):
  994. return [o.coords[0], o.coords[-1]]
  995. geoms = FlatCAMRTreeStorage()
  996. geoms.get_points = get_pts
  997. # Can only result in a Polygon or MultiPolygon
  998. # NOTE: The resulting polygon can be "empty".
  999. current = polygon.buffer((-tooldia / 1.999999), int(int(steps_per_circle) / 4))
  1000. if current.area == 0:
  1001. # Otherwise, trying to to insert current.exterior == None
  1002. # into the FlatCAMStorage will fail.
  1003. # print("Area is None")
  1004. return None
  1005. # current can be a MultiPolygon
  1006. try:
  1007. for p in current:
  1008. geoms.insert(p.exterior)
  1009. for i in p.interiors:
  1010. geoms.insert(i)
  1011. # Not a Multipolygon. Must be a Polygon
  1012. except TypeError:
  1013. geoms.insert(current.exterior)
  1014. for i in current.interiors:
  1015. geoms.insert(i)
  1016. while True:
  1017. if self.app.abort_flag:
  1018. # graceful abort requested by the user
  1019. raise FlatCAMApp.GracefulException
  1020. # provide the app with a way to process the GUI events when in a blocking loop
  1021. QtWidgets.QApplication.processEvents()
  1022. # Can only result in a Polygon or MultiPolygon
  1023. current = current.buffer(-tooldia * (1 - overlap), int(int(steps_per_circle) / 4))
  1024. if current.area > 0:
  1025. # current can be a MultiPolygon
  1026. try:
  1027. for p in current:
  1028. geoms.insert(p.exterior)
  1029. for i in p.interiors:
  1030. geoms.insert(i)
  1031. if prog_plot:
  1032. self.plot_temp_shapes(p)
  1033. # Not a Multipolygon. Must be a Polygon
  1034. except TypeError:
  1035. geoms.insert(current.exterior)
  1036. if prog_plot:
  1037. self.plot_temp_shapes(current.exterior)
  1038. for i in current.interiors:
  1039. geoms.insert(i)
  1040. if prog_plot:
  1041. self.plot_temp_shapes(i)
  1042. else:
  1043. log.debug("camlib.Geometry.clear_polygon() --> Current Area is zero")
  1044. break
  1045. if prog_plot:
  1046. self.temp_shapes.redraw()
  1047. # Optimization: Reduce lifts
  1048. if connect:
  1049. # log.debug("Reducing tool lifts...")
  1050. geoms = Geometry.paint_connect(geoms, polygon, tooldia, int(steps_per_circle))
  1051. return geoms
  1052. def clear_polygon2(self, polygon_to_clear, tooldia, steps_per_circle, seedpoint=None, overlap=0.15,
  1053. connect=True, contour=True, prog_plot=False):
  1054. """
  1055. Creates geometry inside a polygon for a tool to cover
  1056. the whole area.
  1057. This algorithm starts with a seed point inside the polygon
  1058. and draws circles around it. Arcs inside the polygons are
  1059. valid cuts. Finalizes by cutting around the inside edge of
  1060. the polygon.
  1061. :param polygon_to_clear: Shapely.geometry.Polygon
  1062. :param steps_per_circle: how many linear segments to use to approximate a circle
  1063. :param tooldia: Diameter of the tool
  1064. :param seedpoint: Shapely.geometry.Point or None
  1065. :param overlap: Tool fraction overlap bewteen passes
  1066. :param connect: Connect disjoint segment to minumize tool lifts
  1067. :param contour: Cut countour inside the polygon.
  1068. :return: List of toolpaths covering polygon.
  1069. :rtype: FlatCAMRTreeStorage | None
  1070. :param prog_plot: boolean; if True use the progressive plotting
  1071. """
  1072. # log.debug("camlib.clear_polygon2()")
  1073. # Current buffer radius
  1074. radius = tooldia / 2 * (1 - overlap)
  1075. # ## The toolpaths
  1076. # Index first and last points in paths
  1077. def get_pts(o):
  1078. return [o.coords[0], o.coords[-1]]
  1079. geoms = FlatCAMRTreeStorage()
  1080. geoms.get_points = get_pts
  1081. # Path margin
  1082. path_margin = polygon_to_clear.buffer(-tooldia / 2, int(steps_per_circle / 4))
  1083. if path_margin.is_empty or path_margin is None:
  1084. return
  1085. # Estimate good seedpoint if not provided.
  1086. if seedpoint is None:
  1087. seedpoint = path_margin.representative_point()
  1088. # Grow from seed until outside the box. The polygons will
  1089. # never have an interior, so take the exterior LinearRing.
  1090. while True:
  1091. if self.app.abort_flag:
  1092. # graceful abort requested by the user
  1093. raise FlatCAMApp.GracefulException
  1094. # provide the app with a way to process the GUI events when in a blocking loop
  1095. QtWidgets.QApplication.processEvents()
  1096. path = Point(seedpoint).buffer(radius, int(steps_per_circle / 4)).exterior
  1097. path = path.intersection(path_margin)
  1098. # Touches polygon?
  1099. if path.is_empty:
  1100. break
  1101. else:
  1102. # geoms.append(path)
  1103. # geoms.insert(path)
  1104. # path can be a collection of paths.
  1105. try:
  1106. for p in path:
  1107. geoms.insert(p)
  1108. if prog_plot:
  1109. self.plot_temp_shapes(p)
  1110. except TypeError:
  1111. geoms.insert(path)
  1112. if prog_plot:
  1113. self.plot_temp_shapes(path)
  1114. if prog_plot:
  1115. self.temp_shapes.redraw()
  1116. radius += tooldia * (1 - overlap)
  1117. # Clean inside edges (contours) of the original polygon
  1118. if contour:
  1119. outer_edges = [x.exterior for x in autolist(
  1120. polygon_to_clear.buffer(-tooldia / 2, int(steps_per_circle / 4)))]
  1121. inner_edges = []
  1122. # Over resulting polygons
  1123. for x in autolist(polygon_to_clear.buffer(-tooldia / 2, int(steps_per_circle / 4))):
  1124. for y in x.interiors: # Over interiors of each polygon
  1125. inner_edges.append(y)
  1126. # geoms += outer_edges + inner_edges
  1127. for g in outer_edges + inner_edges:
  1128. geoms.insert(g)
  1129. if prog_plot:
  1130. self.plot_temp_shapes(g)
  1131. if prog_plot:
  1132. self.temp_shapes.redraw()
  1133. # Optimization connect touching paths
  1134. # log.debug("Connecting paths...")
  1135. # geoms = Geometry.path_connect(geoms)
  1136. # Optimization: Reduce lifts
  1137. if connect:
  1138. # log.debug("Reducing tool lifts...")
  1139. geoms = Geometry.paint_connect(geoms, polygon_to_clear, tooldia, steps_per_circle)
  1140. return geoms
  1141. def clear_polygon3(self, polygon, tooldia, steps_per_circle, overlap=0.15, connect=True, contour=True,
  1142. prog_plot=False):
  1143. """
  1144. Creates geometry inside a polygon for a tool to cover
  1145. the whole area.
  1146. This algorithm draws horizontal lines inside the polygon.
  1147. :param polygon: The polygon being painted.
  1148. :type polygon: shapely.geometry.Polygon
  1149. :param tooldia: Tool diameter.
  1150. :param steps_per_circle: how many linear segments to use to approximate a circle
  1151. :param overlap: Tool path overlap percentage.
  1152. :param connect: Connect lines to avoid tool lifts.
  1153. :param contour: Paint around the edges.
  1154. :param prog_plot: boolean; if to use the progressive plotting
  1155. :return:
  1156. """
  1157. # log.debug("camlib.clear_polygon3()")
  1158. # ## The toolpaths
  1159. # Index first and last points in paths
  1160. def get_pts(o):
  1161. return [o.coords[0], o.coords[-1]]
  1162. geoms = FlatCAMRTreeStorage()
  1163. geoms.get_points = get_pts
  1164. lines_trimmed = []
  1165. # Bounding box
  1166. left, bot, right, top = polygon.bounds
  1167. margin_poly = polygon.buffer(-tooldia / 1.99999999, (int(steps_per_circle)))
  1168. # First line
  1169. y = top - tooldia / 1.99999999
  1170. while y > bot + tooldia / 1.999999999:
  1171. if self.app.abort_flag:
  1172. # graceful abort requested by the user
  1173. raise FlatCAMApp.GracefulException
  1174. # provide the app with a way to process the GUI events when in a blocking loop
  1175. QtWidgets.QApplication.processEvents()
  1176. line = LineString([(left, y), (right, y)])
  1177. line = line.intersection(margin_poly)
  1178. lines_trimmed.append(line)
  1179. y -= tooldia * (1 - overlap)
  1180. if prog_plot:
  1181. self.plot_temp_shapes(line)
  1182. self.temp_shapes.redraw()
  1183. # Last line
  1184. y = bot + tooldia / 2
  1185. line = LineString([(left, y), (right, y)])
  1186. line = line.intersection(margin_poly)
  1187. for ll in line:
  1188. lines_trimmed.append(ll)
  1189. if prog_plot:
  1190. self.plot_temp_shapes(line)
  1191. # Combine
  1192. # linesgeo = unary_union(lines)
  1193. # Trim to the polygon
  1194. # margin_poly = polygon.buffer(-tooldia / 1.99999999, (int(steps_per_circle)))
  1195. # lines_trimmed = linesgeo.intersection(margin_poly)
  1196. if prog_plot:
  1197. self.temp_shapes.redraw()
  1198. lines_trimmed = unary_union(lines_trimmed)
  1199. # Add lines to storage
  1200. try:
  1201. for line in lines_trimmed:
  1202. geoms.insert(line)
  1203. except TypeError:
  1204. # in case lines_trimmed are not iterable (Linestring, LinearRing)
  1205. geoms.insert(lines_trimmed)
  1206. # Add margin (contour) to storage
  1207. if contour:
  1208. if isinstance(margin_poly, Polygon):
  1209. geoms.insert(margin_poly.exterior)
  1210. if prog_plot:
  1211. self.plot_temp_shapes(margin_poly.exterior)
  1212. for ints in margin_poly.interiors:
  1213. geoms.insert(ints)
  1214. if prog_plot:
  1215. self.plot_temp_shapes(ints)
  1216. elif isinstance(margin_poly, MultiPolygon):
  1217. for poly in margin_poly:
  1218. geoms.insert(poly.exterior)
  1219. if prog_plot:
  1220. self.plot_temp_shapes(poly.exterior)
  1221. for ints in poly.interiors:
  1222. geoms.insert(ints)
  1223. if prog_plot:
  1224. self.plot_temp_shapes(ints)
  1225. if prog_plot:
  1226. self.temp_shapes.redraw()
  1227. # Optimization: Reduce lifts
  1228. if connect:
  1229. # log.debug("Reducing tool lifts...")
  1230. geoms = Geometry.paint_connect(geoms, polygon, tooldia, steps_per_circle)
  1231. return geoms
  1232. def scale(self, xfactor, yfactor, point=None):
  1233. """
  1234. Scales all of the object's geometry by a given factor. Override
  1235. this method.
  1236. :param xfactor: Number by which to scale on X axis.
  1237. :type xfactor: float
  1238. :param yfactor: Number by which to scale on Y axis.
  1239. :type yfactor: float
  1240. :param point: point to be used as reference for scaling; a tuple
  1241. :return: None
  1242. :rtype: None
  1243. """
  1244. return
  1245. def offset(self, vect):
  1246. """
  1247. Offset the geometry by the given vector. Override this method.
  1248. :param vect: (x, y) vector by which to offset the object.
  1249. :type vect: tuple
  1250. :return: None
  1251. """
  1252. return
  1253. @staticmethod
  1254. def paint_connect(storage, boundary, tooldia, steps_per_circle, max_walk=None):
  1255. """
  1256. Connects paths that results in a connection segment that is
  1257. within the paint area. This avoids unnecessary tool lifting.
  1258. :param storage: Geometry to be optimized.
  1259. :type storage: FlatCAMRTreeStorage
  1260. :param boundary: Polygon defining the limits of the paintable area.
  1261. :type boundary: Polygon
  1262. :param tooldia: Tool diameter.
  1263. :rtype tooldia: float
  1264. :param steps_per_circle: how many linear segments to use to approximate a circle
  1265. :param max_walk: Maximum allowable distance without lifting tool.
  1266. :type max_walk: float or None
  1267. :return: Optimized geometry.
  1268. :rtype: FlatCAMRTreeStorage
  1269. """
  1270. # If max_walk is not specified, the maximum allowed is
  1271. # 10 times the tool diameter
  1272. max_walk = max_walk or 10 * tooldia
  1273. # Assuming geolist is a flat list of flat elements
  1274. # ## Index first and last points in paths
  1275. def get_pts(o):
  1276. return [o.coords[0], o.coords[-1]]
  1277. # storage = FlatCAMRTreeStorage()
  1278. # storage.get_points = get_pts
  1279. #
  1280. # for shape in geolist:
  1281. # if shape is not None: # TODO: This shouldn't have happened.
  1282. # # Make LlinearRings into linestrings otherwise
  1283. # # When chaining the coordinates path is messed up.
  1284. # storage.insert(LineString(shape))
  1285. # #storage.insert(shape)
  1286. # ## Iterate over geometry paths getting the nearest each time.
  1287. #optimized_paths = []
  1288. optimized_paths = FlatCAMRTreeStorage()
  1289. optimized_paths.get_points = get_pts
  1290. path_count = 0
  1291. current_pt = (0, 0)
  1292. pt, geo = storage.nearest(current_pt)
  1293. storage.remove(geo)
  1294. geo = LineString(geo)
  1295. current_pt = geo.coords[-1]
  1296. try:
  1297. while True:
  1298. path_count += 1
  1299. # log.debug("Path %d" % path_count)
  1300. pt, candidate = storage.nearest(current_pt)
  1301. storage.remove(candidate)
  1302. candidate = LineString(candidate)
  1303. # If last point in geometry is the nearest
  1304. # then reverse coordinates.
  1305. # but prefer the first one if last == first
  1306. if pt != candidate.coords[0] and pt == candidate.coords[-1]:
  1307. candidate.coords = list(candidate.coords)[::-1]
  1308. # Straight line from current_pt to pt.
  1309. # Is the toolpath inside the geometry?
  1310. walk_path = LineString([current_pt, pt])
  1311. walk_cut = walk_path.buffer(tooldia / 2, int(steps_per_circle / 4))
  1312. if walk_cut.within(boundary) and walk_path.length < max_walk:
  1313. # log.debug("Walk to path #%d is inside. Joining." % path_count)
  1314. # Completely inside. Append...
  1315. geo.coords = list(geo.coords) + list(candidate.coords)
  1316. # try:
  1317. # last = optimized_paths[-1]
  1318. # last.coords = list(last.coords) + list(geo.coords)
  1319. # except IndexError:
  1320. # optimized_paths.append(geo)
  1321. else:
  1322. # Have to lift tool. End path.
  1323. # log.debug("Path #%d not within boundary. Next." % path_count)
  1324. # optimized_paths.append(geo)
  1325. optimized_paths.insert(geo)
  1326. geo = candidate
  1327. current_pt = geo.coords[-1]
  1328. # Next
  1329. # pt, geo = storage.nearest(current_pt)
  1330. except StopIteration: # Nothing left in storage.
  1331. # pass
  1332. optimized_paths.insert(geo)
  1333. return optimized_paths
  1334. @staticmethod
  1335. def path_connect(storage, origin=(0, 0)):
  1336. """
  1337. Simplifies paths in the FlatCAMRTreeStorage storage by
  1338. connecting paths that touch on their enpoints.
  1339. :param storage: Storage containing the initial paths.
  1340. :rtype storage: FlatCAMRTreeStorage
  1341. :return: Simplified storage.
  1342. :rtype: FlatCAMRTreeStorage
  1343. """
  1344. log.debug("path_connect()")
  1345. # ## Index first and last points in paths
  1346. def get_pts(o):
  1347. return [o.coords[0], o.coords[-1]]
  1348. #
  1349. # storage = FlatCAMRTreeStorage()
  1350. # storage.get_points = get_pts
  1351. #
  1352. # for shape in pathlist:
  1353. # if shape is not None: # TODO: This shouldn't have happened.
  1354. # storage.insert(shape)
  1355. path_count = 0
  1356. pt, geo = storage.nearest(origin)
  1357. storage.remove(geo)
  1358. # optimized_geometry = [geo]
  1359. optimized_geometry = FlatCAMRTreeStorage()
  1360. optimized_geometry.get_points = get_pts
  1361. # optimized_geometry.insert(geo)
  1362. try:
  1363. while True:
  1364. path_count += 1
  1365. _, left = storage.nearest(geo.coords[0])
  1366. # If left touches geo, remove left from original
  1367. # storage and append to geo.
  1368. if type(left) == LineString:
  1369. if left.coords[0] == geo.coords[0]:
  1370. storage.remove(left)
  1371. geo.coords = list(geo.coords)[::-1] + list(left.coords)
  1372. continue
  1373. if left.coords[-1] == geo.coords[0]:
  1374. storage.remove(left)
  1375. geo.coords = list(left.coords) + list(geo.coords)
  1376. continue
  1377. if left.coords[0] == geo.coords[-1]:
  1378. storage.remove(left)
  1379. geo.coords = list(geo.coords) + list(left.coords)
  1380. continue
  1381. if left.coords[-1] == geo.coords[-1]:
  1382. storage.remove(left)
  1383. geo.coords = list(geo.coords) + list(left.coords)[::-1]
  1384. continue
  1385. _, right = storage.nearest(geo.coords[-1])
  1386. # If right touches geo, remove left from original
  1387. # storage and append to geo.
  1388. if type(right) == LineString:
  1389. if right.coords[0] == geo.coords[-1]:
  1390. storage.remove(right)
  1391. geo.coords = list(geo.coords) + list(right.coords)
  1392. continue
  1393. if right.coords[-1] == geo.coords[-1]:
  1394. storage.remove(right)
  1395. geo.coords = list(geo.coords) + list(right.coords)[::-1]
  1396. continue
  1397. if right.coords[0] == geo.coords[0]:
  1398. storage.remove(right)
  1399. geo.coords = list(geo.coords)[::-1] + list(right.coords)
  1400. continue
  1401. if right.coords[-1] == geo.coords[0]:
  1402. storage.remove(right)
  1403. geo.coords = list(left.coords) + list(geo.coords)
  1404. continue
  1405. # right is either a LinearRing or it does not connect
  1406. # to geo (nothing left to connect to geo), so we continue
  1407. # with right as geo.
  1408. storage.remove(right)
  1409. if type(right) == LinearRing:
  1410. optimized_geometry.insert(right)
  1411. else:
  1412. # Cannot extend geo any further. Put it away.
  1413. optimized_geometry.insert(geo)
  1414. # Continue with right.
  1415. geo = right
  1416. except StopIteration: # Nothing found in storage.
  1417. optimized_geometry.insert(geo)
  1418. # print path_count
  1419. log.debug("path_count = %d" % path_count)
  1420. return optimized_geometry
  1421. def convert_units(self, obj_units):
  1422. """
  1423. Converts the units of the object to ``units`` by scaling all
  1424. the geometry appropriately. This call ``scale()``. Don't call
  1425. it again in descendents.
  1426. :param units: "IN" or "MM"
  1427. :type units: str
  1428. :return: Scaling factor resulting from unit change.
  1429. :rtype: float
  1430. """
  1431. if obj_units.upper() == self.units.upper():
  1432. log.debug("camlib.Geometry.convert_units() --> Factor: 1")
  1433. return 1.0
  1434. if obj_units.upper() == "MM":
  1435. factor = 25.4
  1436. log.debug("camlib.Geometry.convert_units() --> Factor: 25.4")
  1437. elif obj_units.upper() == "IN":
  1438. factor = 1 / 25.4
  1439. log.debug("camlib.Geometry.convert_units() --> Factor: %s" % str(1 / 25.4))
  1440. else:
  1441. log.error("Unsupported units: %s" % str(obj_units))
  1442. log.debug("camlib.Geometry.convert_units() --> Factor: 1")
  1443. return 1.0
  1444. self.units = obj_units
  1445. self.scale(factor, factor)
  1446. self.file_units_factor = factor
  1447. return factor
  1448. def to_dict(self):
  1449. """
  1450. Returns a representation of the object as a dictionary.
  1451. Attributes to include are listed in ``self.ser_attrs``.
  1452. :return: A dictionary-encoded copy of the object.
  1453. :rtype: dict
  1454. """
  1455. d = {}
  1456. for attr in self.ser_attrs:
  1457. d[attr] = getattr(self, attr)
  1458. return d
  1459. def from_dict(self, d):
  1460. """
  1461. Sets object's attributes from a dictionary.
  1462. Attributes to include are listed in ``self.ser_attrs``.
  1463. This method will look only for only and all the
  1464. attributes in ``self.ser_attrs``. They must all
  1465. be present. Use only for deserializing saved
  1466. objects.
  1467. :param d: Dictionary of attributes to set in the object.
  1468. :type d: dict
  1469. :return: None
  1470. """
  1471. for attr in self.ser_attrs:
  1472. setattr(self, attr, d[attr])
  1473. def union(self):
  1474. """
  1475. Runs a cascaded union on the list of objects in
  1476. solid_geometry.
  1477. :return: None
  1478. """
  1479. self.solid_geometry = [cascaded_union(self.solid_geometry)]
  1480. def export_svg(self, scale_stroke_factor=0.00,
  1481. scale_factor_x=None, scale_factor_y=None,
  1482. skew_factor_x=None, skew_factor_y=None,
  1483. skew_reference='center',
  1484. mirror=None):
  1485. """
  1486. Exports the Geometry Object as a SVG Element
  1487. :return: SVG Element
  1488. """
  1489. # Make sure we see a Shapely Geometry class and not a list
  1490. if str(type(self)) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  1491. flat_geo = []
  1492. if self.multigeo:
  1493. for tool in self.tools:
  1494. flat_geo += self.flatten(self.tools[tool]['solid_geometry'])
  1495. geom_svg = cascaded_union(flat_geo)
  1496. else:
  1497. geom_svg = cascaded_union(self.flatten())
  1498. else:
  1499. geom_svg = cascaded_union(self.flatten())
  1500. skew_ref = 'center'
  1501. if skew_reference != 'center':
  1502. xmin, ymin, xmax, ymax = geom_svg.bounds
  1503. if skew_reference == 'topleft':
  1504. skew_ref = (xmin, ymax)
  1505. elif skew_reference == 'bottomleft':
  1506. skew_ref = (xmin, ymin)
  1507. elif skew_reference == 'topright':
  1508. skew_ref = (xmax, ymax)
  1509. elif skew_reference == 'bottomright':
  1510. skew_ref = (xmax, ymin)
  1511. geom = geom_svg
  1512. if scale_factor_x:
  1513. geom = affinity.scale(geom_svg, scale_factor_x, 1.0)
  1514. if scale_factor_y:
  1515. geom = affinity.scale(geom_svg, 1.0, scale_factor_y)
  1516. if skew_factor_x:
  1517. geom = affinity.skew(geom_svg, skew_factor_x, 0.0, origin=skew_ref)
  1518. if skew_factor_y:
  1519. geom = affinity.skew(geom_svg, 0.0, skew_factor_y, origin=skew_ref)
  1520. if mirror:
  1521. if mirror == 'x':
  1522. geom = affinity.scale(geom_svg, 1.0, -1.0)
  1523. if mirror == 'y':
  1524. geom = affinity.scale(geom_svg, -1.0, 1.0)
  1525. if mirror == 'both':
  1526. geom = affinity.scale(geom_svg, -1.0, -1.0)
  1527. # scale_factor is a multiplication factor for the SVG stroke-width used within shapely's svg export
  1528. # If 0 or less which is invalid then default to 0.01
  1529. # This value appears to work for zooming, and getting the output svg line width
  1530. # to match that viewed on screen with FlatCam
  1531. # MS: I choose a factor of 0.01 so the scale is right for PCB UV film
  1532. if scale_stroke_factor <= 0:
  1533. scale_stroke_factor = 0.01
  1534. # Convert to a SVG
  1535. svg_elem = geom.svg(scale_factor=scale_stroke_factor)
  1536. return svg_elem
  1537. def mirror(self, axis, point):
  1538. """
  1539. Mirrors the object around a specified axis passign through
  1540. the given point.
  1541. :param axis: "X" or "Y" indicates around which axis to mirror.
  1542. :type axis: str
  1543. :param point: [x, y] point belonging to the mirror axis.
  1544. :type point: list
  1545. :return: None
  1546. """
  1547. log.debug("camlib.Geometry.mirror()")
  1548. px, py = point
  1549. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  1550. def mirror_geom(obj):
  1551. if type(obj) is list:
  1552. new_obj = []
  1553. for g in obj:
  1554. new_obj.append(mirror_geom(g))
  1555. return new_obj
  1556. else:
  1557. try:
  1558. self.el_count += 1
  1559. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  1560. if self.old_disp_number < disp_number <= 100:
  1561. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1562. self.old_disp_number = disp_number
  1563. return affinity.scale(obj, xscale, yscale, origin=(px, py))
  1564. except AttributeError:
  1565. return obj
  1566. try:
  1567. if self.multigeo is True:
  1568. for tool in self.tools:
  1569. # variables to display the percentage of work done
  1570. self.geo_len = 0
  1571. try:
  1572. for g in self.tools[tool]['solid_geometry']:
  1573. self.geo_len += 1
  1574. except TypeError:
  1575. self.geo_len = 1
  1576. self.old_disp_number = 0
  1577. self.el_count = 0
  1578. self.tools[tool]['solid_geometry'] = mirror_geom(self.tools[tool]['solid_geometry'])
  1579. else:
  1580. # variables to display the percentage of work done
  1581. self.geo_len = 0
  1582. try:
  1583. for g in self.solid_geometry:
  1584. self.geo_len += 1
  1585. except TypeError:
  1586. self.geo_len = 1
  1587. self.old_disp_number = 0
  1588. self.el_count = 0
  1589. self.solid_geometry = mirror_geom(self.solid_geometry)
  1590. self.app.inform.emit('[success] %s...' %
  1591. _('Object was mirrored'))
  1592. except AttributeError:
  1593. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1594. _("Failed to mirror. No object selected"))
  1595. self.app.proc_container.new_text = ''
  1596. def rotate(self, angle, point):
  1597. """
  1598. Rotate an object by an angle (in degrees) around the provided coordinates.
  1599. Parameters
  1600. ----------
  1601. The angle of rotation are specified in degrees (default). Positive angles are
  1602. counter-clockwise and negative are clockwise rotations.
  1603. The point of origin can be a keyword 'center' for the bounding box
  1604. center (default), 'centroid' for the geometry's centroid, a Point object
  1605. or a coordinate tuple (x0, y0).
  1606. See shapely manual for more information:
  1607. http://toblerity.org/shapely/manual.html#affine-transformations
  1608. """
  1609. log.debug("camlib.Geometry.rotate()")
  1610. px, py = point
  1611. def rotate_geom(obj):
  1612. if type(obj) is list:
  1613. new_obj = []
  1614. for g in obj:
  1615. new_obj.append(rotate_geom(g))
  1616. return new_obj
  1617. else:
  1618. try:
  1619. self.el_count += 1
  1620. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  1621. if self.old_disp_number < disp_number <= 100:
  1622. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1623. self.old_disp_number = disp_number
  1624. return affinity.rotate(obj, angle, origin=(px, py))
  1625. except AttributeError:
  1626. return obj
  1627. try:
  1628. if self.multigeo is True:
  1629. for tool in self.tools:
  1630. # variables to display the percentage of work done
  1631. self.geo_len = 0
  1632. try:
  1633. for g in self.tools[tool]['solid_geometry']:
  1634. self.geo_len += 1
  1635. except TypeError:
  1636. self.geo_len = 1
  1637. self.old_disp_number = 0
  1638. self.el_count = 0
  1639. self.tools[tool]['solid_geometry'] = rotate_geom(self.tools[tool]['solid_geometry'])
  1640. else:
  1641. # variables to display the percentage of work done
  1642. self.geo_len = 0
  1643. try:
  1644. for g in self.solid_geometry:
  1645. self.geo_len += 1
  1646. except TypeError:
  1647. self.geo_len = 1
  1648. self.old_disp_number = 0
  1649. self.el_count = 0
  1650. self.solid_geometry = rotate_geom(self.solid_geometry)
  1651. self.app.inform.emit('[success] %s...' %
  1652. _('Object was rotated'))
  1653. except AttributeError:
  1654. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1655. _("Failed to rotate. No object selected"))
  1656. self.app.proc_container.new_text = ''
  1657. def skew(self, angle_x, angle_y, point):
  1658. """
  1659. Shear/Skew the geometries of an object by angles along x and y dimensions.
  1660. Parameters
  1661. ----------
  1662. angle_x, angle_y : float, float
  1663. The shear angle(s) for the x and y axes respectively. These can be
  1664. specified in either degrees (default) or radians by setting
  1665. use_radians=True.
  1666. point: tuple of coordinates (x,y)
  1667. See shapely manual for more information:
  1668. http://toblerity.org/shapely/manual.html#affine-transformations
  1669. """
  1670. log.debug("camlib.Geometry.skew()")
  1671. px, py = point
  1672. def skew_geom(obj):
  1673. if type(obj) is list:
  1674. new_obj = []
  1675. for g in obj:
  1676. new_obj.append(skew_geom(g))
  1677. return new_obj
  1678. else:
  1679. try:
  1680. self.el_count += 1
  1681. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  1682. if self.old_disp_number < disp_number <= 100:
  1683. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1684. self.old_disp_number = disp_number
  1685. return affinity.skew(obj, angle_x, angle_y, origin=(px, py))
  1686. except AttributeError:
  1687. return obj
  1688. try:
  1689. if self.multigeo is True:
  1690. for tool in self.tools:
  1691. # variables to display the percentage of work done
  1692. self.geo_len = 0
  1693. try:
  1694. for g in self.tools[tool]['solid_geometry']:
  1695. self.geo_len += 1
  1696. except TypeError:
  1697. self.geo_len = 1
  1698. self.old_disp_number = 0
  1699. self.el_count = 0
  1700. self.tools[tool]['solid_geometry'] = skew_geom(self.tools[tool]['solid_geometry'])
  1701. else:
  1702. # variables to display the percentage of work done
  1703. self.geo_len = 0
  1704. try:
  1705. for g in self.solid_geometry:
  1706. self.geo_len += 1
  1707. except TypeError:
  1708. self.geo_len = 1
  1709. self.old_disp_number = 0
  1710. self.el_count = 0
  1711. self.solid_geometry = skew_geom(self.solid_geometry)
  1712. self.app.inform.emit('[success] %s...' %
  1713. _('Object was skewed'))
  1714. except AttributeError:
  1715. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1716. _("Failed to skew. No object selected"))
  1717. self.app.proc_container.new_text = ''
  1718. # if type(self.solid_geometry) == list:
  1719. # self.solid_geometry = [affinity.skew(g, angle_x, angle_y, origin=(px, py))
  1720. # for g in self.solid_geometry]
  1721. # else:
  1722. # self.solid_geometry = affinity.skew(self.solid_geometry, angle_x, angle_y,
  1723. # origin=(px, py))
  1724. class AttrDict(dict):
  1725. def __init__(self, *args, **kwargs):
  1726. super(AttrDict, self).__init__(*args, **kwargs)
  1727. self.__dict__ = self
  1728. class CNCjob(Geometry):
  1729. """
  1730. Represents work to be done by a CNC machine.
  1731. *ATTRIBUTES*
  1732. * ``gcode_parsed`` (list): Each is a dictionary:
  1733. ===================== =========================================
  1734. Key Value
  1735. ===================== =========================================
  1736. geom (Shapely.LineString) Tool path (XY plane)
  1737. kind (string) "AB", A is "T" (travel) or
  1738. "C" (cut). B is "F" (fast) or "S" (slow).
  1739. ===================== =========================================
  1740. """
  1741. defaults = {
  1742. "global_zdownrate": None,
  1743. "pp_geometry_name":'default',
  1744. "pp_excellon_name":'default',
  1745. "excellon_optimization_type": "B",
  1746. }
  1747. settings = QtCore.QSettings("Open Source", "FlatCAM")
  1748. if settings.contains("machinist"):
  1749. machinist_setting = settings.value('machinist', type=int)
  1750. else:
  1751. machinist_setting = 0
  1752. def __init__(self,
  1753. units="in", kind="generic", tooldia=0.0,
  1754. z_cut=-0.002, z_move=0.1,
  1755. feedrate=3.0, feedrate_z=3.0, feedrate_rapid=3.0, feedrate_probe=3.0,
  1756. pp_geometry_name='default', pp_excellon_name='default',
  1757. depthpercut=0.1,z_pdepth=-0.02,
  1758. spindlespeed=None, spindledir='CW', dwell=True, dwelltime=1000,
  1759. toolchangez=0.787402, toolchange_xy=[0.0, 0.0],
  1760. endz=2.0,
  1761. segx=None,
  1762. segy=None,
  1763. steps_per_circle=None):
  1764. # Used when parsing G-code arcs
  1765. self.steps_per_circle = int(self.app.defaults['cncjob_steps_per_circle'])
  1766. Geometry.__init__(self, geo_steps_per_circle=self.steps_per_circle)
  1767. self.kind = kind
  1768. self.origin_kind = None
  1769. self.units = units
  1770. self.z_cut = z_cut
  1771. self.tool_offset = {}
  1772. self.z_move = z_move
  1773. self.feedrate = feedrate
  1774. self.z_feedrate = feedrate_z
  1775. self.feedrate_rapid = feedrate_rapid
  1776. self.tooldia = tooldia
  1777. self.z_toolchange = toolchangez
  1778. self.xy_toolchange = toolchange_xy
  1779. self.toolchange_xy_type = None
  1780. self.toolC = tooldia
  1781. self.z_end = endz
  1782. self.z_depthpercut = depthpercut
  1783. self.unitcode = {"IN": "G20", "MM": "G21"}
  1784. self.feedminutecode = "G94"
  1785. # self.absolutecode = "G90"
  1786. # self.incrementalcode = "G91"
  1787. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  1788. self.gcode = ""
  1789. self.gcode_parsed = None
  1790. self.pp_geometry_name = pp_geometry_name
  1791. self.pp_geometry = self.app.postprocessors[self.pp_geometry_name]
  1792. self.pp_excellon_name = pp_excellon_name
  1793. self.pp_excellon = self.app.postprocessors[self.pp_excellon_name]
  1794. self.pp_solderpaste_name = None
  1795. # Controls if the move from Z_Toolchange to Z_Move is done fast with G0 or normally with G1
  1796. self.f_plunge = None
  1797. # Controls if the move from Z_Cutto Z_Move is done fast with G0 or G1 until zero and then G0 to Z_move
  1798. self.f_retract = None
  1799. # how much depth the probe can probe before error
  1800. self.z_pdepth = z_pdepth if z_pdepth else None
  1801. # the feedrate(speed) with which the probel travel while probing
  1802. self.feedrate_probe = feedrate_probe if feedrate_probe else None
  1803. self.spindlespeed = spindlespeed
  1804. self.spindledir = spindledir
  1805. self.dwell = dwell
  1806. self.dwelltime = dwelltime
  1807. self.segx = float(segx) if segx is not None else 0.0
  1808. self.segy = float(segy) if segy is not None else 0.0
  1809. self.input_geometry_bounds = None
  1810. self.oldx = None
  1811. self.oldy = None
  1812. self.tool = 0.0
  1813. # here store the travelled distance
  1814. self.travel_distance = 0.0
  1815. # here store the routing time
  1816. self.routing_time = 0.0
  1817. # used for creating drill CCode geometry; will be updated in the generate_from_excellon_by_tool()
  1818. self.exc_drills = None
  1819. self.exc_tools = None
  1820. # search for toolchange parameters in the Toolchange Custom Code
  1821. self.re_toolchange_custom = re.compile(r'(%[a-zA-Z0-9\-_]+%)')
  1822. # search for toolchange code: M6
  1823. self.re_toolchange = re.compile(r'^\s*(M6)$')
  1824. # Attributes to be included in serialization
  1825. # Always append to it because it carries contents
  1826. # from Geometry.
  1827. self.ser_attrs += ['kind', 'z_cut', 'z_move', 'z_toolchange', 'feedrate', 'z_feedrate', 'feedrate_rapid',
  1828. 'tooldia', 'gcode', 'input_geometry_bounds', 'gcode_parsed', 'steps_per_circle',
  1829. 'z_depthpercut', 'spindlespeed', 'dwell', 'dwelltime']
  1830. @property
  1831. def postdata(self):
  1832. return self.__dict__
  1833. def convert_units(self, units):
  1834. log.debug("camlib.CNCJob.convert_units()")
  1835. factor = Geometry.convert_units(self, units)
  1836. self.z_cut = float(self.z_cut) * factor
  1837. self.z_move *= factor
  1838. self.feedrate *= factor
  1839. self.z_feedrate *= factor
  1840. self.feedrate_rapid *= factor
  1841. self.tooldia *= factor
  1842. self.z_toolchange *= factor
  1843. self.z_end *= factor
  1844. self.z_depthpercut = float(self.z_depthpercut) * factor
  1845. return factor
  1846. def doformat(self, fun, **kwargs):
  1847. return self.doformat2(fun, **kwargs) + "\n"
  1848. def doformat2(self, fun, **kwargs):
  1849. attributes = AttrDict()
  1850. attributes.update(self.postdata)
  1851. attributes.update(kwargs)
  1852. try:
  1853. returnvalue = fun(attributes)
  1854. return returnvalue
  1855. except Exception:
  1856. self.app.log.error('Exception occurred within a postprocessor: ' + traceback.format_exc())
  1857. return ''
  1858. def parse_custom_toolchange_code(self, data):
  1859. text = data
  1860. match_list = self.re_toolchange_custom.findall(text)
  1861. if match_list:
  1862. for match in match_list:
  1863. command = match.strip('%')
  1864. try:
  1865. value = getattr(self, command)
  1866. except AttributeError:
  1867. self.app.inform.emit('[ERROR] %s: %s' %
  1868. (_("There is no such parameter"), str(match)))
  1869. log.debug("CNCJob.parse_custom_toolchange_code() --> AttributeError ")
  1870. return 'fail'
  1871. text = text.replace(match, str(value))
  1872. return text
  1873. def optimized_travelling_salesman(self, points, start=None):
  1874. """
  1875. As solving the problem in the brute force way is too slow,
  1876. this function implements a simple heuristic: always
  1877. go to the nearest city.
  1878. Even if this algorithm is extremely simple, it works pretty well
  1879. giving a solution only about 25%% longer than the optimal one (cit. Wikipedia),
  1880. and runs very fast in O(N^2) time complexity.
  1881. >>> optimized_travelling_salesman([[i,j] for i in range(5) for j in range(5)])
  1882. [[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],
  1883. [2, 3], [2, 4], [3, 4], [3, 3], [3, 2], [3, 1], [3, 0], [4, 0], [4, 1], [4, 2], [4, 3], [4, 4]]
  1884. >>> optimized_travelling_salesman([[0,0],[10,0],[6,0]])
  1885. [[0, 0], [6, 0], [10, 0]]
  1886. """
  1887. if start is None:
  1888. start = points[0]
  1889. must_visit = points
  1890. path = [start]
  1891. # must_visit.remove(start)
  1892. while must_visit:
  1893. nearest = min(must_visit, key=lambda x: distance(path[-1], x))
  1894. path.append(nearest)
  1895. must_visit.remove(nearest)
  1896. return path
  1897. def generate_from_excellon_by_tool(
  1898. self, exobj, tools="all", drillz = 3.0,
  1899. toolchange=False, toolchangez=0.1, toolchangexy='',
  1900. endz=2.0, startz=None,
  1901. excellon_optimization_type='B'):
  1902. """
  1903. Creates gcode for this object from an Excellon object
  1904. for the specified tools.
  1905. :param exobj: Excellon object to process
  1906. :type exobj: Excellon
  1907. :param tools: Comma separated tool names
  1908. :type: tools: str
  1909. :param drillz: drill Z depth
  1910. :type drillz: float
  1911. :param toolchange: Use tool change sequence between tools.
  1912. :type toolchange: bool
  1913. :param toolchangez: Height at which to perform the tool change.
  1914. :type toolchangez: float
  1915. :param toolchangexy: Toolchange X,Y position
  1916. :type toolchangexy: String containing 2 floats separated by comma
  1917. :param startz: Z position just before starting the job
  1918. :type startz: float
  1919. :param endz: final Z position to move to at the end of the CNC job
  1920. :type endz: float
  1921. :param excellon_optimization_type: Single character that defines which drill re-ordering optimisation algorithm
  1922. is to be used: 'M' for meta-heuristic and 'B' for basic
  1923. :type excellon_optimization_type: string
  1924. :return: None
  1925. :rtype: None
  1926. """
  1927. # create a local copy of the exobj.drills so it can be used for creating drill CCode geometry
  1928. self.exc_drills = deepcopy(exobj.drills)
  1929. self.exc_tools = deepcopy(exobj.tools)
  1930. self.z_cut = drillz
  1931. if self.machinist_setting == 0:
  1932. if drillz > 0:
  1933. self.app.inform.emit('[WARNING] %s' %
  1934. _("The Cut Z parameter has positive value. "
  1935. "It is the depth value to drill into material.\n"
  1936. "The Cut Z parameter needs to have a negative value, assuming it is a typo "
  1937. "therefore the app will convert the value to negative. "
  1938. "Check the resulting CNC code (Gcode etc)."))
  1939. self.z_cut = -drillz
  1940. elif drillz == 0:
  1941. self.app.inform.emit('[WARNING] %s: %s' %
  1942. (_("The Cut Z parameter is zero. There will be no cut, skipping file"),
  1943. exobj.options['name']))
  1944. return 'fail'
  1945. self.z_toolchange = toolchangez
  1946. try:
  1947. if toolchangexy == '':
  1948. self.xy_toolchange = None
  1949. else:
  1950. self.xy_toolchange = [float(eval(a)) for a in toolchangexy.split(",")]
  1951. if len(self.xy_toolchange) < 2:
  1952. self.app.inform.emit('[ERROR]%s' %
  1953. _("The Toolchange X,Y field in Edit -> Preferences has to be "
  1954. "in the format (x, y) \nbut now there is only one value, not two. "))
  1955. return 'fail'
  1956. except Exception as e:
  1957. log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> %s" % str(e))
  1958. pass
  1959. self.startz = startz
  1960. self.z_end = endz
  1961. self.pp_excellon = self.app.postprocessors[self.pp_excellon_name]
  1962. p = self.pp_excellon
  1963. log.debug("Creating CNC Job from Excellon...")
  1964. # Tools
  1965. # sort the tools list by the second item in tuple (here we have a dict with diameter of the tool)
  1966. # so we actually are sorting the tools by diameter
  1967. #sorted_tools = sorted(exobj.tools.items(), key=lambda t1: t1['C'])
  1968. sort = []
  1969. for k, v in list(exobj.tools.items()):
  1970. sort.append((k, v.get('C')))
  1971. sorted_tools = sorted(sort,key=lambda t1: t1[1])
  1972. if tools == "all":
  1973. tools = [i[0] for i in sorted_tools] # we get a array of ordered tools
  1974. log.debug("Tools 'all' and sorted are: %s" % str(tools))
  1975. else:
  1976. selected_tools = [x.strip() for x in tools.split(",")] # we strip spaces and also separate the tools by ','
  1977. selected_tools = [t1 for t1 in selected_tools if t1 in selected_tools]
  1978. # Create a sorted list of selected tools from the sorted_tools list
  1979. tools = [i for i, j in sorted_tools for k in selected_tools if i == k]
  1980. log.debug("Tools selected and sorted are: %s" % str(tools))
  1981. self.app.inform.emit(_("Creating a list of points to drill..."))
  1982. # Points (Group by tool)
  1983. points = {}
  1984. for drill in exobj.drills:
  1985. if self.app.abort_flag:
  1986. # graceful abort requested by the user
  1987. raise FlatCAMApp.GracefulException
  1988. if drill['tool'] in tools:
  1989. try:
  1990. points[drill['tool']].append(drill['point'])
  1991. except KeyError:
  1992. points[drill['tool']] = [drill['point']]
  1993. # log.debug("Found %d drills." % len(points))
  1994. self.gcode = []
  1995. self.f_plunge = self.app.defaults["excellon_f_plunge"]
  1996. self.f_retract = self.app.defaults["excellon_f_retract"]
  1997. # Initialization
  1998. gcode = self.doformat(p.start_code)
  1999. gcode += self.doformat(p.feedrate_code)
  2000. if toolchange is False:
  2001. if self.xy_toolchange is not None:
  2002. gcode += self.doformat(p.lift_code, x=self.xy_toolchange[0], y=self.xy_toolchange[1])
  2003. gcode += self.doformat(p.startz_code, x=self.xy_toolchange[0], y=self.xy_toolchange[1])
  2004. else:
  2005. gcode += self.doformat(p.lift_code, x=0.0, y=0.0)
  2006. gcode += self.doformat(p.startz_code, x=0.0, y=0.0)
  2007. # Distance callback
  2008. class CreateDistanceCallback(object):
  2009. """Create callback to calculate distances between points."""
  2010. def __init__(self):
  2011. """Initialize distance array."""
  2012. locations = create_data_array()
  2013. size = len(locations)
  2014. self.matrix = {}
  2015. for from_node in range(size):
  2016. self.matrix[from_node] = {}
  2017. for to_node in range(size):
  2018. if from_node == to_node:
  2019. self.matrix[from_node][to_node] = 0
  2020. else:
  2021. x1 = locations[from_node][0]
  2022. y1 = locations[from_node][1]
  2023. x2 = locations[to_node][0]
  2024. y2 = locations[to_node][1]
  2025. self.matrix[from_node][to_node] = distance_euclidian(x1, y1, x2, y2)
  2026. # def Distance(self, from_node, to_node):
  2027. # return int(self.matrix[from_node][to_node])
  2028. def Distance(self, from_index, to_index):
  2029. # Convert from routing variable Index to distance matrix NodeIndex.
  2030. from_node = manager.IndexToNode(from_index)
  2031. to_node = manager.IndexToNode(to_index)
  2032. return self.matrix[from_node][to_node]
  2033. # Create the data.
  2034. def create_data_array():
  2035. locations = []
  2036. for point in points[tool]:
  2037. locations.append((point.coords.xy[0][0], point.coords.xy[1][0]))
  2038. return locations
  2039. if self.xy_toolchange is not None:
  2040. self.oldx = self.xy_toolchange[0]
  2041. self.oldy = self.xy_toolchange[1]
  2042. else:
  2043. self.oldx = 0.0
  2044. self.oldy = 0.0
  2045. measured_distance = 0.0
  2046. measured_down_distance = 0.0
  2047. measured_up_to_zero_distance = 0.0
  2048. measured_lift_distance = 0.0
  2049. self.app.inform.emit('%s...' % _("Starting G-Code"))
  2050. current_platform = platform.architecture()[0]
  2051. if current_platform == '64bit':
  2052. used_excellon_optimization_type = excellon_optimization_type
  2053. if used_excellon_optimization_type == 'M':
  2054. log.debug("Using OR-Tools Metaheuristic Guided Local Search drill path optimization.")
  2055. if exobj.drills:
  2056. for tool in tools:
  2057. self.tool=tool
  2058. self.postdata['toolC'] = exobj.tools[tool]["C"]
  2059. self.tooldia = exobj.tools[tool]["C"]
  2060. if self.app.abort_flag:
  2061. # graceful abort requested by the user
  2062. raise FlatCAMApp.GracefulException
  2063. # ###############################################
  2064. # ############ Create the data. #################
  2065. # ###############################################
  2066. node_list = []
  2067. locations = create_data_array()
  2068. tsp_size = len(locations)
  2069. num_routes = 1 # The number of routes, which is 1 in the TSP.
  2070. # Nodes are indexed from 0 to tsp_size - 1. The depot is the starting node of the route.
  2071. depot = 0
  2072. # Create routing model.
  2073. if tsp_size > 0:
  2074. manager = pywrapcp.RoutingIndexManager(tsp_size, num_routes, depot)
  2075. routing = pywrapcp.RoutingModel(manager)
  2076. search_parameters = pywrapcp.DefaultRoutingSearchParameters()
  2077. search_parameters.local_search_metaheuristic = (
  2078. routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH)
  2079. # Set search time limit in milliseconds.
  2080. if float(self.app.defaults["excellon_search_time"]) != 0:
  2081. search_parameters.time_limit.seconds = int(
  2082. float(self.app.defaults["excellon_search_time"]))
  2083. else:
  2084. search_parameters.time_limit.seconds = 3
  2085. # Callback to the distance function. The callback takes two
  2086. # arguments (the from and to node indices) and returns the distance between them.
  2087. dist_between_locations = CreateDistanceCallback()
  2088. dist_callback = dist_between_locations.Distance
  2089. transit_callback_index = routing.RegisterTransitCallback(dist_callback)
  2090. routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)
  2091. # Solve, returns a solution if any.
  2092. assignment = routing.SolveWithParameters(search_parameters)
  2093. if assignment:
  2094. # Solution cost.
  2095. log.info("Total distance: " + str(assignment.ObjectiveValue()))
  2096. # Inspect solution.
  2097. # Only one route here; otherwise iterate from 0 to routing.vehicles() - 1.
  2098. route_number = 0
  2099. node = routing.Start(route_number)
  2100. start_node = node
  2101. while not routing.IsEnd(node):
  2102. if self.app.abort_flag:
  2103. # graceful abort requested by the user
  2104. raise FlatCAMApp.GracefulException
  2105. node_list.append(node)
  2106. node = assignment.Value(routing.NextVar(node))
  2107. else:
  2108. log.warning('No solution found.')
  2109. else:
  2110. log.warning('Specify an instance greater than 0.')
  2111. # ############################################# ##
  2112. # Only if tool has points.
  2113. if tool in points:
  2114. if self.app.abort_flag:
  2115. # graceful abort requested by the user
  2116. raise FlatCAMApp.GracefulException
  2117. # Tool change sequence (optional)
  2118. if toolchange:
  2119. gcode += self.doformat(p.toolchange_code,toolchangexy=(self.oldx, self.oldy))
  2120. gcode += self.doformat(p.spindle_code) # Spindle start
  2121. if self.dwell is True:
  2122. gcode += self.doformat(p.dwell_code) # Dwell time
  2123. else:
  2124. gcode += self.doformat(p.spindle_code)
  2125. if self.dwell is True:
  2126. gcode += self.doformat(p.dwell_code) # Dwell time
  2127. if self.units == 'MM':
  2128. current_tooldia = float('%.2f' % float(exobj.tools[tool]["C"]))
  2129. else:
  2130. current_tooldia = float('%.4f' % float(exobj.tools[tool]["C"]))
  2131. self.app.inform.emit(
  2132. '%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  2133. str(current_tooldia),
  2134. str(self.units))
  2135. )
  2136. # TODO apply offset only when using the GUI, for TclCommand this will create an error
  2137. # because the values for Z offset are created in build_ui()
  2138. try:
  2139. z_offset = float(self.tool_offset[current_tooldia]) * (-1)
  2140. except KeyError:
  2141. z_offset = 0
  2142. self.z_cut += z_offset
  2143. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  2144. if self.coordinates_type == "G90":
  2145. # Drillling! for Absolute coordinates type G90
  2146. # variables to display the percentage of work done
  2147. geo_len = len(node_list)
  2148. old_disp_number = 0
  2149. log.warning("Number of drills for which to generate GCode: %s" % str(geo_len))
  2150. loc_nr = 0
  2151. for k in node_list:
  2152. if self.app.abort_flag:
  2153. # graceful abort requested by the user
  2154. raise FlatCAMApp.GracefulException
  2155. locx = locations[k][0]
  2156. locy = locations[k][1]
  2157. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  2158. gcode += self.doformat(p.down_code, x=locx, y=locy)
  2159. measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  2160. if self.f_retract is False:
  2161. gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  2162. measured_up_to_zero_distance += abs(self.z_cut)
  2163. measured_lift_distance += abs(self.z_move)
  2164. else:
  2165. measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  2166. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  2167. measured_distance += abs(distance_euclidian(locx, locy, self.oldx, self.oldy))
  2168. self.oldx = locx
  2169. self.oldy = locy
  2170. loc_nr += 1
  2171. disp_number = int(np.interp(loc_nr, [0, geo_len], [0, 100]))
  2172. if old_disp_number < disp_number <= 100:
  2173. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  2174. old_disp_number = disp_number
  2175. else:
  2176. self.app.inform.emit('[ERROR_NOTCL] %s...' % _('G91 coordinates not implemented'))
  2177. return 'fail'
  2178. else:
  2179. log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> "
  2180. "The loaded Excellon file has no drills ...")
  2181. self.app.inform.emit('[ERROR_NOTCL] %s...' %
  2182. _('The loaded Excellon file has no drills'))
  2183. return 'fail'
  2184. log.debug("The total travel distance with OR-TOOLS Metaheuristics is: %s" % str(measured_distance))
  2185. if used_excellon_optimization_type == 'B':
  2186. log.debug("Using OR-Tools Basic drill path optimization.")
  2187. if exobj.drills:
  2188. for tool in tools:
  2189. if self.app.abort_flag:
  2190. # graceful abort requested by the user
  2191. raise FlatCAMApp.GracefulException
  2192. self.tool=tool
  2193. self.postdata['toolC']=exobj.tools[tool]["C"]
  2194. self.tooldia = exobj.tools[tool]["C"]
  2195. # ############################################# ##
  2196. node_list = []
  2197. locations = create_data_array()
  2198. tsp_size = len(locations)
  2199. num_routes = 1 # The number of routes, which is 1 in the TSP.
  2200. # Nodes are indexed from 0 to tsp_size - 1. The depot is the starting node of the route.
  2201. depot = 0
  2202. # Create routing model.
  2203. if tsp_size > 0:
  2204. manager = pywrapcp.RoutingIndexManager(tsp_size, num_routes, depot)
  2205. routing = pywrapcp.RoutingModel(manager)
  2206. search_parameters = pywrapcp.DefaultRoutingSearchParameters()
  2207. # Callback to the distance function. The callback takes two
  2208. # arguments (the from and to node indices) and returns the distance between them.
  2209. dist_between_locations = CreateDistanceCallback()
  2210. dist_callback = dist_between_locations.Distance
  2211. transit_callback_index = routing.RegisterTransitCallback(dist_callback)
  2212. routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)
  2213. # Solve, returns a solution if any.
  2214. assignment = routing.SolveWithParameters(search_parameters)
  2215. if assignment:
  2216. # Solution cost.
  2217. log.info("Total distance: " + str(assignment.ObjectiveValue()))
  2218. # Inspect solution.
  2219. # Only one route here; otherwise iterate from 0 to routing.vehicles() - 1.
  2220. route_number = 0
  2221. node = routing.Start(route_number)
  2222. start_node = node
  2223. while not routing.IsEnd(node):
  2224. node_list.append(node)
  2225. node = assignment.Value(routing.NextVar(node))
  2226. else:
  2227. log.warning('No solution found.')
  2228. else:
  2229. log.warning('Specify an instance greater than 0.')
  2230. # ############################################# ##
  2231. # Only if tool has points.
  2232. if tool in points:
  2233. if self.app.abort_flag:
  2234. # graceful abort requested by the user
  2235. raise FlatCAMApp.GracefulException
  2236. # Tool change sequence (optional)
  2237. if toolchange:
  2238. gcode += self.doformat(p.toolchange_code,toolchangexy=(self.oldx, self.oldy))
  2239. gcode += self.doformat(p.spindle_code) # Spindle start)
  2240. if self.dwell is True:
  2241. gcode += self.doformat(p.dwell_code) # Dwell time
  2242. else:
  2243. gcode += self.doformat(p.spindle_code)
  2244. if self.dwell is True:
  2245. gcode += self.doformat(p.dwell_code) # Dwell time
  2246. if self.units == 'MM':
  2247. current_tooldia = float('%.2f' % float(exobj.tools[tool]["C"]))
  2248. else:
  2249. current_tooldia = float('%.4f' % float(exobj.tools[tool]["C"]))
  2250. self.app.inform.emit(
  2251. '%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  2252. str(current_tooldia),
  2253. str(self.units))
  2254. )
  2255. # TODO apply offset only when using the GUI, for TclCommand this will create an error
  2256. # because the values for Z offset are created in build_ui()
  2257. try:
  2258. z_offset = float(self.tool_offset[current_tooldia]) * (-1)
  2259. except KeyError:
  2260. z_offset = 0
  2261. self.z_cut += z_offset
  2262. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  2263. if self.coordinates_type == "G90":
  2264. # Drillling! for Absolute coordinates type G90
  2265. # variables to display the percentage of work done
  2266. geo_len = len(node_list)
  2267. disp_number = 0
  2268. old_disp_number = 0
  2269. log.warning("Number of drills for which to generate GCode: %s" % str(geo_len))
  2270. loc_nr = 0
  2271. for k in node_list:
  2272. if self.app.abort_flag:
  2273. # graceful abort requested by the user
  2274. raise FlatCAMApp.GracefulException
  2275. locx = locations[k][0]
  2276. locy = locations[k][1]
  2277. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  2278. gcode += self.doformat(p.down_code, x=locx, y=locy)
  2279. measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  2280. if self.f_retract is False:
  2281. gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  2282. measured_up_to_zero_distance += abs(self.z_cut)
  2283. measured_lift_distance += abs(self.z_move)
  2284. else:
  2285. measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  2286. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  2287. measured_distance += abs(distance_euclidian(locx, locy, self.oldx, self.oldy))
  2288. self.oldx = locx
  2289. self.oldy = locy
  2290. loc_nr += 1
  2291. disp_number = int(np.interp(loc_nr, [0, geo_len], [0, 100]))
  2292. if old_disp_number < disp_number <= 100:
  2293. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  2294. old_disp_number = disp_number
  2295. else:
  2296. self.app.inform.emit('[ERROR_NOTCL] %s...' % _('G91 coordinates not implemented'))
  2297. return 'fail'
  2298. else:
  2299. log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> "
  2300. "The loaded Excellon file has no drills ...")
  2301. self.app.inform.emit('[ERROR_NOTCL] %s...' %
  2302. _('The loaded Excellon file has no drills'))
  2303. return 'fail'
  2304. log.debug("The total travel distance with OR-TOOLS Basic Algorithm is: %s" % str(measured_distance))
  2305. else:
  2306. used_excellon_optimization_type = 'T'
  2307. if used_excellon_optimization_type == 'T':
  2308. log.debug("Using Travelling Salesman drill path optimization.")
  2309. for tool in tools:
  2310. if self.app.abort_flag:
  2311. # graceful abort requested by the user
  2312. raise FlatCAMApp.GracefulException
  2313. if exobj.drills:
  2314. self.tool = tool
  2315. self.postdata['toolC'] = exobj.tools[tool]["C"]
  2316. self.tooldia = exobj.tools[tool]["C"]
  2317. # Only if tool has points.
  2318. if tool in points:
  2319. if self.app.abort_flag:
  2320. # graceful abort requested by the user
  2321. raise FlatCAMApp.GracefulException
  2322. # Tool change sequence (optional)
  2323. if toolchange:
  2324. gcode += self.doformat(p.toolchange_code, toolchangexy=(self.oldx, self.oldy))
  2325. gcode += self.doformat(p.spindle_code) # Spindle start)
  2326. if self.dwell is True:
  2327. gcode += self.doformat(p.dwell_code) # Dwell time
  2328. else:
  2329. gcode += self.doformat(p.spindle_code)
  2330. if self.dwell is True:
  2331. gcode += self.doformat(p.dwell_code) # Dwell time
  2332. if self.units == 'MM':
  2333. current_tooldia = float('%.2f' % float(exobj.tools[tool]["C"]))
  2334. else:
  2335. current_tooldia = float('%.4f' % float(exobj.tools[tool]["C"]))
  2336. self.app.inform.emit(
  2337. '%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  2338. str(current_tooldia),
  2339. str(self.units))
  2340. )
  2341. # TODO apply offset only when using the GUI, for TclCommand this will create an error
  2342. # because the values for Z offset are created in build_ui()
  2343. try:
  2344. z_offset = float(self.tool_offset[current_tooldia]) * (-1)
  2345. except KeyError:
  2346. z_offset = 0
  2347. self.z_cut += z_offset
  2348. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  2349. if self.coordinates_type == "G90":
  2350. # Drillling! for Absolute coordinates type G90
  2351. altPoints = []
  2352. for point in points[tool]:
  2353. altPoints.append((point.coords.xy[0][0], point.coords.xy[1][0]))
  2354. node_list = self.optimized_travelling_salesman(altPoints)
  2355. # variables to display the percentage of work done
  2356. geo_len = len(node_list)
  2357. disp_number = 0
  2358. old_disp_number = 0
  2359. log.warning("Number of drills for which to generate GCode: %s" % str(geo_len))
  2360. loc_nr = 0
  2361. for point in node_list:
  2362. if self.app.abort_flag:
  2363. # graceful abort requested by the user
  2364. raise FlatCAMApp.GracefulException
  2365. gcode += self.doformat(p.rapid_code, x=point[0], y=point[1])
  2366. gcode += self.doformat(p.down_code, x=point[0], y=point[1])
  2367. measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  2368. if self.f_retract is False:
  2369. gcode += self.doformat(p.up_to_zero_code, x=point[0], y=point[1])
  2370. measured_up_to_zero_distance += abs(self.z_cut)
  2371. measured_lift_distance += abs(self.z_move)
  2372. else:
  2373. measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  2374. gcode += self.doformat(p.lift_code, x=point[0], y=point[1])
  2375. measured_distance += abs(distance_euclidian(point[0], point[1], self.oldx, self.oldy))
  2376. self.oldx = point[0]
  2377. self.oldy = point[1]
  2378. loc_nr += 1
  2379. disp_number = int(np.interp(loc_nr, [0, geo_len], [0, 100]))
  2380. if old_disp_number < disp_number <= 100:
  2381. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  2382. old_disp_number = disp_number
  2383. else:
  2384. self.app.inform.emit('[ERROR_NOTCL] %s...' % _('G91 coordinates not implemented'))
  2385. return 'fail'
  2386. else:
  2387. log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> "
  2388. "The loaded Excellon file has no drills ...")
  2389. self.app.inform.emit('[ERROR_NOTCL] %s...' %
  2390. _('The loaded Excellon file has no drills'))
  2391. return 'fail'
  2392. log.debug("The total travel distance with Travelling Salesman Algorithm is: %s" % str(measured_distance))
  2393. gcode += self.doformat(p.spindle_stop_code) # Spindle stop
  2394. gcode += self.doformat(p.end_code, x=0, y=0)
  2395. measured_distance += abs(distance_euclidian(self.oldx, self.oldy, 0, 0))
  2396. log.debug("The total travel distance including travel to end position is: %s" %
  2397. str(measured_distance) + '\n')
  2398. self.travel_distance = measured_distance
  2399. # I use the value of self.feedrate_rapid for the feadrate in case of the measure_lift_distance and for
  2400. # traveled_time because it is not always possible to determine the feedrate that the CNC machine uses
  2401. # for G0 move (the fastest speed available to the CNC router). Although self.feedrate_rapids is used only with
  2402. # Marlin postprocessor and derivatives.
  2403. self.routing_time = (measured_down_distance + measured_up_to_zero_distance) / self.feedrate
  2404. lift_time = measured_lift_distance / self.feedrate_rapid
  2405. traveled_time = measured_distance / self.feedrate_rapid
  2406. self.routing_time += lift_time + traveled_time
  2407. self.gcode = gcode
  2408. self.app.inform.emit(_("Finished G-Code generation..."))
  2409. return 'OK'
  2410. def generate_from_multitool_geometry(
  2411. self, geometry, append=True,
  2412. tooldia=None, offset=0.0, tolerance=0, z_cut=1.0, z_move=2.0,
  2413. feedrate=2.0, feedrate_z=2.0, feedrate_rapid=30,
  2414. spindlespeed=None, spindledir='CW', dwell=False, dwelltime=1.0,
  2415. multidepth=False, depthpercut=None,
  2416. toolchange=False, toolchangez=1.0, toolchangexy="0.0, 0.0", extracut=False,
  2417. startz=None, endz=2.0, pp_geometry_name=None, tool_no=1):
  2418. """
  2419. Algorithm to generate from multitool Geometry.
  2420. Algorithm description:
  2421. ----------------------
  2422. Uses RTree to find the nearest path to follow.
  2423. :param geometry:
  2424. :param append:
  2425. :param tooldia:
  2426. :param offset:
  2427. :param tolerance:
  2428. :param z_cut:
  2429. :param z_move:
  2430. :param feedrate:
  2431. :param feedrate_z:
  2432. :param feedrate_rapid:
  2433. :param spindlespeed:
  2434. :param spindledir:
  2435. :param dwell:
  2436. :param dwelltime:
  2437. :param multidepth: If True, use multiple passes to reach the desired depth.
  2438. :param depthpercut: Maximum depth in each pass.
  2439. :param toolchange:
  2440. :param toolchangez:
  2441. :param toolchangexy:
  2442. :param extracut: Adds (or not) an extra cut at the end of each path overlapping the
  2443. first point in path to ensure complete copper removal
  2444. :param startz:
  2445. :param endz:
  2446. :param pp_geometry_name:
  2447. :param tool_no:
  2448. :return: GCode - string
  2449. """
  2450. log.debug("Generate_from_multitool_geometry()")
  2451. temp_solid_geometry = []
  2452. if offset != 0.0:
  2453. for it in geometry:
  2454. # if the geometry is a closed shape then create a Polygon out of it
  2455. if isinstance(it, LineString):
  2456. c = it.coords
  2457. if c[0] == c[-1]:
  2458. it = Polygon(it)
  2459. temp_solid_geometry.append(it.buffer(offset, join_style=2))
  2460. else:
  2461. temp_solid_geometry = geometry
  2462. # ## Flatten the geometry. Only linear elements (no polygons) remain.
  2463. flat_geometry = self.flatten(temp_solid_geometry, pathonly=True)
  2464. log.debug("%d paths" % len(flat_geometry))
  2465. self.tooldia = float(tooldia) if tooldia else None
  2466. self.z_cut = float(z_cut) if z_cut else None
  2467. self.z_move = float(z_move) if z_move is not None else None
  2468. self.feedrate = float(feedrate) if feedrate else None
  2469. self.z_feedrate = float(feedrate_z) if feedrate_z is not None else None
  2470. self.feedrate_rapid = float(feedrate_rapid) if feedrate_rapid else None
  2471. self.spindlespeed = int(spindlespeed) if spindlespeed else None
  2472. self.spindledir = spindledir
  2473. self.dwell = dwell
  2474. self.dwelltime = float(dwelltime) if dwelltime else None
  2475. self.startz = float(startz) if startz is not None else None
  2476. self.z_end = float(endz) if endz is not None else None
  2477. self.z_depthpercut = float(depthpercut) if depthpercut else None
  2478. self.multidepth = multidepth
  2479. self.z_toolchange = float(toolchangez) if toolchangez is not None else None
  2480. # it servers in the postprocessor file
  2481. self.tool = tool_no
  2482. try:
  2483. if toolchangexy == '':
  2484. self.xy_toolchange = None
  2485. else:
  2486. self.xy_toolchange = [float(eval(a)) for a in toolchangexy.split(",")]
  2487. if len(self.xy_toolchange) < 2:
  2488. self.app.inform.emit('[ERROR] %s' % _("The Toolchange X,Y field in Edit -> Preferences has to be "
  2489. "in the format (x, y) \n"
  2490. "but now there is only one value, not two."))
  2491. return 'fail'
  2492. except Exception as e:
  2493. log.debug("camlib.CNCJob.generate_from_multitool_geometry() --> %s" % str(e))
  2494. pass
  2495. self.pp_geometry_name = pp_geometry_name if pp_geometry_name else 'default'
  2496. self.f_plunge = self.app.defaults["geometry_f_plunge"]
  2497. if self.z_cut is None:
  2498. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2499. _("Cut_Z parameter is None or zero. Most likely a bad combinations of "
  2500. "other parameters."))
  2501. return 'fail'
  2502. if self.machinist_setting == 0:
  2503. if self.z_cut > 0:
  2504. self.app.inform.emit('[WARNING] %s' %
  2505. _("The Cut Z parameter has positive value. "
  2506. "It is the depth value to cut into material.\n"
  2507. "The Cut Z parameter needs to have a negative value, assuming it is a typo "
  2508. "therefore the app will convert the value to negative."
  2509. "Check the resulting CNC code (Gcode etc)."))
  2510. self.z_cut = -self.z_cut
  2511. elif self.z_cut == 0:
  2512. self.app.inform.emit('[WARNING] %s: %s' %
  2513. (_("The Cut Z parameter is zero. There will be no cut, skipping file"),
  2514. self.options['name']))
  2515. return 'fail'
  2516. if self.z_move is None:
  2517. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Travel Z parameter is None or zero."))
  2518. return 'fail'
  2519. if self.z_move < 0:
  2520. self.app.inform.emit('[WARNING] %s' %
  2521. _("The Travel Z parameter has negative value. "
  2522. "It is the height value to travel between cuts.\n"
  2523. "The Z Travel parameter needs to have a positive value, assuming it is a typo "
  2524. "therefore the app will convert the value to positive."
  2525. "Check the resulting CNC code (Gcode etc)."))
  2526. self.z_move = -self.z_move
  2527. elif self.z_move == 0:
  2528. self.app.inform.emit('[WARNING] %s: %s' %
  2529. (_("The Z Travel parameter is zero. This is dangerous, skipping file"),
  2530. self.options['name']))
  2531. return 'fail'
  2532. # made sure that depth_per_cut is no more then the z_cut
  2533. if abs(self.z_cut) < self.z_depthpercut:
  2534. self.z_depthpercut = abs(self.z_cut)
  2535. # ## Index first and last points in paths
  2536. # What points to index.
  2537. def get_pts(o):
  2538. return [o.coords[0], o.coords[-1]]
  2539. # Create the indexed storage.
  2540. storage = FlatCAMRTreeStorage()
  2541. storage.get_points = get_pts
  2542. # Store the geometry
  2543. log.debug("Indexing geometry before generating G-Code...")
  2544. self.app.inform.emit(_("Indexing geometry before generating G-Code..."))
  2545. for shape in flat_geometry:
  2546. if self.app.abort_flag:
  2547. # graceful abort requested by the user
  2548. raise FlatCAMApp.GracefulException
  2549. if shape is not None: # TODO: This shouldn't have happened.
  2550. storage.insert(shape)
  2551. # self.input_geometry_bounds = geometry.bounds()
  2552. if not append:
  2553. self.gcode = ""
  2554. # tell postprocessor the number of tool (for toolchange)
  2555. self.tool = tool_no
  2556. # this is the tool diameter, it is used as such to accommodate the postprocessor who need the tool diameter
  2557. # given under the name 'toolC'
  2558. self.postdata['toolC'] = self.tooldia
  2559. # Initial G-Code
  2560. self.pp_geometry = self.app.postprocessors[self.pp_geometry_name]
  2561. p = self.pp_geometry
  2562. self.gcode = self.doformat(p.start_code)
  2563. self.gcode += self.doformat(p.feedrate_code) # sets the feed rate
  2564. if toolchange is False:
  2565. self.gcode += self.doformat(p.lift_code, x=0, y=0) # Move (up) to travel height
  2566. self.gcode += self.doformat(p.startz_code, x=0, y=0)
  2567. if toolchange:
  2568. # if "line_xyz" in self.pp_geometry_name:
  2569. # self.gcode += self.doformat(p.toolchange_code, x=self.xy_toolchange[0], y=self.xy_toolchange[1])
  2570. # else:
  2571. # self.gcode += self.doformat(p.toolchange_code)
  2572. self.gcode += self.doformat(p.toolchange_code)
  2573. if 'laser' not in self.pp_geometry_name:
  2574. self.gcode += self.doformat(p.spindle_code) # Spindle start
  2575. else:
  2576. # for laser this will disable the laser
  2577. self.gcode += self.doformat(p.lift_code, x=self.oldx, y=self.oldy) # Move (up) to travel height
  2578. if self.dwell is True:
  2579. self.gcode += self.doformat(p.dwell_code) # Dwell time
  2580. else:
  2581. if 'laser' not in self.pp_geometry_name:
  2582. self.gcode += self.doformat(p.spindle_code) # Spindle start
  2583. if self.dwell is True:
  2584. self.gcode += self.doformat(p.dwell_code) # Dwell time
  2585. total_travel = 0.0
  2586. total_cut = 0.0
  2587. # ## Iterate over geometry paths getting the nearest each time.
  2588. log.debug("Starting G-Code...")
  2589. self.app.inform.emit(_("Starting G-Code..."))
  2590. path_count = 0
  2591. current_pt = (0, 0)
  2592. # variables to display the percentage of work done
  2593. geo_len = len(flat_geometry)
  2594. old_disp_number = 0
  2595. log.warning("Number of paths for which to generate GCode: %s" % str(geo_len))
  2596. if self.units == 'MM':
  2597. current_tooldia = float('%.2f' % float(self.tooldia))
  2598. else:
  2599. current_tooldia = float('%.4f' % float(self.tooldia))
  2600. self.app.inform.emit( '%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  2601. str(current_tooldia),
  2602. str(self.units)))
  2603. pt, geo = storage.nearest(current_pt)
  2604. try:
  2605. while True:
  2606. if self.app.abort_flag:
  2607. # graceful abort requested by the user
  2608. raise FlatCAMApp.GracefulException
  2609. path_count += 1
  2610. # Remove before modifying, otherwise deletion will fail.
  2611. storage.remove(geo)
  2612. # If last point in geometry is the nearest but prefer the first one if last point == first point
  2613. # then reverse coordinates.
  2614. if pt != geo.coords[0] and pt == geo.coords[-1]:
  2615. geo.coords = list(geo.coords)[::-1]
  2616. # ---------- Single depth/pass --------
  2617. if not multidepth:
  2618. # calculate the cut distance
  2619. total_cut = total_cut + geo.length
  2620. self.gcode += self.create_gcode_single_pass(geo, extracut, tolerance, old_point=current_pt)
  2621. # --------- Multi-pass ---------
  2622. else:
  2623. # calculate the cut distance
  2624. # due of the number of cuts (multi depth) it has to multiplied by the number of cuts
  2625. nr_cuts = 0
  2626. depth = abs(self.z_cut)
  2627. while depth > 0:
  2628. nr_cuts += 1
  2629. depth -= float(self.z_depthpercut)
  2630. total_cut += (geo.length * nr_cuts)
  2631. self.gcode += self.create_gcode_multi_pass(geo, extracut, tolerance,
  2632. postproc=p, old_point=current_pt)
  2633. # calculate the total distance
  2634. total_travel = total_travel + abs(distance(pt1=current_pt, pt2=pt))
  2635. current_pt = geo.coords[-1]
  2636. pt, geo = storage.nearest(current_pt) # Next
  2637. disp_number = int(np.interp(path_count, [0, geo_len], [0, 100]))
  2638. if old_disp_number < disp_number <= 100:
  2639. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  2640. old_disp_number = disp_number
  2641. except StopIteration: # Nothing found in storage.
  2642. pass
  2643. log.debug("Finished G-Code... %s paths traced." % path_count)
  2644. # add move to end position
  2645. total_travel += abs(distance_euclidian(current_pt[0], current_pt[1], 0, 0))
  2646. self.travel_distance += total_travel + total_cut
  2647. self.routing_time += total_cut / self.feedrate
  2648. # Finish
  2649. self.gcode += self.doformat(p.spindle_stop_code)
  2650. self.gcode += self.doformat(p.lift_code, x=current_pt[0], y=current_pt[1])
  2651. self.gcode += self.doformat(p.end_code, x=0, y=0)
  2652. self.app.inform.emit('%s... %s %s.' %
  2653. (_("Finished G-Code generation"),
  2654. str(path_count),
  2655. _("paths traced")
  2656. )
  2657. )
  2658. return self.gcode
  2659. def generate_from_geometry_2(
  2660. self, geometry, append=True,
  2661. tooldia=None, offset=0.0, tolerance=0,
  2662. z_cut=1.0, z_move=2.0,
  2663. feedrate=2.0, feedrate_z=2.0, feedrate_rapid=30,
  2664. spindlespeed=None, spindledir='CW', dwell=False, dwelltime=1.0,
  2665. multidepth=False, depthpercut=None,
  2666. toolchange=False, toolchangez=1.0, toolchangexy="0.0, 0.0",
  2667. extracut=False, startz=None, endz=2.0,
  2668. pp_geometry_name=None, tool_no=1):
  2669. """
  2670. Second algorithm to generate from Geometry.
  2671. Algorithm description:
  2672. ----------------------
  2673. Uses RTree to find the nearest path to follow.
  2674. :param geometry:
  2675. :param append:
  2676. :param tooldia:
  2677. :param tolerance:
  2678. :param multidepth: If True, use multiple passes to reach
  2679. the desired depth.
  2680. :param depthpercut: Maximum depth in each pass.
  2681. :param extracut: Adds (or not) an extra cut at the end of each path
  2682. overlapping the first point in path to ensure complete copper removal
  2683. :return: None
  2684. """
  2685. if not isinstance(geometry, Geometry):
  2686. self.app.inform.emit('[ERROR] %s: %s' %
  2687. (_("Expected a Geometry, got"), type(geometry)))
  2688. return 'fail'
  2689. log.debug("Generate_from_geometry_2()")
  2690. # if solid_geometry is empty raise an exception
  2691. if not geometry.solid_geometry:
  2692. self.app.inform.emit(
  2693. '[ERROR_NOTCL] %s' % _("Trying to generate a CNC Job from a Geometry object without solid_geometry.")
  2694. )
  2695. temp_solid_geometry = list()
  2696. def bounds_rec(obj):
  2697. if type(obj) is list:
  2698. minx = np.Inf
  2699. miny = np.Inf
  2700. maxx = -np.Inf
  2701. maxy = -np.Inf
  2702. for k in obj:
  2703. if type(k) is dict:
  2704. for key in k:
  2705. minx_, miny_, maxx_, maxy_ = bounds_rec(k[key])
  2706. minx = min(minx, minx_)
  2707. miny = min(miny, miny_)
  2708. maxx = max(maxx, maxx_)
  2709. maxy = max(maxy, maxy_)
  2710. else:
  2711. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  2712. minx = min(minx, minx_)
  2713. miny = min(miny, miny_)
  2714. maxx = max(maxx, maxx_)
  2715. maxy = max(maxy, maxy_)
  2716. return minx, miny, maxx, maxy
  2717. else:
  2718. # it's a Shapely object, return it's bounds
  2719. return obj.bounds
  2720. if offset != 0.0:
  2721. offset_for_use = offset
  2722. if offset < 0:
  2723. a, b, c, d = bounds_rec(geometry.solid_geometry)
  2724. # if the offset is less than half of the total length or less than half of the total width of the
  2725. # solid geometry it's obvious we can't do the offset
  2726. if -offset > ((c - a) / 2) or -offset > ((d - b) / 2):
  2727. self.app.inform.emit('[ERROR_NOTCL] %s' % _(
  2728. "The Tool Offset value is too negative to use "
  2729. "for the current_geometry.\n"
  2730. "Raise the value (in module) and try again."))
  2731. return 'fail'
  2732. # hack: make offset smaller by 0.0000000001 which is insignificant difference but allow the job
  2733. # to continue
  2734. elif -offset == ((c - a) / 2) or -offset == ((d - b) / 2):
  2735. offset_for_use = offset - 0.0000000001
  2736. for it in geometry.solid_geometry:
  2737. # if the geometry is a closed shape then create a Polygon out of it
  2738. if isinstance(it, LineString):
  2739. c = it.coords
  2740. if c[0] == c[-1]:
  2741. it = Polygon(it)
  2742. temp_solid_geometry.append(it.buffer(offset_for_use, join_style=2))
  2743. else:
  2744. temp_solid_geometry = geometry.solid_geometry
  2745. # ## Flatten the geometry. Only linear elements (no polygons) remain.
  2746. flat_geometry = self.flatten(temp_solid_geometry, pathonly=True)
  2747. log.debug("%d paths" % len(flat_geometry))
  2748. try:
  2749. self.tooldia = float(tooldia) if tooldia else None
  2750. except ValueError:
  2751. self.tooldia = [float(el) for el in tooldia.split(',') if el != ''] if tooldia else None
  2752. self.z_cut = float(z_cut) if z_cut is not None else None
  2753. self.z_move = float(z_move) if z_move is not None else None
  2754. self.feedrate = float(feedrate) if feedrate else None
  2755. self.z_feedrate = float(feedrate_z) if feedrate_z is not None else None
  2756. self.feedrate_rapid = float(feedrate_rapid) if feedrate_rapid else None
  2757. self.spindlespeed = int(spindlespeed) if spindlespeed else None
  2758. self.spindledir = spindledir
  2759. self.dwell = dwell
  2760. self.dwelltime = float(dwelltime) if dwelltime else None
  2761. self.startz = float(startz) if startz is not None else None
  2762. self.z_end = float(endz) if endz is not None else None
  2763. self.z_depthpercut = float(depthpercut) if depthpercut else None
  2764. self.multidepth = multidepth
  2765. self.z_toolchange = float(toolchangez) if toolchangez is not None else None
  2766. try:
  2767. if toolchangexy == '':
  2768. self.xy_toolchange = None
  2769. else:
  2770. self.xy_toolchange = [float(eval(a)) for a in toolchangexy.split(",")]
  2771. if len(self.xy_toolchange) < 2:
  2772. self.app.inform.emit('[ERROR] %s' %
  2773. _("The Toolchange X,Y field in Edit -> Preferences has to be "
  2774. "in the format (x, y) \nbut now there is only one value, not two. "))
  2775. return 'fail'
  2776. except Exception as e:
  2777. log.debug("camlib.CNCJob.generate_from_geometry_2() --> %s" % str(e))
  2778. pass
  2779. self.pp_geometry_name = pp_geometry_name if pp_geometry_name else 'default'
  2780. self.f_plunge = self.app.defaults["geometry_f_plunge"]
  2781. if self.machinist_setting == 0:
  2782. if self.z_cut is None:
  2783. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2784. _("Cut_Z parameter is None or zero. Most likely a bad combinations of "
  2785. "other parameters."))
  2786. return 'fail'
  2787. if self.z_cut > 0:
  2788. self.app.inform.emit('[WARNING] %s' %
  2789. _("The Cut Z parameter has positive value. "
  2790. "It is the depth value to cut into material.\n"
  2791. "The Cut Z parameter needs to have a negative value, assuming it is a typo "
  2792. "therefore the app will convert the value to negative."
  2793. "Check the resulting CNC code (Gcode etc)."))
  2794. self.z_cut = -self.z_cut
  2795. elif self.z_cut == 0:
  2796. self.app.inform.emit('[WARNING] %s: %s' %
  2797. (_("The Cut Z parameter is zero. There will be no cut, skipping file"),
  2798. geometry.options['name']))
  2799. return 'fail'
  2800. if self.z_move is None:
  2801. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2802. _("Travel Z parameter is None or zero."))
  2803. return 'fail'
  2804. if self.z_move < 0:
  2805. self.app.inform.emit('[WARNING] %s' %
  2806. _("The Travel Z parameter has negative value. "
  2807. "It is the height value to travel between cuts.\n"
  2808. "The Z Travel parameter needs to have a positive value, assuming it is a typo "
  2809. "therefore the app will convert the value to positive."
  2810. "Check the resulting CNC code (Gcode etc)."))
  2811. self.z_move = -self.z_move
  2812. elif self.z_move == 0:
  2813. self.app.inform.emit('[WARNING] %s: %s' %
  2814. (_("The Z Travel parameter is zero. "
  2815. "This is dangerous, skipping file"), self.options['name']))
  2816. return 'fail'
  2817. # made sure that depth_per_cut is no more then the z_cut
  2818. if abs(self.z_cut) < self.z_depthpercut:
  2819. self.z_depthpercut = abs(self.z_cut)
  2820. # ## Index first and last points in paths
  2821. # What points to index.
  2822. def get_pts(o):
  2823. return [o.coords[0], o.coords[-1]]
  2824. # Create the indexed storage.
  2825. storage = FlatCAMRTreeStorage()
  2826. storage.get_points = get_pts
  2827. # Store the geometry
  2828. log.debug("Indexing geometry before generating G-Code...")
  2829. self.app.inform.emit(_("Indexing geometry before generating G-Code..."))
  2830. for shape in flat_geometry:
  2831. if self.app.abort_flag:
  2832. # graceful abort requested by the user
  2833. raise FlatCAMApp.GracefulException
  2834. if shape is not None: # TODO: This shouldn't have happened.
  2835. storage.insert(shape)
  2836. if not append:
  2837. self.gcode = ""
  2838. # tell postprocessor the number of tool (for toolchange)
  2839. self.tool = tool_no
  2840. # this is the tool diameter, it is used as such to accommodate the postprocessor who need the tool diameter
  2841. # given under the name 'toolC'
  2842. self.postdata['toolC'] = self.tooldia
  2843. # Initial G-Code
  2844. self.pp_geometry = self.app.postprocessors[self.pp_geometry_name]
  2845. p = self.pp_geometry
  2846. self.oldx = 0.0
  2847. self.oldy = 0.0
  2848. self.gcode = self.doformat(p.start_code)
  2849. self.gcode += self.doformat(p.feedrate_code) # sets the feed rate
  2850. if toolchange is False:
  2851. self.gcode += self.doformat(p.lift_code, x=self.oldx , y=self.oldy ) # Move (up) to travel height
  2852. self.gcode += self.doformat(p.startz_code, x=self.oldx , y=self.oldy )
  2853. if toolchange:
  2854. # if "line_xyz" in self.pp_geometry_name:
  2855. # self.gcode += self.doformat(p.toolchange_code, x=self.xy_toolchange[0], y=self.xy_toolchange[1])
  2856. # else:
  2857. # self.gcode += self.doformat(p.toolchange_code)
  2858. self.gcode += self.doformat(p.toolchange_code)
  2859. if 'laser' not in self.pp_geometry_name:
  2860. self.gcode += self.doformat(p.spindle_code) # Spindle start
  2861. else:
  2862. # for laser this will disable the laser
  2863. self.gcode += self.doformat(p.lift_code, x=self.oldx, y=self.oldy) # Move (up) to travel height
  2864. if self.dwell is True:
  2865. self.gcode += self.doformat(p.dwell_code) # Dwell time
  2866. else:
  2867. if 'laser' not in self.pp_geometry_name:
  2868. self.gcode += self.doformat(p.spindle_code) # Spindle start
  2869. if self.dwell is True:
  2870. self.gcode += self.doformat(p.dwell_code) # Dwell time
  2871. total_travel = 0.0
  2872. total_cut = 0.0
  2873. # Iterate over geometry paths getting the nearest each time.
  2874. log.debug("Starting G-Code...")
  2875. self.app.inform.emit(_("Starting G-Code..."))
  2876. # variables to display the percentage of work done
  2877. geo_len = len(flat_geometry)
  2878. disp_number = 0
  2879. old_disp_number = 0
  2880. log.warning("Number of paths for which to generate GCode: %s" % str(geo_len))
  2881. if self.units == 'MM':
  2882. current_tooldia = float('%.2f' % float(self.tooldia))
  2883. else:
  2884. current_tooldia = float('%.4f' % float(self.tooldia))
  2885. self.app.inform.emit(
  2886. '%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  2887. str(current_tooldia),
  2888. str(self.units))
  2889. )
  2890. path_count = 0
  2891. current_pt = (0, 0)
  2892. pt, geo = storage.nearest(current_pt)
  2893. try:
  2894. while True:
  2895. if self.app.abort_flag:
  2896. # graceful abort requested by the user
  2897. raise FlatCAMApp.GracefulException
  2898. path_count += 1
  2899. # Remove before modifying, otherwise deletion will fail.
  2900. storage.remove(geo)
  2901. # If last point in geometry is the nearest but prefer the first one if last point == first point
  2902. # then reverse coordinates.
  2903. if pt != geo.coords[0] and pt == geo.coords[-1]:
  2904. geo.coords = list(geo.coords)[::-1]
  2905. # ---------- Single depth/pass --------
  2906. if not multidepth:
  2907. # calculate the cut distance
  2908. total_cut += geo.length
  2909. self.gcode += self.create_gcode_single_pass(geo, extracut, tolerance, old_point=current_pt)
  2910. # --------- Multi-pass ---------
  2911. else:
  2912. # calculate the cut distance
  2913. # due of the number of cuts (multi depth) it has to multiplied by the number of cuts
  2914. nr_cuts = 0
  2915. depth = abs(self.z_cut)
  2916. while depth > 0:
  2917. nr_cuts += 1
  2918. depth -= float(self.z_depthpercut)
  2919. total_cut += (geo.length * nr_cuts)
  2920. self.gcode += self.create_gcode_multi_pass(geo, extracut, tolerance,
  2921. postproc=p, old_point=current_pt)
  2922. # calculate the travel distance
  2923. total_travel += abs(distance(pt1=current_pt, pt2=pt))
  2924. current_pt = geo.coords[-1]
  2925. pt, geo = storage.nearest(current_pt) # Next
  2926. disp_number = int(np.interp(path_count, [0, geo_len], [0, 100]))
  2927. if old_disp_number < disp_number <= 100:
  2928. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  2929. old_disp_number = disp_number
  2930. except StopIteration: # Nothing found in storage.
  2931. pass
  2932. log.debug("Finishing G-Code... %s paths traced." % path_count)
  2933. # add move to end position
  2934. total_travel += abs(distance_euclidian(current_pt[0], current_pt[1], 0, 0))
  2935. self.travel_distance += total_travel + total_cut
  2936. self.routing_time += total_cut / self.feedrate
  2937. # Finish
  2938. self.gcode += self.doformat(p.spindle_stop_code)
  2939. self.gcode += self.doformat(p.lift_code, x=current_pt[0], y=current_pt[1])
  2940. self.gcode += self.doformat(p.end_code, x=0, y=0)
  2941. self.app.inform.emit(
  2942. '%s... %s %s' % (_("Finished G-Code generation"), str(path_count), _(" paths traced."))
  2943. )
  2944. return self.gcode
  2945. def generate_gcode_from_solderpaste_geo(self, **kwargs):
  2946. """
  2947. Algorithm to generate from multitool Geometry.
  2948. Algorithm description:
  2949. ----------------------
  2950. Uses RTree to find the nearest path to follow.
  2951. :return: Gcode string
  2952. """
  2953. log.debug("Generate_from_solderpaste_geometry()")
  2954. # ## Index first and last points in paths
  2955. # What points to index.
  2956. def get_pts(o):
  2957. return [o.coords[0], o.coords[-1]]
  2958. self.gcode = ""
  2959. if not kwargs:
  2960. log.debug("camlib.generate_from_solderpaste_geo() --> No tool in the solderpaste geometry.")
  2961. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2962. _("There is no tool data in the SolderPaste geometry."))
  2963. # this is the tool diameter, it is used as such to accommodate the postprocessor who need the tool diameter
  2964. # given under the name 'toolC'
  2965. self.postdata['z_start'] = kwargs['data']['tools_solderpaste_z_start']
  2966. self.postdata['z_dispense'] = kwargs['data']['tools_solderpaste_z_dispense']
  2967. self.postdata['z_stop'] = kwargs['data']['tools_solderpaste_z_stop']
  2968. self.postdata['z_travel'] = kwargs['data']['tools_solderpaste_z_travel']
  2969. self.postdata['z_toolchange'] = kwargs['data']['tools_solderpaste_z_toolchange']
  2970. self.postdata['xy_toolchange'] = kwargs['data']['tools_solderpaste_xy_toolchange']
  2971. self.postdata['frxy'] = kwargs['data']['tools_solderpaste_frxy']
  2972. self.postdata['frz'] = kwargs['data']['tools_solderpaste_frz']
  2973. self.postdata['frz_dispense'] = kwargs['data']['tools_solderpaste_frz_dispense']
  2974. self.postdata['speedfwd'] = kwargs['data']['tools_solderpaste_speedfwd']
  2975. self.postdata['dwellfwd'] = kwargs['data']['tools_solderpaste_dwellfwd']
  2976. self.postdata['speedrev'] = kwargs['data']['tools_solderpaste_speedrev']
  2977. self.postdata['dwellrev'] = kwargs['data']['tools_solderpaste_dwellrev']
  2978. self.postdata['pp_solderpaste_name'] = kwargs['data']['tools_solderpaste_pp']
  2979. self.postdata['toolC'] = kwargs['tooldia']
  2980. self.pp_solderpaste_name = kwargs['data']['tools_solderpaste_pp'] if kwargs['data']['tools_solderpaste_pp'] \
  2981. else self.app.defaults['tools_solderpaste_pp']
  2982. p = self.app.postprocessors[self.pp_solderpaste_name]
  2983. # ## Flatten the geometry. Only linear elements (no polygons) remain.
  2984. flat_geometry = self.flatten(kwargs['solid_geometry'], pathonly=True)
  2985. log.debug("%d paths" % len(flat_geometry))
  2986. # Create the indexed storage.
  2987. storage = FlatCAMRTreeStorage()
  2988. storage.get_points = get_pts
  2989. # Store the geometry
  2990. log.debug("Indexing geometry before generating G-Code...")
  2991. for shape in flat_geometry:
  2992. if shape is not None:
  2993. storage.insert(shape)
  2994. # Initial G-Code
  2995. self.gcode = self.doformat(p.start_code)
  2996. self.gcode += self.doformat(p.spindle_off_code)
  2997. self.gcode += self.doformat(p.toolchange_code)
  2998. # ## Iterate over geometry paths getting the nearest each time.
  2999. log.debug("Starting SolderPaste G-Code...")
  3000. path_count = 0
  3001. current_pt = (0, 0)
  3002. # variables to display the percentage of work done
  3003. geo_len = len(flat_geometry)
  3004. disp_number = 0
  3005. old_disp_number = 0
  3006. pt, geo = storage.nearest(current_pt)
  3007. try:
  3008. while True:
  3009. if self.app.abort_flag:
  3010. # graceful abort requested by the user
  3011. raise FlatCAMApp.GracefulException
  3012. path_count += 1
  3013. # Remove before modifying, otherwise deletion will fail.
  3014. storage.remove(geo)
  3015. # If last point in geometry is the nearest but prefer the first one if last point == first point
  3016. # then reverse coordinates.
  3017. if pt != geo.coords[0] and pt == geo.coords[-1]:
  3018. geo.coords = list(geo.coords)[::-1]
  3019. self.gcode += self.create_soldepaste_gcode(geo, p=p, old_point=current_pt)
  3020. current_pt = geo.coords[-1]
  3021. pt, geo = storage.nearest(current_pt) # Next
  3022. disp_number = int(np.interp(path_count, [0, geo_len], [0, 100]))
  3023. if old_disp_number < disp_number <= 100:
  3024. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  3025. old_disp_number = disp_number
  3026. except StopIteration: # Nothing found in storage.
  3027. pass
  3028. log.debug("Finishing SolderPste G-Code... %s paths traced." % path_count)
  3029. self.app.inform.emit('%s... %s %s' %
  3030. (_("Finished SolderPste G-Code generation"),
  3031. str(path_count),
  3032. _("paths traced.")
  3033. )
  3034. )
  3035. # Finish
  3036. self.gcode += self.doformat(p.lift_code)
  3037. self.gcode += self.doformat(p.end_code)
  3038. return self.gcode
  3039. def create_soldepaste_gcode(self, geometry, p, old_point=(0, 0)):
  3040. gcode = ''
  3041. path = geometry.coords
  3042. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  3043. if self.coordinates_type == "G90":
  3044. # For Absolute coordinates type G90
  3045. first_x = path[0][0]
  3046. first_y = path[0][1]
  3047. else:
  3048. # For Incremental coordinates type G91
  3049. first_x = path[0][0] - old_point[0]
  3050. first_y = path[0][1] - old_point[1]
  3051. if type(geometry) == LineString or type(geometry) == LinearRing:
  3052. # Move fast to 1st point
  3053. gcode += self.doformat(p.rapid_code, x=first_x, y=first_y) # Move to first point
  3054. # Move down to cutting depth
  3055. gcode += self.doformat(p.z_feedrate_code)
  3056. gcode += self.doformat(p.down_z_start_code)
  3057. gcode += self.doformat(p.spindle_fwd_code) # Start dispensing
  3058. gcode += self.doformat(p.dwell_fwd_code)
  3059. gcode += self.doformat(p.feedrate_z_dispense_code)
  3060. gcode += self.doformat(p.lift_z_dispense_code)
  3061. gcode += self.doformat(p.feedrate_xy_code)
  3062. # Cutting...
  3063. prev_x = first_x
  3064. prev_y = first_y
  3065. for pt in path[1:]:
  3066. if self.coordinates_type == "G90":
  3067. # For Absolute coordinates type G90
  3068. next_x = pt[0]
  3069. next_y = pt[1]
  3070. else:
  3071. # For Incremental coordinates type G91
  3072. next_x = pt[0] - prev_x
  3073. next_y = pt[1] - prev_y
  3074. gcode += self.doformat(p.linear_code, x=next_x, y=next_y) # Linear motion to point
  3075. prev_x = next_x
  3076. prev_y = next_y
  3077. # Up to travelling height.
  3078. gcode += self.doformat(p.spindle_off_code) # Stop dispensing
  3079. gcode += self.doformat(p.spindle_rev_code)
  3080. gcode += self.doformat(p.down_z_stop_code)
  3081. gcode += self.doformat(p.spindle_off_code)
  3082. gcode += self.doformat(p.dwell_rev_code)
  3083. gcode += self.doformat(p.z_feedrate_code)
  3084. gcode += self.doformat(p.lift_code)
  3085. elif type(geometry) == Point:
  3086. gcode += self.doformat(p.linear_code, x=first_x, y=first_y) # Move to first point
  3087. gcode += self.doformat(p.feedrate_z_dispense_code)
  3088. gcode += self.doformat(p.down_z_start_code)
  3089. gcode += self.doformat(p.spindle_fwd_code) # Start dispensing
  3090. gcode += self.doformat(p.dwell_fwd_code)
  3091. gcode += self.doformat(p.lift_z_dispense_code)
  3092. gcode += self.doformat(p.spindle_off_code) # Stop dispensing
  3093. gcode += self.doformat(p.spindle_rev_code)
  3094. gcode += self.doformat(p.spindle_off_code)
  3095. gcode += self.doformat(p.down_z_stop_code)
  3096. gcode += self.doformat(p.dwell_rev_code)
  3097. gcode += self.doformat(p.z_feedrate_code)
  3098. gcode += self.doformat(p.lift_code)
  3099. return gcode
  3100. def create_gcode_single_pass(self, geometry, extracut, tolerance, old_point=(0, 0)):
  3101. # G-code. Note: self.linear2gcode() and self.point2gcode() will lower and raise the tool every time.
  3102. gcode_single_pass = ''
  3103. if type(geometry) == LineString or type(geometry) == LinearRing:
  3104. if extracut is False:
  3105. gcode_single_pass = self.linear2gcode(geometry, tolerance=tolerance, old_point=old_point)
  3106. else:
  3107. if geometry.is_ring:
  3108. gcode_single_pass = self.linear2gcode_extra(geometry, tolerance=tolerance, old_point=old_point)
  3109. else:
  3110. gcode_single_pass = self.linear2gcode(geometry, tolerance=tolerance, old_point=old_point)
  3111. elif type(geometry) == Point:
  3112. gcode_single_pass = self.point2gcode(geometry)
  3113. else:
  3114. log.warning("G-code generation not implemented for %s" % (str(type(geometry))))
  3115. return
  3116. return gcode_single_pass
  3117. def create_gcode_multi_pass(self, geometry, extracut, tolerance, postproc, old_point=(0, 0)):
  3118. gcode_multi_pass = ''
  3119. if isinstance(self.z_cut, Decimal):
  3120. z_cut = self.z_cut
  3121. else:
  3122. z_cut = Decimal(self.z_cut).quantize(Decimal('0.000000001'))
  3123. if self.z_depthpercut is None:
  3124. self.z_depthpercut = z_cut
  3125. elif not isinstance(self.z_depthpercut, Decimal):
  3126. self.z_depthpercut = Decimal(self.z_depthpercut).quantize(Decimal('0.000000001'))
  3127. depth = 0
  3128. reverse = False
  3129. while depth > z_cut:
  3130. # Increase depth. Limit to z_cut.
  3131. depth -= self.z_depthpercut
  3132. if depth < z_cut:
  3133. depth = z_cut
  3134. # Cut at specific depth and do not lift the tool.
  3135. # Note: linear2gcode() will use G00 to move to the first point in the path, but it should be already
  3136. # at the first point if the tool is down (in the material). So, an extra G00 should show up but
  3137. # is inconsequential.
  3138. if type(geometry) == LineString or type(geometry) == LinearRing:
  3139. if extracut is False:
  3140. gcode_multi_pass += self.linear2gcode(geometry, tolerance=tolerance, z_cut=depth, up=False,
  3141. old_point=old_point)
  3142. else:
  3143. if geometry.is_ring:
  3144. gcode_multi_pass += self.linear2gcode_extra(geometry, tolerance=tolerance, z_cut=depth,
  3145. up=False, old_point=old_point)
  3146. else:
  3147. gcode_multi_pass += self.linear2gcode(geometry, tolerance=tolerance, z_cut=depth, up=False,
  3148. old_point=old_point)
  3149. # Ignore multi-pass for points.
  3150. elif type(geometry) == Point:
  3151. gcode_multi_pass += self.point2gcode(geometry, old_point=old_point)
  3152. break # Ignoring ...
  3153. else:
  3154. log.warning("G-code generation not implemented for %s" % (str(type(geometry))))
  3155. # Reverse coordinates if not a loop so we can continue cutting without returning to the beginning.
  3156. if type(geometry) == LineString:
  3157. geometry.coords = list(geometry.coords)[::-1]
  3158. reverse = True
  3159. # If geometry is reversed, revert.
  3160. if reverse:
  3161. if type(geometry) == LineString:
  3162. geometry.coords = list(geometry.coords)[::-1]
  3163. # Lift the tool
  3164. gcode_multi_pass += self.doformat(postproc.lift_code, x=old_point[0], y=old_point[1])
  3165. return gcode_multi_pass
  3166. def codes_split(self, gline):
  3167. """
  3168. Parses a line of G-Code such as "G01 X1234 Y987" into
  3169. a dictionary: {'G': 1.0, 'X': 1234.0, 'Y': 987.0}
  3170. :param gline: G-Code line string
  3171. :return: Dictionary with parsed line.
  3172. """
  3173. command = {}
  3174. if 'Roland' in self.pp_excellon_name or 'Roland' in self.pp_geometry_name:
  3175. match_z = re.search(r"^Z(\s*-?\d+\.\d+?),(\s*\s*-?\d+\.\d+?),(\s*\s*-?\d+\.\d+?)*;$", gline)
  3176. if match_z:
  3177. command['G'] = 0
  3178. command['X'] = float(match_z.group(1).replace(" ", "")) * 0.025
  3179. command['Y'] = float(match_z.group(2).replace(" ", "")) * 0.025
  3180. command['Z'] = float(match_z.group(3).replace(" ", "")) * 0.025
  3181. elif 'hpgl' in self.pp_excellon_name or 'hpgl' in self.pp_geometry_name:
  3182. match_pa = re.search(r"^PA(\s*-?\d+\.\d+?),(\s*\s*-?\d+\.\d+?)*;$", gline)
  3183. if match_pa:
  3184. command['G'] = 0
  3185. command['X'] = float(match_pa.group(1).replace(" ", ""))
  3186. command['Y'] = float(match_pa.group(2).replace(" ", ""))
  3187. match_pen = re.search(r"^(P[U|D])", gline)
  3188. if match_pen:
  3189. if match_pen.group(1) == 'PU':
  3190. # the value does not matter, only that it is positive so the gcode_parse() know it is > 0,
  3191. # therefore the move is of kind T (travel)
  3192. command['Z'] = 1
  3193. else:
  3194. command['Z'] = 0
  3195. elif 'grbl_laser' in self.pp_excellon_name or 'grbl_laser' in self.pp_geometry_name or \
  3196. (self.pp_solderpaste_name is not None and 'Paste' in self.pp_solderpaste_name):
  3197. match_lsr = re.search(r"X([\+-]?\d+.[\+-]?\d+)\s*Y([\+-]?\d+.[\+-]?\d+)", gline)
  3198. if match_lsr:
  3199. command['X'] = float(match_lsr.group(1).replace(" ", ""))
  3200. command['Y'] = float(match_lsr.group(2).replace(" ", ""))
  3201. match_lsr_pos = re.search(r"^(M0[3|5])", gline)
  3202. if match_lsr_pos:
  3203. if 'M05' in match_lsr_pos.group(1):
  3204. # the value does not matter, only that it is positive so the gcode_parse() know it is > 0,
  3205. # therefore the move is of kind T (travel)
  3206. command['Z'] = 1
  3207. else:
  3208. command['Z'] = 0
  3209. elif self.pp_solderpaste_name is not None:
  3210. if 'Paste' in self.pp_solderpaste_name:
  3211. match_paste = re.search(r"X([\+-]?\d+.[\+-]?\d+)\s*Y([\+-]?\d+.[\+-]?\d+)", gline)
  3212. if match_paste:
  3213. command['X'] = float(match_paste.group(1).replace(" ", ""))
  3214. command['Y'] = float(match_paste.group(2).replace(" ", ""))
  3215. else:
  3216. match = re.search(r'^\s*([A-Z])\s*([\+\-\.\d\s]+)', gline)
  3217. while match:
  3218. command[match.group(1)] = float(match.group(2).replace(" ", ""))
  3219. gline = gline[match.end():]
  3220. match = re.search(r'^\s*([A-Z])\s*([\+\-\.\d\s]+)', gline)
  3221. return command
  3222. def gcode_parse(self, force_parsing=None):
  3223. """
  3224. G-Code parser (from self.gcode). Generates dictionary with
  3225. single-segment LineString's and "kind" indicating cut or travel,
  3226. fast or feedrate speed.
  3227. """
  3228. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  3229. # Results go here
  3230. geometry = []
  3231. # Last known instruction
  3232. current = {'X': 0.0, 'Y': 0.0, 'Z': 0.0, 'G': 0}
  3233. # Current path: temporary storage until tool is
  3234. # lifted or lowered.
  3235. if self.toolchange_xy_type == "excellon":
  3236. if self.app.defaults["excellon_toolchangexy"] == '':
  3237. pos_xy = [0, 0]
  3238. else:
  3239. pos_xy = [float(eval(a)) for a in self.app.defaults["excellon_toolchangexy"].split(",")]
  3240. else:
  3241. if self.app.defaults["geometry_toolchangexy"] == '':
  3242. pos_xy = [0, 0]
  3243. else:
  3244. pos_xy = [float(eval(a)) for a in self.app.defaults["geometry_toolchangexy"].split(",")]
  3245. path = [pos_xy]
  3246. # path = [(0, 0)]
  3247. self.app.inform.emit('%s: %d' % (_("Parsing GCode file. Number of lines"), len(self.gcode.splitlines())))
  3248. # Process every instruction
  3249. for line in StringIO(self.gcode):
  3250. if force_parsing is False or force_parsing is None:
  3251. if '%MO' in line or '%' in line or 'MOIN' in line or 'MOMM' in line:
  3252. return "fail"
  3253. gobj = self.codes_split(line)
  3254. # ## Units
  3255. if 'G' in gobj and (gobj['G'] == 20.0 or gobj['G'] == 21.0):
  3256. self.units = {20.0: "IN", 21.0: "MM"}[gobj['G']]
  3257. continue
  3258. # ## Changing height
  3259. if 'Z' in gobj:
  3260. if 'Roland' in self.pp_excellon_name or 'Roland' in self.pp_geometry_name:
  3261. pass
  3262. elif 'hpgl' in self.pp_excellon_name or 'hpgl' in self.pp_geometry_name:
  3263. pass
  3264. elif 'laser' in self.pp_excellon_name or 'laser' in self.pp_geometry_name:
  3265. pass
  3266. elif ('X' in gobj or 'Y' in gobj) and gobj['Z'] != current['Z']:
  3267. if self.pp_geometry_name == 'line_xyz' or self.pp_excellon_name == 'line_xyz':
  3268. pass
  3269. else:
  3270. log.warning("Non-orthogonal motion: From %s" % str(current))
  3271. log.warning(" To: %s" % str(gobj))
  3272. current['Z'] = gobj['Z']
  3273. # Store the path into geometry and reset path
  3274. if len(path) > 1:
  3275. geometry.append({"geom": LineString(path),
  3276. "kind": kind})
  3277. path = [path[-1]] # Start with the last point of last path.
  3278. # create the geometry for the holes created when drilling Excellon drills
  3279. if self.origin_kind == 'excellon':
  3280. if current['Z'] < 0:
  3281. current_drill_point_coords = (float('%.4f' % current['X']), float('%.4f' % current['Y']))
  3282. # find the drill diameter knowing the drill coordinates
  3283. for pt_dict in self.exc_drills:
  3284. point_in_dict_coords = (float('%.4f' % pt_dict['point'].x),
  3285. float('%.4f' % pt_dict['point'].y))
  3286. if point_in_dict_coords == current_drill_point_coords:
  3287. tool = pt_dict['tool']
  3288. dia = self.exc_tools[tool]['C']
  3289. kind = ['C', 'F']
  3290. geometry.append({"geom": Point(current_drill_point_coords).
  3291. buffer(dia/2).exterior,
  3292. "kind": kind})
  3293. break
  3294. if 'G' in gobj:
  3295. current['G'] = int(gobj['G'])
  3296. if 'X' in gobj or 'Y' in gobj:
  3297. if 'X' in gobj:
  3298. x = gobj['X']
  3299. # current['X'] = x
  3300. else:
  3301. x = current['X']
  3302. if 'Y' in gobj:
  3303. y = gobj['Y']
  3304. else:
  3305. y = current['Y']
  3306. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  3307. if current['Z'] > 0:
  3308. kind[0] = 'T'
  3309. if current['G'] > 0:
  3310. kind[1] = 'S'
  3311. if current['G'] in [0, 1]: # line
  3312. path.append((x, y))
  3313. arcdir = [None, None, "cw", "ccw"]
  3314. if current['G'] in [2, 3]: # arc
  3315. center = [gobj['I'] + current['X'], gobj['J'] + current['Y']]
  3316. radius = np.sqrt(gobj['I']**2 + gobj['J']**2)
  3317. start = np.arctan2(-gobj['J'], -gobj['I'])
  3318. stop = np.arctan2(-center[1] + y, -center[0] + x)
  3319. path += arc(center, radius, start, stop, arcdir[current['G']], int(self.steps_per_circle / 4))
  3320. # Update current instruction
  3321. for code in gobj:
  3322. current[code] = gobj[code]
  3323. self.app.inform.emit('%s...' % _("Creating Geometry from the parsed GCode file. "))
  3324. # There might not be a change in height at the
  3325. # end, therefore, see here too if there is
  3326. # a final path.
  3327. if len(path) > 1:
  3328. geometry.append({"geom": LineString(path),
  3329. "kind": kind})
  3330. self.gcode_parsed = geometry
  3331. return geometry
  3332. # def plot(self, tooldia=None, dpi=75, margin=0.1,
  3333. # color={"T": ["#F0E24D", "#B5AB3A"], "C": ["#5E6CFF", "#4650BD"]},
  3334. # alpha={"T": 0.3, "C": 1.0}):
  3335. # """
  3336. # Creates a Matplotlib figure with a plot of the
  3337. # G-code job.
  3338. # """
  3339. # if tooldia is None:
  3340. # tooldia = self.tooldia
  3341. #
  3342. # fig = Figure(dpi=dpi)
  3343. # ax = fig.add_subplot(111)
  3344. # ax.set_aspect(1)
  3345. # xmin, ymin, xmax, ymax = self.input_geometry_bounds
  3346. # ax.set_xlim(xmin-margin, xmax+margin)
  3347. # ax.set_ylim(ymin-margin, ymax+margin)
  3348. #
  3349. # if tooldia == 0:
  3350. # for geo in self.gcode_parsed:
  3351. # linespec = '--'
  3352. # linecolor = color[geo['kind'][0]][1]
  3353. # if geo['kind'][0] == 'C':
  3354. # linespec = 'k-'
  3355. # x, y = geo['geom'].coords.xy
  3356. # ax.plot(x, y, linespec, color=linecolor)
  3357. # else:
  3358. # for geo in self.gcode_parsed:
  3359. # poly = geo['geom'].buffer(tooldia/2.0)
  3360. # patch = PolygonPatch(poly, facecolor=color[geo['kind'][0]][0],
  3361. # edgecolor=color[geo['kind'][0]][1],
  3362. # alpha=alpha[geo['kind'][0]], zorder=2)
  3363. # ax.add_patch(patch)
  3364. #
  3365. # return fig
  3366. def plot2(self, tooldia=None, dpi=75, margin=0.1, gcode_parsed=None,
  3367. color={"T": ["#F0E24D4C", "#B5AB3A4C"], "C": ["#5E6CFFFF", "#4650BDFF"]},
  3368. alpha={"T": 0.3, "C": 1.0}, tool_tolerance=0.0005, obj=None, visible=False, kind='all'):
  3369. """
  3370. Plots the G-code job onto the given axes.
  3371. :param tooldia: Tool diameter.
  3372. :param dpi: Not used!
  3373. :param margin: Not used!
  3374. :param color: Color specification.
  3375. :param alpha: Transparency specification.
  3376. :param tool_tolerance: Tolerance when drawing the toolshape.
  3377. :param obj
  3378. :param visible
  3379. :param kind
  3380. :return: None
  3381. """
  3382. # units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3383. gcode_parsed = gcode_parsed if gcode_parsed else self.gcode_parsed
  3384. path_num = 0
  3385. if tooldia is None:
  3386. tooldia = self.tooldia
  3387. # this should be unlikely unless when upstream the tooldia is a tuple made by one dia and a comma like (2.4,)
  3388. if isinstance(tooldia, list):
  3389. tooldia = tooldia[0] if tooldia[0] is not None else self.tooldia
  3390. if tooldia == 0:
  3391. for geo in gcode_parsed:
  3392. if kind == 'all':
  3393. obj.add_shape(shape=geo['geom'], color=color[geo['kind'][0]][1], visible=visible)
  3394. elif kind == 'travel':
  3395. if geo['kind'][0] == 'T':
  3396. obj.add_shape(shape=geo['geom'], color=color['T'][1], visible=visible)
  3397. elif kind == 'cut':
  3398. if geo['kind'][0] == 'C':
  3399. obj.add_shape(shape=geo['geom'], color=color['C'][1], visible=visible)
  3400. else:
  3401. text = []
  3402. pos = []
  3403. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  3404. if self.coordinates_type == "G90":
  3405. # For Absolute coordinates type G90
  3406. for geo in gcode_parsed:
  3407. if geo['kind'][0] == 'T':
  3408. current_position = geo['geom'].coords[0]
  3409. if current_position not in pos:
  3410. pos.append(current_position)
  3411. path_num += 1
  3412. text.append(str(path_num))
  3413. current_position = geo['geom'].coords[-1]
  3414. if current_position not in pos:
  3415. pos.append(current_position)
  3416. path_num += 1
  3417. text.append(str(path_num))
  3418. # plot the geometry of Excellon objects
  3419. if self.origin_kind == 'excellon':
  3420. try:
  3421. poly = Polygon(geo['geom'])
  3422. except ValueError:
  3423. # if the geos are travel lines it will enter into Exception
  3424. poly = geo['geom'].buffer(distance=(tooldia / 1.99999999), resolution=self.steps_per_circle)
  3425. poly = poly.simplify(tool_tolerance)
  3426. else:
  3427. # plot the geometry of any objects other than Excellon
  3428. poly = geo['geom'].buffer(distance=(tooldia / 1.99999999), resolution=self.steps_per_circle)
  3429. poly = poly.simplify(tool_tolerance)
  3430. if kind == 'all':
  3431. obj.add_shape(shape=poly, color=color[geo['kind'][0]][1], face_color=color[geo['kind'][0]][0],
  3432. visible=visible, layer=1 if geo['kind'][0] == 'C' else 2)
  3433. elif kind == 'travel':
  3434. if geo['kind'][0] == 'T':
  3435. obj.add_shape(shape=poly, color=color['T'][1], face_color=color['T'][0],
  3436. visible=visible, layer=2)
  3437. elif kind == 'cut':
  3438. if geo['kind'][0] == 'C':
  3439. obj.add_shape(shape=poly, color=color['C'][1], face_color=color['C'][0],
  3440. visible=visible, layer=1)
  3441. else:
  3442. # For Incremental coordinates type G91
  3443. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3444. _('G91 coordinates not implemented ...'))
  3445. for geo in gcode_parsed:
  3446. if geo['kind'][0] == 'T':
  3447. current_position = geo['geom'].coords[0]
  3448. if current_position not in pos:
  3449. pos.append(current_position)
  3450. path_num += 1
  3451. text.append(str(path_num))
  3452. current_position = geo['geom'].coords[-1]
  3453. if current_position not in pos:
  3454. pos.append(current_position)
  3455. path_num += 1
  3456. text.append(str(path_num))
  3457. # plot the geometry of Excellon objects
  3458. if self.origin_kind == 'excellon':
  3459. try:
  3460. poly = Polygon(geo['geom'])
  3461. except ValueError:
  3462. # if the geos are travel lines it will enter into Exception
  3463. poly = geo['geom'].buffer(distance=(tooldia / 1.99999999), resolution=self.steps_per_circle)
  3464. poly = poly.simplify(tool_tolerance)
  3465. else:
  3466. # plot the geometry of any objects other than Excellon
  3467. poly = geo['geom'].buffer(distance=(tooldia / 1.99999999), resolution=self.steps_per_circle)
  3468. poly = poly.simplify(tool_tolerance)
  3469. if kind == 'all':
  3470. obj.add_shape(shape=poly, color=color[geo['kind'][0]][1], face_color=color[geo['kind'][0]][0],
  3471. visible=visible, layer=1 if geo['kind'][0] == 'C' else 2)
  3472. elif kind == 'travel':
  3473. if geo['kind'][0] == 'T':
  3474. obj.add_shape(shape=poly, color=color['T'][1], face_color=color['T'][0],
  3475. visible=visible, layer=2)
  3476. elif kind == 'cut':
  3477. if geo['kind'][0] == 'C':
  3478. obj.add_shape(shape=poly, color=color['C'][1], face_color=color['C'][0],
  3479. visible=visible, layer=1)
  3480. # current_x = gcode_parsed[0]['geom'].coords[0][0]
  3481. # current_y = gcode_parsed[0]['geom'].coords[0][1]
  3482. # old_pos = (
  3483. # current_x,
  3484. # current_y
  3485. # )
  3486. #
  3487. # for geo in gcode_parsed:
  3488. # if geo['kind'][0] == 'T':
  3489. # current_position = (
  3490. # geo['geom'].coords[0][0] + old_pos[0],
  3491. # geo['geom'].coords[0][1] + old_pos[1]
  3492. # )
  3493. # if current_position not in pos:
  3494. # pos.append(current_position)
  3495. # path_num += 1
  3496. # text.append(str(path_num))
  3497. #
  3498. # delta = (
  3499. # geo['geom'].coords[-1][0] - geo['geom'].coords[0][0],
  3500. # geo['geom'].coords[-1][1] - geo['geom'].coords[0][1]
  3501. # )
  3502. # current_position = (
  3503. # current_position[0] + geo['geom'].coords[-1][0],
  3504. # current_position[1] + geo['geom'].coords[-1][1]
  3505. # )
  3506. # if current_position not in pos:
  3507. # pos.append(current_position)
  3508. # path_num += 1
  3509. # text.append(str(path_num))
  3510. #
  3511. # # plot the geometry of Excellon objects
  3512. # if self.origin_kind == 'excellon':
  3513. # if isinstance(geo['geom'], Point):
  3514. # # if geo is Point
  3515. # current_position = (
  3516. # current_position[0] + geo['geom'].x,
  3517. # current_position[1] + geo['geom'].y
  3518. # )
  3519. # poly = Polygon(Point(current_position))
  3520. # elif isinstance(geo['geom'], LineString):
  3521. # # if the geos are travel lines (LineStrings)
  3522. # new_line_pts = []
  3523. # old_line_pos = deepcopy(current_position)
  3524. # for p in list(geo['geom'].coords):
  3525. # current_position = (
  3526. # current_position[0] + p[0],
  3527. # current_position[1] + p[1]
  3528. # )
  3529. # new_line_pts.append(current_position)
  3530. # old_line_pos = p
  3531. # new_line = LineString(new_line_pts)
  3532. #
  3533. # poly = new_line.buffer(distance=(tooldia / 1.99999999), resolution=self.steps_per_circle)
  3534. # poly = poly.simplify(tool_tolerance)
  3535. # else:
  3536. # # plot the geometry of any objects other than Excellon
  3537. # new_line_pts = []
  3538. # old_line_pos = deepcopy(current_position)
  3539. # for p in list(geo['geom'].coords):
  3540. # current_position = (
  3541. # current_position[0] + p[0],
  3542. # current_position[1] + p[1]
  3543. # )
  3544. # new_line_pts.append(current_position)
  3545. # old_line_pos = p
  3546. # new_line = LineString(new_line_pts)
  3547. #
  3548. # poly = new_line.buffer(distance=(tooldia / 1.99999999), resolution=self.steps_per_circle)
  3549. # poly = poly.simplify(tool_tolerance)
  3550. #
  3551. # old_pos = deepcopy(current_position)
  3552. #
  3553. # if kind == 'all':
  3554. # obj.add_shape(shape=poly, color=color[geo['kind'][0]][1], face_color=color[geo['kind'][0]][0],
  3555. # visible=visible, layer=1 if geo['kind'][0] == 'C' else 2)
  3556. # elif kind == 'travel':
  3557. # if geo['kind'][0] == 'T':
  3558. # obj.add_shape(shape=poly, color=color['T'][1], face_color=color['T'][0],
  3559. # visible=visible, layer=2)
  3560. # elif kind == 'cut':
  3561. # if geo['kind'][0] == 'C':
  3562. # obj.add_shape(shape=poly, color=color['C'][1], face_color=color['C'][0],
  3563. # visible=visible, layer=1)
  3564. try:
  3565. obj.annotation.set(text=text, pos=pos, visible=obj.options['plot'],
  3566. font_size=self.app.defaults["cncjob_annotation_fontsize"],
  3567. color=self.app.defaults["cncjob_annotation_fontcolor"])
  3568. except Exception as e:
  3569. pass
  3570. def create_geometry(self):
  3571. self.app.inform.emit('%s: %s' % (_("Unifying Geometry from parsed Geometry segments"),
  3572. str(len(self.gcode_parsed))))
  3573. # TODO: This takes forever. Too much data?
  3574. # self.solid_geometry = cascaded_union([geo['geom'] for geo in self.gcode_parsed])
  3575. # This is much faster but not so nice to look at as you can see different segments of the geometry
  3576. self.solid_geometry = [geo['geom'] for geo in self.gcode_parsed]
  3577. return self.solid_geometry
  3578. # code snippet added by Lei Zheng in a rejected pull request on FlatCAM https://bitbucket.org/realthunder/
  3579. def segment(self, coords):
  3580. """
  3581. break long linear lines to make it more auto level friendly
  3582. """
  3583. if len(coords) < 2 or self.segx <= 0 and self.segy <= 0:
  3584. return list(coords)
  3585. path = [coords[0]]
  3586. # break the line in either x or y dimension only
  3587. def linebreak_single(line, dim, dmax):
  3588. if dmax <= 0:
  3589. return None
  3590. if line[1][dim] > line[0][dim]:
  3591. sign = 1.0
  3592. d = line[1][dim] - line[0][dim]
  3593. else:
  3594. sign = -1.0
  3595. d = line[0][dim] - line[1][dim]
  3596. if d > dmax:
  3597. # make sure we don't make any new lines too short
  3598. if d > dmax * 2:
  3599. dd = dmax
  3600. else:
  3601. dd = d / 2
  3602. other = dim ^ 1
  3603. return (line[0][dim] + dd * sign, line[0][other] + \
  3604. dd * (line[1][other] - line[0][other]) / d)
  3605. return None
  3606. # recursively breaks down a given line until it is within the
  3607. # required step size
  3608. def linebreak(line):
  3609. pt_new = linebreak_single(line, 0, self.segx)
  3610. if pt_new is None:
  3611. pt_new2 = linebreak_single(line, 1, self.segy)
  3612. else:
  3613. pt_new2 = linebreak_single((line[0], pt_new), 1, self.segy)
  3614. if pt_new2 is not None:
  3615. pt_new = pt_new2[::-1]
  3616. if pt_new is None:
  3617. path.append(line[1])
  3618. else:
  3619. path.append(pt_new)
  3620. linebreak((pt_new, line[1]))
  3621. for pt in coords[1:]:
  3622. linebreak((path[-1], pt))
  3623. return path
  3624. def linear2gcode(self, linear, tolerance=0, down=True, up=True,
  3625. z_cut=None, z_move=None, zdownrate=None,
  3626. feedrate=None, feedrate_z=None, feedrate_rapid=None, cont=False, old_point=(0, 0)):
  3627. """
  3628. Generates G-code to cut along the linear feature.
  3629. :param linear: The path to cut along.
  3630. :type: Shapely.LinearRing or Shapely.Linear String
  3631. :param tolerance: All points in the simplified object will be within the
  3632. tolerance distance of the original geometry.
  3633. :type tolerance: float
  3634. :param feedrate: speed for cut on X - Y plane
  3635. :param feedrate_z: speed for cut on Z plane
  3636. :param feedrate_rapid: speed to move between cuts; usually is G0 but some CNC require to specify it
  3637. :return: G-code to cut along the linear feature.
  3638. :rtype: str
  3639. """
  3640. if z_cut is None:
  3641. z_cut = self.z_cut
  3642. if z_move is None:
  3643. z_move = self.z_move
  3644. #
  3645. # if zdownrate is None:
  3646. # zdownrate = self.zdownrate
  3647. if feedrate is None:
  3648. feedrate = self.feedrate
  3649. if feedrate_z is None:
  3650. feedrate_z = self.z_feedrate
  3651. if feedrate_rapid is None:
  3652. feedrate_rapid = self.feedrate_rapid
  3653. # Simplify paths?
  3654. if tolerance > 0:
  3655. target_linear = linear.simplify(tolerance)
  3656. else:
  3657. target_linear = linear
  3658. gcode = ""
  3659. # path = list(target_linear.coords)
  3660. path = self.segment(target_linear.coords)
  3661. p = self.pp_geometry
  3662. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  3663. if self.coordinates_type == "G90":
  3664. # For Absolute coordinates type G90
  3665. first_x = path[0][0]
  3666. first_y = path[0][1]
  3667. else:
  3668. # For Incremental coordinates type G91
  3669. first_x = path[0][0] - old_point[0]
  3670. first_y = path[0][1] - old_point[1]
  3671. # Move fast to 1st point
  3672. if not cont:
  3673. gcode += self.doformat(p.rapid_code, x=first_x, y=first_y) # Move to first point
  3674. # Move down to cutting depth
  3675. if down:
  3676. # Different feedrate for vertical cut?
  3677. gcode += self.doformat(p.z_feedrate_code)
  3678. # gcode += self.doformat(p.feedrate_code)
  3679. gcode += self.doformat(p.down_code, x=first_x, y=first_y, z_cut=z_cut)
  3680. gcode += self.doformat(p.feedrate_code, feedrate=feedrate)
  3681. # Cutting...
  3682. prev_x = first_x
  3683. prev_y = first_y
  3684. for pt in path[1:]:
  3685. if self.app.abort_flag:
  3686. # graceful abort requested by the user
  3687. raise FlatCAMApp.GracefulException
  3688. if self.coordinates_type == "G90":
  3689. # For Absolute coordinates type G90
  3690. next_x = pt[0]
  3691. next_y = pt[1]
  3692. else:
  3693. # For Incremental coordinates type G91
  3694. # next_x = pt[0] - prev_x
  3695. # next_y = pt[1] - prev_y
  3696. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3697. _('G91 coordinates not implemented ...'))
  3698. next_x = pt[0]
  3699. next_y = pt[1]
  3700. gcode += self.doformat(p.linear_code, x=next_x, y=next_y, z=z_cut) # Linear motion to point
  3701. prev_x = pt[0]
  3702. prev_y = pt[1]
  3703. # Up to travelling height.
  3704. if up:
  3705. gcode += self.doformat(p.lift_code, x=prev_x, y=prev_y, z_move=z_move) # Stop cutting
  3706. return gcode
  3707. def linear2gcode_extra(self, linear, tolerance=0, down=True, up=True,
  3708. z_cut=None, z_move=None, zdownrate=None,
  3709. feedrate=None, feedrate_z=None, feedrate_rapid=None, cont=False, old_point=(0, 0)):
  3710. """
  3711. Generates G-code to cut along the linear feature.
  3712. :param linear: The path to cut along.
  3713. :type: Shapely.LinearRing or Shapely.Linear String
  3714. :param tolerance: All points in the simplified object will be within the
  3715. tolerance distance of the original geometry.
  3716. :type tolerance: float
  3717. :param feedrate: speed for cut on X - Y plane
  3718. :param feedrate_z: speed for cut on Z plane
  3719. :param feedrate_rapid: speed to move between cuts; usually is G0 but some CNC require to specify it
  3720. :return: G-code to cut along the linear feature.
  3721. :rtype: str
  3722. """
  3723. if z_cut is None:
  3724. z_cut = self.z_cut
  3725. if z_move is None:
  3726. z_move = self.z_move
  3727. #
  3728. # if zdownrate is None:
  3729. # zdownrate = self.zdownrate
  3730. if feedrate is None:
  3731. feedrate = self.feedrate
  3732. if feedrate_z is None:
  3733. feedrate_z = self.z_feedrate
  3734. if feedrate_rapid is None:
  3735. feedrate_rapid = self.feedrate_rapid
  3736. # Simplify paths?
  3737. if tolerance > 0:
  3738. target_linear = linear.simplify(tolerance)
  3739. else:
  3740. target_linear = linear
  3741. gcode = ""
  3742. path = list(target_linear.coords)
  3743. p = self.pp_geometry
  3744. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  3745. if self.coordinates_type == "G90":
  3746. # For Absolute coordinates type G90
  3747. first_x = path[0][0]
  3748. first_y = path[0][1]
  3749. else:
  3750. # For Incremental coordinates type G91
  3751. first_x = path[0][0] - old_point[0]
  3752. first_y = path[0][1] - old_point[1]
  3753. # Move fast to 1st point
  3754. if not cont:
  3755. gcode += self.doformat(p.rapid_code, x=first_x, y=first_y) # Move to first point
  3756. # Move down to cutting depth
  3757. if down:
  3758. # Different feedrate for vertical cut?
  3759. if self.z_feedrate is not None:
  3760. gcode += self.doformat(p.z_feedrate_code)
  3761. # gcode += self.doformat(p.feedrate_code)
  3762. gcode += self.doformat(p.down_code, x=first_x, y=first_y, z_cut=z_cut)
  3763. gcode += self.doformat(p.feedrate_code, feedrate=feedrate)
  3764. else:
  3765. gcode += self.doformat(p.down_code, x=first_x, y=first_y, z_cut=z_cut) # Start cutting
  3766. # Cutting...
  3767. prev_x = first_x
  3768. prev_y = first_y
  3769. for pt in path[1:]:
  3770. if self.app.abort_flag:
  3771. # graceful abort requested by the user
  3772. raise FlatCAMApp.GracefulException
  3773. if self.coordinates_type == "G90":
  3774. # For Absolute coordinates type G90
  3775. next_x = pt[0]
  3776. next_y = pt[1]
  3777. else:
  3778. # For Incremental coordinates type G91
  3779. # For Incremental coordinates type G91
  3780. # next_x = pt[0] - prev_x
  3781. # next_y = pt[1] - prev_y
  3782. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3783. _('G91 coordinates not implemented ...'))
  3784. next_x = pt[0]
  3785. next_y = pt[1]
  3786. gcode += self.doformat(p.linear_code, x=next_x, y=next_y, z=z_cut) # Linear motion to point
  3787. prev_x = pt[0]
  3788. prev_y = pt[1]
  3789. # this line is added to create an extra cut over the first point in patch
  3790. # to make sure that we remove the copper leftovers
  3791. # Linear motion to the 1st point in the cut path
  3792. if self.coordinates_type == "G90":
  3793. # For Absolute coordinates type G90
  3794. last_x = path[1][0]
  3795. last_y = path[1][1]
  3796. else:
  3797. # For Incremental coordinates type G91
  3798. last_x = path[1][0] - first_x
  3799. last_y = path[1][1] - first_y
  3800. gcode += self.doformat(p.linear_code, x=last_x, y=last_y)
  3801. # Up to travelling height.
  3802. if up:
  3803. gcode += self.doformat(p.lift_code, x=last_x, y=last_y, z_move=z_move) # Stop cutting
  3804. return gcode
  3805. def point2gcode(self, point, old_point=(0, 0)):
  3806. gcode = ""
  3807. if self.app.abort_flag:
  3808. # graceful abort requested by the user
  3809. raise FlatCAMApp.GracefulException
  3810. path = list(point.coords)
  3811. p = self.pp_geometry
  3812. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  3813. if self.coordinates_type == "G90":
  3814. # For Absolute coordinates type G90
  3815. first_x = path[0][0]
  3816. first_y = path[0][1]
  3817. else:
  3818. # For Incremental coordinates type G91
  3819. # first_x = path[0][0] - old_point[0]
  3820. # first_y = path[0][1] - old_point[1]
  3821. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3822. _('G91 coordinates not implemented ...'))
  3823. first_x = path[0][0]
  3824. first_y = path[0][1]
  3825. gcode += self.doformat(p.linear_code, x=first_x, y=first_y) # Move to first point
  3826. if self.z_feedrate is not None:
  3827. gcode += self.doformat(p.z_feedrate_code)
  3828. gcode += self.doformat(p.down_code, x=first_x, y=first_y, z_cut = self.z_cut)
  3829. gcode += self.doformat(p.feedrate_code)
  3830. else:
  3831. gcode += self.doformat(p.down_code, x=first_x, y=first_y, z_cut = self.z_cut) # Start cutting
  3832. gcode += self.doformat(p.lift_code, x=first_x, y=first_y) # Stop cutting
  3833. return gcode
  3834. def export_svg(self, scale_stroke_factor=0.00):
  3835. """
  3836. Exports the CNC Job as a SVG Element
  3837. :scale_factor: float
  3838. :return: SVG Element string
  3839. """
  3840. # scale_factor is a multiplication factor for the SVG stroke-width used within shapely's svg export
  3841. # If not specified then try and use the tool diameter
  3842. # This way what is on screen will match what is outputed for the svg
  3843. # This is quite a useful feature for svg's used with visicut
  3844. if scale_stroke_factor <= 0:
  3845. scale_stroke_factor = self.options['tooldia'] / 2
  3846. # If still 0 then default to 0.05
  3847. # This value appears to work for zooming, and getting the output svg line width
  3848. # to match that viewed on screen with FlatCam
  3849. if scale_stroke_factor == 0:
  3850. scale_stroke_factor = 0.01
  3851. # Separate the list of cuts and travels into 2 distinct lists
  3852. # This way we can add different formatting / colors to both
  3853. cuts = []
  3854. travels = []
  3855. for g in self.gcode_parsed:
  3856. if self.app.abort_flag:
  3857. # graceful abort requested by the user
  3858. raise FlatCAMApp.GracefulException
  3859. if g['kind'][0] == 'C': cuts.append(g)
  3860. if g['kind'][0] == 'T': travels.append(g)
  3861. # Used to determine the overall board size
  3862. self.solid_geometry = cascaded_union([geo['geom'] for geo in self.gcode_parsed])
  3863. # Convert the cuts and travels into single geometry objects we can render as svg xml
  3864. if travels:
  3865. travelsgeom = cascaded_union([geo['geom'] for geo in travels])
  3866. if self.app.abort_flag:
  3867. # graceful abort requested by the user
  3868. raise FlatCAMApp.GracefulException
  3869. if cuts:
  3870. cutsgeom = cascaded_union([geo['geom'] for geo in cuts])
  3871. # Render the SVG Xml
  3872. # The scale factor affects the size of the lines, and the stroke color adds different formatting for each set
  3873. # It's better to have the travels sitting underneath the cuts for visicut
  3874. svg_elem = ""
  3875. if travels:
  3876. svg_elem = travelsgeom.svg(scale_factor=scale_stroke_factor, stroke_color="#F0E24D")
  3877. if cuts:
  3878. svg_elem += cutsgeom.svg(scale_factor=scale_stroke_factor, stroke_color="#5E6CFF")
  3879. return svg_elem
  3880. def bounds(self):
  3881. """
  3882. Returns coordinates of rectangular bounds
  3883. of geometry: (xmin, ymin, xmax, ymax).
  3884. """
  3885. # fixed issue of getting bounds only for one level lists of objects
  3886. # now it can get bounds for nested lists of objects
  3887. log.debug("camlib.CNCJob.bounds()")
  3888. def bounds_rec(obj):
  3889. if type(obj) is list:
  3890. minx = np.Inf
  3891. miny = np.Inf
  3892. maxx = -np.Inf
  3893. maxy = -np.Inf
  3894. for k in obj:
  3895. if type(k) is dict:
  3896. for key in k:
  3897. minx_, miny_, maxx_, maxy_ = bounds_rec(k[key])
  3898. minx = min(minx, minx_)
  3899. miny = min(miny, miny_)
  3900. maxx = max(maxx, maxx_)
  3901. maxy = max(maxy, maxy_)
  3902. else:
  3903. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  3904. minx = min(minx, minx_)
  3905. miny = min(miny, miny_)
  3906. maxx = max(maxx, maxx_)
  3907. maxy = max(maxy, maxy_)
  3908. return minx, miny, maxx, maxy
  3909. else:
  3910. # it's a Shapely object, return it's bounds
  3911. return obj.bounds
  3912. if self.multitool is False:
  3913. log.debug("CNCJob->bounds()")
  3914. if self.solid_geometry is None:
  3915. log.debug("solid_geometry is None")
  3916. return 0, 0, 0, 0
  3917. bounds_coords = bounds_rec(self.solid_geometry)
  3918. else:
  3919. minx = np.Inf
  3920. miny = np.Inf
  3921. maxx = -np.Inf
  3922. maxy = -np.Inf
  3923. for k, v in self.cnc_tools.items():
  3924. minx = np.Inf
  3925. miny = np.Inf
  3926. maxx = -np.Inf
  3927. maxy = -np.Inf
  3928. try:
  3929. for k in v['solid_geometry']:
  3930. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  3931. minx = min(minx, minx_)
  3932. miny = min(miny, miny_)
  3933. maxx = max(maxx, maxx_)
  3934. maxy = max(maxy, maxy_)
  3935. except TypeError:
  3936. minx_, miny_, maxx_, maxy_ = bounds_rec(v['solid_geometry'])
  3937. minx = min(minx, minx_)
  3938. miny = min(miny, miny_)
  3939. maxx = max(maxx, maxx_)
  3940. maxy = max(maxy, maxy_)
  3941. bounds_coords = minx, miny, maxx, maxy
  3942. return bounds_coords
  3943. # TODO This function should be replaced at some point with a "real" function. Until then it's an ugly hack ...
  3944. def scale(self, xfactor, yfactor=None, point=None):
  3945. """
  3946. Scales all the geometry on the XY plane in the object by the
  3947. given factor. Tool sizes, feedrates, or Z-axis dimensions are
  3948. not altered.
  3949. :param factor: Number by which to scale the object.
  3950. :type factor: float
  3951. :param point: the (x,y) coords for the point of origin of scale
  3952. :type tuple of floats
  3953. :return: None
  3954. :rtype: None
  3955. """
  3956. log.debug("camlib.CNCJob.scale()")
  3957. if yfactor is None:
  3958. yfactor = xfactor
  3959. if point is None:
  3960. px = 0
  3961. py = 0
  3962. else:
  3963. px, py = point
  3964. def scale_g(g):
  3965. """
  3966. :param g: 'g' parameter it's a gcode string
  3967. :return: scaled gcode string
  3968. """
  3969. temp_gcode = ''
  3970. header_start = False
  3971. header_stop = False
  3972. units = self.app.defaults['units'].upper()
  3973. lines = StringIO(g)
  3974. for line in lines:
  3975. # this changes the GCODE header ---- UGLY HACK
  3976. if "TOOL DIAMETER" in line or "Feedrate:" in line:
  3977. header_start = True
  3978. if "G20" in line or "G21" in line:
  3979. header_start = False
  3980. header_stop = True
  3981. if header_start is True:
  3982. header_stop = False
  3983. if "in" in line:
  3984. if units == 'MM':
  3985. line = line.replace("in", "mm")
  3986. if "mm" in line:
  3987. if units == 'IN':
  3988. line = line.replace("mm", "in")
  3989. # find any float number in header (even multiple on the same line) and convert it
  3990. numbers_in_header = re.findall(self.g_nr_re, line)
  3991. if numbers_in_header:
  3992. for nr in numbers_in_header:
  3993. new_nr = float(nr) * xfactor
  3994. # replace the updated string
  3995. line = line.replace(nr, ('%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_nr))
  3996. )
  3997. # this scales all the X and Y and Z and F values and also the Tool Dia in the toolchange message
  3998. if header_stop is True:
  3999. if "G20" in line:
  4000. if units == 'MM':
  4001. line = line.replace("G20", "G21")
  4002. if "G21" in line:
  4003. if units == 'IN':
  4004. line = line.replace("G21", "G20")
  4005. # find the X group
  4006. match_x = self.g_x_re.search(line)
  4007. if match_x:
  4008. if match_x.group(1) is not None:
  4009. new_x = float(match_x.group(1)[1:]) * xfactor
  4010. # replace the updated string
  4011. line = line.replace(
  4012. match_x.group(1),
  4013. 'X%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_x)
  4014. )
  4015. # find the Y group
  4016. match_y = self.g_y_re.search(line)
  4017. if match_y:
  4018. if match_y.group(1) is not None:
  4019. new_y = float(match_y.group(1)[1:]) * yfactor
  4020. line = line.replace(
  4021. match_y.group(1),
  4022. 'Y%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_y)
  4023. )
  4024. # find the Z group
  4025. match_z = self.g_z_re.search(line)
  4026. if match_z:
  4027. if match_z.group(1) is not None:
  4028. new_z = float(match_z.group(1)[1:]) * xfactor
  4029. line = line.replace(
  4030. match_z.group(1),
  4031. 'Z%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_z)
  4032. )
  4033. # find the F group
  4034. match_f = self.g_f_re.search(line)
  4035. if match_f:
  4036. if match_f.group(1) is not None:
  4037. new_f = float(match_f.group(1)[1:]) * xfactor
  4038. line = line.replace(
  4039. match_f.group(1),
  4040. 'F%.*f' % (self.app.defaults["cncjob_fr_decimals"], new_f)
  4041. )
  4042. # find the T group (tool dia on toolchange)
  4043. match_t = self.g_t_re.search(line)
  4044. if match_t:
  4045. if match_t.group(1) is not None:
  4046. new_t = float(match_t.group(1)[1:]) * xfactor
  4047. line = line.replace(
  4048. match_t.group(1),
  4049. '= %.*f' % (self.app.defaults["cncjob_coords_decimals"], new_t)
  4050. )
  4051. temp_gcode += line
  4052. lines.close()
  4053. header_stop = False
  4054. return temp_gcode
  4055. if self.multitool is False:
  4056. # offset Gcode
  4057. self.gcode = scale_g(self.gcode)
  4058. # variables to display the percentage of work done
  4059. self.geo_len = 0
  4060. try:
  4061. for g in self.gcode_parsed:
  4062. self.geo_len += 1
  4063. except TypeError:
  4064. self.geo_len = 1
  4065. self.old_disp_number = 0
  4066. self.el_count = 0
  4067. # scale geometry
  4068. for g in self.gcode_parsed:
  4069. try:
  4070. g['geom'] = affinity.scale(g['geom'], xfactor, yfactor, origin=(px, py))
  4071. except AttributeError:
  4072. return g['geom']
  4073. self.el_count += 1
  4074. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  4075. if self.old_disp_number < disp_number <= 100:
  4076. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  4077. self.old_disp_number = disp_number
  4078. self.create_geometry()
  4079. else:
  4080. for k, v in self.cnc_tools.items():
  4081. # scale Gcode
  4082. v['gcode'] = scale_g(v['gcode'])
  4083. # variables to display the percentage of work done
  4084. self.geo_len = 0
  4085. try:
  4086. for g in v['gcode_parsed']:
  4087. self.geo_len += 1
  4088. except TypeError:
  4089. self.geo_len = 1
  4090. self.old_disp_number = 0
  4091. self.el_count = 0
  4092. # scale gcode_parsed
  4093. for g in v['gcode_parsed']:
  4094. try:
  4095. g['geom'] = affinity.scale(g['geom'], xfactor, yfactor, origin=(px, py))
  4096. except AttributeError:
  4097. return g['geom']
  4098. self.el_count += 1
  4099. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  4100. if self.old_disp_number < disp_number <= 100:
  4101. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  4102. self.old_disp_number = disp_number
  4103. v['solid_geometry'] = cascaded_union([geo['geom'] for geo in v['gcode_parsed']])
  4104. self.create_geometry()
  4105. self.app.proc_container.new_text = ''
  4106. def offset(self, vect):
  4107. """
  4108. Offsets all the geometry on the XY plane in the object by the
  4109. given vector.
  4110. Offsets all the GCODE on the XY plane in the object by the
  4111. given vector.
  4112. g_offsetx_re, g_offsety_re, multitool, cnnc_tools are attributes of FlatCAMCNCJob class in camlib
  4113. :param vect: (x, y) offset vector.
  4114. :type vect: tuple
  4115. :return: None
  4116. """
  4117. log.debug("camlib.CNCJob.offset()")
  4118. dx, dy = vect
  4119. def offset_g(g):
  4120. """
  4121. :param g: 'g' parameter it's a gcode string
  4122. :return: offseted gcode string
  4123. """
  4124. temp_gcode = ''
  4125. lines = StringIO(g)
  4126. for line in lines:
  4127. # find the X group
  4128. match_x = self.g_x_re.search(line)
  4129. if match_x:
  4130. if match_x.group(1) is not None:
  4131. # get the coordinate and add X offset
  4132. new_x = float(match_x.group(1)[1:]) + dx
  4133. # replace the updated string
  4134. line = line.replace(
  4135. match_x.group(1),
  4136. 'X%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_x)
  4137. )
  4138. match_y = self.g_y_re.search(line)
  4139. if match_y:
  4140. if match_y.group(1) is not None:
  4141. new_y = float(match_y.group(1)[1:]) + dy
  4142. line = line.replace(
  4143. match_y.group(1),
  4144. 'Y%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_y)
  4145. )
  4146. temp_gcode += line
  4147. lines.close()
  4148. return temp_gcode
  4149. if self.multitool is False:
  4150. # offset Gcode
  4151. self.gcode = offset_g(self.gcode)
  4152. # variables to display the percentage of work done
  4153. self.geo_len = 0
  4154. try:
  4155. for g in self.gcode_parsed:
  4156. self.geo_len += 1
  4157. except TypeError:
  4158. self.geo_len = 1
  4159. self.old_disp_number = 0
  4160. self.el_count = 0
  4161. # offset geometry
  4162. for g in self.gcode_parsed:
  4163. try:
  4164. g['geom'] = affinity.translate(g['geom'], xoff=dx, yoff=dy)
  4165. except AttributeError:
  4166. return g['geom']
  4167. self.el_count += 1
  4168. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  4169. if self.old_disp_number < disp_number <= 100:
  4170. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  4171. self.old_disp_number = disp_number
  4172. self.create_geometry()
  4173. else:
  4174. for k, v in self.cnc_tools.items():
  4175. # offset Gcode
  4176. v['gcode'] = offset_g(v['gcode'])
  4177. # variables to display the percentage of work done
  4178. self.geo_len = 0
  4179. try:
  4180. for g in v['gcode_parsed']:
  4181. self.geo_len += 1
  4182. except TypeError:
  4183. self.geo_len = 1
  4184. self.old_disp_number = 0
  4185. self.el_count = 0
  4186. # offset gcode_parsed
  4187. for g in v['gcode_parsed']:
  4188. try:
  4189. g['geom'] = affinity.translate(g['geom'], xoff=dx, yoff=dy)
  4190. except AttributeError:
  4191. return g['geom']
  4192. self.el_count += 1
  4193. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  4194. if self.old_disp_number < disp_number <= 100:
  4195. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  4196. self.old_disp_number = disp_number
  4197. # for the bounding box
  4198. v['solid_geometry'] = cascaded_union([geo['geom'] for geo in v['gcode_parsed']])
  4199. self.app.proc_container.new_text = ''
  4200. def mirror(self, axis, point):
  4201. """
  4202. Mirror the geometrys of an object by an given axis around the coordinates of the 'point'
  4203. :param angle:
  4204. :param point: tupple of coordinates (x,y)
  4205. :return:
  4206. """
  4207. log.debug("camlib.CNCJob.mirror()")
  4208. px, py = point
  4209. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  4210. # variables to display the percentage of work done
  4211. self.geo_len = 0
  4212. try:
  4213. for g in self.gcode_parsed:
  4214. self.geo_len += 1
  4215. except TypeError:
  4216. self.geo_len = 1
  4217. self.old_disp_number = 0
  4218. self.el_count = 0
  4219. for g in self.gcode_parsed:
  4220. try:
  4221. g['geom'] = affinity.scale(g['geom'], xscale, yscale, origin=(px, py))
  4222. except AttributeError:
  4223. return g['geom']
  4224. self.el_count += 1
  4225. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  4226. if self.old_disp_number < disp_number <= 100:
  4227. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  4228. self.old_disp_number = disp_number
  4229. self.create_geometry()
  4230. self.app.proc_container.new_text = ''
  4231. def skew(self, angle_x, angle_y, point):
  4232. """
  4233. Shear/Skew the geometries of an object by angles along x and y dimensions.
  4234. Parameters
  4235. ----------
  4236. angle_x, angle_y : float, float
  4237. The shear angle(s) for the x and y axes respectively. These can be
  4238. specified in either degrees (default) or radians by setting
  4239. use_radians=True.
  4240. point: tupple of coordinates (x,y)
  4241. See shapely manual for more information:
  4242. http://toblerity.org/shapely/manual.html#affine-transformations
  4243. """
  4244. log.debug("camlib.CNCJob.skew()")
  4245. px, py = point
  4246. # variables to display the percentage of work done
  4247. self.geo_len = 0
  4248. try:
  4249. for g in self.gcode_parsed:
  4250. self.geo_len += 1
  4251. except TypeError:
  4252. self.geo_len = 1
  4253. self.old_disp_number = 0
  4254. self.el_count = 0
  4255. for g in self.gcode_parsed:
  4256. try:
  4257. g['geom'] = affinity.skew(g['geom'], angle_x, angle_y, origin=(px, py))
  4258. except AttributeError:
  4259. return g['geom']
  4260. self.el_count += 1
  4261. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  4262. if self.old_disp_number < disp_number <= 100:
  4263. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  4264. self.old_disp_number = disp_number
  4265. self.create_geometry()
  4266. self.app.proc_container.new_text = ''
  4267. def rotate(self, angle, point):
  4268. """
  4269. Rotate the geometrys of an object by an given angle around the coordinates of the 'point'
  4270. :param angle:
  4271. :param point: tupple of coordinates (x,y)
  4272. :return:
  4273. """
  4274. log.debug("camlib.CNCJob.rotate()")
  4275. px, py = point
  4276. # variables to display the percentage of work done
  4277. self.geo_len = 0
  4278. try:
  4279. for g in self.gcode_parsed:
  4280. self.geo_len += 1
  4281. except TypeError:
  4282. self.geo_len = 1
  4283. self.old_disp_number = 0
  4284. self.el_count = 0
  4285. for g in self.gcode_parsed:
  4286. try:
  4287. g['geom'] = affinity.rotate(g['geom'], angle, origin=(px, py))
  4288. except AttributeError:
  4289. return g['geom']
  4290. self.el_count += 1
  4291. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  4292. if self.old_disp_number < disp_number <= 100:
  4293. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  4294. self.old_disp_number = disp_number
  4295. self.create_geometry()
  4296. self.app.proc_container.new_text = ''
  4297. def get_bounds(geometry_list):
  4298. xmin = np.Inf
  4299. ymin = np.Inf
  4300. xmax = -np.Inf
  4301. ymax = -np.Inf
  4302. for gs in geometry_list:
  4303. try:
  4304. gxmin, gymin, gxmax, gymax = gs.bounds()
  4305. xmin = min([xmin, gxmin])
  4306. ymin = min([ymin, gymin])
  4307. xmax = max([xmax, gxmax])
  4308. ymax = max([ymax, gymax])
  4309. except Exception:
  4310. log.warning("DEVELOPMENT: Tried to get bounds of empty geometry.")
  4311. return [xmin, ymin, xmax, ymax]
  4312. def arc(center, radius, start, stop, direction, steps_per_circ):
  4313. """
  4314. Creates a list of point along the specified arc.
  4315. :param center: Coordinates of the center [x, y]
  4316. :type center: list
  4317. :param radius: Radius of the arc.
  4318. :type radius: float
  4319. :param start: Starting angle in radians
  4320. :type start: float
  4321. :param stop: End angle in radians
  4322. :type stop: float
  4323. :param direction: Orientation of the arc, "CW" or "CCW"
  4324. :type direction: string
  4325. :param steps_per_circ: Number of straight line segments to
  4326. represent a circle.
  4327. :type steps_per_circ: int
  4328. :return: The desired arc, as list of tuples
  4329. :rtype: list
  4330. """
  4331. # TODO: Resolution should be established by maximum error from the exact arc.
  4332. da_sign = {"cw": -1.0, "ccw": 1.0}
  4333. points = []
  4334. if direction == "ccw" and stop <= start:
  4335. stop += 2 * np.pi
  4336. if direction == "cw" and stop >= start:
  4337. stop -= 2 * np.pi
  4338. angle = abs(stop - start)
  4339. # angle = stop-start
  4340. steps = max([int(np.ceil(angle / (2 * np.pi) * steps_per_circ)), 2])
  4341. delta_angle = da_sign[direction] * angle * 1.0 / steps
  4342. for i in range(steps + 1):
  4343. theta = start + delta_angle * i
  4344. points.append((center[0] + radius * np.cos(theta), center[1] + radius * np.sin(theta)))
  4345. return points
  4346. def arc2(p1, p2, center, direction, steps_per_circ):
  4347. r = np.sqrt((center[0] - p1[0]) ** 2 + (center[1] - p1[1]) ** 2)
  4348. start = np.arctan2(p1[1] - center[1], p1[0] - center[0])
  4349. stop = np.arctan2(p2[1] - center[1], p2[0] - center[0])
  4350. return arc(center, r, start, stop, direction, steps_per_circ)
  4351. def arc_angle(start, stop, direction):
  4352. if direction == "ccw" and stop <= start:
  4353. stop += 2 * np.pi
  4354. if direction == "cw" and stop >= start:
  4355. stop -= 2 * np.pi
  4356. angle = abs(stop - start)
  4357. return angle
  4358. # def find_polygon(poly, point):
  4359. # """
  4360. # Find an object that object.contains(Point(point)) in
  4361. # poly, which can can be iterable, contain iterable of, or
  4362. # be itself an implementer of .contains().
  4363. #
  4364. # :param poly: See description
  4365. # :return: Polygon containing point or None.
  4366. # """
  4367. #
  4368. # if poly is None:
  4369. # return None
  4370. #
  4371. # try:
  4372. # for sub_poly in poly:
  4373. # p = find_polygon(sub_poly, point)
  4374. # if p is not None:
  4375. # return p
  4376. # except TypeError:
  4377. # try:
  4378. # if poly.contains(Point(point)):
  4379. # return poly
  4380. # except AttributeError:
  4381. # return None
  4382. #
  4383. # return None
  4384. def to_dict(obj):
  4385. """
  4386. Makes the following types into serializable form:
  4387. * ApertureMacro
  4388. * BaseGeometry
  4389. :param obj: Shapely geometry.
  4390. :type obj: BaseGeometry
  4391. :return: Dictionary with serializable form if ``obj`` was
  4392. BaseGeometry or ApertureMacro, otherwise returns ``obj``.
  4393. """
  4394. if isinstance(obj, ApertureMacro):
  4395. return {
  4396. "__class__": "ApertureMacro",
  4397. "__inst__": obj.to_dict()
  4398. }
  4399. if isinstance(obj, BaseGeometry):
  4400. return {
  4401. "__class__": "Shply",
  4402. "__inst__": sdumps(obj)
  4403. }
  4404. return obj
  4405. def dict2obj(d):
  4406. """
  4407. Default deserializer.
  4408. :param d: Serializable dictionary representation of an object
  4409. to be reconstructed.
  4410. :return: Reconstructed object.
  4411. """
  4412. if '__class__' in d and '__inst__' in d:
  4413. if d['__class__'] == "Shply":
  4414. return sloads(d['__inst__'])
  4415. if d['__class__'] == "ApertureMacro":
  4416. am = ApertureMacro()
  4417. am.from_dict(d['__inst__'])
  4418. return am
  4419. return d
  4420. else:
  4421. return d
  4422. # def plotg(geo, solid_poly=False, color="black"):
  4423. # try:
  4424. # __ = iter(geo)
  4425. # except:
  4426. # geo = [geo]
  4427. #
  4428. # for g in geo:
  4429. # if type(g) == Polygon:
  4430. # if solid_poly:
  4431. # patch = PolygonPatch(g,
  4432. # facecolor="#BBF268",
  4433. # edgecolor="#006E20",
  4434. # alpha=0.75,
  4435. # zorder=2)
  4436. # ax = subplot(111)
  4437. # ax.add_patch(patch)
  4438. # else:
  4439. # x, y = g.exterior.coords.xy
  4440. # plot(x, y, color=color)
  4441. # for ints in g.interiors:
  4442. # x, y = ints.coords.xy
  4443. # plot(x, y, color=color)
  4444. # continue
  4445. #
  4446. # if type(g) == LineString or type(g) == LinearRing:
  4447. # x, y = g.coords.xy
  4448. # plot(x, y, color=color)
  4449. # continue
  4450. #
  4451. # if type(g) == Point:
  4452. # x, y = g.coords.xy
  4453. # plot(x, y, 'o')
  4454. # continue
  4455. #
  4456. # try:
  4457. # __ = iter(g)
  4458. # plotg(g, color=color)
  4459. # except:
  4460. # log.error("Cannot plot: " + str(type(g)))
  4461. # continue
  4462. # def alpha_shape(points, alpha):
  4463. # """
  4464. # Compute the alpha shape (concave hull) of a set of points.
  4465. #
  4466. # @param points: Iterable container of points.
  4467. # @param alpha: alpha value to influence the gooeyness of the border. Smaller
  4468. # numbers don't fall inward as much as larger numbers. Too large,
  4469. # and you lose everything!
  4470. # """
  4471. # if len(points) < 4:
  4472. # # When you have a triangle, there is no sense in computing an alpha
  4473. # # shape.
  4474. # return MultiPoint(list(points)).convex_hull
  4475. #
  4476. # def add_edge(edges, edge_points, coords, i, j):
  4477. # """Add a line between the i-th and j-th points, if not in the list already"""
  4478. # if (i, j) in edges or (j, i) in edges:
  4479. # # already added
  4480. # return
  4481. # edges.add( (i, j) )
  4482. # edge_points.append(coords[ [i, j] ])
  4483. #
  4484. # coords = np.array([point.coords[0] for point in points])
  4485. #
  4486. # tri = Delaunay(coords)
  4487. # edges = set()
  4488. # edge_points = []
  4489. # # loop over triangles:
  4490. # # ia, ib, ic = indices of corner points of the triangle
  4491. # for ia, ib, ic in tri.vertices:
  4492. # pa = coords[ia]
  4493. # pb = coords[ib]
  4494. # pc = coords[ic]
  4495. #
  4496. # # Lengths of sides of triangle
  4497. # a = math.sqrt((pa[0]-pb[0])**2 + (pa[1]-pb[1])**2)
  4498. # b = math.sqrt((pb[0]-pc[0])**2 + (pb[1]-pc[1])**2)
  4499. # c = math.sqrt((pc[0]-pa[0])**2 + (pc[1]-pa[1])**2)
  4500. #
  4501. # # Semiperimeter of triangle
  4502. # s = (a + b + c)/2.0
  4503. #
  4504. # # Area of triangle by Heron's formula
  4505. # area = math.sqrt(s*(s-a)*(s-b)*(s-c))
  4506. # circum_r = a*b*c/(4.0*area)
  4507. #
  4508. # # Here's the radius filter.
  4509. # #print circum_r
  4510. # if circum_r < 1.0/alpha:
  4511. # add_edge(edges, edge_points, coords, ia, ib)
  4512. # add_edge(edges, edge_points, coords, ib, ic)
  4513. # add_edge(edges, edge_points, coords, ic, ia)
  4514. #
  4515. # m = MultiLineString(edge_points)
  4516. # triangles = list(polygonize(m))
  4517. # return cascaded_union(triangles), edge_points
  4518. # def voronoi(P):
  4519. # """
  4520. # Returns a list of all edges of the voronoi diagram for the given input points.
  4521. # """
  4522. # delauny = Delaunay(P)
  4523. # triangles = delauny.points[delauny.vertices]
  4524. #
  4525. # circum_centers = np.array([triangle_csc(tri) for tri in triangles])
  4526. # long_lines_endpoints = []
  4527. #
  4528. # lineIndices = []
  4529. # for i, triangle in enumerate(triangles):
  4530. # circum_center = circum_centers[i]
  4531. # for j, neighbor in enumerate(delauny.neighbors[i]):
  4532. # if neighbor != -1:
  4533. # lineIndices.append((i, neighbor))
  4534. # else:
  4535. # ps = triangle[(j+1)%3] - triangle[(j-1)%3]
  4536. # ps = np.array((ps[1], -ps[0]))
  4537. #
  4538. # middle = (triangle[(j+1)%3] + triangle[(j-1)%3]) * 0.5
  4539. # di = middle - triangle[j]
  4540. #
  4541. # ps /= np.linalg.norm(ps)
  4542. # di /= np.linalg.norm(di)
  4543. #
  4544. # if np.dot(di, ps) < 0.0:
  4545. # ps *= -1000.0
  4546. # else:
  4547. # ps *= 1000.0
  4548. #
  4549. # long_lines_endpoints.append(circum_center + ps)
  4550. # lineIndices.append((i, len(circum_centers) + len(long_lines_endpoints)-1))
  4551. #
  4552. # vertices = np.vstack((circum_centers, long_lines_endpoints))
  4553. #
  4554. # # filter out any duplicate lines
  4555. # lineIndicesSorted = np.sort(lineIndices) # make (1,2) and (2,1) both (1,2)
  4556. # lineIndicesTupled = [tuple(row) for row in lineIndicesSorted]
  4557. # lineIndicesUnique = np.unique(lineIndicesTupled)
  4558. #
  4559. # return vertices, lineIndicesUnique
  4560. #
  4561. #
  4562. # def triangle_csc(pts):
  4563. # rows, cols = pts.shape
  4564. #
  4565. # A = np.bmat([[2 * np.dot(pts, pts.T), np.ones((rows, 1))],
  4566. # [np.ones((1, rows)), np.zeros((1, 1))]])
  4567. #
  4568. # b = np.hstack((np.sum(pts * pts, axis=1), np.ones((1))))
  4569. # x = np.linalg.solve(A,b)
  4570. # bary_coords = x[:-1]
  4571. # return np.sum(pts * np.tile(bary_coords.reshape((pts.shape[0], 1)), (1, pts.shape[1])), axis=0)
  4572. #
  4573. #
  4574. # def voronoi_cell_lines(points, vertices, lineIndices):
  4575. # """
  4576. # Returns a mapping from a voronoi cell to its edges.
  4577. #
  4578. # :param points: shape (m,2)
  4579. # :param vertices: shape (n,2)
  4580. # :param lineIndices: shape (o,2)
  4581. # :rtype: dict point index -> list of shape (n,2) with vertex indices
  4582. # """
  4583. # kd = KDTree(points)
  4584. #
  4585. # cells = collections.defaultdict(list)
  4586. # for i1, i2 in lineIndices:
  4587. # v1, v2 = vertices[i1], vertices[i2]
  4588. # mid = (v1+v2)/2
  4589. # _, (p1Idx, p2Idx) = kd.query(mid, 2)
  4590. # cells[p1Idx].append((i1, i2))
  4591. # cells[p2Idx].append((i1, i2))
  4592. #
  4593. # return cells
  4594. #
  4595. #
  4596. # def voronoi_edges2polygons(cells):
  4597. # """
  4598. # Transforms cell edges into polygons.
  4599. #
  4600. # :param cells: as returned from voronoi_cell_lines
  4601. # :rtype: dict point index -> list of vertex indices which form a polygon
  4602. # """
  4603. #
  4604. # # first, close the outer cells
  4605. # for pIdx, lineIndices_ in cells.items():
  4606. # dangling_lines = []
  4607. # for i1, i2 in lineIndices_:
  4608. # p = (i1, i2)
  4609. # connections = filter(lambda k: p != k and
  4610. # (p[0] == k[0] or p[0] == k[1] or p[1] == k[0] or p[1] == k[1]), lineIndices_)
  4611. # # connections = filter(lambda (i1_, i2_): (i1, i2) != (i1_, i2_) and
  4612. # (i1 == i1_ or i1 == i2_ or i2 == i1_ or i2 == i2_), lineIndices_)
  4613. # assert 1 <= len(connections) <= 2
  4614. # if len(connections) == 1:
  4615. # dangling_lines.append((i1, i2))
  4616. # assert len(dangling_lines) in [0, 2]
  4617. # if len(dangling_lines) == 2:
  4618. # (i11, i12), (i21, i22) = dangling_lines
  4619. # s = (i11, i12)
  4620. # t = (i21, i22)
  4621. #
  4622. # # determine which line ends are unconnected
  4623. # connected = filter(lambda k: k != s and (k[0] == s[0] or k[1] == s[0]), lineIndices_)
  4624. # # connected = filter(lambda (i1,i2): (i1,i2) != (i11,i12) and (i1 == i11 or i2 == i11), lineIndices_)
  4625. # i11Unconnected = len(connected) == 0
  4626. #
  4627. # connected = filter(lambda k: k != t and (k[0] == t[0] or k[1] == t[0]), lineIndices_)
  4628. # # connected = filter(lambda (i1,i2): (i1,i2) != (i21,i22) and (i1 == i21 or i2 == i21), lineIndices_)
  4629. # i21Unconnected = len(connected) == 0
  4630. #
  4631. # startIdx = i11 if i11Unconnected else i12
  4632. # endIdx = i21 if i21Unconnected else i22
  4633. #
  4634. # cells[pIdx].append((startIdx, endIdx))
  4635. #
  4636. # # then, form polygons by storing vertex indices in (counter-)clockwise order
  4637. # polys = dict()
  4638. # for pIdx, lineIndices_ in cells.items():
  4639. # # get a directed graph which contains both directions and arbitrarily follow one of both
  4640. # directedGraph = lineIndices_ + [(i2, i1) for (i1, i2) in lineIndices_]
  4641. # directedGraphMap = collections.defaultdict(list)
  4642. # for (i1, i2) in directedGraph:
  4643. # directedGraphMap[i1].append(i2)
  4644. # orderedEdges = []
  4645. # currentEdge = directedGraph[0]
  4646. # while len(orderedEdges) < len(lineIndices_):
  4647. # i1 = currentEdge[1]
  4648. # i2 = directedGraphMap[i1][0] if directedGraphMap[i1][0] != currentEdge[0] else directedGraphMap[i1][1]
  4649. # nextEdge = (i1, i2)
  4650. # orderedEdges.append(nextEdge)
  4651. # currentEdge = nextEdge
  4652. #
  4653. # polys[pIdx] = [i1 for (i1, i2) in orderedEdges]
  4654. #
  4655. # return polys
  4656. #
  4657. #
  4658. # def voronoi_polygons(points):
  4659. # """
  4660. # Returns the voronoi polygon for each input point.
  4661. #
  4662. # :param points: shape (n,2)
  4663. # :rtype: list of n polygons where each polygon is an array of vertices
  4664. # """
  4665. # vertices, lineIndices = voronoi(points)
  4666. # cells = voronoi_cell_lines(points, vertices, lineIndices)
  4667. # polys = voronoi_edges2polygons(cells)
  4668. # polylist = []
  4669. # for i in range(len(points)):
  4670. # poly = vertices[np.asarray(polys[i])]
  4671. # polylist.append(poly)
  4672. # return polylist
  4673. #
  4674. #
  4675. # class Zprofile:
  4676. # def __init__(self):
  4677. #
  4678. # # data contains lists of [x, y, z]
  4679. # self.data = []
  4680. #
  4681. # # Computed voronoi polygons (shapely)
  4682. # self.polygons = []
  4683. # pass
  4684. #
  4685. # # def plot_polygons(self):
  4686. # # axes = plt.subplot(1, 1, 1)
  4687. # #
  4688. # # plt.axis([-0.05, 1.05, -0.05, 1.05])
  4689. # #
  4690. # # for poly in self.polygons:
  4691. # # p = PolygonPatch(poly, facecolor=np.random.rand(3, 1), alpha=0.3)
  4692. # # axes.add_patch(p)
  4693. #
  4694. # def init_from_csv(self, filename):
  4695. # pass
  4696. #
  4697. # def init_from_string(self, zpstring):
  4698. # pass
  4699. #
  4700. # def init_from_list(self, zplist):
  4701. # self.data = zplist
  4702. #
  4703. # def generate_polygons(self):
  4704. # self.polygons = [Polygon(p) for p in voronoi_polygons(array([[x[0], x[1]] for x in self.data]))]
  4705. #
  4706. # def normalize(self, origin):
  4707. # pass
  4708. #
  4709. # def paste(self, path):
  4710. # """
  4711. # Return a list of dictionaries containing the parts of the original
  4712. # path and their z-axis offset.
  4713. # """
  4714. #
  4715. # # At most one region/polygon will contain the path
  4716. # containing = [i for i in range(len(self.polygons)) if self.polygons[i].contains(path)]
  4717. #
  4718. # if len(containing) > 0:
  4719. # return [{"path": path, "z": self.data[containing[0]][2]}]
  4720. #
  4721. # # All region indexes that intersect with the path
  4722. # crossing = [i for i in range(len(self.polygons)) if self.polygons[i].intersects(path)]
  4723. #
  4724. # return [{"path": path.intersection(self.polygons[i]),
  4725. # "z": self.data[i][2]} for i in crossing]
  4726. def autolist(obj):
  4727. try:
  4728. __ = iter(obj)
  4729. return obj
  4730. except TypeError:
  4731. return [obj]
  4732. def three_point_circle(p1, p2, p3):
  4733. """
  4734. Computes the center and radius of a circle from
  4735. 3 points on its circumference.
  4736. :param p1: Point 1
  4737. :param p2: Point 2
  4738. :param p3: Point 3
  4739. :return: center, radius
  4740. """
  4741. # Midpoints
  4742. a1 = (p1 + p2) / 2.0
  4743. a2 = (p2 + p3) / 2.0
  4744. # Normals
  4745. b1 = np.dot((p2 - p1), np.array([[0, -1], [1, 0]], dtype=np.float32))
  4746. b2 = np.dot((p3 - p2), np.array([[0, 1], [-1, 0]], dtype=np.float32))
  4747. # Params
  4748. try:
  4749. T = solve(np.transpose(np.array([-b1, b2])), a1 - a2)
  4750. except Exception as e:
  4751. log.debug("camlib.three_point_circle() --> %s" % str(e))
  4752. return
  4753. # Center
  4754. center = a1 + b1 * T[0]
  4755. # Radius
  4756. radius = np.linalg.norm(center - p1)
  4757. return center, radius, T[0]
  4758. def distance(pt1, pt2):
  4759. return np.sqrt((pt1[0] - pt2[0]) ** 2 + (pt1[1] - pt2[1]) ** 2)
  4760. def distance_euclidian(x1, y1, x2, y2):
  4761. return np.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
  4762. class FlatCAMRTree(object):
  4763. """
  4764. Indexes geometry (Any object with "cooords" property containing
  4765. a list of tuples with x, y values). Objects are indexed by
  4766. all their points by default. To index by arbitrary points,
  4767. override self.points2obj.
  4768. """
  4769. def __init__(self):
  4770. # Python RTree Index
  4771. self.rti = rtindex.Index()
  4772. # ## Track object-point relationship
  4773. # Each is list of points in object.
  4774. self.obj2points = []
  4775. # Index is index in rtree, value is index of
  4776. # object in obj2points.
  4777. self.points2obj = []
  4778. self.get_points = lambda go: go.coords
  4779. def grow_obj2points(self, idx):
  4780. """
  4781. Increases the size of self.obj2points to fit
  4782. idx + 1 items.
  4783. :param idx: Index to fit into list.
  4784. :return: None
  4785. """
  4786. if len(self.obj2points) > idx:
  4787. # len == 2, idx == 1, ok.
  4788. return
  4789. else:
  4790. # len == 2, idx == 2, need 1 more.
  4791. # range(2, 3)
  4792. for i in range(len(self.obj2points), idx + 1):
  4793. self.obj2points.append([])
  4794. def insert(self, objid, obj):
  4795. self.grow_obj2points(objid)
  4796. self.obj2points[objid] = []
  4797. for pt in self.get_points(obj):
  4798. self.rti.insert(len(self.points2obj), (pt[0], pt[1], pt[0], pt[1]), obj=objid)
  4799. self.obj2points[objid].append(len(self.points2obj))
  4800. self.points2obj.append(objid)
  4801. def remove_obj(self, objid, obj):
  4802. # Use all ptids to delete from index
  4803. for i, pt in enumerate(self.get_points(obj)):
  4804. try:
  4805. self.rti.delete(self.obj2points[objid][i], (pt[0], pt[1], pt[0], pt[1]))
  4806. except IndexError:
  4807. pass
  4808. def nearest(self, pt):
  4809. """
  4810. Will raise StopIteration if no items are found.
  4811. :param pt:
  4812. :return:
  4813. """
  4814. return next(self.rti.nearest(pt, objects=True))
  4815. class FlatCAMRTreeStorage(FlatCAMRTree):
  4816. """
  4817. Just like FlatCAMRTree it indexes geometry, but also serves
  4818. as storage for the geometry.
  4819. """
  4820. def __init__(self):
  4821. # super(FlatCAMRTreeStorage, self).__init__()
  4822. super().__init__()
  4823. self.objects = []
  4824. # Optimization attempt!
  4825. self.indexes = {}
  4826. def insert(self, obj):
  4827. self.objects.append(obj)
  4828. idx = len(self.objects) - 1
  4829. # Note: Shapely objects are not hashable any more, althought
  4830. # there seem to be plans to re-introduce the feature in
  4831. # version 2.0. For now, we will index using the object's id,
  4832. # but it's important to remember that shapely geometry is
  4833. # mutable, ie. it can be modified to a totally different shape
  4834. # and continue to have the same id.
  4835. # self.indexes[obj] = idx
  4836. self.indexes[id(obj)] = idx
  4837. # super(FlatCAMRTreeStorage, self).insert(idx, obj)
  4838. super().insert(idx, obj)
  4839. # @profile
  4840. def remove(self, obj):
  4841. # See note about self.indexes in insert().
  4842. # objidx = self.indexes[obj]
  4843. objidx = self.indexes[id(obj)]
  4844. # Remove from list
  4845. self.objects[objidx] = None
  4846. # Remove from index
  4847. self.remove_obj(objidx, obj)
  4848. def get_objects(self):
  4849. return (o for o in self.objects if o is not None)
  4850. def nearest(self, pt):
  4851. """
  4852. Returns the nearest matching points and the object
  4853. it belongs to.
  4854. :param pt: Query point.
  4855. :return: (match_x, match_y), Object owner of
  4856. matching point.
  4857. :rtype: tuple
  4858. """
  4859. tidx = super(FlatCAMRTreeStorage, self).nearest(pt)
  4860. return (tidx.bbox[0], tidx.bbox[1]), self.objects[tidx.object]
  4861. # class myO:
  4862. # def __init__(self, coords):
  4863. # self.coords = coords
  4864. #
  4865. #
  4866. # def test_rti():
  4867. #
  4868. # o1 = myO([(0, 0), (0, 1), (1, 1)])
  4869. # o2 = myO([(2, 0), (2, 1), (2, 1)])
  4870. # o3 = myO([(2, 0), (2, 1), (3, 1)])
  4871. #
  4872. # os = [o1, o2]
  4873. #
  4874. # idx = FlatCAMRTree()
  4875. #
  4876. # for o in range(len(os)):
  4877. # idx.insert(o, os[o])
  4878. #
  4879. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  4880. #
  4881. # idx.remove_obj(0, o1)
  4882. #
  4883. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  4884. #
  4885. # idx.remove_obj(1, o2)
  4886. #
  4887. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  4888. #
  4889. #
  4890. # def test_rtis():
  4891. #
  4892. # o1 = myO([(0, 0), (0, 1), (1, 1)])
  4893. # o2 = myO([(2, 0), (2, 1), (2, 1)])
  4894. # o3 = myO([(2, 0), (2, 1), (3, 1)])
  4895. #
  4896. # os = [o1, o2]
  4897. #
  4898. # idx = FlatCAMRTreeStorage()
  4899. #
  4900. # for o in range(len(os)):
  4901. # idx.insert(os[o])
  4902. #
  4903. # #os = None
  4904. # #o1 = None
  4905. # #o2 = None
  4906. #
  4907. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  4908. #
  4909. # idx.remove(idx.nearest((2,0))[1])
  4910. #
  4911. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  4912. #
  4913. # idx.remove(idx.nearest((0,0))[1])
  4914. #
  4915. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]