camlib.py 228 KB

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