camlib.py 261 KB

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