camlib.py 228 KB

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