camlib.py 352 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533
  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. from numpy.linalg import solve, norm
  11. import platform
  12. from copy import deepcopy
  13. import traceback
  14. from decimal import Decimal
  15. from rtree import index as rtindex
  16. from lxml import etree as ET
  17. # See: http://toblerity.org/shapely/manual.html
  18. from shapely.geometry import Polygon, Point, LinearRing
  19. from shapely.geometry import box as shply_box
  20. from shapely.ops import cascaded_union, unary_union, substring, linemerge
  21. import shapely.affinity as affinity
  22. from shapely.wkt import loads as sloads
  23. from shapely.wkt import dumps as sdumps
  24. from shapely.geometry.base import BaseGeometry
  25. from shapely.geometry import shape
  26. # ---------------------------------------
  27. # NEEDED for Legacy mode
  28. # Used for solid polygons in Matplotlib
  29. from descartes.patch import PolygonPatch
  30. # ---------------------------------------
  31. from collections import Iterable
  32. import rasterio
  33. from rasterio.features import shapes
  34. import ezdxf
  35. from appCommon.Common import GracefulException as grace
  36. # Commented for FlatCAM packaging with cx_freeze
  37. # from scipy.spatial import KDTree, Delaunay
  38. # from scipy.spatial import Delaunay
  39. from appParsers.ParseSVG import *
  40. from appParsers.ParseDXF import *
  41. if platform.architecture()[0] == '64bit':
  42. from ortools.constraint_solver import pywrapcp
  43. from ortools.constraint_solver import routing_enums_pb2
  44. import logging
  45. import gettext
  46. import appTranslation 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. self.drawing_tolerance = 0.0
  365. self.tools = None
  366. # Final geometry: MultiPolygon or list (of geometry constructs)
  367. self.solid_geometry = None
  368. # Final geometry: MultiLineString or list (of LineString or Points)
  369. self.follow_geometry = None
  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_collection(layers=1)
  383. else:
  384. from appGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  385. self.temp_shapes = ShapeCollectionLegacy(obj=self, app=self.app, name='camlib.geometry')
  386. # Attributes to be included in serialization
  387. self.ser_attrs = ["units", 'solid_geometry', 'follow_geometry', 'tools']
  388. def plot_temp_shapes(self, element, color='red'):
  389. try:
  390. for sub_el in element:
  391. self.plot_temp_shapes(sub_el)
  392. except TypeError: # Element is not iterable...
  393. # self.add_shape(shape=element, color=color, visible=visible, layer=0)
  394. self.temp_shapes.add(tolerance=float(self.app.defaults["global_tolerance"]),
  395. shape=element, color=color, visible=True, layer=0)
  396. def make_index(self):
  397. self.flatten()
  398. self.index = FlatCAMRTree()
  399. for i, g in enumerate(self.flat_geometry):
  400. self.index.insert(i, g)
  401. def add_circle(self, origin, radius):
  402. """
  403. Adds a circle to the object.
  404. :param origin: Center of the circle.
  405. :param radius: Radius of the circle.
  406. :return: None
  407. """
  408. if self.solid_geometry is None:
  409. self.solid_geometry = []
  410. if type(self.solid_geometry) is list:
  411. self.solid_geometry.append(Point(origin).buffer(radius, int(self.geo_steps_per_circle)))
  412. return
  413. try:
  414. self.solid_geometry = self.solid_geometry.union(
  415. Point(origin).buffer(radius, int(self.geo_steps_per_circle))
  416. )
  417. except Exception as e:
  418. log.error("Failed to run union on polygons. %s" % str(e))
  419. return
  420. def add_polygon(self, points):
  421. """
  422. Adds a polygon to the object (by union)
  423. :param points: The vertices of the polygon.
  424. :return: None
  425. """
  426. if self.solid_geometry is None:
  427. self.solid_geometry = []
  428. if type(self.solid_geometry) is list:
  429. self.solid_geometry.append(Polygon(points))
  430. return
  431. try:
  432. self.solid_geometry = self.solid_geometry.union(Polygon(points))
  433. except Exception as e:
  434. log.error("Failed to run union on polygons. %s" % str(e))
  435. return
  436. def add_polyline(self, points):
  437. """
  438. Adds a polyline to the object (by union)
  439. :param points: The vertices of the polyline.
  440. :return: None
  441. """
  442. if self.solid_geometry is None:
  443. self.solid_geometry = []
  444. if type(self.solid_geometry) is list:
  445. self.solid_geometry.append(LineString(points))
  446. return
  447. try:
  448. self.solid_geometry = self.solid_geometry.union(LineString(points))
  449. except Exception as e:
  450. log.error("Failed to run union on polylines. %s" % str(e))
  451. return
  452. def is_empty(self):
  453. if isinstance(self.solid_geometry, BaseGeometry) or isinstance(self.solid_geometry, Polygon) or \
  454. isinstance(self.solid_geometry, MultiPolygon):
  455. return self.solid_geometry.is_empty
  456. if isinstance(self.solid_geometry, list):
  457. return len(self.solid_geometry) == 0
  458. self.app.inform.emit('[ERROR_NOTCL] %s' % _("self.solid_geometry is neither BaseGeometry or list."))
  459. return
  460. def subtract_polygon(self, points):
  461. """
  462. Subtract polygon from the given object. This only operates on the paths in the original geometry,
  463. i.e. it converts polygons into paths.
  464. :param points: The vertices of the polygon.
  465. :return: none
  466. """
  467. if self.solid_geometry is None:
  468. self.solid_geometry = []
  469. # pathonly should be allways True, otherwise polygons are not subtracted
  470. flat_geometry = self.flatten(pathonly=True)
  471. log.debug("%d paths" % len(flat_geometry))
  472. if not isinstance(points, Polygon):
  473. polygon = Polygon(points)
  474. else:
  475. polygon = points
  476. toolgeo = cascaded_union(polygon)
  477. diffs = []
  478. for target in flat_geometry:
  479. if isinstance(target, LineString) or isinstance(target, LineString) or isinstance(target, MultiLineString):
  480. diffs.append(target.difference(toolgeo))
  481. else:
  482. log.warning("Not implemented.")
  483. self.solid_geometry = unary_union(diffs)
  484. def bounds(self, flatten=False):
  485. """
  486. Returns coordinates of rectangular bounds
  487. of geometry: (xmin, ymin, xmax, ymax).
  488. :param flatten: will flatten the solid_geometry if True
  489. :return:
  490. """
  491. # fixed issue of getting bounds only for one level lists of objects
  492. # now it can get bounds for nested lists of objects
  493. log.debug("camlib.Geometry.bounds()")
  494. if self.solid_geometry is None:
  495. log.debug("solid_geometry is None")
  496. return 0, 0, 0, 0
  497. def bounds_rec(obj):
  498. if type(obj) is list:
  499. gminx = np.Inf
  500. gminy = np.Inf
  501. gmaxx = -np.Inf
  502. gmaxy = -np.Inf
  503. for k in obj:
  504. if type(k) is dict:
  505. for key in k:
  506. minx_, miny_, maxx_, maxy_ = bounds_rec(k[key])
  507. gminx = min(gminx, minx_)
  508. gminy = min(gminy, miny_)
  509. gmaxx = max(gmaxx, maxx_)
  510. gmaxy = max(gmaxy, maxy_)
  511. else:
  512. try:
  513. if k.is_empty:
  514. continue
  515. except Exception:
  516. pass
  517. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  518. gminx = min(gminx, minx_)
  519. gminy = min(gminy, miny_)
  520. gmaxx = max(gmaxx, maxx_)
  521. gmaxy = max(gmaxy, maxy_)
  522. return gminx, gminy, gmaxx, gmaxy
  523. else:
  524. # it's a Shapely object, return it's bounds
  525. return obj.bounds
  526. if self.multigeo is True:
  527. minx_list = []
  528. miny_list = []
  529. maxx_list = []
  530. maxy_list = []
  531. for tool in self.tools:
  532. working_geo = self.tools[tool]['solid_geometry']
  533. if flatten:
  534. self.flatten(geometry=working_geo, reset=True)
  535. working_geo = self.flat_geometry
  536. minx, miny, maxx, maxy = bounds_rec(working_geo)
  537. minx_list.append(minx)
  538. miny_list.append(miny)
  539. maxx_list.append(maxx)
  540. maxy_list.append(maxy)
  541. return min(minx_list), min(miny_list), max(maxx_list), max(maxy_list)
  542. else:
  543. if flatten:
  544. self.flatten(reset=True)
  545. self.solid_geometry = self.flat_geometry
  546. bounds_coords = bounds_rec(self.solid_geometry)
  547. return bounds_coords
  548. # try:
  549. # # from here: http://rightfootin.blogspot.com/2006/09/more-on-python-flatten.html
  550. # def flatten(l, ltypes=(list, tuple)):
  551. # ltype = type(l)
  552. # l = list(l)
  553. # i = 0
  554. # while i < len(l):
  555. # while isinstance(l[i], ltypes):
  556. # if not l[i]:
  557. # l.pop(i)
  558. # i -= 1
  559. # break
  560. # else:
  561. # l[i:i + 1] = l[i]
  562. # i += 1
  563. # return ltype(l)
  564. #
  565. # log.debug("Geometry->bounds()")
  566. # if self.solid_geometry is None:
  567. # log.debug("solid_geometry is None")
  568. # return 0, 0, 0, 0
  569. #
  570. # if type(self.solid_geometry) is list:
  571. # if len(self.solid_geometry) == 0:
  572. # log.debug('solid_geometry is empty []')
  573. # return 0, 0, 0, 0
  574. # return cascaded_union(flatten(self.solid_geometry)).bounds
  575. # else:
  576. # return self.solid_geometry.bounds
  577. # except Exception as e:
  578. # self.app.inform.emit("[ERROR_NOTCL] Error cause: %s" % str(e))
  579. # log.debug("Geometry->bounds()")
  580. # if self.solid_geometry is None:
  581. # log.debug("solid_geometry is None")
  582. # return 0, 0, 0, 0
  583. #
  584. # if type(self.solid_geometry) is list:
  585. # if len(self.solid_geometry) == 0:
  586. # log.debug('solid_geometry is empty []')
  587. # return 0, 0, 0, 0
  588. # return cascaded_union(self.solid_geometry).bounds
  589. # else:
  590. # return self.solid_geometry.bounds
  591. def find_polygon(self, point, geoset=None):
  592. """
  593. Find an object that object.contains(Point(point)) in
  594. poly, which can can be iterable, contain iterable of, or
  595. be itself an implementer of .contains().
  596. :param point: See description
  597. :param geoset: a polygon or list of polygons where to find if the param point is contained
  598. :return: Polygon containing point or None.
  599. """
  600. if geoset is None:
  601. geoset = self.solid_geometry
  602. try: # Iterable
  603. for sub_geo in geoset:
  604. p = self.find_polygon(point, geoset=sub_geo)
  605. if p is not None:
  606. return p
  607. except TypeError: # Non-iterable
  608. try: # Implements .contains()
  609. if isinstance(geoset, LinearRing):
  610. geoset = Polygon(geoset)
  611. if geoset.contains(Point(point)):
  612. return geoset
  613. except AttributeError: # Does not implement .contains()
  614. return None
  615. return None
  616. def get_interiors(self, geometry=None):
  617. interiors = []
  618. if geometry is None:
  619. geometry = self.solid_geometry
  620. # ## If iterable, expand recursively.
  621. try:
  622. for geo in geometry:
  623. interiors.extend(self.get_interiors(geometry=geo))
  624. # ## Not iterable, get the interiors if polygon.
  625. except TypeError:
  626. if type(geometry) == Polygon:
  627. interiors.extend(geometry.interiors)
  628. return interiors
  629. def get_exteriors(self, geometry=None):
  630. """
  631. Returns all exteriors of polygons in geometry. Uses
  632. ``self.solid_geometry`` if geometry is not provided.
  633. :param geometry: Shapely type or list or list of list of such.
  634. :return: List of paths constituting the exteriors
  635. of polygons in geometry.
  636. """
  637. exteriors = []
  638. if geometry is None:
  639. geometry = self.solid_geometry
  640. # ## If iterable, expand recursively.
  641. try:
  642. for geo in geometry:
  643. exteriors.extend(self.get_exteriors(geometry=geo))
  644. # ## Not iterable, get the exterior if polygon.
  645. except TypeError:
  646. if type(geometry) == Polygon:
  647. exteriors.append(geometry.exterior)
  648. return exteriors
  649. def flatten(self, geometry=None, reset=True, pathonly=False):
  650. """
  651. Creates a list of non-iterable linear geometry objects.
  652. Polygons are expanded into its exterior and interiors if specified.
  653. Results are placed in self.flat_geometry
  654. :param geometry: Shapely type or list or list of list of such.
  655. :param reset: Clears the contents of self.flat_geometry.
  656. :param pathonly: Expands polygons into linear elements.
  657. """
  658. if geometry is None:
  659. geometry = self.solid_geometry
  660. if reset:
  661. self.flat_geometry = []
  662. # ## If iterable, expand recursively.
  663. try:
  664. for geo in geometry:
  665. if geo is not None:
  666. self.flatten(geometry=geo,
  667. reset=False,
  668. pathonly=pathonly)
  669. # ## Not iterable, do the actual indexing and add.
  670. except TypeError:
  671. if pathonly and type(geometry) == Polygon:
  672. self.flat_geometry.append(geometry.exterior)
  673. self.flatten(geometry=geometry.interiors,
  674. reset=False,
  675. pathonly=True)
  676. else:
  677. self.flat_geometry.append(geometry)
  678. return self.flat_geometry
  679. # def make2Dstorage(self):
  680. #
  681. # self.flatten()
  682. #
  683. # def get_pts(o):
  684. # pts = []
  685. # if type(o) == Polygon:
  686. # g = o.exterior
  687. # pts += list(g.coords)
  688. # for i in o.interiors:
  689. # pts += list(i.coords)
  690. # else:
  691. # pts += list(o.coords)
  692. # return pts
  693. #
  694. # storage = FlatCAMRTreeStorage()
  695. # storage.get_points = get_pts
  696. # for shape in self.flat_geometry:
  697. # storage.insert(shape)
  698. # return storage
  699. # def flatten_to_paths(self, geometry=None, reset=True):
  700. # """
  701. # Creates a list of non-iterable linear geometry elements and
  702. # indexes them in rtree.
  703. #
  704. # :param geometry: Iterable geometry
  705. # :param reset: Wether to clear (True) or append (False) to self.flat_geometry
  706. # :return: self.flat_geometry, self.flat_geometry_rtree
  707. # """
  708. #
  709. # if geometry is None:
  710. # geometry = self.solid_geometry
  711. #
  712. # if reset:
  713. # self.flat_geometry = []
  714. #
  715. # # ## If iterable, expand recursively.
  716. # try:
  717. # for geo in geometry:
  718. # self.flatten_to_paths(geometry=geo, reset=False)
  719. #
  720. # # ## Not iterable, do the actual indexing and add.
  721. # except TypeError:
  722. # if type(geometry) == Polygon:
  723. # g = geometry.exterior
  724. # self.flat_geometry.append(g)
  725. #
  726. # # ## Add first and last points of the path to the index.
  727. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[0])
  728. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[-1])
  729. #
  730. # for interior in geometry.interiors:
  731. # g = interior
  732. # self.flat_geometry.append(g)
  733. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[0])
  734. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[-1])
  735. # else:
  736. # g = geometry
  737. # self.flat_geometry.append(g)
  738. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[0])
  739. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[-1])
  740. #
  741. # return self.flat_geometry, self.flat_geometry_rtree
  742. def isolation_geometry(self, offset, geometry=None, iso_type=2, corner=None, follow=None, passes=0,
  743. prog_plot=False):
  744. """
  745. Creates contours around geometry at a given
  746. offset distance.
  747. :param offset: Offset distance.
  748. :type offset: float
  749. :param geometry The geometry to work with
  750. :param iso_type: type of isolation, can be 0 = exteriors or 1 = interiors or 2 = both (complete)
  751. :param corner: type of corner for the isolation:
  752. 0 = round; 1 = square; 2= beveled (line that connects the ends)
  753. :param follow: whether the geometry to be isolated is a follow_geometry
  754. :param passes: current pass out of possible multiple passes for which the isolation is done
  755. :param prog_plot: type of plotting: "normal" or "progressive"
  756. :return: The buffered geometry.
  757. :rtype: Shapely.MultiPolygon or Shapely.Polygon
  758. """
  759. if self.app.abort_flag:
  760. # graceful abort requested by the user
  761. raise grace
  762. geo_iso = []
  763. if follow:
  764. return geometry
  765. if geometry:
  766. working_geo = geometry
  767. else:
  768. working_geo = self.solid_geometry
  769. try:
  770. geo_len = len(working_geo)
  771. except TypeError:
  772. geo_len = 1
  773. old_disp_number = 0
  774. pol_nr = 0
  775. # yet, it can be done by issuing an unary_union in the end, thus getting rid of the overlapping geo
  776. try:
  777. for pol in working_geo:
  778. if self.app.abort_flag:
  779. # graceful abort requested by the user
  780. raise grace
  781. if offset == 0:
  782. temp_geo = pol
  783. else:
  784. corner_type = 1 if corner is None else corner
  785. temp_geo = pol.buffer(offset, int(self.geo_steps_per_circle), join_style=corner_type)
  786. geo_iso.append(temp_geo)
  787. pol_nr += 1
  788. # activity view update
  789. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  790. if old_disp_number < disp_number <= 100:
  791. self.app.proc_container.update_view_text(' %s %d: %d%%' %
  792. (_("Pass"), int(passes + 1), int(disp_number)))
  793. old_disp_number = disp_number
  794. except TypeError:
  795. # taking care of the case when the self.solid_geometry is just a single Polygon, not a list or a
  796. # MultiPolygon (not an iterable)
  797. if offset == 0:
  798. temp_geo = working_geo
  799. else:
  800. corner_type = 1 if corner is None else corner
  801. temp_geo = working_geo.buffer(offset, int(self.geo_steps_per_circle), join_style=corner_type)
  802. geo_iso.append(temp_geo)
  803. self.app.proc_container.update_view_text(' %s' % _("Buffering"))
  804. geo_iso = unary_union(geo_iso)
  805. self.app.proc_container.update_view_text('')
  806. # end of replaced block
  807. if iso_type == 2:
  808. ret_geo = geo_iso
  809. elif iso_type == 0:
  810. self.app.proc_container.update_view_text(' %s' % _("Get Exteriors"))
  811. ret_geo = self.get_exteriors(geo_iso)
  812. elif iso_type == 1:
  813. self.app.proc_container.update_view_text(' %s' % _("Get Interiors"))
  814. ret_geo = self.get_interiors(geo_iso)
  815. else:
  816. log.debug("Geometry.isolation_geometry() --> Type of isolation not supported")
  817. return "fail"
  818. if prog_plot == 'progressive':
  819. for elem in ret_geo:
  820. self.plot_temp_shapes(elem)
  821. return ret_geo
  822. def flatten_list(self, obj_list):
  823. for item in obj_list:
  824. if isinstance(item, Iterable) and not isinstance(item, (str, bytes)):
  825. yield from self.flatten_list(item)
  826. else:
  827. yield item
  828. def import_svg(self, filename, object_type=None, flip=True, units='MM'):
  829. """
  830. Imports shapes from an SVG file into the object's geometry.
  831. :param filename: Path to the SVG file.
  832. :type filename: str
  833. :param object_type: parameter passed further along
  834. :param flip: Flip the vertically.
  835. :type flip: bool
  836. :param units: FlatCAM units
  837. :return: None
  838. """
  839. log.debug("camlib.Geometry.import_svg()")
  840. # Parse into list of shapely objects
  841. svg_tree = ET.parse(filename)
  842. svg_root = svg_tree.getroot()
  843. # Change origin to bottom left
  844. # h = float(svg_root.get('height'))
  845. # w = float(svg_root.get('width'))
  846. h = svgparselength(svg_root.get('height'))[0] # TODO: No units support yet
  847. geos = getsvggeo(svg_root, object_type)
  848. if flip:
  849. geos = [translate(scale(g, 1.0, -1.0, origin=(0, 0)), yoff=h) for g in geos]
  850. # trying to optimize the resulting geometry by merging contiguous lines
  851. geos = list(self.flatten_list(geos))
  852. geos_polys = []
  853. geos_lines = []
  854. for g in geos:
  855. if isinstance(g, Polygon):
  856. geos_polys.append(g)
  857. else:
  858. geos_lines.append(g)
  859. merged_lines = linemerge(geos_lines)
  860. geos = geos_polys
  861. for l in merged_lines:
  862. geos.append(l)
  863. # Add to object
  864. if self.solid_geometry is None:
  865. self.solid_geometry = []
  866. if type(self.solid_geometry) is list:
  867. if type(geos) is list:
  868. self.solid_geometry += geos
  869. else:
  870. self.solid_geometry.append(geos)
  871. else: # It's shapely geometry
  872. self.solid_geometry = [self.solid_geometry, geos]
  873. # flatten the self.solid_geometry list for import_svg() to import SVG as Gerber
  874. self.solid_geometry = list(self.flatten_list(self.solid_geometry))
  875. geos_text = getsvgtext(svg_root, object_type, units=units)
  876. if geos_text is not None:
  877. geos_text_f = []
  878. if flip:
  879. # Change origin to bottom left
  880. for i in geos_text:
  881. __, minimy, __, maximy = i.bounds
  882. h2 = (maximy - minimy) * 0.5
  883. geos_text_f.append(translate(scale(i, 1.0, -1.0, origin=(0, 0)), yoff=(h + h2)))
  884. if geos_text_f:
  885. self.solid_geometry = self.solid_geometry + geos_text_f
  886. tooldia = float(self.app.defaults["geometry_cnctooldia"])
  887. tooldia = float('%.*f' % (self.decimals, tooldia))
  888. new_data = {k: v for k, v in self.options.items()}
  889. self.tools.update({
  890. 1: {
  891. 'tooldia': tooldia,
  892. 'offset': 'Path',
  893. 'offset_value': 0.0,
  894. 'type': _('Rough'),
  895. 'tool_type': 'C1',
  896. 'data': deepcopy(new_data),
  897. 'solid_geometry': self.solid_geometry
  898. }
  899. })
  900. self.tools[1]['data']['name'] = self.options['name']
  901. def import_dxf_as_geo(self, filename, units='MM'):
  902. """
  903. Imports shapes from an DXF file into the object's geometry.
  904. :param filename: Path to the DXF file.
  905. :type filename: str
  906. :param units: Application units
  907. :return: None
  908. """
  909. log.debug("Parsing DXF file geometry into a Geometry object solid geometry.")
  910. # Parse into list of shapely objects
  911. dxf = ezdxf.readfile(filename)
  912. geos = getdxfgeo(dxf)
  913. # trying to optimize the resulting geometry by merging contiguous lines
  914. geos = list(self.flatten_list(geos))
  915. geos_polys = []
  916. geos_lines = []
  917. for g in geos:
  918. if isinstance(g, Polygon):
  919. geos_polys.append(g)
  920. else:
  921. geos_lines.append(g)
  922. merged_lines = linemerge(geos_lines)
  923. geos = geos_polys
  924. for l in merged_lines:
  925. geos.append(l)
  926. # Add to object
  927. if self.solid_geometry is None:
  928. self.solid_geometry = []
  929. if type(self.solid_geometry) is list:
  930. if type(geos) is list:
  931. self.solid_geometry += geos
  932. else:
  933. self.solid_geometry.append(geos)
  934. else: # It's shapely geometry
  935. self.solid_geometry = [self.solid_geometry, geos]
  936. tooldia = float(self.app.defaults["geometry_cnctooldia"])
  937. tooldia = float('%.*f' % (self.decimals, tooldia))
  938. new_data = {k: v for k, v in self.options.items()}
  939. self.tools.update({
  940. 1: {
  941. 'tooldia': tooldia,
  942. 'offset': 'Path',
  943. 'offset_value': 0.0,
  944. 'type': _('Rough'),
  945. 'tool_type': 'C1',
  946. 'data': deepcopy(new_data),
  947. 'solid_geometry': self.solid_geometry
  948. }
  949. })
  950. self.tools[1]['data']['name'] = self.options['name']
  951. # commented until this function is ready
  952. # geos_text = getdxftext(dxf, object_type, units=units)
  953. # if geos_text is not None:
  954. # geos_text_f = []
  955. # self.solid_geometry = [self.solid_geometry, geos_text_f]
  956. def import_image(self, filename, flip=True, units='MM', dpi=96, mode='black', mask=None):
  957. """
  958. Imports shapes from an IMAGE file into the object's geometry.
  959. :param filename: Path to the IMAGE file.
  960. :type filename: str
  961. :param flip: Flip the object vertically.
  962. :type flip: bool
  963. :param units: FlatCAM units
  964. :type units: str
  965. :param dpi: dots per inch on the imported image
  966. :param mode: how to import the image: as 'black' or 'color'
  967. :type mode: str
  968. :param mask: level of detail for the import
  969. :return: None
  970. """
  971. if mask is None:
  972. mask = [128, 128, 128, 128]
  973. scale_factor = 25.4 / dpi if units.lower() == 'mm' else 1 / dpi
  974. geos = []
  975. unscaled_geos = []
  976. with rasterio.open(filename) as src:
  977. # if filename.lower().rpartition('.')[-1] == 'bmp':
  978. # red = green = blue = src.read(1)
  979. # print("BMP")
  980. # elif filename.lower().rpartition('.')[-1] == 'png':
  981. # red, green, blue, alpha = src.read()
  982. # elif filename.lower().rpartition('.')[-1] == 'jpg':
  983. # red, green, blue = src.read()
  984. red = green = blue = src.read(1)
  985. try:
  986. green = src.read(2)
  987. except Exception:
  988. pass
  989. try:
  990. blue = src.read(3)
  991. except Exception:
  992. pass
  993. if mode == 'black':
  994. mask_setting = red <= mask[0]
  995. total = red
  996. log.debug("Image import as monochrome.")
  997. else:
  998. mask_setting = (red <= mask[1]) + (green <= mask[2]) + (blue <= mask[3])
  999. total = np.zeros(red.shape, dtype=np.float32)
  1000. for band in red, green, blue:
  1001. total += band
  1002. total /= 3
  1003. log.debug("Image import as colored. Thresholds are: R = %s , G = %s, B = %s" %
  1004. (str(mask[1]), str(mask[2]), str(mask[3])))
  1005. for geom, val in shapes(total, mask=mask_setting):
  1006. unscaled_geos.append(shape(geom))
  1007. for g in unscaled_geos:
  1008. geos.append(scale(g, scale_factor, scale_factor, origin=(0, 0)))
  1009. if flip:
  1010. geos = [translate(scale(g, 1.0, -1.0, origin=(0, 0))) for g in geos]
  1011. # Add to object
  1012. if self.solid_geometry is None:
  1013. self.solid_geometry = []
  1014. if type(self.solid_geometry) is list:
  1015. # self.solid_geometry.append(cascaded_union(geos))
  1016. if type(geos) is list:
  1017. self.solid_geometry += geos
  1018. else:
  1019. self.solid_geometry.append(geos)
  1020. else: # It's shapely geometry
  1021. self.solid_geometry = [self.solid_geometry, geos]
  1022. # flatten the self.solid_geometry list for import_svg() to import SVG as Gerber
  1023. self.solid_geometry = list(self.flatten_list(self.solid_geometry))
  1024. self.solid_geometry = cascaded_union(self.solid_geometry)
  1025. # self.solid_geometry = MultiPolygon(self.solid_geometry)
  1026. # self.solid_geometry = self.solid_geometry.buffer(0.00000001)
  1027. # self.solid_geometry = self.solid_geometry.buffer(-0.00000001)
  1028. def size(self):
  1029. """
  1030. Returns (width, height) of rectangular
  1031. bounds of geometry.
  1032. """
  1033. if self.solid_geometry is None:
  1034. log.warning("Solid_geometry not computed yet.")
  1035. return 0
  1036. bounds = self.bounds()
  1037. return bounds[2] - bounds[0], bounds[3] - bounds[1]
  1038. def get_empty_area(self, boundary=None):
  1039. """
  1040. Returns the complement of self.solid_geometry within
  1041. the given boundary polygon. If not specified, it defaults to
  1042. the rectangular bounding box of self.solid_geometry.
  1043. """
  1044. if boundary is None:
  1045. boundary = self.solid_geometry.envelope
  1046. return boundary.difference(self.solid_geometry)
  1047. def clear_polygon(self, polygon, tooldia, steps_per_circle, overlap=0.15, connect=True, contour=True,
  1048. prog_plot=False):
  1049. """
  1050. Creates geometry inside a polygon for a tool to cover
  1051. the whole area.
  1052. This algorithm shrinks the edges of the polygon and takes
  1053. the resulting edges as toolpaths.
  1054. :param polygon: Polygon to clear.
  1055. :param tooldia: Diameter of the tool.
  1056. :param steps_per_circle: number of linear segments to be used to approximate a circle
  1057. :param overlap: Overlap of toolpasses.
  1058. :param connect: Draw lines between disjoint segments to
  1059. minimize tool lifts.
  1060. :param contour: Paint around the edges. Inconsequential in
  1061. this painting method.
  1062. :param prog_plot: boolean; if Ture use the progressive plotting
  1063. :return:
  1064. """
  1065. # log.debug("camlib.clear_polygon()")
  1066. assert type(polygon) == Polygon or type(polygon) == MultiPolygon, \
  1067. "Expected a Polygon or MultiPolygon, got %s" % type(polygon)
  1068. # ## The toolpaths
  1069. # Index first and last points in paths
  1070. def get_pts(o):
  1071. return [o.coords[0], o.coords[-1]]
  1072. geoms = FlatCAMRTreeStorage()
  1073. geoms.get_points = get_pts
  1074. # Can only result in a Polygon or MultiPolygon
  1075. # NOTE: The resulting polygon can be "empty".
  1076. current = polygon.buffer((-tooldia / 1.999999), int(steps_per_circle))
  1077. if current.area == 0:
  1078. # Otherwise, trying to to insert current.exterior == None
  1079. # into the FlatCAMStorage will fail.
  1080. # print("Area is None")
  1081. return None
  1082. # current can be a MultiPolygon
  1083. try:
  1084. for p in current:
  1085. geoms.insert(p.exterior)
  1086. for i in p.interiors:
  1087. geoms.insert(i)
  1088. # Not a Multipolygon. Must be a Polygon
  1089. except TypeError:
  1090. geoms.insert(current.exterior)
  1091. for i in current.interiors:
  1092. geoms.insert(i)
  1093. while True:
  1094. if self.app.abort_flag:
  1095. # graceful abort requested by the user
  1096. raise grace
  1097. # provide the app with a way to process the GUI events when in a blocking loop
  1098. QtWidgets.QApplication.processEvents()
  1099. # Can only result in a Polygon or MultiPolygon
  1100. current = current.buffer(-tooldia * (1 - overlap), int(steps_per_circle))
  1101. if current.area > 0:
  1102. # current can be a MultiPolygon
  1103. try:
  1104. for p in current:
  1105. geoms.insert(p.exterior)
  1106. for i in p.interiors:
  1107. geoms.insert(i)
  1108. if prog_plot:
  1109. self.plot_temp_shapes(p)
  1110. # Not a Multipolygon. Must be a Polygon
  1111. except TypeError:
  1112. geoms.insert(current.exterior)
  1113. if prog_plot:
  1114. self.plot_temp_shapes(current.exterior)
  1115. for i in current.interiors:
  1116. geoms.insert(i)
  1117. if prog_plot:
  1118. self.plot_temp_shapes(i)
  1119. else:
  1120. log.debug("camlib.Geometry.clear_polygon() --> Current Area is zero")
  1121. break
  1122. if prog_plot:
  1123. self.temp_shapes.redraw()
  1124. # Optimization: Reduce lifts
  1125. if connect:
  1126. # log.debug("Reducing tool lifts...")
  1127. geoms = Geometry.paint_connect(geoms, polygon, tooldia, int(steps_per_circle))
  1128. return geoms
  1129. def clear_polygon2(self, polygon_to_clear, tooldia, steps_per_circle, seedpoint=None, overlap=0.15,
  1130. connect=True, contour=True, prog_plot=False):
  1131. """
  1132. Creates geometry inside a polygon for a tool to cover
  1133. the whole area.
  1134. This algorithm starts with a seed point inside the polygon
  1135. and draws circles around it. Arcs inside the polygons are
  1136. valid cuts. Finalizes by cutting around the inside edge of
  1137. the polygon.
  1138. :param polygon_to_clear: Shapely.geometry.Polygon
  1139. :param steps_per_circle: how many linear segments to use to approximate a circle
  1140. :param tooldia: Diameter of the tool
  1141. :param seedpoint: Shapely.geometry.Point or None
  1142. :param overlap: Tool fraction overlap bewteen passes
  1143. :param connect: Connect disjoint segment to minumize tool lifts
  1144. :param contour: Cut countour inside the polygon.
  1145. :param prog_plot: boolean; if True use the progressive plotting
  1146. :return: List of toolpaths covering polygon.
  1147. :rtype: FlatCAMRTreeStorage | None
  1148. """
  1149. # log.debug("camlib.clear_polygon2()")
  1150. # Current buffer radius
  1151. radius = tooldia / 2 * (1 - overlap)
  1152. # ## The toolpaths
  1153. # Index first and last points in paths
  1154. def get_pts(o):
  1155. return [o.coords[0], o.coords[-1]]
  1156. geoms = FlatCAMRTreeStorage()
  1157. geoms.get_points = get_pts
  1158. # Path margin
  1159. path_margin = polygon_to_clear.buffer(-tooldia / 2, int(steps_per_circle))
  1160. if path_margin.is_empty or path_margin is None:
  1161. return None
  1162. # Estimate good seedpoint if not provided.
  1163. if seedpoint is None:
  1164. seedpoint = path_margin.representative_point()
  1165. # Grow from seed until outside the box. The polygons will
  1166. # never have an interior, so take the exterior LinearRing.
  1167. while True:
  1168. if self.app.abort_flag:
  1169. # graceful abort requested by the user
  1170. raise grace
  1171. # provide the app with a way to process the GUI events when in a blocking loop
  1172. QtWidgets.QApplication.processEvents()
  1173. path = Point(seedpoint).buffer(radius, int(steps_per_circle)).exterior
  1174. path = path.intersection(path_margin)
  1175. # Touches polygon?
  1176. if path.is_empty:
  1177. break
  1178. else:
  1179. # geoms.append(path)
  1180. # geoms.insert(path)
  1181. # path can be a collection of paths.
  1182. try:
  1183. for p in path:
  1184. geoms.insert(p)
  1185. if prog_plot:
  1186. self.plot_temp_shapes(p)
  1187. except TypeError:
  1188. geoms.insert(path)
  1189. if prog_plot:
  1190. self.plot_temp_shapes(path)
  1191. if prog_plot:
  1192. self.temp_shapes.redraw()
  1193. radius += tooldia * (1 - overlap)
  1194. # Clean inside edges (contours) of the original polygon
  1195. if contour:
  1196. buffered_poly = autolist(polygon_to_clear.buffer(-tooldia / 2, int(steps_per_circle)))
  1197. outer_edges = [x.exterior for x in buffered_poly]
  1198. inner_edges = []
  1199. # Over resulting polygons
  1200. for x in buffered_poly:
  1201. for y in x.interiors: # Over interiors of each polygon
  1202. inner_edges.append(y)
  1203. # geoms += outer_edges + inner_edges
  1204. for g in outer_edges + inner_edges:
  1205. if g and not g.is_empty:
  1206. geoms.insert(g)
  1207. if prog_plot:
  1208. self.plot_temp_shapes(g)
  1209. if prog_plot:
  1210. self.temp_shapes.redraw()
  1211. # Optimization connect touching paths
  1212. # log.debug("Connecting paths...")
  1213. # geoms = Geometry.path_connect(geoms)
  1214. # Optimization: Reduce lifts
  1215. if connect:
  1216. # log.debug("Reducing tool lifts...")
  1217. geoms_conn = Geometry.paint_connect(geoms, polygon_to_clear, tooldia, steps_per_circle)
  1218. if geoms_conn:
  1219. return geoms_conn
  1220. return geoms
  1221. def clear_polygon3(self, polygon, tooldia, steps_per_circle, overlap=0.15, connect=True, contour=True,
  1222. prog_plot=False):
  1223. """
  1224. Creates geometry inside a polygon for a tool to cover
  1225. the whole area.
  1226. This algorithm draws horizontal lines inside the polygon.
  1227. :param polygon: The polygon being painted.
  1228. :type polygon: shapely.geometry.Polygon
  1229. :param tooldia: Tool diameter.
  1230. :param steps_per_circle: how many linear segments to use to approximate a circle
  1231. :param overlap: Tool path overlap percentage.
  1232. :param connect: Connect lines to avoid tool lifts.
  1233. :param contour: Paint around the edges.
  1234. :param prog_plot: boolean; if to use the progressive plotting
  1235. :return:
  1236. """
  1237. # log.debug("camlib.clear_polygon3()")
  1238. if not isinstance(polygon, Polygon):
  1239. log.debug("camlib.Geometry.clear_polygon3() --> Not a Polygon but %s" % str(type(polygon)))
  1240. return None
  1241. # ## The toolpaths
  1242. # Index first and last points in paths
  1243. def get_pts(o):
  1244. return [o.coords[0], o.coords[-1]]
  1245. geoms = FlatCAMRTreeStorage()
  1246. geoms.get_points = get_pts
  1247. lines_trimmed = []
  1248. # Bounding box
  1249. left, bot, right, top = polygon.bounds
  1250. try:
  1251. margin_poly = polygon.buffer(-tooldia / 1.99999999, (int(steps_per_circle)))
  1252. except Exception:
  1253. log.debug("camlib.Geometry.clear_polygon3() --> Could not buffer the Polygon")
  1254. return None
  1255. # decide the direction of the lines
  1256. if abs(left - right) >= abs(top - bot):
  1257. # First line
  1258. try:
  1259. y = top - tooldia / 1.99999999
  1260. while y > bot + tooldia / 1.999999999:
  1261. if self.app.abort_flag:
  1262. # graceful abort requested by the user
  1263. raise grace
  1264. # provide the app with a way to process the GUI events when in a blocking loop
  1265. QtWidgets.QApplication.processEvents()
  1266. line = LineString([(left, y), (right, y)])
  1267. line = line.intersection(margin_poly)
  1268. lines_trimmed.append(line)
  1269. y -= tooldia * (1 - overlap)
  1270. if prog_plot:
  1271. self.plot_temp_shapes(line)
  1272. self.temp_shapes.redraw()
  1273. # Last line
  1274. y = bot + tooldia / 2
  1275. line = LineString([(left, y), (right, y)])
  1276. line = line.intersection(margin_poly)
  1277. try:
  1278. for ll in line:
  1279. lines_trimmed.append(ll)
  1280. if prog_plot:
  1281. self.plot_temp_shapes(ll)
  1282. except TypeError:
  1283. lines_trimmed.append(line)
  1284. if prog_plot:
  1285. self.plot_temp_shapes(line)
  1286. except Exception as e:
  1287. log.debug('camlib.Geometry.clear_polygon3() Processing poly --> %s' % str(e))
  1288. return None
  1289. else:
  1290. # First line
  1291. try:
  1292. x = left + tooldia / 1.99999999
  1293. while x < right - tooldia / 1.999999999:
  1294. if self.app.abort_flag:
  1295. # graceful abort requested by the user
  1296. raise grace
  1297. # provide the app with a way to process the GUI events when in a blocking loop
  1298. QtWidgets.QApplication.processEvents()
  1299. line = LineString([(x, top), (x, bot)])
  1300. line = line.intersection(margin_poly)
  1301. lines_trimmed.append(line)
  1302. x += tooldia * (1 - overlap)
  1303. if prog_plot:
  1304. self.plot_temp_shapes(line)
  1305. self.temp_shapes.redraw()
  1306. # Last line
  1307. x = right + tooldia / 2
  1308. line = LineString([(x, top), (x, bot)])
  1309. line = line.intersection(margin_poly)
  1310. try:
  1311. for ll in line:
  1312. lines_trimmed.append(ll)
  1313. if prog_plot:
  1314. self.plot_temp_shapes(ll)
  1315. except TypeError:
  1316. lines_trimmed.append(line)
  1317. if prog_plot:
  1318. self.plot_temp_shapes(line)
  1319. except Exception as e:
  1320. log.debug('camlib.Geometry.clear_polygon3() Processing poly --> %s' % str(e))
  1321. return None
  1322. if prog_plot:
  1323. self.temp_shapes.redraw()
  1324. lines_trimmed = unary_union(lines_trimmed)
  1325. # Add lines to storage
  1326. try:
  1327. for line in lines_trimmed:
  1328. if isinstance(line, LineString) or isinstance(line, LinearRing):
  1329. if not line.is_empty:
  1330. geoms.insert(line)
  1331. else:
  1332. log.debug("camlib.Geometry.clear_polygon3(). Not a line: %s" % str(type(line)))
  1333. except TypeError:
  1334. # in case lines_trimmed are not iterable (Linestring, LinearRing)
  1335. if not lines_trimmed.is_empty:
  1336. geoms.insert(lines_trimmed)
  1337. # Add margin (contour) to storage
  1338. if contour:
  1339. try:
  1340. for poly in margin_poly:
  1341. if isinstance(poly, Polygon) and not poly.is_empty:
  1342. geoms.insert(poly.exterior)
  1343. if prog_plot:
  1344. self.plot_temp_shapes(poly.exterior)
  1345. for ints in poly.interiors:
  1346. geoms.insert(ints)
  1347. if prog_plot:
  1348. self.plot_temp_shapes(ints)
  1349. except TypeError:
  1350. if isinstance(margin_poly, Polygon) and not margin_poly.is_empty:
  1351. marg_ext = margin_poly.exterior
  1352. geoms.insert(marg_ext)
  1353. if prog_plot:
  1354. self.plot_temp_shapes(margin_poly.exterior)
  1355. for ints in margin_poly.interiors:
  1356. geoms.insert(ints)
  1357. if prog_plot:
  1358. self.plot_temp_shapes(ints)
  1359. if prog_plot:
  1360. self.temp_shapes.redraw()
  1361. # Optimization: Reduce lifts
  1362. if connect:
  1363. # log.debug("Reducing tool lifts...")
  1364. geoms_conn = Geometry.paint_connect(geoms, polygon, tooldia, steps_per_circle)
  1365. if geoms_conn:
  1366. return geoms_conn
  1367. return geoms
  1368. def fill_with_lines(self, line, aperture_size, tooldia, steps_per_circle, overlap=0.15, connect=True, contour=True,
  1369. prog_plot=False):
  1370. """
  1371. Creates geometry of lines inside a polygon for a tool to cover
  1372. the whole area.
  1373. This algorithm draws parallel lines inside the polygon.
  1374. :param line: The target line that create painted polygon.
  1375. :param aperture_size: the size of the aperture that is used to draw the 'line' as a polygon
  1376. :type line: shapely.geometry.LineString or shapely.geometry.MultiLineString
  1377. :param tooldia: Tool diameter.
  1378. :param steps_per_circle: how many linear segments to use to approximate a circle
  1379. :param overlap: Tool path overlap percentage.
  1380. :param connect: Connect lines to avoid tool lifts.
  1381. :param contour: Paint around the edges.
  1382. :param prog_plot: boolean; if to use the progressive plotting
  1383. :return:
  1384. """
  1385. # log.debug("camlib.fill_with_lines()")
  1386. if not isinstance(line, LineString):
  1387. log.debug("camlib.Geometry.fill_with_lines() --> Not a LineString/MultiLineString but %s" % str(type(line)))
  1388. return None
  1389. # ## The toolpaths
  1390. # Index first and last points in paths
  1391. def get_pts(o):
  1392. return [o.coords[0], o.coords[-1]]
  1393. geoms = FlatCAMRTreeStorage()
  1394. geoms.get_points = get_pts
  1395. lines_trimmed = []
  1396. polygon = line.buffer(aperture_size / 2.0, int(steps_per_circle))
  1397. try:
  1398. margin_poly = polygon.buffer(-tooldia / 2.0, int(steps_per_circle))
  1399. except Exception:
  1400. log.debug("camlib.Geometry.fill_with_lines() --> Could not buffer the Polygon, tool diameter too high")
  1401. return None
  1402. # First line
  1403. try:
  1404. delta = 0
  1405. while delta < aperture_size / 2:
  1406. if self.app.abort_flag:
  1407. # graceful abort requested by the user
  1408. raise grace
  1409. # provide the app with a way to process the GUI events when in a blocking loop
  1410. QtWidgets.QApplication.processEvents()
  1411. new_line = line.parallel_offset(distance=delta, side='left', resolution=int(steps_per_circle))
  1412. new_line = new_line.intersection(margin_poly)
  1413. lines_trimmed.append(new_line)
  1414. new_line = line.parallel_offset(distance=delta, side='right', resolution=int(steps_per_circle))
  1415. new_line = new_line.intersection(margin_poly)
  1416. lines_trimmed.append(new_line)
  1417. delta += tooldia * (1 - overlap)
  1418. if prog_plot:
  1419. self.plot_temp_shapes(new_line)
  1420. self.temp_shapes.redraw()
  1421. # Last line
  1422. delta = (aperture_size / 2) - (tooldia / 2.00000001)
  1423. new_line = line.parallel_offset(distance=delta, side='left', resolution=int(steps_per_circle))
  1424. new_line = new_line.intersection(margin_poly)
  1425. except Exception as e:
  1426. log.debug('camlib.Geometry.fill_with_lines() Processing poly --> %s' % str(e))
  1427. return None
  1428. try:
  1429. for ll in new_line:
  1430. lines_trimmed.append(ll)
  1431. if prog_plot:
  1432. self.plot_temp_shapes(ll)
  1433. except TypeError:
  1434. lines_trimmed.append(new_line)
  1435. if prog_plot:
  1436. self.plot_temp_shapes(new_line)
  1437. new_line = line.parallel_offset(distance=delta, side='right', resolution=int(steps_per_circle))
  1438. new_line = new_line.intersection(margin_poly)
  1439. try:
  1440. for ll in new_line:
  1441. lines_trimmed.append(ll)
  1442. if prog_plot:
  1443. self.plot_temp_shapes(ll)
  1444. except TypeError:
  1445. lines_trimmed.append(new_line)
  1446. if prog_plot:
  1447. self.plot_temp_shapes(new_line)
  1448. if prog_plot:
  1449. self.temp_shapes.redraw()
  1450. lines_trimmed = unary_union(lines_trimmed)
  1451. # Add lines to storage
  1452. try:
  1453. for line in lines_trimmed:
  1454. if isinstance(line, LineString) or isinstance(line, LinearRing):
  1455. geoms.insert(line)
  1456. else:
  1457. log.debug("camlib.Geometry.fill_with_lines(). Not a line: %s" % str(type(line)))
  1458. except TypeError:
  1459. # in case lines_trimmed are not iterable (Linestring, LinearRing)
  1460. geoms.insert(lines_trimmed)
  1461. # Add margin (contour) to storage
  1462. if contour:
  1463. try:
  1464. for poly in margin_poly:
  1465. if isinstance(poly, Polygon) and not poly.is_empty:
  1466. geoms.insert(poly.exterior)
  1467. if prog_plot:
  1468. self.plot_temp_shapes(poly.exterior)
  1469. for ints in poly.interiors:
  1470. geoms.insert(ints)
  1471. if prog_plot:
  1472. self.plot_temp_shapes(ints)
  1473. except TypeError:
  1474. if isinstance(margin_poly, Polygon) and not margin_poly.is_empty:
  1475. marg_ext = margin_poly.exterior
  1476. geoms.insert(marg_ext)
  1477. if prog_plot:
  1478. self.plot_temp_shapes(margin_poly.exterior)
  1479. for ints in margin_poly.interiors:
  1480. geoms.insert(ints)
  1481. if prog_plot:
  1482. self.plot_temp_shapes(ints)
  1483. if prog_plot:
  1484. self.temp_shapes.redraw()
  1485. # Optimization: Reduce lifts
  1486. if connect:
  1487. # log.debug("Reducing tool lifts...")
  1488. geoms_conn = Geometry.paint_connect(geoms, polygon, tooldia, steps_per_circle)
  1489. if geoms_conn:
  1490. return geoms_conn
  1491. return geoms
  1492. def scale(self, xfactor, yfactor, point=None):
  1493. """
  1494. Scales all of the object's geometry by a given factor. Override
  1495. this method.
  1496. :param xfactor: Number by which to scale on X axis.
  1497. :type xfactor: float
  1498. :param yfactor: Number by which to scale on Y axis.
  1499. :type yfactor: float
  1500. :param point: point to be used as reference for scaling; a tuple
  1501. :return: None
  1502. :rtype: None
  1503. """
  1504. return
  1505. def offset(self, vect):
  1506. """
  1507. Offset the geometry by the given vector. Override this method.
  1508. :param vect: (x, y) vector by which to offset the object.
  1509. :type vect: tuple
  1510. :return: None
  1511. """
  1512. return
  1513. @staticmethod
  1514. def paint_connect(storage, boundary, tooldia, steps_per_circle, max_walk=None):
  1515. """
  1516. Connects paths that results in a connection segment that is
  1517. within the paint area. This avoids unnecessary tool lifting.
  1518. :param storage: Geometry to be optimized.
  1519. :type storage: FlatCAMRTreeStorage
  1520. :param boundary: Polygon defining the limits of the paintable area.
  1521. :type boundary: Polygon
  1522. :param tooldia: Tool diameter.
  1523. :rtype tooldia: float
  1524. :param steps_per_circle: how many linear segments to use to approximate a circle
  1525. :param max_walk: Maximum allowable distance without lifting tool.
  1526. :type max_walk: float or None
  1527. :return: Optimized geometry.
  1528. :rtype: FlatCAMRTreeStorage
  1529. """
  1530. # If max_walk is not specified, the maximum allowed is
  1531. # 10 times the tool diameter
  1532. max_walk = max_walk or 10 * tooldia
  1533. # Assuming geolist is a flat list of flat elements
  1534. # ## Index first and last points in paths
  1535. def get_pts(o):
  1536. return [o.coords[0], o.coords[-1]]
  1537. # storage = FlatCAMRTreeStorage()
  1538. # storage.get_points = get_pts
  1539. #
  1540. # for shape in geolist:
  1541. # if shape is not None:
  1542. # # Make LlinearRings into linestrings otherwise
  1543. # # When chaining the coordinates path is messed up.
  1544. # storage.insert(LineString(shape))
  1545. # #storage.insert(shape)
  1546. # ## Iterate over geometry paths getting the nearest each time.
  1547. # optimized_paths = []
  1548. optimized_paths = FlatCAMRTreeStorage()
  1549. optimized_paths.get_points = get_pts
  1550. path_count = 0
  1551. current_pt = (0, 0)
  1552. try:
  1553. pt, geo = storage.nearest(current_pt)
  1554. except StopIteration:
  1555. log.debug("camlib.Geometry.paint_connect(). Storage empty")
  1556. return None
  1557. storage.remove(geo)
  1558. geo = LineString(geo)
  1559. current_pt = geo.coords[-1]
  1560. try:
  1561. while True:
  1562. path_count += 1
  1563. # log.debug("Path %d" % path_count)
  1564. pt, candidate = storage.nearest(current_pt)
  1565. storage.remove(candidate)
  1566. candidate = LineString(candidate)
  1567. # If last point in geometry is the nearest
  1568. # then reverse coordinates.
  1569. # but prefer the first one if last == first
  1570. if pt != candidate.coords[0] and pt == candidate.coords[-1]:
  1571. # in place coordinates update deprecated in Shapely 2.0
  1572. # candidate.coords = list(candidate.coords)[::-1]
  1573. candidate = LineString(list(candidate.coords)[::-1])
  1574. # Straight line from current_pt to pt.
  1575. # Is the toolpath inside the geometry?
  1576. walk_path = LineString([current_pt, pt])
  1577. walk_cut = walk_path.buffer(tooldia / 2, int(steps_per_circle))
  1578. if walk_cut.within(boundary) and walk_path.length < max_walk:
  1579. # log.debug("Walk to path #%d is inside. Joining." % path_count)
  1580. # Completely inside. Append...
  1581. # in place coordinates update deprecated in Shapely 2.0
  1582. # geo.coords = list(geo.coords) + list(candidate.coords)
  1583. geo = LineString(list(geo.coords) + list(candidate.coords))
  1584. # try:
  1585. # last = optimized_paths[-1]
  1586. # last.coords = list(last.coords) + list(geo.coords)
  1587. # except IndexError:
  1588. # optimized_paths.append(geo)
  1589. else:
  1590. # Have to lift tool. End path.
  1591. # log.debug("Path #%d not within boundary. Next." % path_count)
  1592. # optimized_paths.append(geo)
  1593. optimized_paths.insert(geo)
  1594. geo = candidate
  1595. current_pt = geo.coords[-1]
  1596. # Next
  1597. # pt, geo = storage.nearest(current_pt)
  1598. except StopIteration: # Nothing left in storage.
  1599. # pass
  1600. optimized_paths.insert(geo)
  1601. return optimized_paths
  1602. @staticmethod
  1603. def path_connect(storage, origin=(0, 0)):
  1604. """
  1605. Simplifies paths in the FlatCAMRTreeStorage storage by
  1606. connecting paths that touch on their endpoints.
  1607. :param storage: Storage containing the initial paths.
  1608. :rtype storage: FlatCAMRTreeStorage
  1609. :param origin: tuple; point from which to calculate the nearest point
  1610. :return: Simplified storage.
  1611. :rtype: FlatCAMRTreeStorage
  1612. """
  1613. log.debug("path_connect()")
  1614. # ## Index first and last points in paths
  1615. def get_pts(o):
  1616. return [o.coords[0], o.coords[-1]]
  1617. #
  1618. # storage = FlatCAMRTreeStorage()
  1619. # storage.get_points = get_pts
  1620. #
  1621. # for shape in pathlist:
  1622. # if shape is not None:
  1623. # storage.insert(shape)
  1624. path_count = 0
  1625. pt, geo = storage.nearest(origin)
  1626. storage.remove(geo)
  1627. # optimized_geometry = [geo]
  1628. optimized_geometry = FlatCAMRTreeStorage()
  1629. optimized_geometry.get_points = get_pts
  1630. # optimized_geometry.insert(geo)
  1631. try:
  1632. while True:
  1633. path_count += 1
  1634. _, left = storage.nearest(geo.coords[0])
  1635. # If left touches geo, remove left from original
  1636. # storage and append to geo.
  1637. if type(left) == LineString:
  1638. if left.coords[0] == geo.coords[0]:
  1639. storage.remove(left)
  1640. geo.coords = list(geo.coords)[::-1] + list(left.coords)
  1641. continue
  1642. if left.coords[-1] == geo.coords[0]:
  1643. storage.remove(left)
  1644. geo.coords = list(left.coords) + list(geo.coords)
  1645. continue
  1646. if left.coords[0] == geo.coords[-1]:
  1647. storage.remove(left)
  1648. geo.coords = list(geo.coords) + list(left.coords)
  1649. continue
  1650. if left.coords[-1] == geo.coords[-1]:
  1651. storage.remove(left)
  1652. geo.coords = list(geo.coords) + list(left.coords)[::-1]
  1653. continue
  1654. _, right = storage.nearest(geo.coords[-1])
  1655. # If right touches geo, remove left from original
  1656. # storage and append to geo.
  1657. if type(right) == LineString:
  1658. if right.coords[0] == geo.coords[-1]:
  1659. storage.remove(right)
  1660. geo.coords = list(geo.coords) + list(right.coords)
  1661. continue
  1662. if right.coords[-1] == geo.coords[-1]:
  1663. storage.remove(right)
  1664. geo.coords = list(geo.coords) + list(right.coords)[::-1]
  1665. continue
  1666. if right.coords[0] == geo.coords[0]:
  1667. storage.remove(right)
  1668. geo.coords = list(geo.coords)[::-1] + list(right.coords)
  1669. continue
  1670. if right.coords[-1] == geo.coords[0]:
  1671. storage.remove(right)
  1672. geo.coords = list(left.coords) + list(geo.coords)
  1673. continue
  1674. # right is either a LinearRing or it does not connect
  1675. # to geo (nothing left to connect to geo), so we continue
  1676. # with right as geo.
  1677. storage.remove(right)
  1678. if type(right) == LinearRing:
  1679. optimized_geometry.insert(right)
  1680. else:
  1681. # Cannot extend geo any further. Put it away.
  1682. optimized_geometry.insert(geo)
  1683. # Continue with right.
  1684. geo = right
  1685. except StopIteration: # Nothing found in storage.
  1686. optimized_geometry.insert(geo)
  1687. # print path_count
  1688. log.debug("path_count = %d" % path_count)
  1689. return optimized_geometry
  1690. def convert_units(self, obj_units):
  1691. """
  1692. Converts the units of the object to ``units`` by scaling all
  1693. the geometry appropriately. This call ``scale()``. Don't call
  1694. it again in descendents.
  1695. :param obj_units: "IN" or "MM"
  1696. :type obj_units: str
  1697. :return: Scaling factor resulting from unit change.
  1698. :rtype: float
  1699. """
  1700. if obj_units.upper() == self.units.upper():
  1701. log.debug("camlib.Geometry.convert_units() --> Factor: 1")
  1702. return 1.0
  1703. if obj_units.upper() == "MM":
  1704. factor = 25.4
  1705. log.debug("camlib.Geometry.convert_units() --> Factor: 25.4")
  1706. elif obj_units.upper() == "IN":
  1707. factor = 1 / 25.4
  1708. log.debug("camlib.Geometry.convert_units() --> Factor: %s" % str(1 / 25.4))
  1709. else:
  1710. log.error("Unsupported units: %s" % str(obj_units))
  1711. log.debug("camlib.Geometry.convert_units() --> Factor: 1")
  1712. return 1.0
  1713. self.units = obj_units
  1714. self.scale(factor, factor)
  1715. self.file_units_factor = factor
  1716. return factor
  1717. def to_dict(self):
  1718. """
  1719. Returns a representation of the object as a dictionary.
  1720. Attributes to include are listed in ``self.ser_attrs``.
  1721. :return: A dictionary-encoded copy of the object.
  1722. :rtype: dict
  1723. """
  1724. d = {}
  1725. for attr in self.ser_attrs:
  1726. d[attr] = getattr(self, attr)
  1727. return d
  1728. def from_dict(self, d):
  1729. """
  1730. Sets object's attributes from a dictionary.
  1731. Attributes to include are listed in ``self.ser_attrs``.
  1732. This method will look only for only and all the
  1733. attributes in ``self.ser_attrs``. They must all
  1734. be present. Use only for deserializing saved
  1735. objects.
  1736. :param d: Dictionary of attributes to set in the object.
  1737. :type d: dict
  1738. :return: None
  1739. """
  1740. for attr in self.ser_attrs:
  1741. setattr(self, attr, d[attr])
  1742. def union(self):
  1743. """
  1744. Runs a cascaded union on the list of objects in
  1745. solid_geometry.
  1746. :return: None
  1747. """
  1748. self.solid_geometry = [cascaded_union(self.solid_geometry)]
  1749. def export_svg(self, scale_stroke_factor=0.00,
  1750. scale_factor_x=None, scale_factor_y=None,
  1751. skew_factor_x=None, skew_factor_y=None,
  1752. skew_reference='center',
  1753. mirror=None):
  1754. """
  1755. Exports the Geometry Object as a SVG Element
  1756. :return: SVG Element
  1757. """
  1758. # Make sure we see a Shapely Geometry class and not a list
  1759. if self.kind.lower() == 'geometry':
  1760. flat_geo = []
  1761. if self.multigeo:
  1762. for tool in self.tools:
  1763. flat_geo += self.flatten(self.tools[tool]['solid_geometry'])
  1764. geom_svg = cascaded_union(flat_geo)
  1765. else:
  1766. geom_svg = cascaded_union(self.flatten())
  1767. else:
  1768. geom_svg = cascaded_union(self.flatten())
  1769. skew_ref = 'center'
  1770. if skew_reference != 'center':
  1771. xmin, ymin, xmax, ymax = geom_svg.bounds
  1772. if skew_reference == 'topleft':
  1773. skew_ref = (xmin, ymax)
  1774. elif skew_reference == 'bottomleft':
  1775. skew_ref = (xmin, ymin)
  1776. elif skew_reference == 'topright':
  1777. skew_ref = (xmax, ymax)
  1778. elif skew_reference == 'bottomright':
  1779. skew_ref = (xmax, ymin)
  1780. geom = geom_svg
  1781. if scale_factor_x:
  1782. geom = affinity.scale(geom_svg, scale_factor_x, 1.0)
  1783. if scale_factor_y:
  1784. geom = affinity.scale(geom_svg, 1.0, scale_factor_y)
  1785. if skew_factor_x:
  1786. geom = affinity.skew(geom_svg, skew_factor_x, 0.0, origin=skew_ref)
  1787. if skew_factor_y:
  1788. geom = affinity.skew(geom_svg, 0.0, skew_factor_y, origin=skew_ref)
  1789. if mirror:
  1790. if mirror == 'x':
  1791. geom = affinity.scale(geom_svg, 1.0, -1.0)
  1792. if mirror == 'y':
  1793. geom = affinity.scale(geom_svg, -1.0, 1.0)
  1794. if mirror == 'both':
  1795. geom = affinity.scale(geom_svg, -1.0, -1.0)
  1796. # scale_factor is a multiplication factor for the SVG stroke-width used within shapely's svg export
  1797. # If 0 or less which is invalid then default to 0.01
  1798. # This value appears to work for zooming, and getting the output svg line width
  1799. # to match that viewed on screen with FlatCam
  1800. # MS: I choose a factor of 0.01 so the scale is right for PCB UV film
  1801. if scale_stroke_factor <= 0:
  1802. scale_stroke_factor = 0.01
  1803. # Convert to a SVG
  1804. svg_elem = geom.svg(scale_factor=scale_stroke_factor)
  1805. return svg_elem
  1806. def mirror(self, axis, point):
  1807. """
  1808. Mirrors the object around a specified axis passign through
  1809. the given point.
  1810. :param axis: "X" or "Y" indicates around which axis to mirror.
  1811. :type axis: str
  1812. :param point: [x, y] point belonging to the mirror axis.
  1813. :type point: list
  1814. :return: None
  1815. """
  1816. log.debug("camlib.Geometry.mirror()")
  1817. px, py = point
  1818. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  1819. def mirror_geom(obj):
  1820. if type(obj) is list:
  1821. new_obj = []
  1822. for g in obj:
  1823. new_obj.append(mirror_geom(g))
  1824. return new_obj
  1825. else:
  1826. try:
  1827. self.el_count += 1
  1828. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  1829. if self.old_disp_number < disp_number <= 100:
  1830. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1831. self.old_disp_number = disp_number
  1832. return affinity.scale(obj, xscale, yscale, origin=(px, py))
  1833. except AttributeError:
  1834. return obj
  1835. try:
  1836. if self.multigeo is True:
  1837. for tool in self.tools:
  1838. # variables to display the percentage of work done
  1839. self.geo_len = 0
  1840. try:
  1841. self.geo_len = len(self.tools[tool]['solid_geometry'])
  1842. except TypeError:
  1843. self.geo_len = 1
  1844. self.old_disp_number = 0
  1845. self.el_count = 0
  1846. self.tools[tool]['solid_geometry'] = mirror_geom(self.tools[tool]['solid_geometry'])
  1847. else:
  1848. # variables to display the percentage of work done
  1849. self.geo_len = 0
  1850. try:
  1851. self.geo_len = len(self.solid_geometry)
  1852. except TypeError:
  1853. self.geo_len = 1
  1854. self.old_disp_number = 0
  1855. self.el_count = 0
  1856. self.solid_geometry = mirror_geom(self.solid_geometry)
  1857. self.app.inform.emit('[success] %s...' % _('Object was mirrored'))
  1858. except AttributeError:
  1859. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Failed to mirror. No object selected"))
  1860. self.app.proc_container.new_text = ''
  1861. def rotate(self, angle, point):
  1862. """
  1863. Rotate an object by an angle (in degrees) around the provided coordinates.
  1864. :param angle:
  1865. The angle of rotation are specified in degrees (default). Positive angles are
  1866. counter-clockwise and negative are clockwise rotations.
  1867. :param point:
  1868. The point of origin can be a keyword 'center' for the bounding box
  1869. center (default), 'centroid' for the geometry's centroid, a Point object
  1870. or a coordinate tuple (x0, y0).
  1871. See shapely manual for more information: http://toblerity.org/shapely/manual.html#affine-transformations
  1872. """
  1873. log.debug("camlib.Geometry.rotate()")
  1874. px, py = point
  1875. def rotate_geom(obj):
  1876. try:
  1877. new_obj = []
  1878. for g in obj:
  1879. new_obj.append(rotate_geom(g))
  1880. return new_obj
  1881. except TypeError:
  1882. try:
  1883. self.el_count += 1
  1884. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  1885. if self.old_disp_number < disp_number <= 100:
  1886. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1887. self.old_disp_number = disp_number
  1888. return affinity.rotate(obj, angle, origin=(px, py))
  1889. except AttributeError:
  1890. return obj
  1891. try:
  1892. if self.multigeo is True:
  1893. for tool in self.tools:
  1894. # variables to display the percentage of work done
  1895. self.geo_len = 0
  1896. try:
  1897. self.geo_len = len(self.tools[tool]['solid_geometry'])
  1898. except TypeError:
  1899. self.geo_len = 1
  1900. self.old_disp_number = 0
  1901. self.el_count = 0
  1902. self.tools[tool]['solid_geometry'] = rotate_geom(self.tools[tool]['solid_geometry'])
  1903. else:
  1904. # variables to display the percentage of work done
  1905. self.geo_len = 0
  1906. try:
  1907. self.geo_len = len(self.solid_geometry)
  1908. except TypeError:
  1909. self.geo_len = 1
  1910. self.old_disp_number = 0
  1911. self.el_count = 0
  1912. self.solid_geometry = rotate_geom(self.solid_geometry)
  1913. self.app.inform.emit('[success] %s...' % _('Object was rotated'))
  1914. except AttributeError:
  1915. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Failed to rotate. No object selected"))
  1916. self.app.proc_container.new_text = ''
  1917. def skew(self, angle_x, angle_y, point):
  1918. """
  1919. Shear/Skew the geometries of an object by angles along x and y dimensions.
  1920. :param angle_x:
  1921. :param angle_y:
  1922. angle_x, angle_y : float, float
  1923. The shear angle(s) for the x and y axes respectively. These can be
  1924. specified in either degrees (default) or radians by setting
  1925. use_radians=True.
  1926. :param point: Origin point for Skew
  1927. point: tuple of coordinates (x,y)
  1928. See shapely manual for more information: http://toblerity.org/shapely/manual.html#affine-transformations
  1929. """
  1930. log.debug("camlib.Geometry.skew()")
  1931. px, py = point
  1932. def skew_geom(obj):
  1933. try:
  1934. new_obj = []
  1935. for g in obj:
  1936. new_obj.append(skew_geom(g))
  1937. return new_obj
  1938. except TypeError:
  1939. try:
  1940. self.el_count += 1
  1941. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  1942. if self.old_disp_number < disp_number <= 100:
  1943. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1944. self.old_disp_number = disp_number
  1945. return affinity.skew(obj, angle_x, angle_y, origin=(px, py))
  1946. except AttributeError:
  1947. return obj
  1948. try:
  1949. if self.multigeo is True:
  1950. for tool in self.tools:
  1951. # variables to display the percentage of work done
  1952. self.geo_len = 0
  1953. try:
  1954. self.geo_len = len(self.tools[tool]['solid_geometry'])
  1955. except TypeError:
  1956. self.geo_len = 1
  1957. self.old_disp_number = 0
  1958. self.el_count = 0
  1959. self.tools[tool]['solid_geometry'] = skew_geom(self.tools[tool]['solid_geometry'])
  1960. else:
  1961. # variables to display the percentage of work done
  1962. self.geo_len = 0
  1963. try:
  1964. self.geo_len = len(self.solid_geometry)
  1965. except TypeError:
  1966. self.geo_len = 1
  1967. self.old_disp_number = 0
  1968. self.el_count = 0
  1969. self.solid_geometry = skew_geom(self.solid_geometry)
  1970. self.app.inform.emit('[success] %s...' % _('Object was skewed'))
  1971. except AttributeError:
  1972. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Failed to skew. No object selected"))
  1973. self.app.proc_container.new_text = ''
  1974. # if type(self.solid_geometry) == list:
  1975. # self.solid_geometry = [affinity.skew(g, angle_x, angle_y, origin=(px, py))
  1976. # for g in self.solid_geometry]
  1977. # else:
  1978. # self.solid_geometry = affinity.skew(self.solid_geometry, angle_x, angle_y,
  1979. # origin=(px, py))
  1980. def buffer(self, distance, join, factor):
  1981. """
  1982. :param distance: if 'factor' is True then distance is the factor
  1983. :param join: The kind of join used by the shapely buffer method: round, square or bevel
  1984. :param factor: True or False (None)
  1985. :return:
  1986. """
  1987. log.debug("camlib.Geometry.buffer()")
  1988. if distance == 0:
  1989. return
  1990. def buffer_geom(obj):
  1991. if type(obj) is list:
  1992. new_obj = []
  1993. for g in obj:
  1994. new_obj.append(buffer_geom(g))
  1995. return new_obj
  1996. else:
  1997. try:
  1998. self.el_count += 1
  1999. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  2000. if self.old_disp_number < disp_number <= 100:
  2001. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  2002. self.old_disp_number = disp_number
  2003. if factor is None:
  2004. return obj.buffer(distance, resolution=self.geo_steps_per_circle, join_style=join)
  2005. else:
  2006. return affinity.scale(obj, xfact=distance, yfact=distance, origin='center')
  2007. except AttributeError:
  2008. return obj
  2009. try:
  2010. if self.multigeo is True:
  2011. for tool in self.tools:
  2012. # variables to display the percentage of work done
  2013. self.geo_len = 0
  2014. try:
  2015. self.geo_len += len(self.tools[tool]['solid_geometry'])
  2016. except TypeError:
  2017. self.geo_len += 1
  2018. self.old_disp_number = 0
  2019. self.el_count = 0
  2020. res = buffer_geom(self.tools[tool]['solid_geometry'])
  2021. try:
  2022. __ = iter(res)
  2023. self.tools[tool]['solid_geometry'] = res
  2024. except TypeError:
  2025. self.tools[tool]['solid_geometry'] = [res]
  2026. # variables to display the percentage of work done
  2027. self.geo_len = 0
  2028. try:
  2029. self.geo_len = len(self.solid_geometry)
  2030. except TypeError:
  2031. self.geo_len = 1
  2032. self.old_disp_number = 0
  2033. self.el_count = 0
  2034. self.solid_geometry = buffer_geom(self.solid_geometry)
  2035. self.app.inform.emit('[success] %s...' % _('Object was buffered'))
  2036. except AttributeError:
  2037. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Failed to buffer. No object selected"))
  2038. self.app.proc_container.new_text = ''
  2039. class AttrDict(dict):
  2040. def __init__(self, *args, **kwargs):
  2041. super(AttrDict, self).__init__(*args, **kwargs)
  2042. self.__dict__ = self
  2043. class CNCjob(Geometry):
  2044. """
  2045. Represents work to be done by a CNC machine.
  2046. *ATTRIBUTES*
  2047. * ``gcode_parsed`` (list): Each is a dictionary:
  2048. ===================== =========================================
  2049. Key Value
  2050. ===================== =========================================
  2051. geom (Shapely.LineString) Tool path (XY plane)
  2052. kind (string) "AB", A is "T" (travel) or
  2053. "C" (cut). B is "F" (fast) or "S" (slow).
  2054. ===================== =========================================
  2055. """
  2056. defaults = {
  2057. "global_zdownrate": None,
  2058. "pp_geometry_name": 'default',
  2059. "pp_excellon_name": 'default',
  2060. "excellon_optimization_type": "B",
  2061. }
  2062. settings = QtCore.QSettings("Open Source", "FlatCAM")
  2063. if settings.contains("machinist"):
  2064. machinist_setting = settings.value('machinist', type=int)
  2065. else:
  2066. machinist_setting = 0
  2067. def __init__(self,
  2068. units="in", kind="generic", tooldia=0.0,
  2069. z_cut=-0.002, z_move=0.1,
  2070. feedrate=3.0, feedrate_z=3.0, feedrate_rapid=3.0, feedrate_probe=3.0,
  2071. pp_geometry_name='default', pp_excellon_name='default',
  2072. depthpercut=0.1, z_pdepth=-0.02,
  2073. spindlespeed=None, spindledir='CW', dwell=True, dwelltime=1000,
  2074. toolchangez=0.787402, toolchange_xy='0.0,0.0',
  2075. endz=2.0, endxy='',
  2076. segx=None,
  2077. segy=None,
  2078. steps_per_circle=None):
  2079. self.decimals = self.app.decimals
  2080. # Used when parsing G-code arcs
  2081. self.steps_per_circle = steps_per_circle if steps_per_circle is not None else \
  2082. int(self.app.defaults['cncjob_steps_per_circle'])
  2083. Geometry.__init__(self, geo_steps_per_circle=self.steps_per_circle)
  2084. self.kind = kind
  2085. self.units = units
  2086. self.z_cut = z_cut
  2087. self.multidepth = False
  2088. self.z_depthpercut = depthpercut
  2089. self.z_move = z_move
  2090. self.feedrate = feedrate
  2091. self.z_feedrate = feedrate_z
  2092. self.feedrate_rapid = feedrate_rapid
  2093. self.tooldia = tooldia
  2094. self.toolC = tooldia
  2095. self.toolchange = False
  2096. self.z_toolchange = toolchangez
  2097. self.xy_toolchange = toolchange_xy
  2098. self.toolchange_xy_type = None
  2099. self.startz = None
  2100. self.z_end = endz
  2101. self.xy_end = endxy
  2102. self.extracut = False
  2103. self.extracut_length = None
  2104. self.tolerance = self.drawing_tolerance
  2105. # used by the self.generate_from_excellon_by_tool() method
  2106. # but set directly before the actual usage of the method with obj.excellon_optimization_type = value
  2107. self.excellon_optimization_type = 'No'
  2108. # if set True then the GCode generation will use UI; used in Excellon GVode for now
  2109. self.use_ui = False
  2110. self.unitcode = {"IN": "G20", "MM": "G21"}
  2111. self.feedminutecode = "G94"
  2112. # self.absolutecode = "G90"
  2113. # self.incrementalcode = "G91"
  2114. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  2115. self.gcode = ""
  2116. self.gcode_parsed = None
  2117. self.pp_geometry_name = pp_geometry_name
  2118. self.pp_geometry = self.app.preprocessors[self.pp_geometry_name]
  2119. self.pp_excellon_name = pp_excellon_name
  2120. self.pp_excellon = self.app.preprocessors[self.pp_excellon_name]
  2121. self.pp_solderpaste_name = None
  2122. # Controls if the move from Z_Toolchange to Z_Move is done fast with G0 or normally with G1
  2123. self.f_plunge = None
  2124. # Controls if the move from Z_Cutto Z_Move is done fast with G0 or G1 until zero and then G0 to Z_move
  2125. self.f_retract = None
  2126. # how much depth the probe can probe before error
  2127. self.z_pdepth = z_pdepth if z_pdepth else None
  2128. # the feedrate(speed) with which the probel travel while probing
  2129. self.feedrate_probe = feedrate_probe if feedrate_probe else None
  2130. self.spindlespeed = spindlespeed
  2131. self.spindledir = spindledir
  2132. self.dwell = dwell
  2133. self.dwelltime = dwelltime
  2134. self.segx = float(segx) if segx is not None else 0.0
  2135. self.segy = float(segy) if segy is not None else 0.0
  2136. self.input_geometry_bounds = None
  2137. self.oldx = None
  2138. self.oldy = None
  2139. self.tool = 0.0
  2140. self.measured_distance = 0.0
  2141. self.measured_down_distance = 0.0
  2142. self.measured_up_to_zero_distance = 0.0
  2143. self.measured_lift_distance = 0.0
  2144. # here store the travelled distance
  2145. self.travel_distance = 0.0
  2146. # here store the routing time
  2147. self.routing_time = 0.0
  2148. # store here the Excellon source object tools to be accessible locally
  2149. self.exc_tools = None
  2150. # search for toolchange parameters in the Toolchange Custom Code
  2151. self.re_toolchange_custom = re.compile(r'(%[a-zA-Z0-9\-_]+%)')
  2152. # search for toolchange code: M6
  2153. self.re_toolchange = re.compile(r'^\s*(M6)$')
  2154. # Attributes to be included in serialization
  2155. # Always append to it because it carries contents
  2156. # from Geometry.
  2157. self.ser_attrs += ['kind', 'z_cut', 'z_move', 'z_toolchange', 'feedrate', 'z_feedrate', 'feedrate_rapid',
  2158. 'tooldia', 'gcode', 'input_geometry_bounds', 'gcode_parsed', 'steps_per_circle',
  2159. 'z_depthpercut', 'spindlespeed', 'dwell', 'dwelltime']
  2160. @property
  2161. def postdata(self):
  2162. """
  2163. This will return all the attributes of the class in the form of a dictionary
  2164. :return: Class attributes
  2165. :rtype: dict
  2166. """
  2167. return self.__dict__
  2168. def convert_units(self, units):
  2169. """
  2170. Will convert the parameters in the class that are relevant, from metric to imperial and reverse
  2171. :param units: FlatCAM units
  2172. :type units: str
  2173. :return: conversion factor
  2174. :rtype: float
  2175. """
  2176. log.debug("camlib.CNCJob.convert_units()")
  2177. factor = Geometry.convert_units(self, units)
  2178. self.z_cut = float(self.z_cut) * factor
  2179. self.z_move *= factor
  2180. self.feedrate *= factor
  2181. self.z_feedrate *= factor
  2182. self.feedrate_rapid *= factor
  2183. self.tooldia *= factor
  2184. self.z_toolchange *= factor
  2185. self.z_end *= factor
  2186. self.z_depthpercut = float(self.z_depthpercut) * factor
  2187. return factor
  2188. def doformat(self, fun, **kwargs):
  2189. return self.doformat2(fun, **kwargs) + "\n"
  2190. def doformat2(self, fun, **kwargs):
  2191. """
  2192. This method will call one of the current preprocessor methods having as parameters all the attributes of
  2193. current class to which will add the kwargs parameters
  2194. :param fun: One of the methods inside the preprocessor classes which get loaded here in the 'p' object
  2195. :type fun: class 'function'
  2196. :param kwargs: keyword args which will update attributes of the current class
  2197. :type kwargs: dict
  2198. :return: Gcode line
  2199. :rtype: str
  2200. """
  2201. attributes = AttrDict()
  2202. attributes.update(self.postdata)
  2203. attributes.update(kwargs)
  2204. try:
  2205. returnvalue = fun(attributes)
  2206. return returnvalue
  2207. except Exception:
  2208. self.app.log.error('Exception occurred within a preprocessor: ' + traceback.format_exc())
  2209. return ''
  2210. def parse_custom_toolchange_code(self, data):
  2211. """
  2212. Will parse a text and get a toolchange sequence in text format suitable to be included in a Gcode file.
  2213. The '%' symbol is used to surround class variables name and must be removed in the returned string.
  2214. After that, the class variables (attributes) are replaced with the current values. The result is returned.
  2215. :param data: Toolchange sequence
  2216. :type data: str
  2217. :return: Processed toolchange sequence
  2218. :rtype: str
  2219. """
  2220. text = data
  2221. match_list = self.re_toolchange_custom.findall(text)
  2222. if match_list:
  2223. for match in match_list:
  2224. command = match.strip('%')
  2225. try:
  2226. value = getattr(self, command)
  2227. except AttributeError:
  2228. self.app.inform.emit('[ERROR] %s: %s' %
  2229. (_("There is no such parameter"), str(match)))
  2230. log.debug("CNCJob.parse_custom_toolchange_code() --> AttributeError ")
  2231. return 'fail'
  2232. text = text.replace(match, str(value))
  2233. return text
  2234. # Distance callback
  2235. class CreateDistanceCallback(object):
  2236. """Create callback to calculate distances between points."""
  2237. def __init__(self, locs, manager):
  2238. self.manager = manager
  2239. self.matrix = {}
  2240. if locs:
  2241. size = len(locs)
  2242. for from_node in range(size):
  2243. self.matrix[from_node] = {}
  2244. for to_node in range(size):
  2245. if from_node == to_node:
  2246. self.matrix[from_node][to_node] = 0
  2247. else:
  2248. x1 = locs[from_node][0]
  2249. y1 = locs[from_node][1]
  2250. x2 = locs[to_node][0]
  2251. y2 = locs[to_node][1]
  2252. self.matrix[from_node][to_node] = distance_euclidian(x1, y1, x2, y2)
  2253. # def Distance(self, from_node, to_node):
  2254. # return int(self.matrix[from_node][to_node])
  2255. def Distance(self, from_index, to_index):
  2256. # Convert from routing variable Index to distance matrix NodeIndex.
  2257. from_node = self.manager.IndexToNode(from_index)
  2258. to_node = self.manager.IndexToNode(to_index)
  2259. return self.matrix[from_node][to_node]
  2260. @staticmethod
  2261. def create_tool_data_array(points):
  2262. # Create the data.
  2263. return [(pt.coords.xy[0][0], pt.coords.xy[1][0]) for pt in points]
  2264. def optimized_ortools_meta(self, locations, start=None, opt_time=0):
  2265. optimized_path = []
  2266. tsp_size = len(locations)
  2267. num_routes = 1 # The number of routes, which is 1 in the TSP.
  2268. # Nodes are indexed from 0 to tsp_size - 1. The depot is the starting node of the route.
  2269. depot = 0 if start is None else start
  2270. # Create routing model.
  2271. if tsp_size == 0:
  2272. log.warning('OR-tools metaheuristics - Specify an instance greater than 0.')
  2273. return optimized_path
  2274. manager = pywrapcp.RoutingIndexManager(tsp_size, num_routes, depot)
  2275. routing = pywrapcp.RoutingModel(manager)
  2276. search_parameters = pywrapcp.DefaultRoutingSearchParameters()
  2277. search_parameters.local_search_metaheuristic = (
  2278. routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH)
  2279. # Set search time limit in milliseconds.
  2280. if float(opt_time) != 0:
  2281. search_parameters.time_limit.seconds = int(
  2282. float(opt_time))
  2283. else:
  2284. search_parameters.time_limit.seconds = 3
  2285. # Callback to the distance function. The callback takes two
  2286. # arguments (the from and to node indices) and returns the distance between them.
  2287. dist_between_locations = self.CreateDistanceCallback(locs=locations, manager=manager)
  2288. # if there are no distances then go to the next tool
  2289. if not dist_between_locations:
  2290. return
  2291. dist_callback = dist_between_locations.Distance
  2292. transit_callback_index = routing.RegisterTransitCallback(dist_callback)
  2293. routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)
  2294. # Solve, returns a solution if any.
  2295. assignment = routing.SolveWithParameters(search_parameters)
  2296. if assignment:
  2297. # Solution cost.
  2298. log.info("OR-tools metaheuristics - Total distance: " + str(assignment.ObjectiveValue()))
  2299. # Inspect solution.
  2300. # Only one route here; otherwise iterate from 0 to routing.vehicles() - 1.
  2301. route_number = 0
  2302. node = routing.Start(route_number)
  2303. start_node = node
  2304. while not routing.IsEnd(node):
  2305. if self.app.abort_flag:
  2306. # graceful abort requested by the user
  2307. raise grace
  2308. optimized_path.append(node)
  2309. node = assignment.Value(routing.NextVar(node))
  2310. else:
  2311. log.warning('OR-tools metaheuristics - No solution found.')
  2312. return optimized_path
  2313. # ############################################# ##
  2314. def optimized_ortools_basic(self, locations, start=None):
  2315. optimized_path = []
  2316. tsp_size = len(locations)
  2317. num_routes = 1 # The number of routes, which is 1 in the TSP.
  2318. # Nodes are indexed from 0 to tsp_size - 1. The depot is the starting node of the route.
  2319. depot = 0 if start is None else start
  2320. # Create routing model.
  2321. if tsp_size == 0:
  2322. log.warning('Specify an instance greater than 0.')
  2323. return optimized_path
  2324. manager = pywrapcp.RoutingIndexManager(tsp_size, num_routes, depot)
  2325. routing = pywrapcp.RoutingModel(manager)
  2326. search_parameters = pywrapcp.DefaultRoutingSearchParameters()
  2327. # Callback to the distance function. The callback takes two
  2328. # arguments (the from and to node indices) and returns the distance between them.
  2329. dist_between_locations = self.CreateDistanceCallback(locs=locations, manager=manager)
  2330. # if there are no distances then go to the next tool
  2331. if not dist_between_locations:
  2332. return
  2333. dist_callback = dist_between_locations.Distance
  2334. transit_callback_index = routing.RegisterTransitCallback(dist_callback)
  2335. routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)
  2336. # Solve, returns a solution if any.
  2337. assignment = routing.SolveWithParameters(search_parameters)
  2338. if assignment:
  2339. # Solution cost.
  2340. log.info("Total distance: " + str(assignment.ObjectiveValue()))
  2341. # Inspect solution.
  2342. # Only one route here; otherwise iterate from 0 to routing.vehicles() - 1.
  2343. route_number = 0
  2344. node = routing.Start(route_number)
  2345. start_node = node
  2346. while not routing.IsEnd(node):
  2347. optimized_path.append(node)
  2348. node = assignment.Value(routing.NextVar(node))
  2349. else:
  2350. log.warning('No solution found.')
  2351. return optimized_path
  2352. # ############################################# ##
  2353. def optimized_travelling_salesman(self, points, start=None):
  2354. """
  2355. As solving the problem in the brute force way is too slow,
  2356. this function implements a simple heuristic: always
  2357. go to the nearest city.
  2358. Even if this algorithm is extremely simple, it works pretty well
  2359. giving a solution only about 25%% longer than the optimal one (cit. Wikipedia),
  2360. and runs very fast in O(N^2) time complexity.
  2361. >>> optimized_travelling_salesman([[i,j] for i in range(5) for j in range(5)])
  2362. [[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],
  2363. [2, 3], [2, 4], [3, 4], [3, 3], [3, 2], [3, 1], [3, 0], [4, 0], [4, 1], [4, 2], [4, 3], [4, 4]]
  2364. >>> optimized_travelling_salesman([[0,0],[10,0],[6,0]])
  2365. [[0, 0], [6, 0], [10, 0]]
  2366. :param points: List of tuples with x, y coordinates
  2367. :type points: list
  2368. :param start: a tuple with a x,y coordinates of the start point
  2369. :type start: tuple
  2370. :return: List of points ordered in a optimized way
  2371. :rtype: list
  2372. """
  2373. if start is None:
  2374. start = points[0]
  2375. must_visit = points
  2376. path = [start]
  2377. # must_visit.remove(start)
  2378. while must_visit:
  2379. nearest = min(must_visit, key=lambda x: distance(path[-1], x))
  2380. path.append(nearest)
  2381. must_visit.remove(nearest)
  2382. return path
  2383. def geo_optimized_rtree(self, geometry):
  2384. locations = []
  2385. # ## Index first and last points in paths. What points to index.
  2386. def get_pts(o):
  2387. return [o.coords[0], o.coords[-1]]
  2388. # Create the indexed storage.
  2389. storage = FlatCAMRTreeStorage()
  2390. storage.get_points = get_pts
  2391. # Store the geometry
  2392. log.debug("Indexing geometry before generating G-Code...")
  2393. self.app.inform.emit(_("Indexing geometry before generating G-Code..."))
  2394. for geo_shape in geometry:
  2395. if self.app.abort_flag:
  2396. # graceful abort requested by the user
  2397. raise grace
  2398. if geo_shape is not None:
  2399. storage.insert(geo_shape)
  2400. current_pt = (0, 0)
  2401. pt, geo = storage.nearest(current_pt)
  2402. try:
  2403. while True:
  2404. storage.remove(geo)
  2405. locations.append((pt, geo))
  2406. current_pt = geo.coords[-1]
  2407. pt, geo = storage.nearest(current_pt)
  2408. except StopIteration:
  2409. pass
  2410. # if there are no locations then go to the next tool
  2411. if not locations:
  2412. return 'fail'
  2413. return locations
  2414. def check_zcut(self, zcut):
  2415. if zcut > 0:
  2416. self.app.inform.emit('[WARNING] %s' %
  2417. _("The Cut Z parameter has positive value. "
  2418. "It is the depth value to drill into material.\n"
  2419. "The Cut Z parameter needs to have a negative value, assuming it is a typo "
  2420. "therefore the app will convert the value to negative. "
  2421. "Check the resulting CNC code (Gcode etc)."))
  2422. return -zcut
  2423. elif zcut == 0:
  2424. self.app.inform.emit('[WARNING] %s.' % _("The Cut Z parameter is zero. There will be no cut, aborting"))
  2425. return 'fail'
  2426. def excellon_tool_gcode_gen(self, tool, points, tools, first_pt, is_first=False, is_last=False, opt_type='T',
  2427. toolchange=False):
  2428. """
  2429. Creates Gcode for this object from an Excellon object
  2430. for the specified tools.
  2431. :return: A tuple made from tool_gcode, another tuple holding the coordinates of the last point
  2432. and the start gcode
  2433. :rtype: tuple
  2434. """
  2435. log.debug("Creating CNC Job from Excellon for tool: %s" % str(tool))
  2436. self.exc_tools = deepcopy(tools)
  2437. t_gcode = ''
  2438. # holds the temporary coordinates of the processed drill point
  2439. locx, locy = first_pt
  2440. temp_locx, temp_locy = first_pt
  2441. # #############################################################################################################
  2442. # #############################################################################################################
  2443. # ################################## DRILLING !!! #########################################################
  2444. # #############################################################################################################
  2445. # #############################################################################################################
  2446. if opt_type == 'M':
  2447. log.debug("Using OR-Tools Metaheuristic Guided Local Search drill path optimization.")
  2448. elif opt_type == 'B':
  2449. log.debug("Using OR-Tools Basic drill path optimization.")
  2450. elif opt_type == 'T':
  2451. log.debug("Using Travelling Salesman drill path optimization.")
  2452. else:
  2453. log.debug("Using no path optimization.")
  2454. tool_dict = tools[tool]['data']
  2455. # check if it has drills
  2456. if not points:
  2457. log.debug("Failed. No drills for tool: %s" % str(tool))
  2458. return 'fail'
  2459. if self.app.abort_flag:
  2460. # graceful abort requested by the user
  2461. raise grace
  2462. # #########################################################################################################
  2463. # #########################################################################################################
  2464. # ############# PARAMETERS used in PREPROCESSORS so they need to be updated ###############################
  2465. # #########################################################################################################
  2466. # #########################################################################################################
  2467. self.tool = str(tool)
  2468. # Preprocessor
  2469. p = self.pp_excellon
  2470. # Z_cut parameter
  2471. if self.machinist_setting == 0:
  2472. self.z_cut = self.check_zcut(zcut=tool_dict["tools_drill_cutz"])
  2473. if self.z_cut == 'fail':
  2474. return 'fail'
  2475. # Depth parameters
  2476. self.z_cut = tool_dict['tools_drill_cutz']
  2477. old_zcut = deepcopy(tool_dict["tools_drill_cutz"]) # multidepth use this
  2478. self.multidepth = tool_dict['tools_drill_multidepth']
  2479. self.z_depthpercut = tool_dict['tools_drill_depthperpass']
  2480. self.z_move = tool_dict['tools_drill_travelz']
  2481. self.f_plunge = tool_dict["tools_drill_f_plunge"] # used directly in the preprocessor Toolchange method
  2482. self.f_retract = tool_dict["tools_drill_f_retract"] # used in the current method
  2483. # Feedrate parameters
  2484. self.z_feedrate = tool_dict['tools_drill_feedrate_z']
  2485. self.feedrate = tool_dict['tools_drill_feedrate_z']
  2486. self.feedrate_rapid = tool_dict['tools_drill_feedrate_rapid']
  2487. # Spindle parameters
  2488. self.spindlespeed = tool_dict['tools_drill_spindlespeed']
  2489. self.dwell = tool_dict['tools_drill_dwell']
  2490. self.dwelltime = tool_dict['tools_drill_dwelltime']
  2491. self.spindledir = tool_dict['tools_drill_spindledir']
  2492. self.tooldia = tools[tool]["tooldia"]
  2493. self.postdata['toolC'] = tools[tool]["tooldia"]
  2494. self.toolchange = toolchange
  2495. # Z_toolchange parameter
  2496. self.z_toolchange = tool_dict['tools_drill_toolchangez']
  2497. # XY_toolchange parameter
  2498. self.xy_toolchange = tool_dict["tools_drill_toolchangexy"]
  2499. try:
  2500. if self.xy_toolchange == '':
  2501. self.xy_toolchange = None
  2502. else:
  2503. # either originally it was a string or not, xy_toolchange will be made string
  2504. self.xy_toolchange = re.sub('[()\[\]]', '', str(self.xy_toolchange)) if self.xy_toolchange else None
  2505. # and now, xy_toolchange is made into a list of floats in format [x, y]
  2506. if self.xy_toolchange:
  2507. self.xy_toolchange = [float(eval(a)) for a in self.xy_toolchange.split(",")]
  2508. if self.xy_toolchange and len(self.xy_toolchange) != 2:
  2509. self.app.inform.emit('[ERROR] %s' % _("The Toolchange X,Y format has to be (x, y)."))
  2510. return 'fail'
  2511. except Exception as e:
  2512. log.debug("camlib.CNCJob.generate_from_excellon_by_tool() xy_toolchange --> %s" % str(e))
  2513. self.xy_toolchange = [0, 0]
  2514. # End position parameters
  2515. self.startz = tool_dict["tools_drill_startz"]
  2516. if self.startz == '':
  2517. self.startz = None
  2518. self.z_end = tool_dict["tools_drill_endz"]
  2519. self.xy_end = tool_dict["tools_drill_endxy"]
  2520. try:
  2521. if self.xy_end == '':
  2522. self.xy_end = None
  2523. else:
  2524. # either originally it was a string or not, xy_end will be made string
  2525. self.xy_end = re.sub('[()\[\]]', '', str(self.xy_end)) if self.xy_end else None
  2526. # and now, xy_end is made into a list of floats in format [x, y]
  2527. if self.xy_end:
  2528. self.xy_end = [float(eval(a)) for a in self.xy_end.split(",")]
  2529. if self.xy_end and len(self.xy_end) != 2:
  2530. self.app.inform.emit('[ERROR]%s' % _("The End X,Y format has to be (x, y)."))
  2531. return 'fail'
  2532. except Exception as e:
  2533. log.debug("camlib.CNCJob.generate_from_excellon_by_tool() xy_end --> %s" % str(e))
  2534. self.xy_end = [0, 0]
  2535. # Probe parameters
  2536. self.z_pdepth = tool_dict["tools_drill_z_pdepth"]
  2537. self.feedrate_probe = tool_dict["tools_drill_feedrate_probe"]
  2538. # #########################################################################################################
  2539. # #########################################################################################################
  2540. # #########################################################################################################
  2541. # ############ Create the data. ###########################################################################
  2542. # #########################################################################################################
  2543. locations = []
  2544. optimized_path = []
  2545. if opt_type == 'M':
  2546. locations = self.create_tool_data_array(points=points)
  2547. # if there are no locations then go to the next tool
  2548. if not locations:
  2549. return 'fail'
  2550. opt_time = self.app.defaults["excellon_search_time"]
  2551. optimized_path = self.optimized_ortools_meta(locations=locations, opt_time=opt_time)
  2552. elif opt_type == 'B':
  2553. locations = self.create_tool_data_array(points=points)
  2554. # if there are no locations then go to the next tool
  2555. if not locations:
  2556. return 'fail'
  2557. optimized_path = self.optimized_ortools_basic(locations=locations)
  2558. elif opt_type == 'T':
  2559. locations = self.create_tool_data_array(points=points)
  2560. # if there are no locations then go to the next tool
  2561. if not locations:
  2562. return 'fail'
  2563. optimized_path = self.optimized_travelling_salesman(locations)
  2564. else:
  2565. # it's actually not optimized path but here we build a list of (x,y) coordinates
  2566. # out of the tool's drills
  2567. for drill in tools[tool]['drills']:
  2568. unoptimized_coords = (
  2569. drill.x,
  2570. drill.y
  2571. )
  2572. optimized_path.append(unoptimized_coords)
  2573. # #########################################################################################################
  2574. # #########################################################################################################
  2575. # Only if there are locations to drill
  2576. if not optimized_path:
  2577. log.debug("CNCJob.excellon_tool_gcode_gen() -> Optimized path is empty.")
  2578. return 'fail'
  2579. if self.app.abort_flag:
  2580. # graceful abort requested by the user
  2581. raise grace
  2582. start_gcode = ''
  2583. if is_first:
  2584. start_gcode = self.doformat(p.start_code)
  2585. t_gcode += start_gcode
  2586. # do the ToolChange event
  2587. t_gcode += self.doformat(p.z_feedrate_code)
  2588. t_gcode += self.doformat(p.toolchange_code, toolchangexy=(temp_locx, temp_locy))
  2589. t_gcode += self.doformat(p.z_feedrate_code)
  2590. # Spindle start
  2591. t_gcode += self.doformat(p.spindle_code)
  2592. # Dwell time
  2593. if self.dwell is True:
  2594. t_gcode += self.doformat(p.dwell_code)
  2595. current_tooldia = float('%.*f' % (self.decimals, float(tools[tool]["tooldia"])))
  2596. self.app.inform.emit(
  2597. '%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  2598. str(current_tooldia),
  2599. str(self.units))
  2600. )
  2601. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  2602. # APPLY Offset only when using the appGUI, for TclCommand this will create an error
  2603. # because the values for Z offset are created in build_tool_ui()
  2604. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  2605. try:
  2606. z_offset = float(tool_dict['tools_drill_offset']) * (-1)
  2607. except KeyError:
  2608. z_offset = 0
  2609. self.z_cut = z_offset + old_zcut
  2610. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  2611. if self.coordinates_type == "G90":
  2612. # Drillling! for Absolute coordinates type G90
  2613. # variables to display the percentage of work done
  2614. geo_len = len(optimized_path)
  2615. old_disp_number = 0
  2616. log.warning("Number of drills for which to generate GCode: %s" % str(geo_len))
  2617. loc_nr = 0
  2618. for point in optimized_path:
  2619. if self.app.abort_flag:
  2620. # graceful abort requested by the user
  2621. raise grace
  2622. if opt_type == 'T':
  2623. locx = point[0]
  2624. locy = point[1]
  2625. else:
  2626. locx = locations[point][0]
  2627. locy = locations[point][1]
  2628. travels = self.app.exc_areas.travel_coordinates(start_point=(temp_locx, temp_locy),
  2629. end_point=(locx, locy),
  2630. tooldia=current_tooldia)
  2631. prev_z = None
  2632. for travel in travels:
  2633. locx = travel[1][0]
  2634. locy = travel[1][1]
  2635. if travel[0] is not None:
  2636. # move to next point
  2637. t_gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  2638. # raise to safe Z (travel[0]) each time because safe Z may be different
  2639. self.z_move = travel[0]
  2640. t_gcode += self.doformat(p.lift_code, x=locx, y=locy)
  2641. # restore z_move
  2642. self.z_move = tool_dict['tools_drill_travelz']
  2643. else:
  2644. if prev_z is not None:
  2645. # move to next point
  2646. t_gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  2647. # we assume that previously the z_move was altered therefore raise to
  2648. # the travel_z (z_move)
  2649. self.z_move = tool_dict['tools_drill_travelz']
  2650. t_gcode += self.doformat(p.lift_code, x=locx, y=locy)
  2651. else:
  2652. # move to next point
  2653. t_gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  2654. # store prev_z
  2655. prev_z = travel[0]
  2656. # t_gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  2657. if self.multidepth and abs(self.z_cut) > abs(self.z_depthpercut):
  2658. doc = deepcopy(self.z_cut)
  2659. self.z_cut = 0.0
  2660. while abs(self.z_cut) < abs(doc):
  2661. self.z_cut -= self.z_depthpercut
  2662. if abs(doc) < abs(self.z_cut) < (abs(doc) + self.z_depthpercut):
  2663. self.z_cut = doc
  2664. # Move down the drill bit
  2665. t_gcode += self.doformat(p.down_code, x=locx, y=locy)
  2666. # Update the distance travelled down with the current one
  2667. self.measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  2668. if self.f_retract is False:
  2669. t_gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  2670. self.measured_up_to_zero_distance += abs(self.z_cut)
  2671. self.measured_lift_distance += abs(self.z_move)
  2672. else:
  2673. self.measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  2674. t_gcode += self.doformat(p.lift_code, x=locx, y=locy)
  2675. else:
  2676. t_gcode += self.doformat(p.down_code, x=locx, y=locy)
  2677. self.measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  2678. if self.f_retract is False:
  2679. t_gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  2680. self.measured_up_to_zero_distance += abs(self.z_cut)
  2681. self.measured_lift_distance += abs(self.z_move)
  2682. else:
  2683. self.measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  2684. t_gcode += self.doformat(p.lift_code, x=locx, y=locy)
  2685. self.measured_distance += abs(distance_euclidian(locx, locy, temp_locx, temp_locy))
  2686. temp_locx = locx
  2687. temp_locy = locy
  2688. self.oldx = locx
  2689. self.oldy = locy
  2690. loc_nr += 1
  2691. disp_number = int(np.interp(loc_nr, [0, geo_len], [0, 100]))
  2692. if old_disp_number < disp_number <= 100:
  2693. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  2694. old_disp_number = disp_number
  2695. else:
  2696. self.app.inform.emit('[ERROR_NOTCL] %s...' % _('G91 coordinates not implemented'))
  2697. return 'fail'
  2698. self.z_cut = deepcopy(old_zcut)
  2699. if is_last:
  2700. t_gcode += self.doformat(p.spindle_stop_code)
  2701. # Move to End position
  2702. t_gcode += self.doformat(p.end_code, x=0, y=0)
  2703. self.app.inform.emit(_("Finished G-Code generation for tool: %s" % str(tool)))
  2704. return t_gcode, (locx, locy), start_gcode
  2705. def generate_from_excellon_by_tool(self, exobj, tools="all", order='fwd', use_ui=False):
  2706. """
  2707. Creates Gcode for this object from an Excellon object
  2708. for the specified tools.
  2709. :param exobj: Excellon object to process
  2710. :type exobj: Excellon
  2711. :param tools: Comma separated tool names
  2712. :type tools: str
  2713. :param order: order of tools processing: "fwd", "rev" or "no"
  2714. :type order: str
  2715. :param use_ui: if True the method will use parameters set in UI
  2716. :type use_ui: bool
  2717. :return: None
  2718. :rtype: None
  2719. """
  2720. # #############################################################################################################
  2721. # #############################################################################################################
  2722. # create a local copy of the exobj.tools so it can be used for creating drill CCode geometry
  2723. # #############################################################################################################
  2724. # #############################################################################################################
  2725. self.exc_tools = deepcopy(exobj.tools)
  2726. # the Excellon GCode preprocessor will use this info in the start_code() method
  2727. self.use_ui = True if use_ui else False
  2728. # Z_cut parameter
  2729. if self.machinist_setting == 0:
  2730. self.z_cut = self.check_zcut(zcut=self.z_cut)
  2731. if self.z_cut == 'fail':
  2732. return 'fail'
  2733. # multidepth use this
  2734. old_zcut = deepcopy(self.z_cut)
  2735. # XY_toolchange parameter
  2736. try:
  2737. if self.xy_toolchange == '':
  2738. self.xy_toolchange = None
  2739. else:
  2740. self.xy_toolchange = re.sub('[()\[\]]', '', str(self.xy_toolchange)) if self.xy_toolchange else None
  2741. if self.xy_toolchange:
  2742. self.xy_toolchange = [float(eval(a)) for a in self.xy_toolchange.split(",")]
  2743. if self.xy_toolchange and len(self.xy_toolchange) != 2:
  2744. self.app.inform.emit('[ERROR]%s' %
  2745. _("The Toolchange X,Y field in Edit -> Preferences has to be "
  2746. "in the format (x, y) \nbut now there is only one value, not two. "))
  2747. return 'fail'
  2748. except Exception as e:
  2749. log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> %s" % str(e))
  2750. pass
  2751. # XY_end parameter
  2752. self.xy_end = re.sub('[()\[\]]', '', str(self.xy_end)) if self.xy_end else None
  2753. if self.xy_end and self.xy_end != '':
  2754. self.xy_end = [float(eval(a)) for a in self.xy_end.split(",")]
  2755. if self.xy_end and len(self.xy_end) < 2:
  2756. self.app.inform.emit('[ERROR] %s' % _("The End Move X,Y field in Edit -> Preferences has to be "
  2757. "in the format (x, y) but now there is only one value, not two."))
  2758. return 'fail'
  2759. # Prepprocessor
  2760. self.pp_excellon = self.app.preprocessors[self.pp_excellon_name]
  2761. p = self.pp_excellon
  2762. log.debug("Creating CNC Job from Excellon...")
  2763. # #############################################################################################################
  2764. # #############################################################################################################
  2765. # TOOLS
  2766. # sort the tools list by the second item in tuple (here we have a dict with diameter of the tool)
  2767. # so we actually are sorting the tools by diameter
  2768. # #############################################################################################################
  2769. # #############################################################################################################
  2770. all_tools = []
  2771. for tool_as_key, v in list(self.exc_tools.items()):
  2772. all_tools.append((int(tool_as_key), float(v['tooldia'])))
  2773. if order == 'fwd':
  2774. sorted_tools = sorted(all_tools, key=lambda t1: t1[1])
  2775. elif order == 'rev':
  2776. sorted_tools = sorted(all_tools, key=lambda t1: t1[1], reverse=True)
  2777. else:
  2778. sorted_tools = all_tools
  2779. if tools == "all":
  2780. selected_tools = [i[0] for i in all_tools] # we get a array of ordered tools
  2781. else:
  2782. selected_tools = eval(tools)
  2783. # Create a sorted list of selected tools from the sorted_tools list
  2784. tools = [i for i, j in sorted_tools for k in selected_tools if i == k]
  2785. log.debug("Tools sorted are: %s" % str(tools))
  2786. # #############################################################################################################
  2787. # #############################################################################################################
  2788. # build a self.options['Tools_in_use'] list from scratch if we don't have one like in the case of
  2789. # running this method from a Tcl Command
  2790. # #############################################################################################################
  2791. # #############################################################################################################
  2792. build_tools_in_use_list = False
  2793. if 'Tools_in_use' not in self.options:
  2794. self.options['Tools_in_use'] = []
  2795. # if the list is empty (either we just added the key or it was already there but empty) signal to build it
  2796. if not self.options['Tools_in_use']:
  2797. build_tools_in_use_list = True
  2798. # #############################################################################################################
  2799. # #############################################################################################################
  2800. # fill the data into the self.exc_cnc_tools dictionary
  2801. # #############################################################################################################
  2802. # #############################################################################################################
  2803. for it in all_tools:
  2804. for to_ol in tools:
  2805. if to_ol == it[0]:
  2806. sol_geo = []
  2807. drill_no = 0
  2808. if 'drills' in exobj.tools[to_ol]:
  2809. drill_no = len(exobj.tools[to_ol]['drills'])
  2810. for drill in exobj.tools[to_ol]['drills']:
  2811. sol_geo.append(drill.buffer((it[1] / 2.0), resolution=self.geo_steps_per_circle))
  2812. slot_no = 0
  2813. if 'slots' in exobj.tools[to_ol]:
  2814. slot_no = len(exobj.tools[to_ol]['slots'])
  2815. for slot in exobj.tools[to_ol]['slots']:
  2816. start = (slot[0].x, slot[0].y)
  2817. stop = (slot[1].x, slot[1].y)
  2818. sol_geo.append(
  2819. LineString([start, stop]).buffer((it[1] / 2.0), resolution=self.geo_steps_per_circle)
  2820. )
  2821. if self.use_ui:
  2822. try:
  2823. z_off = float(exobj.tools[it[0]]['data']['tools_drill_offset']) * (-1)
  2824. except KeyError:
  2825. z_off = 0
  2826. else:
  2827. z_off = 0
  2828. default_data = {}
  2829. for k, v in list(self.options.items()):
  2830. default_data[k] = deepcopy(v)
  2831. self.exc_cnc_tools[it[1]] = {}
  2832. self.exc_cnc_tools[it[1]]['tool'] = it[0]
  2833. self.exc_cnc_tools[it[1]]['nr_drills'] = drill_no
  2834. self.exc_cnc_tools[it[1]]['nr_slots'] = slot_no
  2835. self.exc_cnc_tools[it[1]]['offset_z'] = z_off
  2836. self.exc_cnc_tools[it[1]]['data'] = default_data
  2837. self.exc_cnc_tools[it[1]]['solid_geometry'] = deepcopy(sol_geo)
  2838. # build a self.options['Tools_in_use'] list from scratch if we don't have one like in the case of
  2839. # running this method from a Tcl Command
  2840. if build_tools_in_use_list is True:
  2841. self.options['Tools_in_use'].append(
  2842. [it[0], it[1], drill_no, slot_no]
  2843. )
  2844. self.app.inform.emit(_("Creating a list of points to drill..."))
  2845. # #############################################################################################################
  2846. # #############################################################################################################
  2847. # Points (Group by tool): a dictionary of shapely Point geo elements grouped by tool number
  2848. # #############################################################################################################
  2849. # #############################################################################################################
  2850. points = {}
  2851. for tool, tool_dict in self.exc_tools.items():
  2852. if tool in tools:
  2853. if self.app.abort_flag:
  2854. # graceful abort requested by the user
  2855. raise grace
  2856. if 'drills' in tool_dict and tool_dict['drills']:
  2857. for drill_pt in tool_dict['drills']:
  2858. try:
  2859. points[tool].append(drill_pt)
  2860. except KeyError:
  2861. points[tool] = [drill_pt]
  2862. log.debug("Found %d TOOLS with drills." % len(points))
  2863. # check if there are drill points in the exclusion areas.
  2864. # If we find any within the exclusion areas return 'fail'
  2865. for tool in points:
  2866. for pt in points[tool]:
  2867. for area in self.app.exc_areas.exclusion_areas_storage:
  2868. pt_buf = pt.buffer(self.exc_tools[tool]['tooldia'] / 2.0)
  2869. if pt_buf.within(area['shape']) or pt_buf.intersects(area['shape']):
  2870. self.app.inform.emit("[ERROR_NOTCL] %s" % _("Failed. Drill points inside the exclusion zones."))
  2871. return 'fail'
  2872. # this holds the resulting GCode
  2873. self.gcode = []
  2874. # #############################################################################################################
  2875. # #############################################################################################################
  2876. # Initialization
  2877. # #############################################################################################################
  2878. # #############################################################################################################
  2879. gcode = self.doformat(p.start_code)
  2880. if use_ui is False:
  2881. gcode += self.doformat(p.z_feedrate_code)
  2882. if self.toolchange is False:
  2883. if self.xy_toolchange is not None:
  2884. gcode += self.doformat(p.lift_code, x=self.xy_toolchange[0], y=self.xy_toolchange[1])
  2885. gcode += self.doformat(p.startz_code, x=self.xy_toolchange[0], y=self.xy_toolchange[1])
  2886. else:
  2887. gcode += self.doformat(p.lift_code, x=0.0, y=0.0)
  2888. gcode += self.doformat(p.startz_code, x=0.0, y=0.0)
  2889. if self.xy_toolchange is not None:
  2890. self.oldx = self.xy_toolchange[0]
  2891. self.oldy = self.xy_toolchange[1]
  2892. else:
  2893. self.oldx = 0.0
  2894. self.oldy = 0.0
  2895. measured_distance = 0.0
  2896. measured_down_distance = 0.0
  2897. measured_up_to_zero_distance = 0.0
  2898. measured_lift_distance = 0.0
  2899. # #############################################################################################################
  2900. # #############################################################################################################
  2901. # GCODE creation
  2902. # #############################################################################################################
  2903. # #############################################################################################################
  2904. self.app.inform.emit('%s...' % _("Starting G-Code"))
  2905. has_drills = None
  2906. for tool, tool_dict in self.exc_tools.items():
  2907. if 'drills' in tool_dict and tool_dict['drills']:
  2908. has_drills = True
  2909. break
  2910. if not has_drills:
  2911. log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> "
  2912. "The loaded Excellon file has no drills ...")
  2913. self.app.inform.emit('[ERROR_NOTCL] %s...' % _('The loaded Excellon file has no drills'))
  2914. return 'fail'
  2915. current_platform = platform.architecture()[0]
  2916. if current_platform == '64bit':
  2917. used_excellon_optimization_type = self.excellon_optimization_type
  2918. else:
  2919. used_excellon_optimization_type = 'T'
  2920. # #############################################################################################################
  2921. # #############################################################################################################
  2922. # ################################## DRILLING !!! #########################################################
  2923. # #############################################################################################################
  2924. # #############################################################################################################
  2925. if used_excellon_optimization_type == 'M':
  2926. log.debug("Using OR-Tools Metaheuristic Guided Local Search drill path optimization.")
  2927. elif used_excellon_optimization_type == 'B':
  2928. log.debug("Using OR-Tools Basic drill path optimization.")
  2929. elif used_excellon_optimization_type == 'T':
  2930. log.debug("Using Travelling Salesman drill path optimization.")
  2931. else:
  2932. log.debug("Using no path optimization.")
  2933. if self.toolchange is True:
  2934. for tool in tools:
  2935. # check if it has drills
  2936. if not self.exc_tools[tool]['drills']:
  2937. continue
  2938. if self.app.abort_flag:
  2939. # graceful abort requested by the user
  2940. raise grace
  2941. self.tool = tool
  2942. self.tooldia = self.exc_tools[tool]["tooldia"]
  2943. self.postdata['toolC'] = self.tooldia
  2944. if self.use_ui:
  2945. self.z_feedrate = self.exc_tools[tool]['data']['tools_drill_feedrate_z']
  2946. self.feedrate = self.exc_tools[tool]['data']['tools_drill_feedrate_z']
  2947. self.z_cut = self.exc_tools[tool]['data']['tools_drill_cutz']
  2948. gcode += self.doformat(p.z_feedrate_code)
  2949. if self.machinist_setting == 0:
  2950. if self.z_cut > 0:
  2951. self.app.inform.emit('[WARNING] %s' %
  2952. _("The Cut Z parameter has positive value. "
  2953. "It is the depth value to drill into material.\n"
  2954. "The Cut Z parameter needs to have a negative value, "
  2955. "assuming it is a typo "
  2956. "therefore the app will convert the value to negative. "
  2957. "Check the resulting CNC code (Gcode etc)."))
  2958. self.z_cut = -self.z_cut
  2959. elif self.z_cut == 0:
  2960. self.app.inform.emit('[WARNING] %s: %s' %
  2961. (_(
  2962. "The Cut Z parameter is zero. There will be no cut, "
  2963. "skipping file"),
  2964. exobj.options['name']))
  2965. return 'fail'
  2966. old_zcut = deepcopy(self.z_cut)
  2967. self.z_move = self.exc_tools[tool]['data']['tools_drill_travelz']
  2968. self.spindlespeed = self.exc_tools[tool]['data']['tools_drill_spindlespeed']
  2969. self.dwell = self.exc_tools[tool]['data']['tools_drill_dwell']
  2970. self.dwelltime = self.exc_tools[tool]['data']['tools_drill_dwelltime']
  2971. self.multidepth = self.exc_tools[tool]['data']['tools_drill_multidepth']
  2972. self.z_depthpercut = self.exc_tools[tool]['data']['tools_drill_depthperpass']
  2973. else:
  2974. old_zcut = deepcopy(self.z_cut)
  2975. # #########################################################################################################
  2976. # ############ Create the data. #################
  2977. # #########################################################################################################
  2978. locations = []
  2979. altPoints = []
  2980. optimized_path = []
  2981. if used_excellon_optimization_type == 'M':
  2982. if tool in points:
  2983. locations = self.create_tool_data_array(points=points[tool])
  2984. # if there are no locations then go to the next tool
  2985. if not locations:
  2986. continue
  2987. opt_time = self.app.defaults["excellon_search_time"]
  2988. optimized_path = self.optimized_ortools_meta(locations=locations, opt_time=opt_time)
  2989. elif used_excellon_optimization_type == 'B':
  2990. if tool in points:
  2991. locations = self.create_tool_data_array(points=points[tool])
  2992. # if there are no locations then go to the next tool
  2993. if not locations:
  2994. continue
  2995. optimized_path = self.optimized_ortools_basic(locations=locations)
  2996. elif used_excellon_optimization_type == 'T':
  2997. for point in points[tool]:
  2998. altPoints.append((point.coords.xy[0][0], point.coords.xy[1][0]))
  2999. optimized_path = self.optimized_travelling_salesman(altPoints)
  3000. else:
  3001. # it's actually not optimized path but here we build a list of (x,y) coordinates
  3002. # out of the tool's drills
  3003. for drill in self.exc_tools[tool]['drills']:
  3004. unoptimized_coords = (
  3005. drill.x,
  3006. drill.y
  3007. )
  3008. optimized_path.append(unoptimized_coords)
  3009. # #########################################################################################################
  3010. # #########################################################################################################
  3011. # Only if there are locations to drill
  3012. if not optimized_path:
  3013. continue
  3014. if self.app.abort_flag:
  3015. # graceful abort requested by the user
  3016. raise grace
  3017. # Tool change sequence (optional)
  3018. if self.toolchange:
  3019. gcode += self.doformat(p.toolchange_code, toolchangexy=(self.oldx, self.oldy))
  3020. # Spindle start
  3021. gcode += self.doformat(p.spindle_code)
  3022. # Dwell time
  3023. if self.dwell is True:
  3024. gcode += self.doformat(p.dwell_code)
  3025. current_tooldia = float('%.*f' % (self.decimals, float(self.exc_tools[tool]["tooldia"])))
  3026. self.app.inform.emit(
  3027. '%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  3028. str(current_tooldia),
  3029. str(self.units))
  3030. )
  3031. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  3032. # APPLY Offset only when using the appGUI, for TclCommand this will create an error
  3033. # because the values for Z offset are created in build_ui()
  3034. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  3035. try:
  3036. z_offset = float(self.exc_tools[tool]['data']['tools_drill_offset']) * (-1)
  3037. except KeyError:
  3038. z_offset = 0
  3039. self.z_cut = z_offset + old_zcut
  3040. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  3041. if self.coordinates_type == "G90":
  3042. # Drillling! for Absolute coordinates type G90
  3043. # variables to display the percentage of work done
  3044. geo_len = len(optimized_path)
  3045. old_disp_number = 0
  3046. log.warning("Number of drills for which to generate GCode: %s" % str(geo_len))
  3047. loc_nr = 0
  3048. for point in optimized_path:
  3049. if self.app.abort_flag:
  3050. # graceful abort requested by the user
  3051. raise grace
  3052. if used_excellon_optimization_type == 'T':
  3053. locx = point[0]
  3054. locy = point[1]
  3055. else:
  3056. locx = locations[point][0]
  3057. locy = locations[point][1]
  3058. travels = self.app.exc_areas.travel_coordinates(start_point=(self.oldx, self.oldy),
  3059. end_point=(locx, locy),
  3060. tooldia=current_tooldia)
  3061. prev_z = None
  3062. for travel in travels:
  3063. locx = travel[1][0]
  3064. locy = travel[1][1]
  3065. if travel[0] is not None:
  3066. # move to next point
  3067. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3068. # raise to safe Z (travel[0]) each time because safe Z may be different
  3069. self.z_move = travel[0]
  3070. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3071. # restore z_move
  3072. self.z_move = self.exc_tools[tool]['data']['tools_drill_travelz']
  3073. else:
  3074. if prev_z is not None:
  3075. # move to next point
  3076. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3077. # we assume that previously the z_move was altered therefore raise to
  3078. # the travel_z (z_move)
  3079. self.z_move = self.exc_tools[tool]['data']['tools_drill_travelz']
  3080. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3081. else:
  3082. # move to next point
  3083. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3084. # store prev_z
  3085. prev_z = travel[0]
  3086. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3087. if self.multidepth and abs(self.z_cut) > abs(self.z_depthpercut):
  3088. doc = deepcopy(self.z_cut)
  3089. self.z_cut = 0.0
  3090. while abs(self.z_cut) < abs(doc):
  3091. self.z_cut -= self.z_depthpercut
  3092. if abs(doc) < abs(self.z_cut) < (abs(doc) + self.z_depthpercut):
  3093. self.z_cut = doc
  3094. gcode += self.doformat(p.down_code, x=locx, y=locy)
  3095. measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  3096. if self.f_retract is False:
  3097. gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  3098. measured_up_to_zero_distance += abs(self.z_cut)
  3099. measured_lift_distance += abs(self.z_move)
  3100. else:
  3101. measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  3102. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3103. else:
  3104. gcode += self.doformat(p.down_code, x=locx, y=locy)
  3105. measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  3106. if self.f_retract is False:
  3107. gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  3108. measured_up_to_zero_distance += abs(self.z_cut)
  3109. measured_lift_distance += abs(self.z_move)
  3110. else:
  3111. measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  3112. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3113. measured_distance += abs(distance_euclidian(locx, locy, self.oldx, self.oldy))
  3114. self.oldx = locx
  3115. self.oldy = locy
  3116. loc_nr += 1
  3117. disp_number = int(np.interp(loc_nr, [0, geo_len], [0, 100]))
  3118. if old_disp_number < disp_number <= 100:
  3119. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  3120. old_disp_number = disp_number
  3121. else:
  3122. self.app.inform.emit('[ERROR_NOTCL] %s...' % _('G91 coordinates not implemented'))
  3123. return 'fail'
  3124. self.z_cut = deepcopy(old_zcut)
  3125. else:
  3126. # We are not using Toolchange therefore we need to decide which tool properties to use
  3127. one_tool = 1
  3128. all_points = []
  3129. for tool in points:
  3130. # check if it has drills
  3131. if not points[tool]:
  3132. continue
  3133. all_points += points[tool]
  3134. if self.app.abort_flag:
  3135. # graceful abort requested by the user
  3136. raise grace
  3137. self.tool = one_tool
  3138. self.tooldia = self.exc_tools[one_tool]["tooldia"]
  3139. self.postdata['toolC'] = self.tooldia
  3140. if self.use_ui:
  3141. self.z_feedrate = self.exc_tools[one_tool]['data']['tools_drill_feedrate_z']
  3142. self.feedrate = self.exc_tools[one_tool]['data']['tools_drill_feedrate_z']
  3143. self.z_cut = self.exc_tools[one_tool]['data']['tools_drill_cutz']
  3144. gcode += self.doformat(p.z_feedrate_code)
  3145. if self.machinist_setting == 0:
  3146. if self.z_cut > 0:
  3147. self.app.inform.emit('[WARNING] %s' %
  3148. _("The Cut Z parameter has positive value. "
  3149. "It is the depth value to drill into material.\n"
  3150. "The Cut Z parameter needs to have a negative value, "
  3151. "assuming it is a typo "
  3152. "therefore the app will convert the value to negative. "
  3153. "Check the resulting CNC code (Gcode etc)."))
  3154. self.z_cut = -self.z_cut
  3155. elif self.z_cut == 0:
  3156. self.app.inform.emit('[WARNING] %s: %s' %
  3157. (_(
  3158. "The Cut Z parameter is zero. There will be no cut, "
  3159. "skipping file"),
  3160. exobj.options['name']))
  3161. return 'fail'
  3162. old_zcut = deepcopy(self.z_cut)
  3163. self.z_move = self.exc_tools[one_tool]['data']['tools_drill_travelz']
  3164. self.spindlespeed = self.exc_tools[one_tool]['data']['tools_drill_spindlespeed']
  3165. self.dwell = self.exc_tools[one_tool]['data']['tools_drill_dwell']
  3166. self.dwelltime = self.exc_tools[one_tool]['data']['tools_drill_dwelltime']
  3167. self.multidepth = self.exc_tools[one_tool]['data']['tools_drill_multidepth']
  3168. self.z_depthpercut = self.exc_tools[one_tool]['data']['tools_drill_depthperpass']
  3169. else:
  3170. old_zcut = deepcopy(self.z_cut)
  3171. # #########################################################################################################
  3172. # ############ Create the data. #################
  3173. # #########################################################################################################
  3174. locations = []
  3175. altPoints = []
  3176. optimized_path = []
  3177. if used_excellon_optimization_type == 'M':
  3178. if all_points:
  3179. locations = self.create_tool_data_array(points=all_points)
  3180. # if there are no locations then go to the next tool
  3181. if not locations:
  3182. return 'fail'
  3183. opt_time = self.app.defaults["excellon_search_time"]
  3184. optimized_path = self.optimized_ortools_meta(locations=locations, opt_time=opt_time)
  3185. elif used_excellon_optimization_type == 'B':
  3186. if all_points:
  3187. locations = self.create_tool_data_array(points=all_points)
  3188. # if there are no locations then go to the next tool
  3189. if not locations:
  3190. return 'fail'
  3191. optimized_path = self.optimized_ortools_basic(locations=locations)
  3192. elif used_excellon_optimization_type == 'T':
  3193. for point in all_points:
  3194. altPoints.append((point.coords.xy[0][0], point.coords.xy[1][0]))
  3195. optimized_path = self.optimized_travelling_salesman(altPoints)
  3196. else:
  3197. # it's actually not optimized path but here we build a list of (x,y) coordinates
  3198. # out of the tool's drills
  3199. for pt in all_points:
  3200. unoptimized_coords = (
  3201. pt.x,
  3202. pt.y
  3203. )
  3204. optimized_path.append(unoptimized_coords)
  3205. # #########################################################################################################
  3206. # #########################################################################################################
  3207. # Only if there are locations to drill
  3208. if not optimized_path:
  3209. return 'fail'
  3210. if self.app.abort_flag:
  3211. # graceful abort requested by the user
  3212. raise grace
  3213. # Spindle start
  3214. gcode += self.doformat(p.spindle_code)
  3215. # Dwell time
  3216. if self.dwell is True:
  3217. gcode += self.doformat(p.dwell_code)
  3218. current_tooldia = float('%.*f' % (self.decimals, float(self.exc_tools[one_tool]["tooldia"])))
  3219. self.app.inform.emit(
  3220. '%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  3221. str(current_tooldia),
  3222. str(self.units))
  3223. )
  3224. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  3225. # APPLY Offset only when using the appGUI, for TclCommand this will create an error
  3226. # because the values for Z offset are created in build_ui()
  3227. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  3228. try:
  3229. z_offset = float(self.exc_tools[one_tool]['data']['tools_drill_offset']) * (-1)
  3230. except KeyError:
  3231. z_offset = 0
  3232. self.z_cut = z_offset + old_zcut
  3233. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  3234. if self.coordinates_type == "G90":
  3235. # Drillling! for Absolute coordinates type G90
  3236. # variables to display the percentage of work done
  3237. geo_len = len(optimized_path)
  3238. old_disp_number = 0
  3239. log.warning("Number of drills for which to generate GCode: %s" % str(geo_len))
  3240. loc_nr = 0
  3241. for point in optimized_path:
  3242. if self.app.abort_flag:
  3243. # graceful abort requested by the user
  3244. raise grace
  3245. if used_excellon_optimization_type == 'T':
  3246. locx = point[0]
  3247. locy = point[1]
  3248. else:
  3249. locx = locations[point][0]
  3250. locy = locations[point][1]
  3251. travels = self.app.exc_areas.travel_coordinates(start_point=(self.oldx, self.oldy),
  3252. end_point=(locx, locy),
  3253. tooldia=current_tooldia)
  3254. prev_z = None
  3255. for travel in travels:
  3256. locx = travel[1][0]
  3257. locy = travel[1][1]
  3258. if travel[0] is not None:
  3259. # move to next point
  3260. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3261. # raise to safe Z (travel[0]) each time because safe Z may be different
  3262. self.z_move = travel[0]
  3263. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3264. # restore z_move
  3265. self.z_move = self.exc_tools[one_tool]['data']['tools_drill_travelz']
  3266. else:
  3267. if prev_z is not None:
  3268. # move to next point
  3269. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3270. # we assume that previously the z_move was altered therefore raise to
  3271. # the travel_z (z_move)
  3272. self.z_move = self.exc_tools[one_tool]['data']['tools_drill_travelz']
  3273. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3274. else:
  3275. # move to next point
  3276. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3277. # store prev_z
  3278. prev_z = travel[0]
  3279. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3280. if self.multidepth and abs(self.z_cut) > abs(self.z_depthpercut):
  3281. doc = deepcopy(self.z_cut)
  3282. self.z_cut = 0.0
  3283. while abs(self.z_cut) < abs(doc):
  3284. self.z_cut -= self.z_depthpercut
  3285. if abs(doc) < abs(self.z_cut) < (abs(doc) + self.z_depthpercut):
  3286. self.z_cut = doc
  3287. gcode += self.doformat(p.down_code, x=locx, y=locy)
  3288. measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  3289. if self.f_retract is False:
  3290. gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  3291. measured_up_to_zero_distance += abs(self.z_cut)
  3292. measured_lift_distance += abs(self.z_move)
  3293. else:
  3294. measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  3295. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3296. else:
  3297. gcode += self.doformat(p.down_code, x=locx, y=locy)
  3298. measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  3299. if self.f_retract is False:
  3300. gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  3301. measured_up_to_zero_distance += abs(self.z_cut)
  3302. measured_lift_distance += abs(self.z_move)
  3303. else:
  3304. measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  3305. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3306. measured_distance += abs(distance_euclidian(locx, locy, self.oldx, self.oldy))
  3307. self.oldx = locx
  3308. self.oldy = locy
  3309. loc_nr += 1
  3310. disp_number = int(np.interp(loc_nr, [0, geo_len], [0, 100]))
  3311. if old_disp_number < disp_number <= 100:
  3312. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  3313. old_disp_number = disp_number
  3314. else:
  3315. self.app.inform.emit('[ERROR_NOTCL] %s...' % _('G91 coordinates not implemented'))
  3316. return 'fail'
  3317. self.z_cut = deepcopy(old_zcut)
  3318. if used_excellon_optimization_type == 'M':
  3319. log.debug("The total travel distance with OR-TOOLS Metaheuristics is: %s" % str(measured_distance))
  3320. elif used_excellon_optimization_type == 'B':
  3321. log.debug("The total travel distance with OR-TOOLS Basic Algorithm is: %s" % str(measured_distance))
  3322. elif used_excellon_optimization_type == 'T':
  3323. log.debug("The total travel distance with Travelling Salesman Algorithm is: %s" % str(measured_distance))
  3324. else:
  3325. log.debug("The total travel distance with with no optimization is: %s" % str(measured_distance))
  3326. # if used_excellon_optimization_type == 'M':
  3327. # log.debug("Using OR-Tools Metaheuristic Guided Local Search drill path optimization.")
  3328. #
  3329. # if has_drills:
  3330. # for tool in tools:
  3331. # if self.app.abort_flag:
  3332. # # graceful abort requested by the user
  3333. # raise grace
  3334. #
  3335. # self.tool = tool
  3336. # self.tooldia = self.exc_tools[tool]["tooldia"]
  3337. # self.postdata['toolC'] = self.tooldia
  3338. #
  3339. # if self.use_ui:
  3340. # self.z_feedrate = self.exc_tools[tool]['data']['feedrate_z']
  3341. # self.feedrate = self.exc_tools[tool]['data']['feedrate']
  3342. # gcode += self.doformat(p.z_feedrate_code)
  3343. # self.z_cut = self.exc_tools[tool]['data']['cutz']
  3344. #
  3345. # if self.machinist_setting == 0:
  3346. # if self.z_cut > 0:
  3347. # self.app.inform.emit('[WARNING] %s' %
  3348. # _("The Cut Z parameter has positive value. "
  3349. # "It is the depth value to drill into material.\n"
  3350. # "The Cut Z parameter needs to have a negative value, "
  3351. # "assuming it is a typo "
  3352. # "therefore the app will convert the value to negative. "
  3353. # "Check the resulting CNC code (Gcode etc)."))
  3354. # self.z_cut = -self.z_cut
  3355. # elif self.z_cut == 0:
  3356. # self.app.inform.emit('[WARNING] %s: %s' %
  3357. # (_(
  3358. # "The Cut Z parameter is zero. There will be no cut, "
  3359. # "skipping file"),
  3360. # exobj.options['name']))
  3361. # return 'fail'
  3362. #
  3363. # old_zcut = deepcopy(self.z_cut)
  3364. #
  3365. # self.z_move = self.exc_tools[tool]['data']['travelz']
  3366. # self.spindlespeed = self.exc_tools[tool]['data']['spindlespeed']
  3367. # self.dwell = self.exc_tools[tool]['data']['dwell']
  3368. # self.dwelltime = self.exc_tools[tool]['data']['dwelltime']
  3369. # self.multidepth = self.exc_tools[tool]['data']['multidepth']
  3370. # self.z_depthpercut = self.exc_tools[tool]['data']['depthperpass']
  3371. # else:
  3372. # old_zcut = deepcopy(self.z_cut)
  3373. #
  3374. # # ###############################################
  3375. # # ############ Create the data. #################
  3376. # # ###############################################
  3377. # locations = self.create_tool_data_array(tool=tool, points=points)
  3378. # # if there are no locations then go to the next tool
  3379. # if not locations:
  3380. # continue
  3381. # optimized_path = self.optimized_ortools_meta(locations=locations)
  3382. #
  3383. # # Only if tool has points.
  3384. # if tool in points:
  3385. # if self.app.abort_flag:
  3386. # # graceful abort requested by the user
  3387. # raise grace
  3388. #
  3389. # # Tool change sequence (optional)
  3390. # if self.toolchange:
  3391. # gcode += self.doformat(p.toolchange_code, toolchangexy=(self.oldx, self.oldy))
  3392. # # Spindle start
  3393. # gcode += self.doformat(p.spindle_code)
  3394. # # Dwell time
  3395. # if self.dwell is True:
  3396. # gcode += self.doformat(p.dwell_code)
  3397. #
  3398. # current_tooldia = float('%.*f' % (self.decimals, float(self.exc_tools[tool]["tooldia"])))
  3399. #
  3400. # self.app.inform.emit(
  3401. # '%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  3402. # str(current_tooldia),
  3403. # str(self.units))
  3404. # )
  3405. #
  3406. # # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  3407. # # APPLY Offset only when using the appGUI, for TclCommand this will create an error
  3408. # # because the values for Z offset are created in build_ui()
  3409. # # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  3410. # try:
  3411. # z_offset = float(self.exc_tools[tool]['data']['offset']) * (-1)
  3412. # except KeyError:
  3413. # z_offset = 0
  3414. # self.z_cut = z_offset + old_zcut
  3415. #
  3416. # self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  3417. # if self.coordinates_type == "G90":
  3418. # # Drillling! for Absolute coordinates type G90
  3419. # # variables to display the percentage of work done
  3420. # geo_len = len(optimized_path)
  3421. #
  3422. # old_disp_number = 0
  3423. # log.warning("Number of drills for which to generate GCode: %s" % str(geo_len))
  3424. #
  3425. # loc_nr = 0
  3426. # for k in optimized_path:
  3427. # if self.app.abort_flag:
  3428. # # graceful abort requested by the user
  3429. # raise grace
  3430. #
  3431. # locx = locations[k][0]
  3432. # locy = locations[k][1]
  3433. #
  3434. # travels = self.app.exc_areas.travel_coordinates(start_point=(self.oldx, self.oldy),
  3435. # end_point=(locx, locy),
  3436. # tooldia=current_tooldia)
  3437. # prev_z = None
  3438. # for travel in travels:
  3439. # locx = travel[1][0]
  3440. # locy = travel[1][1]
  3441. #
  3442. # if travel[0] is not None:
  3443. # # move to next point
  3444. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3445. #
  3446. # # raise to safe Z (travel[0]) each time because safe Z may be different
  3447. # self.z_move = travel[0]
  3448. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3449. #
  3450. # # restore z_move
  3451. # self.z_move = self.exc_tools[tool]['data']['travelz']
  3452. # else:
  3453. # if prev_z is not None:
  3454. # # move to next point
  3455. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3456. #
  3457. # # we assume that previously the z_move was altered therefore raise to
  3458. # # the travel_z (z_move)
  3459. # self.z_move = self.exc_tools[tool]['data']['travelz']
  3460. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3461. # else:
  3462. # # move to next point
  3463. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3464. #
  3465. # # store prev_z
  3466. # prev_z = travel[0]
  3467. #
  3468. # # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3469. #
  3470. # if self.multidepth and abs(self.z_cut) > abs(self.z_depthpercut):
  3471. # doc = deepcopy(self.z_cut)
  3472. # self.z_cut = 0.0
  3473. #
  3474. # while abs(self.z_cut) < abs(doc):
  3475. #
  3476. # self.z_cut -= self.z_depthpercut
  3477. # if abs(doc) < abs(self.z_cut) < (abs(doc) + self.z_depthpercut):
  3478. # self.z_cut = doc
  3479. # gcode += self.doformat(p.down_code, x=locx, y=locy)
  3480. #
  3481. # measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  3482. #
  3483. # if self.f_retract is False:
  3484. # gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  3485. # measured_up_to_zero_distance += abs(self.z_cut)
  3486. # measured_lift_distance += abs(self.z_move)
  3487. # else:
  3488. # measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  3489. #
  3490. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3491. #
  3492. # else:
  3493. # gcode += self.doformat(p.down_code, x=locx, y=locy)
  3494. #
  3495. # measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  3496. #
  3497. # if self.f_retract is False:
  3498. # gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  3499. # measured_up_to_zero_distance += abs(self.z_cut)
  3500. # measured_lift_distance += abs(self.z_move)
  3501. # else:
  3502. # measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  3503. #
  3504. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3505. #
  3506. # measured_distance += abs(distance_euclidian(locx, locy, self.oldx, self.oldy))
  3507. # self.oldx = locx
  3508. # self.oldy = locy
  3509. #
  3510. # loc_nr += 1
  3511. # disp_number = int(np.interp(loc_nr, [0, geo_len], [0, 100]))
  3512. #
  3513. # if old_disp_number < disp_number <= 100:
  3514. # self.app.proc_container.update_view_text(' %d%%' % disp_number)
  3515. # old_disp_number = disp_number
  3516. #
  3517. # else:
  3518. # self.app.inform.emit('[ERROR_NOTCL] %s...' % _('G91 coordinates not implemented'))
  3519. # return 'fail'
  3520. # self.z_cut = deepcopy(old_zcut)
  3521. # else:
  3522. # log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> "
  3523. # "The loaded Excellon file has no drills ...")
  3524. # self.app.inform.emit('[ERROR_NOTCL] %s...' % _('The loaded Excellon file has no drills'))
  3525. # return 'fail'
  3526. #
  3527. # log.debug("The total travel distance with OR-TOOLS Metaheuristics is: %s" % str(measured_distance))
  3528. #
  3529. # elif used_excellon_optimization_type == 'B':
  3530. # log.debug("Using OR-Tools Basic drill path optimization.")
  3531. #
  3532. # if has_drills:
  3533. # for tool in tools:
  3534. # if self.app.abort_flag:
  3535. # # graceful abort requested by the user
  3536. # raise grace
  3537. #
  3538. # self.tool = tool
  3539. # self.tooldia = self.exc_tools[tool]["tooldia"]
  3540. # self.postdata['toolC'] = self.tooldia
  3541. #
  3542. # if self.use_ui:
  3543. # self.z_feedrate = self.exc_tools[tool]['data']['feedrate_z']
  3544. # self.feedrate = self.exc_tools[tool]['data']['feedrate']
  3545. # gcode += self.doformat(p.z_feedrate_code)
  3546. # self.z_cut = self.exc_tools[tool]['data']['cutz']
  3547. #
  3548. # if self.machinist_setting == 0:
  3549. # if self.z_cut > 0:
  3550. # self.app.inform.emit('[WARNING] %s' %
  3551. # _("The Cut Z parameter has positive value. "
  3552. # "It is the depth value to drill into material.\n"
  3553. # "The Cut Z parameter needs to have a negative value, "
  3554. # "assuming it is a typo "
  3555. # "therefore the app will convert the value to negative. "
  3556. # "Check the resulting CNC code (Gcode etc)."))
  3557. # self.z_cut = -self.z_cut
  3558. # elif self.z_cut == 0:
  3559. # self.app.inform.emit('[WARNING] %s: %s' %
  3560. # (_(
  3561. # "The Cut Z parameter is zero. There will be no cut, "
  3562. # "skipping file"),
  3563. # exobj.options['name']))
  3564. # return 'fail'
  3565. #
  3566. # old_zcut = deepcopy(self.z_cut)
  3567. #
  3568. # self.z_move = self.exc_tools[tool]['data']['travelz']
  3569. #
  3570. # self.spindlespeed = self.exc_tools[tool]['data']['spindlespeed']
  3571. # self.dwell = self.exc_tools[tool]['data']['dwell']
  3572. # self.dwelltime = self.exc_tools[tool]['data']['dwelltime']
  3573. # self.multidepth = self.exc_tools[tool]['data']['multidepth']
  3574. # self.z_depthpercut = self.exc_tools[tool]['data']['depthperpass']
  3575. # else:
  3576. # old_zcut = deepcopy(self.z_cut)
  3577. #
  3578. # # ###############################################
  3579. # # ############ Create the data. #################
  3580. # # ###############################################
  3581. # locations = self.create_tool_data_array(tool=tool, points=points)
  3582. # # if there are no locations then go to the next tool
  3583. # if not locations:
  3584. # continue
  3585. # optimized_path = self.optimized_ortools_basic(locations=locations)
  3586. #
  3587. # # Only if tool has points.
  3588. # if tool in points:
  3589. # if self.app.abort_flag:
  3590. # # graceful abort requested by the user
  3591. # raise grace
  3592. #
  3593. # # Tool change sequence (optional)
  3594. # if self.toolchange:
  3595. # gcode += self.doformat(p.toolchange_code, toolchangexy=(self.oldx, self.oldy))
  3596. # gcode += self.doformat(p.spindle_code) # Spindle start)
  3597. # if self.dwell is True:
  3598. # gcode += self.doformat(p.dwell_code) # Dwell time
  3599. # else:
  3600. # gcode += self.doformat(p.spindle_code)
  3601. # if self.dwell is True:
  3602. # gcode += self.doformat(p.dwell_code) # Dwell time
  3603. #
  3604. # current_tooldia = float('%.*f' % (self.decimals, float(self.exc_tools[tool]["tooldia"])))
  3605. #
  3606. # self.app.inform.emit(
  3607. # '%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  3608. # str(current_tooldia),
  3609. # str(self.units))
  3610. # )
  3611. #
  3612. # # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  3613. # # APPLY Offset only when using the appGUI, for TclCommand this will create an error
  3614. # # because the values for Z offset are created in build_ui()
  3615. # # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  3616. # try:
  3617. # z_offset = float(self.exc_tools[tool]['data']['offset']) * (-1)
  3618. # except KeyError:
  3619. # z_offset = 0
  3620. # self.z_cut = z_offset + old_zcut
  3621. #
  3622. # self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  3623. # if self.coordinates_type == "G90":
  3624. # # Drillling! for Absolute coordinates type G90
  3625. # # variables to display the percentage of work done
  3626. # geo_len = len(optimized_path)
  3627. # old_disp_number = 0
  3628. # log.warning("Number of drills for which to generate GCode: %s" % str(geo_len))
  3629. #
  3630. # loc_nr = 0
  3631. # for k in optimized_path:
  3632. # if self.app.abort_flag:
  3633. # # graceful abort requested by the user
  3634. # raise grace
  3635. #
  3636. # locx = locations[k][0]
  3637. # locy = locations[k][1]
  3638. #
  3639. # travels = self.app.exc_areas.travel_coordinates(start_point=(self.oldx, self.oldy),
  3640. # end_point=(locx, locy),
  3641. # tooldia=current_tooldia)
  3642. # prev_z = None
  3643. # for travel in travels:
  3644. # locx = travel[1][0]
  3645. # locy = travel[1][1]
  3646. #
  3647. # if travel[0] is not None:
  3648. # # move to next point
  3649. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3650. #
  3651. # # raise to safe Z (travel[0]) each time because safe Z may be different
  3652. # self.z_move = travel[0]
  3653. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3654. #
  3655. # # restore z_move
  3656. # self.z_move = self.exc_tools[tool]['data']['travelz']
  3657. # else:
  3658. # if prev_z is not None:
  3659. # # move to next point
  3660. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3661. #
  3662. # # we assume that previously the z_move was altered therefore raise to
  3663. # # the travel_z (z_move)
  3664. # self.z_move = self.exc_tools[tool]['data']['travelz']
  3665. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3666. # else:
  3667. # # move to next point
  3668. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3669. #
  3670. # # store prev_z
  3671. # prev_z = travel[0]
  3672. #
  3673. # # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3674. #
  3675. # if self.multidepth and abs(self.z_cut) > abs(self.z_depthpercut):
  3676. # doc = deepcopy(self.z_cut)
  3677. # self.z_cut = 0.0
  3678. #
  3679. # while abs(self.z_cut) < abs(doc):
  3680. #
  3681. # self.z_cut -= self.z_depthpercut
  3682. # if abs(doc) < abs(self.z_cut) < (abs(doc) + self.z_depthpercut):
  3683. # self.z_cut = doc
  3684. # gcode += self.doformat(p.down_code, x=locx, y=locy)
  3685. #
  3686. # measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  3687. #
  3688. # if self.f_retract is False:
  3689. # gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  3690. # measured_up_to_zero_distance += abs(self.z_cut)
  3691. # measured_lift_distance += abs(self.z_move)
  3692. # else:
  3693. # measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  3694. #
  3695. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3696. #
  3697. # else:
  3698. # gcode += self.doformat(p.down_code, x=locx, y=locy)
  3699. #
  3700. # measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  3701. #
  3702. # if self.f_retract is False:
  3703. # gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  3704. # measured_up_to_zero_distance += abs(self.z_cut)
  3705. # measured_lift_distance += abs(self.z_move)
  3706. # else:
  3707. # measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  3708. #
  3709. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3710. #
  3711. # measured_distance += abs(distance_euclidian(locx, locy, self.oldx, self.oldy))
  3712. # self.oldx = locx
  3713. # self.oldy = locy
  3714. #
  3715. # loc_nr += 1
  3716. # disp_number = int(np.interp(loc_nr, [0, geo_len], [0, 100]))
  3717. #
  3718. # if old_disp_number < disp_number <= 100:
  3719. # self.app.proc_container.update_view_text(' %d%%' % disp_number)
  3720. # old_disp_number = disp_number
  3721. #
  3722. # else:
  3723. # self.app.inform.emit('[ERROR_NOTCL] %s...' % _('G91 coordinates not implemented'))
  3724. # return 'fail'
  3725. # self.z_cut = deepcopy(old_zcut)
  3726. # else:
  3727. # log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> "
  3728. # "The loaded Excellon file has no drills ...")
  3729. # self.app.inform.emit('[ERROR_NOTCL] %s...' % _('The loaded Excellon file has no drills'))
  3730. # return 'fail'
  3731. #
  3732. # log.debug("The total travel distance with OR-TOOLS Basic Algorithm is: %s" % str(measured_distance))
  3733. #
  3734. # elif used_excellon_optimization_type == 'T':
  3735. # log.debug("Using Travelling Salesman drill path optimization.")
  3736. #
  3737. # for tool in tools:
  3738. # if self.app.abort_flag:
  3739. # # graceful abort requested by the user
  3740. # raise grace
  3741. #
  3742. # if has_drills:
  3743. # self.tool = tool
  3744. # self.tooldia = self.exc_tools[tool]["tooldia"]
  3745. # self.postdata['toolC'] = self.tooldia
  3746. #
  3747. # if self.use_ui:
  3748. # self.z_feedrate = self.exc_tools[tool]['data']['feedrate_z']
  3749. # self.feedrate = self.exc_tools[tool]['data']['feedrate']
  3750. # gcode += self.doformat(p.z_feedrate_code)
  3751. #
  3752. # self.z_cut = self.exc_tools[tool]['data']['cutz']
  3753. #
  3754. # if self.machinist_setting == 0:
  3755. # if self.z_cut > 0:
  3756. # self.app.inform.emit('[WARNING] %s' %
  3757. # _("The Cut Z parameter has positive value. "
  3758. # "It is the depth value to drill into material.\n"
  3759. # "The Cut Z parameter needs to have a negative value, "
  3760. # "assuming it is a typo "
  3761. # "therefore the app will convert the value to negative. "
  3762. # "Check the resulting CNC code (Gcode etc)."))
  3763. # self.z_cut = -self.z_cut
  3764. # elif self.z_cut == 0:
  3765. # self.app.inform.emit('[WARNING] %s: %s' %
  3766. # (_(
  3767. # "The Cut Z parameter is zero. There will be no cut, "
  3768. # "skipping file"),
  3769. # exobj.options['name']))
  3770. # return 'fail'
  3771. #
  3772. # old_zcut = deepcopy(self.z_cut)
  3773. #
  3774. # self.z_move = self.exc_tools[tool]['data']['travelz']
  3775. # self.spindlespeed = self.exc_tools[tool]['data']['spindlespeed']
  3776. # self.dwell = self.exc_tools[tool]['data']['dwell']
  3777. # self.dwelltime = self.exc_tools[tool]['data']['dwelltime']
  3778. # self.multidepth = self.exc_tools[tool]['data']['multidepth']
  3779. # self.z_depthpercut = self.exc_tools[tool]['data']['depthperpass']
  3780. # else:
  3781. # old_zcut = deepcopy(self.z_cut)
  3782. #
  3783. # # ###############################################
  3784. # # ############ Create the data. #################
  3785. # # ###############################################
  3786. # altPoints = []
  3787. # for point in points[tool]:
  3788. # altPoints.append((point.coords.xy[0][0], point.coords.xy[1][0]))
  3789. # optimized_path = self.optimized_travelling_salesman(altPoints)
  3790. #
  3791. # # Only if tool has points.
  3792. # if tool in points:
  3793. # if self.app.abort_flag:
  3794. # # graceful abort requested by the user
  3795. # raise grace
  3796. #
  3797. # # Tool change sequence (optional)
  3798. # if self.toolchange:
  3799. # gcode += self.doformat(p.toolchange_code, toolchangexy=(self.oldx, self.oldy))
  3800. # gcode += self.doformat(p.spindle_code) # Spindle start)
  3801. # if self.dwell is True:
  3802. # gcode += self.doformat(p.dwell_code) # Dwell time
  3803. # else:
  3804. # gcode += self.doformat(p.spindle_code)
  3805. # if self.dwell is True:
  3806. # gcode += self.doformat(p.dwell_code) # Dwell time
  3807. #
  3808. # current_tooldia = float('%.*f' % (self.decimals, float(self.exc_tools[tool]["tooldia"])))
  3809. #
  3810. # self.app.inform.emit(
  3811. # '%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  3812. # str(current_tooldia),
  3813. # str(self.units))
  3814. # )
  3815. #
  3816. # # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  3817. # # APPLY Offset only when using the appGUI, for TclCommand this will create an error
  3818. # # because the values for Z offset are created in build_ui()
  3819. # # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  3820. # try:
  3821. # z_offset = float(self.exc_tools[tool]['data']['offset']) * (-1)
  3822. # except KeyError:
  3823. # z_offset = 0
  3824. # self.z_cut = z_offset + old_zcut
  3825. #
  3826. # self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  3827. # if self.coordinates_type == "G90":
  3828. # # Drillling! for Absolute coordinates type G90
  3829. # # variables to display the percentage of work done
  3830. # geo_len = len(optimized_path)
  3831. # old_disp_number = 0
  3832. # log.warning("Number of drills for which to generate GCode: %s" % str(geo_len))
  3833. #
  3834. # loc_nr = 0
  3835. # for point in optimized_path:
  3836. # if self.app.abort_flag:
  3837. # # graceful abort requested by the user
  3838. # raise grace
  3839. #
  3840. # locx = point[0]
  3841. # locy = point[1]
  3842. #
  3843. # travels = self.app.exc_areas.travel_coordinates(start_point=(self.oldx, self.oldy),
  3844. # end_point=(locx, locy),
  3845. # tooldia=current_tooldia)
  3846. # prev_z = None
  3847. # for travel in travels:
  3848. # locx = travel[1][0]
  3849. # locy = travel[1][1]
  3850. #
  3851. # if travel[0] is not None:
  3852. # # move to next point
  3853. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3854. #
  3855. # # raise to safe Z (travel[0]) each time because safe Z may be different
  3856. # self.z_move = travel[0]
  3857. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3858. #
  3859. # # restore z_move
  3860. # self.z_move = self.exc_tools[tool]['data']['travelz']
  3861. # else:
  3862. # if prev_z is not None:
  3863. # # move to next point
  3864. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3865. #
  3866. # # we assume that previously the z_move was altered therefore raise to
  3867. # # the travel_z (z_move)
  3868. # self.z_move = self.exc_tools[tool]['data']['travelz']
  3869. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3870. # else:
  3871. # # move to next point
  3872. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3873. #
  3874. # # store prev_z
  3875. # prev_z = travel[0]
  3876. #
  3877. # # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3878. #
  3879. # if self.multidepth and abs(self.z_cut) > abs(self.z_depthpercut):
  3880. # doc = deepcopy(self.z_cut)
  3881. # self.z_cut = 0.0
  3882. #
  3883. # while abs(self.z_cut) < abs(doc):
  3884. #
  3885. # self.z_cut -= self.z_depthpercut
  3886. # if abs(doc) < abs(self.z_cut) < (abs(doc) + self.z_depthpercut):
  3887. # self.z_cut = doc
  3888. # gcode += self.doformat(p.down_code, x=locx, y=locy)
  3889. #
  3890. # measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  3891. #
  3892. # if self.f_retract is False:
  3893. # gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  3894. # measured_up_to_zero_distance += abs(self.z_cut)
  3895. # measured_lift_distance += abs(self.z_move)
  3896. # else:
  3897. # measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  3898. #
  3899. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3900. #
  3901. # else:
  3902. # gcode += self.doformat(p.down_code, x=locx, y=locy)
  3903. #
  3904. # measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  3905. #
  3906. # if self.f_retract is False:
  3907. # gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  3908. # measured_up_to_zero_distance += abs(self.z_cut)
  3909. # measured_lift_distance += abs(self.z_move)
  3910. # else:
  3911. # measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  3912. #
  3913. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3914. #
  3915. # measured_distance += abs(distance_euclidian(locx, locy, self.oldx, self.oldy))
  3916. # self.oldx = locx
  3917. # self.oldy = locy
  3918. #
  3919. # loc_nr += 1
  3920. # disp_number = int(np.interp(loc_nr, [0, geo_len], [0, 100]))
  3921. #
  3922. # if old_disp_number < disp_number <= 100:
  3923. # self.app.proc_container.update_view_text(' %d%%' % disp_number)
  3924. # old_disp_number = disp_number
  3925. # else:
  3926. # self.app.inform.emit('[ERROR_NOTCL] %s...' % _('G91 coordinates not implemented'))
  3927. # return 'fail'
  3928. # else:
  3929. # log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> "
  3930. # "The loaded Excellon file has no drills ...")
  3931. # self.app.inform.emit('[ERROR_NOTCL] %s...' % _('The loaded Excellon file has no drills'))
  3932. # return 'fail'
  3933. # self.z_cut = deepcopy(old_zcut)
  3934. # log.debug("The total travel distance with Travelling Salesman Algorithm is: %s" % str(measured_distance))
  3935. #
  3936. # else:
  3937. # log.debug("camlib.CNCJob.generate_from_excellon_by_tool(): Chosen drill optimization doesn't exist.")
  3938. # return 'fail'
  3939. # Spindle stop
  3940. gcode += self.doformat(p.spindle_stop_code)
  3941. # Move to End position
  3942. gcode += self.doformat(p.end_code, x=0, y=0)
  3943. # #############################################################################################################
  3944. # ############################# Calculate DISTANCE and ESTIMATED TIME #########################################
  3945. # #############################################################################################################
  3946. measured_distance += abs(distance_euclidian(self.oldx, self.oldy, 0, 0))
  3947. log.debug("The total travel distance including travel to end position is: %s" %
  3948. str(measured_distance) + '\n')
  3949. self.travel_distance = measured_distance
  3950. # I use the value of self.feedrate_rapid for the feadrate in case of the measure_lift_distance and for
  3951. # traveled_time because it is not always possible to determine the feedrate that the CNC machine uses
  3952. # for G0 move (the fastest speed available to the CNC router). Although self.feedrate_rapids is used only with
  3953. # Marlin preprocessor and derivatives.
  3954. self.routing_time = (measured_down_distance + measured_up_to_zero_distance) / self.feedrate
  3955. lift_time = measured_lift_distance / self.feedrate_rapid
  3956. traveled_time = measured_distance / self.feedrate_rapid
  3957. self.routing_time += lift_time + traveled_time
  3958. # #############################################################################################################
  3959. # ############################# Store the GCODE for further usage ############################################
  3960. # #############################################################################################################
  3961. self.gcode = gcode
  3962. self.app.inform.emit(_("Finished G-Code generation..."))
  3963. return 'OK'
  3964. def generate_from_multitool_geometry(self, geometry, append=True, tooldia=None, offset=0.0, tolerance=0, z_cut=1.0,
  3965. z_move=2.0, feedrate=2.0, feedrate_z=2.0, feedrate_rapid=30,
  3966. spindlespeed=None, spindledir='CW', dwell=False, dwelltime=1.0,
  3967. multidepth=False, depthpercut=None, toolchange=False, toolchangez=1.0,
  3968. toolchangexy="0.0, 0.0", extracut=False, extracut_length=0.2,
  3969. startz=None, endz=2.0, endxy='', pp_geometry_name=None, tool_no=1):
  3970. """
  3971. Algorithm to generate from multitool Geometry.
  3972. Algorithm description:
  3973. ----------------------
  3974. Uses RTree to find the nearest path to follow.
  3975. :param geometry:
  3976. :param append:
  3977. :param tooldia:
  3978. :param offset:
  3979. :param tolerance:
  3980. :param z_cut:
  3981. :param z_move:
  3982. :param feedrate:
  3983. :param feedrate_z:
  3984. :param feedrate_rapid:
  3985. :param spindlespeed:
  3986. :param spindledir: Direction of rotation for the spindle. If using GRBL laser mode will
  3987. adjust the laser mode
  3988. :param dwell:
  3989. :param dwelltime:
  3990. :param multidepth: If True, use multiple passes to reach the desired depth.
  3991. :param depthpercut: Maximum depth in each pass.
  3992. :param toolchange:
  3993. :param toolchangez:
  3994. :param toolchangexy:
  3995. :param extracut: Adds (or not) an extra cut at the end of each path overlapping the
  3996. first point in path to ensure complete copper removal
  3997. :param extracut_length: Extra cut legth at the end of the path
  3998. :param startz:
  3999. :param endz:
  4000. :param endxy:
  4001. :param pp_geometry_name:
  4002. :param tool_no:
  4003. :return: GCode - string
  4004. """
  4005. log.debug("Generate_from_multitool_geometry()")
  4006. temp_solid_geometry = []
  4007. if offset != 0.0:
  4008. for it in geometry:
  4009. # if the geometry is a closed shape then create a Polygon out of it
  4010. if isinstance(it, LineString):
  4011. c = it.coords
  4012. if c[0] == c[-1]:
  4013. it = Polygon(it)
  4014. temp_solid_geometry.append(it.buffer(offset, join_style=2))
  4015. else:
  4016. temp_solid_geometry = geometry
  4017. # ## Flatten the geometry. Only linear elements (no polygons) remain.
  4018. flat_geometry = self.flatten(temp_solid_geometry, pathonly=True)
  4019. log.debug("%d paths" % len(flat_geometry))
  4020. try:
  4021. self.tooldia = float(tooldia)
  4022. except Exception as e:
  4023. self.app.inform.emit('[ERROR] %s\n%s' % (_("Failed."), str(e)))
  4024. return 'fail'
  4025. self.z_cut = float(z_cut) if z_cut else None
  4026. self.z_move = float(z_move) if z_move is not None else None
  4027. self.feedrate = float(feedrate) if feedrate else self.app.defaults["geometry_feedrate"]
  4028. self.z_feedrate = float(feedrate_z) if feedrate_z is not None else self.app.defaults["geometry_feedrate_z"]
  4029. self.feedrate_rapid = float(feedrate_rapid) if feedrate_rapid else self.app.defaults["geometry_feedrate_rapid"]
  4030. self.spindlespeed = int(spindlespeed) if spindlespeed != 0 else None
  4031. self.spindledir = spindledir
  4032. self.dwell = dwell
  4033. self.dwelltime = float(dwelltime) if dwelltime else self.app.defaults["geometry_dwelltime"]
  4034. self.startz = float(startz) if startz is not None else self.app.defaults["geometry_startz"]
  4035. self.z_end = float(endz) if endz is not None else self.app.defaults["geometry_endz"]
  4036. self.xy_end = re.sub('[()\[\]]', '', str(endxy)) if endxy else self.app.defaults["geometry_endxy"]
  4037. if self.xy_end and self.xy_end != '':
  4038. self.xy_end = [float(eval(a)) for a in self.xy_end.split(",")]
  4039. if self.xy_end and len(self.xy_end) < 2:
  4040. self.app.inform.emit('[ERROR] %s' % _("The End Move X,Y field in Edit -> Preferences has to be "
  4041. "in the format (x, y) but now there is only one value, not two."))
  4042. return 'fail'
  4043. self.z_depthpercut = float(depthpercut) if depthpercut else self.app.defaults["geometry_depthperpass"]
  4044. self.multidepth = multidepth
  4045. self.z_toolchange = float(toolchangez) if toolchangez is not None else self.app.defaults["geometry_toolchangez"]
  4046. # it servers in the preprocessor file
  4047. self.tool = tool_no
  4048. try:
  4049. if toolchangexy == '':
  4050. self.xy_toolchange = None
  4051. else:
  4052. self.xy_toolchange = re.sub('[()\[\]]', '', str(toolchangexy)) \
  4053. if toolchangexy else self.app.defaults["geometry_toolchangexy"]
  4054. if self.xy_toolchange and self.xy_toolchange != '':
  4055. self.xy_toolchange = [float(eval(a)) for a in self.xy_toolchange.split(",")]
  4056. if len(self.xy_toolchange) < 2:
  4057. self.app.inform.emit('[ERROR] %s' % _("The Toolchange X,Y field in Edit -> Preferences has to be "
  4058. "in the format (x, y) \n"
  4059. "but now there is only one value, not two."))
  4060. return 'fail'
  4061. except Exception as e:
  4062. log.debug("camlib.CNCJob.generate_from_multitool_geometry() --> %s" % str(e))
  4063. pass
  4064. self.pp_geometry_name = pp_geometry_name if pp_geometry_name else 'default'
  4065. self.f_plunge = self.app.defaults["geometry_f_plunge"]
  4066. if self.z_cut is None:
  4067. if 'laser' not in self.pp_geometry_name:
  4068. self.app.inform.emit(
  4069. '[ERROR_NOTCL] %s' % _("Cut_Z parameter is None or zero. Most likely a bad combinations of "
  4070. "other parameters."))
  4071. return 'fail'
  4072. else:
  4073. self.z_cut = 0
  4074. if self.machinist_setting == 0:
  4075. if self.z_cut > 0:
  4076. self.app.inform.emit('[WARNING] %s' %
  4077. _("The Cut Z parameter has positive value. "
  4078. "It is the depth value to cut into material.\n"
  4079. "The Cut Z parameter needs to have a negative value, assuming it is a typo "
  4080. "therefore the app will convert the value to negative."
  4081. "Check the resulting CNC code (Gcode etc)."))
  4082. self.z_cut = -self.z_cut
  4083. elif self.z_cut == 0 and 'laser' not in self.pp_geometry_name:
  4084. self.app.inform.emit('[WARNING] %s: %s' %
  4085. (_("The Cut Z parameter is zero. There will be no cut, skipping file"),
  4086. self.options['name']))
  4087. return 'fail'
  4088. if self.z_move is None:
  4089. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Travel Z parameter is None or zero."))
  4090. return 'fail'
  4091. if self.z_move < 0:
  4092. self.app.inform.emit('[WARNING] %s' %
  4093. _("The Travel Z parameter has negative value. "
  4094. "It is the height value to travel between cuts.\n"
  4095. "The Z Travel parameter needs to have a positive value, assuming it is a typo "
  4096. "therefore the app will convert the value to positive."
  4097. "Check the resulting CNC code (Gcode etc)."))
  4098. self.z_move = -self.z_move
  4099. elif self.z_move == 0:
  4100. self.app.inform.emit('[WARNING] %s: %s' %
  4101. (_("The Z Travel parameter is zero. This is dangerous, skipping file"),
  4102. self.options['name']))
  4103. return 'fail'
  4104. # made sure that depth_per_cut is no more then the z_cut
  4105. if abs(self.z_cut) < self.z_depthpercut:
  4106. self.z_depthpercut = abs(self.z_cut)
  4107. # ## Index first and last points in paths
  4108. # What points to index.
  4109. def get_pts(o):
  4110. return [o.coords[0], o.coords[-1]]
  4111. # Create the indexed storage.
  4112. storage = FlatCAMRTreeStorage()
  4113. storage.get_points = get_pts
  4114. # Store the geometry
  4115. log.debug("Indexing geometry before generating G-Code...")
  4116. self.app.inform.emit(_("Indexing geometry before generating G-Code..."))
  4117. for geo_shape in flat_geometry:
  4118. if self.app.abort_flag:
  4119. # graceful abort requested by the user
  4120. raise grace
  4121. if geo_shape is not None:
  4122. storage.insert(geo_shape)
  4123. # self.input_geometry_bounds = geometry.bounds()
  4124. if not append:
  4125. self.gcode = ""
  4126. # tell preprocessor the number of tool (for toolchange)
  4127. self.tool = tool_no
  4128. # this is the tool diameter, it is used as such to accommodate the preprocessor who need the tool diameter
  4129. # given under the name 'toolC'
  4130. self.postdata['toolC'] = self.tooldia
  4131. # Initial G-Code
  4132. self.pp_geometry = self.app.preprocessors[self.pp_geometry_name]
  4133. p = self.pp_geometry
  4134. self.gcode = self.doformat(p.start_code)
  4135. self.gcode += self.doformat(p.feedrate_code) # sets the feed rate
  4136. if toolchange is False:
  4137. self.gcode += self.doformat(p.lift_code, x=0, y=0) # Move (up) to travel height
  4138. self.gcode += self.doformat(p.startz_code, x=0, y=0)
  4139. if toolchange:
  4140. # if "line_xyz" in self.pp_geometry_name:
  4141. # self.gcode += self.doformat(p.toolchange_code, x=self.xy_toolchange[0], y=self.xy_toolchange[1])
  4142. # else:
  4143. # self.gcode += self.doformat(p.toolchange_code)
  4144. self.gcode += self.doformat(p.toolchange_code)
  4145. if 'laser' not in self.pp_geometry_name:
  4146. self.gcode += self.doformat(p.spindle_code) # Spindle start
  4147. else:
  4148. # for laser this will disable the laser
  4149. self.gcode += self.doformat(p.lift_code, x=self.oldx, y=self.oldy) # Move (up) to travel height
  4150. if self.dwell is True:
  4151. self.gcode += self.doformat(p.dwell_code) # Dwell time
  4152. else:
  4153. if 'laser' not in self.pp_geometry_name:
  4154. self.gcode += self.doformat(p.spindle_code) # Spindle start
  4155. if self.dwell is True:
  4156. self.gcode += self.doformat(p.dwell_code) # Dwell time
  4157. total_travel = 0.0
  4158. total_cut = 0.0
  4159. # ## Iterate over geometry paths getting the nearest each time.
  4160. log.debug("Starting G-Code...")
  4161. self.app.inform.emit('%s...' % _("Starting G-Code"))
  4162. path_count = 0
  4163. current_pt = (0, 0)
  4164. # variables to display the percentage of work done
  4165. geo_len = len(flat_geometry)
  4166. old_disp_number = 0
  4167. log.warning("Number of paths for which to generate GCode: %s" % str(geo_len))
  4168. current_tooldia = float('%.*f' % (self.decimals, float(self.tooldia)))
  4169. self.app.inform.emit('%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  4170. str(current_tooldia),
  4171. str(self.units)))
  4172. pt, geo = storage.nearest(current_pt)
  4173. try:
  4174. while True:
  4175. if self.app.abort_flag:
  4176. # graceful abort requested by the user
  4177. raise grace
  4178. path_count += 1
  4179. # Remove before modifying, otherwise deletion will fail.
  4180. storage.remove(geo)
  4181. # If last point in geometry is the nearest but prefer the first one if last point == first point
  4182. # then reverse coordinates.
  4183. if pt != geo.coords[0] and pt == geo.coords[-1]:
  4184. geo.coords = list(geo.coords)[::-1]
  4185. # ---------- Single depth/pass --------
  4186. if not multidepth:
  4187. # calculate the cut distance
  4188. total_cut = total_cut + geo.length
  4189. self.gcode += self.create_gcode_single_pass(geo, current_tooldia, extracut, extracut_length,
  4190. tolerance, z_move=z_move, old_point=current_pt)
  4191. # --------- Multi-pass ---------
  4192. else:
  4193. # calculate the cut distance
  4194. # due of the number of cuts (multi depth) it has to multiplied by the number of cuts
  4195. nr_cuts = 0
  4196. depth = abs(self.z_cut)
  4197. while depth > 0:
  4198. nr_cuts += 1
  4199. depth -= float(self.z_depthpercut)
  4200. total_cut += (geo.length * nr_cuts)
  4201. self.gcode += self.create_gcode_multi_pass(geo, current_tooldia, extracut, extracut_length,
  4202. tolerance, z_move=z_move, postproc=p,
  4203. old_point=current_pt)
  4204. # calculate the total distance
  4205. total_travel = total_travel + abs(distance(pt1=current_pt, pt2=pt))
  4206. current_pt = geo.coords[-1]
  4207. pt, geo = storage.nearest(current_pt) # Next
  4208. disp_number = int(np.interp(path_count, [0, geo_len], [0, 100]))
  4209. if old_disp_number < disp_number <= 100:
  4210. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  4211. old_disp_number = disp_number
  4212. except StopIteration: # Nothing found in storage.
  4213. pass
  4214. log.debug("Finished G-Code... %s paths traced." % path_count)
  4215. # add move to end position
  4216. total_travel += abs(distance_euclidian(current_pt[0], current_pt[1], 0, 0))
  4217. self.travel_distance += total_travel + total_cut
  4218. self.routing_time += total_cut / self.feedrate
  4219. # Finish
  4220. self.gcode += self.doformat(p.spindle_stop_code)
  4221. self.gcode += self.doformat(p.lift_code, x=current_pt[0], y=current_pt[1])
  4222. self.gcode += self.doformat(p.end_code, x=0, y=0)
  4223. self.app.inform.emit(
  4224. '%s... %s %s.' % (_("Finished G-Code generation"), str(path_count), _("paths traced"))
  4225. )
  4226. return self.gcode
  4227. def geometry_tool_gcode_gen(self, tool, tools, first_pt, tolerance, is_first=False, is_last=False,
  4228. toolchange=False):
  4229. """
  4230. Algorithm to generate GCode from multitool Geometry.
  4231. :param tool: tool number for which to generate GCode
  4232. :type tool: int
  4233. :param tools: a dictionary holding all the tools and data
  4234. :type tools: dict
  4235. :param first_pt: a tuple of coordinates for the first point of the current tool
  4236. :type first_pt: tuple
  4237. :param tolerance: geometry tolerance
  4238. :type tolerance:
  4239. :param is_first: if the current tool is the first tool (for this we need to add start GCode)
  4240. :type is_first: bool
  4241. :param is_last: if the current tool is the last tool (for this we need to add the end GCode)
  4242. :type is_last: bool
  4243. :param toolchange: add toolchange event
  4244. :type toolchange: bool
  4245. :return: GCode
  4246. :rtype: str
  4247. """
  4248. log.debug("Generate_from_multitool_geometry()")
  4249. t_gcode = ''
  4250. temp_solid_geometry = []
  4251. # The Geometry from which we create GCode
  4252. geometry = tools[tool]['solid_geometry']
  4253. # ## Flatten the geometry. Only linear elements (no polygons) remain.
  4254. flat_geometry = self.flatten(geometry, reset=True, pathonly=True)
  4255. log.debug("%d paths" % len(flat_geometry))
  4256. # #########################################################################################################
  4257. # #########################################################################################################
  4258. # ############# PARAMETERS used in PREPROCESSORS so they need to be updated ###############################
  4259. # #########################################################################################################
  4260. # #########################################################################################################
  4261. self.tool = str(tool)
  4262. tool_dict = tools[tool]['data']
  4263. # this is the tool diameter, it is used as such to accommodate the preprocessor who need the tool diameter
  4264. # given under the name 'toolC'
  4265. self.postdata['toolC'] = float(tools[tool]['tooldia'])
  4266. self.tooldia = float(tools[tool]['tooldia'])
  4267. self.use_ui = True
  4268. self.tolerance = tolerance
  4269. # Optimization type. Can be: 'M', 'B', 'T', 'R', 'No'
  4270. opt_type = tool_dict['optimization_type']
  4271. opt_time = tool_dict['search_time'] if 'search_time' in tool_dict else 'R'
  4272. if opt_type == 'M':
  4273. log.debug("Using OR-Tools Metaheuristic Guided Local Search path optimization.")
  4274. elif opt_type == 'B':
  4275. log.debug("Using OR-Tools Basic path optimization.")
  4276. elif opt_type == 'T':
  4277. log.debug("Using Travelling Salesman path optimization.")
  4278. elif opt_type == 'R':
  4279. log.debug("Using RTree path optimization.")
  4280. else:
  4281. log.debug("Using no path optimization.")
  4282. # Preprocessor
  4283. self.pp_geometry_name = tool_dict['ppname_g']
  4284. self.pp_geometry = self.app.preprocessors[self.pp_geometry_name]
  4285. p = self.pp_geometry
  4286. # Offset the Geometry if it is the case
  4287. # FIXME need to test if in ["Path", "In", "Out", "Custom"]. For now only 'Custom' is somehow done
  4288. offset = tools[tool]['offset_value']
  4289. if offset != 0.0:
  4290. for it in flat_geometry:
  4291. # if the geometry is a closed shape then create a Polygon out of it
  4292. if isinstance(it, LineString):
  4293. if it.is_ring:
  4294. it = Polygon(it)
  4295. temp_solid_geometry.append(it.buffer(offset, join_style=2))
  4296. temp_solid_geometry = self.flatten(temp_solid_geometry, reset=True, pathonly=True)
  4297. else:
  4298. temp_solid_geometry = flat_geometry
  4299. if self.z_cut is None:
  4300. if 'laser' not in self.pp_geometry_name:
  4301. self.app.inform.emit(
  4302. '[ERROR_NOTCL] %s' % _("Cut_Z parameter is None or zero. Most likely a bad combinations of "
  4303. "other parameters."))
  4304. return 'fail'
  4305. else:
  4306. self.z_cut = 0
  4307. if self.machinist_setting == 0:
  4308. if self.z_cut > 0:
  4309. self.app.inform.emit('[WARNING] %s' %
  4310. _("The Cut Z parameter has positive value. "
  4311. "It is the depth value to cut into material.\n"
  4312. "The Cut Z parameter needs to have a negative value, assuming it is a typo "
  4313. "therefore the app will convert the value to negative."
  4314. "Check the resulting CNC code (Gcode etc)."))
  4315. self.z_cut = -self.z_cut
  4316. elif self.z_cut == 0 and 'laser' not in self.pp_geometry_name:
  4317. self.app.inform.emit('[WARNING] %s: %s' %
  4318. (_("The Cut Z parameter is zero. There will be no cut, skipping file"),
  4319. self.options['name']))
  4320. return 'fail'
  4321. if self.z_move is None:
  4322. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Travel Z parameter is None or zero."))
  4323. return 'fail'
  4324. if self.z_move < 0:
  4325. self.app.inform.emit('[WARNING] %s' %
  4326. _("The Travel Z parameter has negative value. "
  4327. "It is the height value to travel between cuts.\n"
  4328. "The Z Travel parameter needs to have a positive value, assuming it is a typo "
  4329. "therefore the app will convert the value to positive."
  4330. "Check the resulting CNC code (Gcode etc)."))
  4331. self.z_move = -self.z_move
  4332. elif self.z_move == 0:
  4333. self.app.inform.emit('[WARNING] %s: %s' %
  4334. (_("The Z Travel parameter is zero. This is dangerous, skipping file"),
  4335. self.options['name']))
  4336. return 'fail'
  4337. # made sure that depth_per_cut is no more then the z_cut
  4338. if abs(self.z_cut) < self.z_depthpercut:
  4339. self.z_depthpercut = abs(self.z_cut)
  4340. # Depth parameters
  4341. self.z_cut = float(tool_dict['cutz'])
  4342. self.multidepth = tool_dict['multidepth']
  4343. self.z_depthpercut = float(tool_dict['depthperpass'])
  4344. self.z_move = float(tool_dict['travelz'])
  4345. self.f_plunge = self.app.defaults["geometry_f_plunge"]
  4346. self.feedrate = float(tool_dict['feedrate'])
  4347. self.z_feedrate = float(tool_dict['feedrate_z'])
  4348. self.feedrate_rapid = float(tool_dict['feedrate_rapid'])
  4349. self.spindlespeed = float(tool_dict['spindlespeed'])
  4350. self.spindledir = tool_dict['spindledir']
  4351. self.dwell = tool_dict['dwell']
  4352. self.dwelltime = float(tool_dict['dwelltime'])
  4353. self.startz = float(tool_dict['startz']) if tool_dict['startz'] else None
  4354. if self.startz == '':
  4355. self.startz = None
  4356. self.z_end = float(tool_dict['endz'])
  4357. try:
  4358. if self.xy_end == '':
  4359. self.xy_end = None
  4360. else:
  4361. # either originally it was a string or not, xy_end will be made string
  4362. self.xy_end = re.sub('[()\[\]]', '', str(self.xy_end)) if self.xy_end else None
  4363. # and now, xy_end is made into a list of floats in format [x, y]
  4364. if self.xy_end:
  4365. self.xy_end = [float(eval(a)) for a in self.xy_end.split(",")]
  4366. if self.xy_end and len(self.xy_end) != 2:
  4367. self.app.inform.emit('[ERROR]%s' % _("The End X,Y format has to be (x, y)."))
  4368. return 'fail'
  4369. except Exception as e:
  4370. log.debug("camlib.CNCJob.geometry_from_excellon_by_tool() xy_end --> %s" % str(e))
  4371. self.xy_end = [0, 0]
  4372. self.z_toolchange = tool_dict['toolchangez']
  4373. self.xy_toolchange = tool_dict["toolchangexy"]
  4374. try:
  4375. if self.xy_toolchange == '':
  4376. self.xy_toolchange = None
  4377. else:
  4378. # either originally it was a string or not, xy_toolchange will be made string
  4379. self.xy_toolchange = re.sub('[()\[\]]', '', str(self.xy_toolchange)) if self.xy_toolchange else None
  4380. # and now, xy_toolchange is made into a list of floats in format [x, y]
  4381. if self.xy_toolchange:
  4382. self.xy_toolchange = [float(eval(a)) for a in self.xy_toolchange.split(",")]
  4383. if self.xy_toolchange and len(self.xy_toolchange) != 2:
  4384. self.app.inform.emit('[ERROR] %s' % _("The Toolchange X,Y format has to be (x, y)."))
  4385. return 'fail'
  4386. except Exception as e:
  4387. log.debug("camlib.CNCJob.geometry_from_excellon_by_tool() --> %s" % str(e))
  4388. pass
  4389. self.extracut = tool_dict['extracut']
  4390. self.extracut_length = tool_dict['extracut_length']
  4391. # Probe parameters
  4392. # self.z_pdepth = tool_dict["tools_drill_z_pdepth"]
  4393. # self.feedrate_probe = tool_dict["tools_drill_feedrate_probe"]
  4394. # #########################################################################################################
  4395. # ############ Create the data. ###########################################################################
  4396. # #########################################################################################################
  4397. optimized_path = []
  4398. geo_storage = {}
  4399. for geo in temp_solid_geometry:
  4400. if not geo is None:
  4401. geo_storage[geo.coords[0]] = geo
  4402. locations = list(geo_storage.keys())
  4403. if opt_type == 'M':
  4404. # if there are no locations then go to the next tool
  4405. if not locations:
  4406. return 'fail'
  4407. optimized_locations = self.optimized_ortools_meta(locations=locations, opt_time=opt_time)
  4408. optimized_path = [(locations[loc], geo_storage[locations[loc]]) for loc in optimized_locations]
  4409. elif opt_type == 'B':
  4410. # if there are no locations then go to the next tool
  4411. if not locations:
  4412. return 'fail'
  4413. optimized_locations = self.optimized_ortools_basic(locations=locations)
  4414. optimized_path = [(locations[loc], geo_storage[locations[loc]]) for loc in optimized_locations]
  4415. elif opt_type == 'T':
  4416. # if there are no locations then go to the next tool
  4417. if not locations:
  4418. return 'fail'
  4419. optimized_locations = self.optimized_travelling_salesman(locations)
  4420. optimized_path = [(loc, geo_storage[loc]) for loc in optimized_locations]
  4421. elif opt_type == 'R':
  4422. optimized_path = self.geo_optimized_rtree(temp_solid_geometry)
  4423. if optimized_path == 'fail':
  4424. return 'fail'
  4425. else:
  4426. # it's actually not optimized path but here we build a list of (x,y) coordinates
  4427. # out of the tool's drills
  4428. for geo in temp_solid_geometry:
  4429. optimized_path.append(geo.coords[0])
  4430. # #########################################################################################################
  4431. # #########################################################################################################
  4432. # Only if there are locations to mill
  4433. if not optimized_path:
  4434. log.debug("camlib.CNCJob.geometry_tool_gcode_gen() -> Optimized path is empty.")
  4435. return 'fail'
  4436. if self.app.abort_flag:
  4437. # graceful abort requested by the user
  4438. raise grace
  4439. # #############################################################################################################
  4440. # #############################################################################################################
  4441. # ################# MILLING !!! ##############################################################################
  4442. # #############################################################################################################
  4443. # #############################################################################################################
  4444. log.debug("Starting G-Code...")
  4445. current_tooldia = float('%.*f' % (self.decimals, float(self.tooldia)))
  4446. self.app.inform.emit('%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  4447. str(current_tooldia),
  4448. str(self.units)))
  4449. # Measurements
  4450. total_travel = 0.0
  4451. total_cut = 0.0
  4452. # Start GCode
  4453. start_gcode = ''
  4454. if is_first:
  4455. start_gcode = self.doformat(p.start_code)
  4456. t_gcode += start_gcode
  4457. # Toolchange code
  4458. t_gcode += self.doformat(p.feedrate_code) # sets the feed rate
  4459. if toolchange:
  4460. t_gcode += self.doformat(p.toolchange_code)
  4461. if 'laser' not in self.pp_geometry_name.lower():
  4462. t_gcode += self.doformat(p.spindle_code) # Spindle start
  4463. else:
  4464. # for laser this will disable the laser
  4465. t_gcode += self.doformat(p.lift_code, x=self.oldx, y=self.oldy) # Move (up) to travel height
  4466. if self.dwell:
  4467. t_gcode += self.doformat(p.dwell_code) # Dwell time
  4468. else:
  4469. t_gcode += self.doformat(p.lift_code, x=0, y=0) # Move (up) to travel height
  4470. t_gcode += self.doformat(p.startz_code, x=0, y=0)
  4471. if 'laser' not in self.pp_geometry_name.lower():
  4472. t_gcode += self.doformat(p.spindle_code) # Spindle start
  4473. if self.dwell is True:
  4474. t_gcode += self.doformat(p.dwell_code) # Dwell time
  4475. t_gcode += self.doformat(p.feedrate_code) # sets the feed rate
  4476. # ## Iterate over geometry paths getting the nearest each time.
  4477. path_count = 0
  4478. # variables to display the percentage of work done
  4479. geo_len = len(flat_geometry)
  4480. log.warning("Number of paths for which to generate GCode: %s" % str(geo_len))
  4481. old_disp_number = 0
  4482. current_pt = (0, 0)
  4483. for pt, geo in optimized_path:
  4484. if self.app.abort_flag:
  4485. # graceful abort requested by the user
  4486. raise grace
  4487. path_count += 1
  4488. # If last point in geometry is the nearest but prefer the first one if last point == first point
  4489. # then reverse coordinates.
  4490. if pt != geo.coords[0] and pt == geo.coords[-1]:
  4491. geo.coords = list(geo.coords)[::-1]
  4492. # ---------- Single depth/pass --------
  4493. if not self.multidepth:
  4494. # calculate the cut distance
  4495. total_cut = total_cut + geo.length
  4496. t_gcode += self.create_gcode_single_pass(geo, current_tooldia, self.extracut,
  4497. self.extracut_length, self.tolerance,
  4498. z_move=self.z_move, old_point=current_pt)
  4499. # --------- Multi-pass ---------
  4500. else:
  4501. # calculate the cut distance
  4502. # due of the number of cuts (multi depth) it has to multiplied by the number of cuts
  4503. nr_cuts = 0
  4504. depth = abs(self.z_cut)
  4505. while depth > 0:
  4506. nr_cuts += 1
  4507. depth -= float(self.z_depthpercut)
  4508. total_cut += (geo.length * nr_cuts)
  4509. t_gcode += self.create_gcode_multi_pass(geo, current_tooldia, self.extracut,
  4510. self.extracut_length, self.tolerance,
  4511. z_move=self.z_move, postproc=p, old_point=current_pt)
  4512. # calculate the total distance
  4513. total_travel = total_travel + abs(distance(pt1=current_pt, pt2=pt))
  4514. current_pt = geo.coords[-1]
  4515. disp_number = int(np.interp(path_count, [0, geo_len], [0, 100]))
  4516. if old_disp_number < disp_number <= 100:
  4517. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  4518. old_disp_number = disp_number
  4519. log.debug("Finished G-Code... %s paths traced." % path_count)
  4520. # add move to end position
  4521. total_travel += abs(distance_euclidian(current_pt[0], current_pt[1], 0, 0))
  4522. self.travel_distance += total_travel + total_cut
  4523. self.routing_time += total_cut / self.feedrate
  4524. # Finish
  4525. if is_last:
  4526. t_gcode += self.doformat(p.spindle_stop_code)
  4527. t_gcode += self.doformat(p.lift_code, x=current_pt[0], y=current_pt[1])
  4528. t_gcode += self.doformat(p.end_code, x=0, y=0)
  4529. self.app.inform.emit(
  4530. '%s... %s %s.' % (_("Finished G-Code generation"), str(path_count), _("paths traced"))
  4531. )
  4532. self.gcode = t_gcode
  4533. return self.gcode, start_gcode
  4534. def generate_from_geometry_2(self, geometry, append=True, tooldia=None, offset=0.0, tolerance=0, z_cut=None,
  4535. z_move=None, feedrate=None, feedrate_z=None, feedrate_rapid=None, spindlespeed=None,
  4536. spindledir='CW', dwell=False, dwelltime=None, multidepth=False, depthpercut=None,
  4537. toolchange=False, toolchangez=None, toolchangexy="0.0, 0.0", extracut=False,
  4538. extracut_length=None, startz=None, endz=None, endxy='', pp_geometry_name=None,
  4539. tool_no=1):
  4540. """
  4541. Second algorithm to generate from Geometry.
  4542. Algorithm description:
  4543. ----------------------
  4544. Uses RTree to find the nearest path to follow.
  4545. :param geometry:
  4546. :param append:
  4547. :param tooldia:
  4548. :param offset:
  4549. :param tolerance:
  4550. :param z_cut:
  4551. :param z_move:
  4552. :param feedrate:
  4553. :param feedrate_z:
  4554. :param feedrate_rapid:
  4555. :param spindlespeed:
  4556. :param spindledir:
  4557. :param dwell:
  4558. :param dwelltime:
  4559. :param multidepth: If True, use multiple passes to reach the desired depth.
  4560. :param depthpercut: Maximum depth in each pass.
  4561. :param toolchange:
  4562. :param toolchangez:
  4563. :param toolchangexy:
  4564. :param extracut: Adds (or not) an extra cut at the end of each path overlapping the first point in
  4565. path to ensure complete copper removal
  4566. :param extracut_length: The extra cut length
  4567. :param startz:
  4568. :param endz:
  4569. :param endxy:
  4570. :param pp_geometry_name:
  4571. :param tool_no:
  4572. :return: None
  4573. """
  4574. log.debug("Executing camlib.CNCJob.generate_from_geometry_2()")
  4575. # if solid_geometry is empty raise an exception
  4576. if not geometry.solid_geometry:
  4577. self.app.inform.emit(
  4578. '[ERROR_NOTCL] %s' % _("Trying to generate a CNC Job from a Geometry object without solid_geometry.")
  4579. )
  4580. return 'fail'
  4581. def bounds_rec(obj):
  4582. if type(obj) is list:
  4583. minx = np.Inf
  4584. miny = np.Inf
  4585. maxx = -np.Inf
  4586. maxy = -np.Inf
  4587. for k in obj:
  4588. if type(k) is dict:
  4589. for key in k:
  4590. minx_, miny_, maxx_, maxy_ = bounds_rec(k[key])
  4591. minx = min(minx, minx_)
  4592. miny = min(miny, miny_)
  4593. maxx = max(maxx, maxx_)
  4594. maxy = max(maxy, maxy_)
  4595. else:
  4596. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  4597. minx = min(minx, minx_)
  4598. miny = min(miny, miny_)
  4599. maxx = max(maxx, maxx_)
  4600. maxy = max(maxy, maxy_)
  4601. return minx, miny, maxx, maxy
  4602. else:
  4603. # it's a Shapely object, return it's bounds
  4604. return obj.bounds
  4605. # Create the solid geometry which will be used to generate GCode
  4606. temp_solid_geometry = []
  4607. if offset != 0.0:
  4608. offset_for_use = offset
  4609. if offset < 0:
  4610. a, b, c, d = bounds_rec(geometry.solid_geometry)
  4611. # if the offset is less than half of the total length or less than half of the total width of the
  4612. # solid geometry it's obvious we can't do the offset
  4613. if -offset > ((c - a) / 2) or -offset > ((d - b) / 2):
  4614. self.app.inform.emit(
  4615. '[ERROR_NOTCL] %s' %
  4616. _("The Tool Offset value is too negative to use for the current_geometry.\n"
  4617. "Raise the value (in module) and try again.")
  4618. )
  4619. return 'fail'
  4620. # hack: make offset smaller by 0.0000000001 which is insignificant difference but allow the job
  4621. # to continue
  4622. elif -offset == ((c - a) / 2) or -offset == ((d - b) / 2):
  4623. offset_for_use = offset - 0.0000000001
  4624. for it in geometry.solid_geometry:
  4625. # if the geometry is a closed shape then create a Polygon out of it
  4626. if isinstance(it, LineString):
  4627. c = it.coords
  4628. if c[0] == c[-1]:
  4629. it = Polygon(it)
  4630. temp_solid_geometry.append(it.buffer(offset_for_use, join_style=2))
  4631. else:
  4632. temp_solid_geometry = geometry.solid_geometry
  4633. # ## Flatten the geometry. Only linear elements (no polygons) remain.
  4634. flat_geometry = self.flatten(temp_solid_geometry, pathonly=True)
  4635. log.debug("%d paths" % len(flat_geometry))
  4636. default_dia = None
  4637. if isinstance(self.app.defaults["geometry_cnctooldia"], float):
  4638. default_dia = self.app.defaults["geometry_cnctooldia"]
  4639. else:
  4640. try:
  4641. tools_string = self.app.defaults["geometry_cnctooldia"].split(",")
  4642. tools_diameters = [eval(a) for a in tools_string if a != '']
  4643. default_dia = tools_diameters[0] if tools_diameters else 0.0
  4644. except Exception as e:
  4645. self.app.log.debug("camlib.CNCJob.generate_from_geometry_2() --> %s" % str(e))
  4646. try:
  4647. self.tooldia = float(tooldia) if tooldia else default_dia
  4648. except ValueError:
  4649. self.tooldia = [float(el) for el in tooldia.split(',') if el != ''] if tooldia is not None else default_dia
  4650. if self.tooldia is None:
  4651. self.app.inform.emit('[ERROR] %s' % _("Failed."))
  4652. return 'fail'
  4653. self.z_cut = float(z_cut) if z_cut is not None else self.app.defaults["geometry_cutz"]
  4654. self.z_move = float(z_move) if z_move is not None else self.app.defaults["geometry_travelz"]
  4655. self.feedrate = float(feedrate) if feedrate is not None else self.app.defaults["geometry_feedrate"]
  4656. self.z_feedrate = float(feedrate_z) if feedrate_z is not None else self.app.defaults["geometry_feedrate_z"]
  4657. self.feedrate_rapid = float(feedrate_rapid) if feedrate_rapid is not None else \
  4658. self.app.defaults["geometry_feedrate_rapid"]
  4659. self.spindlespeed = int(spindlespeed) if spindlespeed != 0 and spindlespeed is not None else None
  4660. self.spindledir = spindledir
  4661. self.dwell = dwell
  4662. self.dwelltime = float(dwelltime) if dwelltime is not None else self.app.defaults["geometry_dwelltime"]
  4663. self.startz = float(startz) if startz is not None and startz != '' else self.app.defaults["geometry_startz"]
  4664. self.z_end = float(endz) if endz is not None else self.app.defaults["geometry_endz"]
  4665. self.xy_end = endxy if endxy != '' and endxy else self.app.defaults["geometry_endxy"]
  4666. self.xy_end = re.sub('[()\[\]]', '', str(self.xy_end)) if self.xy_end else None
  4667. if self.xy_end is not None and self.xy_end != '':
  4668. self.xy_end = [float(eval(a)) for a in self.xy_end.split(",")]
  4669. if self.xy_end and len(self.xy_end) < 2:
  4670. self.app.inform.emit('[ERROR] %s' % _("The End Move X,Y field in Edit -> Preferences has to be "
  4671. "in the format (x, y) but now there is only one value, not two."))
  4672. return 'fail'
  4673. self.z_depthpercut = float(depthpercut) if depthpercut is not None and depthpercut != 0 else abs(self.z_cut)
  4674. self.multidepth = multidepth
  4675. self.z_toolchange = float(toolchangez) if toolchangez is not None else self.app.defaults["geometry_toolchangez"]
  4676. self.extracut_length = float(extracut_length) if extracut_length is not None else \
  4677. self.app.defaults["geometry_extracut_length"]
  4678. try:
  4679. if toolchangexy == '':
  4680. self.xy_toolchange = None
  4681. else:
  4682. self.xy_toolchange = re.sub('[()\[\]]', '', str(toolchangexy)) if self.xy_toolchange else None
  4683. if self.xy_toolchange and self.xy_toolchange != '':
  4684. self.xy_toolchange = [float(eval(a)) for a in self.xy_toolchange.split(",")]
  4685. if len(self.xy_toolchange) < 2:
  4686. self.app.inform.emit('[ERROR] %s' % _("The Toolchange X,Y format has to be (x, y)."))
  4687. return 'fail'
  4688. except Exception as e:
  4689. log.debug("camlib.CNCJob.generate_from_geometry_2() --> %s" % str(e))
  4690. pass
  4691. self.pp_geometry_name = pp_geometry_name if pp_geometry_name else 'default'
  4692. self.f_plunge = self.app.defaults["geometry_f_plunge"]
  4693. if self.machinist_setting == 0:
  4694. if self.z_cut is None:
  4695. if 'laser' not in self.pp_geometry_name:
  4696. self.app.inform.emit(
  4697. '[ERROR_NOTCL] %s' % _("Cut_Z parameter is None or zero. Most likely a bad combinations of "
  4698. "other parameters.")
  4699. )
  4700. return 'fail'
  4701. else:
  4702. self.z_cut = 0.0
  4703. if self.z_cut > 0:
  4704. self.app.inform.emit('[WARNING] %s' %
  4705. _("The Cut Z parameter has positive value. "
  4706. "It is the depth value to cut into material.\n"
  4707. "The Cut Z parameter needs to have a negative value, assuming it is a typo "
  4708. "therefore the app will convert the value to negative."
  4709. "Check the resulting CNC code (Gcode etc)."))
  4710. self.z_cut = -self.z_cut
  4711. elif self.z_cut == 0 and 'laser' not in self.pp_geometry_name:
  4712. self.app.inform.emit(
  4713. '[WARNING] %s: %s' % (_("The Cut Z parameter is zero. There will be no cut, skipping file"),
  4714. geometry.options['name'])
  4715. )
  4716. return 'fail'
  4717. if self.z_move is None:
  4718. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Travel Z parameter is None or zero."))
  4719. return 'fail'
  4720. if self.z_move < 0:
  4721. self.app.inform.emit('[WARNING] %s' %
  4722. _("The Travel Z parameter has negative value. "
  4723. "It is the height value to travel between cuts.\n"
  4724. "The Z Travel parameter needs to have a positive value, assuming it is a typo "
  4725. "therefore the app will convert the value to positive."
  4726. "Check the resulting CNC code (Gcode etc)."))
  4727. self.z_move = -self.z_move
  4728. elif self.z_move == 0:
  4729. self.app.inform.emit(
  4730. '[WARNING] %s: %s' % (_("The Z Travel parameter is zero. This is dangerous, skipping file"),
  4731. self.options['name'])
  4732. )
  4733. return 'fail'
  4734. # made sure that depth_per_cut is no more then the z_cut
  4735. try:
  4736. if abs(self.z_cut) < self.z_depthpercut:
  4737. self.z_depthpercut = abs(self.z_cut)
  4738. except TypeError:
  4739. self.z_depthpercut = abs(self.z_cut)
  4740. # ## Index first and last points in paths
  4741. # What points to index.
  4742. def get_pts(o):
  4743. return [o.coords[0], o.coords[-1]]
  4744. # Create the indexed storage.
  4745. storage = FlatCAMRTreeStorage()
  4746. storage.get_points = get_pts
  4747. # Store the geometry
  4748. log.debug("Indexing geometry before generating G-Code...")
  4749. self.app.inform.emit(_("Indexing geometry before generating G-Code..."))
  4750. for geo_shape in flat_geometry:
  4751. if self.app.abort_flag:
  4752. # graceful abort requested by the user
  4753. raise grace
  4754. if geo_shape is not None:
  4755. storage.insert(geo_shape)
  4756. if not append:
  4757. self.gcode = ""
  4758. # tell preprocessor the number of tool (for toolchange)
  4759. self.tool = tool_no
  4760. # this is the tool diameter, it is used as such to accommodate the preprocessor who need the tool diameter
  4761. # given under the name 'toolC'
  4762. # this is a fancy way of adding a class attribute (which should be added in the __init__ method) without doing
  4763. # it there :)
  4764. self.postdata['toolC'] = self.tooldia
  4765. # Initial G-Code
  4766. self.pp_geometry = self.app.preprocessors[self.pp_geometry_name]
  4767. # the 'p' local attribute is a reference to the current preprocessor class
  4768. p = self.pp_geometry
  4769. self.oldx = 0.0
  4770. self.oldy = 0.0
  4771. self.gcode = self.doformat(p.start_code)
  4772. self.gcode += self.doformat(p.feedrate_code) # sets the feed rate
  4773. if toolchange is False:
  4774. # all the x and y parameters in self.doformat() are used only by some preprocessors not by all
  4775. self.gcode += self.doformat(p.lift_code, x=self.oldx, y=self.oldy) # Move (up) to travel height
  4776. self.gcode += self.doformat(p.startz_code, x=self.oldx, y=self.oldy)
  4777. if toolchange:
  4778. # if "line_xyz" in self.pp_geometry_name:
  4779. # self.gcode += self.doformat(p.toolchange_code, x=self.xy_toolchange[0], y=self.xy_toolchange[1])
  4780. # else:
  4781. # self.gcode += self.doformat(p.toolchange_code)
  4782. self.gcode += self.doformat(p.toolchange_code)
  4783. if 'laser' not in self.pp_geometry_name:
  4784. self.gcode += self.doformat(p.spindle_code) # Spindle start
  4785. else:
  4786. # for laser this will disable the laser
  4787. self.gcode += self.doformat(p.lift_code, x=self.oldx, y=self.oldy) # Move (up) to travel height
  4788. if self.dwell is True:
  4789. self.gcode += self.doformat(p.dwell_code) # Dwell time
  4790. else:
  4791. if 'laser' not in self.pp_geometry_name:
  4792. self.gcode += self.doformat(p.spindle_code) # Spindle start
  4793. if self.dwell is True:
  4794. self.gcode += self.doformat(p.dwell_code) # Dwell time
  4795. total_travel = 0.0
  4796. total_cut = 0.0
  4797. # Iterate over geometry paths getting the nearest each time.
  4798. log.debug("Starting G-Code...")
  4799. self.app.inform.emit('%s...' % _("Starting G-Code"))
  4800. # variables to display the percentage of work done
  4801. geo_len = len(flat_geometry)
  4802. old_disp_number = 0
  4803. log.warning("Number of paths for which to generate GCode: %s" % str(geo_len))
  4804. current_tooldia = float('%.*f' % (self.decimals, float(self.tooldia)))
  4805. self.app.inform.emit(
  4806. '%s: %s%s.' % (_("Starting G-Code for tool with diameter"), str(current_tooldia), str(self.units))
  4807. )
  4808. path_count = 0
  4809. current_pt = (0, 0)
  4810. pt, geo = storage.nearest(current_pt)
  4811. # when nothing is left in the storage a StopIteration exception will be raised therefore stopping
  4812. # the whole process including the infinite loop while True below.
  4813. try:
  4814. while True:
  4815. if self.app.abort_flag:
  4816. # graceful abort requested by the user
  4817. raise grace
  4818. path_count += 1
  4819. # Remove before modifying, otherwise deletion will fail.
  4820. storage.remove(geo)
  4821. # If last point in geometry is the nearest but prefer the first one if last point == first point
  4822. # then reverse coordinates.
  4823. if pt != geo.coords[0] and pt == geo.coords[-1]:
  4824. geo.coords = list(geo.coords)[::-1]
  4825. # ---------- Single depth/pass --------
  4826. if not multidepth:
  4827. # calculate the cut distance
  4828. total_cut += geo.length
  4829. self.gcode += self.create_gcode_single_pass(geo, current_tooldia, extracut, self.extracut_length,
  4830. tolerance, z_move=z_move, old_point=current_pt)
  4831. # --------- Multi-pass ---------
  4832. else:
  4833. # calculate the cut distance
  4834. # due of the number of cuts (multi depth) it has to multiplied by the number of cuts
  4835. nr_cuts = 0
  4836. depth = abs(self.z_cut)
  4837. while depth > 0:
  4838. nr_cuts += 1
  4839. depth -= float(self.z_depthpercut)
  4840. total_cut += (geo.length * nr_cuts)
  4841. self.gcode += self.create_gcode_multi_pass(geo, current_tooldia, extracut, self.extracut_length,
  4842. tolerance, z_move=z_move, postproc=p,
  4843. old_point=current_pt)
  4844. # calculate the travel distance
  4845. total_travel += abs(distance(pt1=current_pt, pt2=pt))
  4846. current_pt = geo.coords[-1]
  4847. pt, geo = storage.nearest(current_pt) # Next
  4848. # update the activity counter (lower left side of the app, status bar)
  4849. disp_number = int(np.interp(path_count, [0, geo_len], [0, 100]))
  4850. if old_disp_number < disp_number <= 100:
  4851. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  4852. old_disp_number = disp_number
  4853. except StopIteration: # Nothing found in storage.
  4854. pass
  4855. log.debug("Finishing G-Code... %s paths traced." % path_count)
  4856. # add move to end position
  4857. total_travel += abs(distance_euclidian(current_pt[0], current_pt[1], 0, 0))
  4858. self.travel_distance += total_travel + total_cut
  4859. self.routing_time += total_cut / self.feedrate
  4860. # Finish
  4861. self.gcode += self.doformat(p.spindle_stop_code)
  4862. self.gcode += self.doformat(p.lift_code, x=current_pt[0], y=current_pt[1])
  4863. self.gcode += self.doformat(p.end_code, x=0, y=0)
  4864. self.app.inform.emit(
  4865. '%s... %s %s' % (_("Finished G-Code generation"), str(path_count), _(" paths traced."))
  4866. )
  4867. return self.gcode
  4868. def generate_gcode_from_solderpaste_geo(self, **kwargs):
  4869. """
  4870. Algorithm to generate from multitool Geometry.
  4871. Algorithm description:
  4872. ----------------------
  4873. Uses RTree to find the nearest path to follow.
  4874. :return: Gcode string
  4875. """
  4876. log.debug("Generate_from_solderpaste_geometry()")
  4877. # ## Index first and last points in paths
  4878. # What points to index.
  4879. def get_pts(o):
  4880. return [o.coords[0], o.coords[-1]]
  4881. self.gcode = ""
  4882. if not kwargs:
  4883. log.debug("camlib.generate_from_solderpaste_geo() --> No tool in the solderpaste geometry.")
  4884. self.app.inform.emit('[ERROR_NOTCL] %s' %
  4885. _("There is no tool data in the SolderPaste geometry."))
  4886. # this is the tool diameter, it is used as such to accommodate the preprocessor who need the tool diameter
  4887. # given under the name 'toolC'
  4888. self.postdata['z_start'] = kwargs['data']['tools_solderpaste_z_start']
  4889. self.postdata['z_dispense'] = kwargs['data']['tools_solderpaste_z_dispense']
  4890. self.postdata['z_stop'] = kwargs['data']['tools_solderpaste_z_stop']
  4891. self.postdata['z_travel'] = kwargs['data']['tools_solderpaste_z_travel']
  4892. self.postdata['z_toolchange'] = kwargs['data']['tools_solderpaste_z_toolchange']
  4893. self.postdata['xy_toolchange'] = kwargs['data']['tools_solderpaste_xy_toolchange']
  4894. self.postdata['frxy'] = kwargs['data']['tools_solderpaste_frxy']
  4895. self.postdata['frz'] = kwargs['data']['tools_solderpaste_frz']
  4896. self.postdata['frz_dispense'] = kwargs['data']['tools_solderpaste_frz_dispense']
  4897. self.postdata['speedfwd'] = kwargs['data']['tools_solderpaste_speedfwd']
  4898. self.postdata['dwellfwd'] = kwargs['data']['tools_solderpaste_dwellfwd']
  4899. self.postdata['speedrev'] = kwargs['data']['tools_solderpaste_speedrev']
  4900. self.postdata['dwellrev'] = kwargs['data']['tools_solderpaste_dwellrev']
  4901. self.postdata['pp_solderpaste_name'] = kwargs['data']['tools_solderpaste_pp']
  4902. self.postdata['toolC'] = kwargs['tooldia']
  4903. self.pp_solderpaste_name = kwargs['data']['tools_solderpaste_pp'] if kwargs['data']['tools_solderpaste_pp'] \
  4904. else self.app.defaults['tools_solderpaste_pp']
  4905. p = self.app.preprocessors[self.pp_solderpaste_name]
  4906. # ## Flatten the geometry. Only linear elements (no polygons) remain.
  4907. flat_geometry = self.flatten(kwargs['solid_geometry'], pathonly=True)
  4908. log.debug("%d paths" % len(flat_geometry))
  4909. # Create the indexed storage.
  4910. storage = FlatCAMRTreeStorage()
  4911. storage.get_points = get_pts
  4912. # Store the geometry
  4913. log.debug("Indexing geometry before generating G-Code...")
  4914. for geo_shape in flat_geometry:
  4915. if self.app.abort_flag:
  4916. # graceful abort requested by the user
  4917. raise grace
  4918. if geo_shape is not None:
  4919. storage.insert(geo_shape)
  4920. # Initial G-Code
  4921. self.gcode = self.doformat(p.start_code)
  4922. self.gcode += self.doformat(p.spindle_off_code)
  4923. self.gcode += self.doformat(p.toolchange_code)
  4924. # ## Iterate over geometry paths getting the nearest each time.
  4925. log.debug("Starting SolderPaste G-Code...")
  4926. path_count = 0
  4927. current_pt = (0, 0)
  4928. # variables to display the percentage of work done
  4929. geo_len = len(flat_geometry)
  4930. old_disp_number = 0
  4931. pt, geo = storage.nearest(current_pt)
  4932. try:
  4933. while True:
  4934. if self.app.abort_flag:
  4935. # graceful abort requested by the user
  4936. raise grace
  4937. path_count += 1
  4938. # Remove before modifying, otherwise deletion will fail.
  4939. storage.remove(geo)
  4940. # If last point in geometry is the nearest but prefer the first one if last point == first point
  4941. # then reverse coordinates.
  4942. if pt != geo.coords[0] and pt == geo.coords[-1]:
  4943. geo.coords = list(geo.coords)[::-1]
  4944. self.gcode += self.create_soldepaste_gcode(geo, p=p, old_point=current_pt)
  4945. current_pt = geo.coords[-1]
  4946. pt, geo = storage.nearest(current_pt) # Next
  4947. disp_number = int(np.interp(path_count, [0, geo_len], [0, 100]))
  4948. if old_disp_number < disp_number <= 100:
  4949. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  4950. old_disp_number = disp_number
  4951. except StopIteration: # Nothing found in storage.
  4952. pass
  4953. log.debug("Finishing SolderPste G-Code... %s paths traced." % path_count)
  4954. self.app.inform.emit(
  4955. '%s... %s %s' % (_("Finished SolderPaste G-Code generation"), str(path_count), _("paths traced."))
  4956. )
  4957. # Finish
  4958. self.gcode += self.doformat(p.lift_code)
  4959. self.gcode += self.doformat(p.end_code)
  4960. return self.gcode
  4961. def create_soldepaste_gcode(self, geometry, p, old_point=(0, 0)):
  4962. gcode = ''
  4963. path = geometry.coords
  4964. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  4965. if self.coordinates_type == "G90":
  4966. # For Absolute coordinates type G90
  4967. first_x = path[0][0]
  4968. first_y = path[0][1]
  4969. else:
  4970. # For Incremental coordinates type G91
  4971. first_x = path[0][0] - old_point[0]
  4972. first_y = path[0][1] - old_point[1]
  4973. if type(geometry) == LineString or type(geometry) == LinearRing:
  4974. # Move fast to 1st point
  4975. gcode += self.doformat(p.rapid_code, x=first_x, y=first_y) # Move to first point
  4976. # Move down to cutting depth
  4977. gcode += self.doformat(p.z_feedrate_code)
  4978. gcode += self.doformat(p.down_z_start_code)
  4979. gcode += self.doformat(p.spindle_fwd_code) # Start dispensing
  4980. gcode += self.doformat(p.dwell_fwd_code)
  4981. gcode += self.doformat(p.feedrate_z_dispense_code)
  4982. gcode += self.doformat(p.lift_z_dispense_code)
  4983. gcode += self.doformat(p.feedrate_xy_code)
  4984. # Cutting...
  4985. prev_x = first_x
  4986. prev_y = first_y
  4987. for pt in path[1:]:
  4988. if self.coordinates_type == "G90":
  4989. # For Absolute coordinates type G90
  4990. next_x = pt[0]
  4991. next_y = pt[1]
  4992. else:
  4993. # For Incremental coordinates type G91
  4994. next_x = pt[0] - prev_x
  4995. next_y = pt[1] - prev_y
  4996. gcode += self.doformat(p.linear_code, x=next_x, y=next_y) # Linear motion to point
  4997. prev_x = next_x
  4998. prev_y = next_y
  4999. # Up to travelling height.
  5000. gcode += self.doformat(p.spindle_off_code) # Stop dispensing
  5001. gcode += self.doformat(p.spindle_rev_code)
  5002. gcode += self.doformat(p.down_z_stop_code)
  5003. gcode += self.doformat(p.spindle_off_code)
  5004. gcode += self.doformat(p.dwell_rev_code)
  5005. gcode += self.doformat(p.z_feedrate_code)
  5006. gcode += self.doformat(p.lift_code)
  5007. elif type(geometry) == Point:
  5008. gcode += self.doformat(p.linear_code, x=first_x, y=first_y) # Move to first point
  5009. gcode += self.doformat(p.feedrate_z_dispense_code)
  5010. gcode += self.doformat(p.down_z_start_code)
  5011. gcode += self.doformat(p.spindle_fwd_code) # Start dispensing
  5012. gcode += self.doformat(p.dwell_fwd_code)
  5013. gcode += self.doformat(p.lift_z_dispense_code)
  5014. gcode += self.doformat(p.spindle_off_code) # Stop dispensing
  5015. gcode += self.doformat(p.spindle_rev_code)
  5016. gcode += self.doformat(p.spindle_off_code)
  5017. gcode += self.doformat(p.down_z_stop_code)
  5018. gcode += self.doformat(p.dwell_rev_code)
  5019. gcode += self.doformat(p.z_feedrate_code)
  5020. gcode += self.doformat(p.lift_code)
  5021. return gcode
  5022. def create_gcode_single_pass(self, geometry, cdia, extracut, extracut_length, tolerance, z_move, old_point=(0, 0)):
  5023. """
  5024. # G-code. Note: self.linear2gcode() and self.point2gcode() will lower and raise the tool every time.
  5025. :param geometry: A Shapely Geometry (LineString or LinearRing) which is the path to be cut
  5026. :type geometry: LineString, LinearRing
  5027. :param cdia: Tool diameter
  5028. :type cdia: float
  5029. :param extracut: Will add an extra cut over the point where start of the cut is met with the end cut
  5030. :type extracut: bool
  5031. :param extracut_length: The length of the extra cut: half before the meeting point, half after
  5032. :type extracut_length: float
  5033. :param tolerance: Tolerance used to simplify the paths (making them mre rough)
  5034. :type tolerance: float
  5035. :param z_move: Travel Z
  5036. :type z_move: float
  5037. :param old_point: Previous point
  5038. :type old_point: tuple
  5039. :return: Gcode
  5040. :rtype: str
  5041. """
  5042. # p = postproc
  5043. if type(geometry) == LineString or type(geometry) == LinearRing:
  5044. if extracut is False or not geometry.is_ring:
  5045. gcode_single_pass = self.linear2gcode(geometry, cdia, z_move=z_move, tolerance=tolerance,
  5046. old_point=old_point)
  5047. else:
  5048. gcode_single_pass = self.linear2gcode_extra(geometry, cdia, extracut_length, tolerance=tolerance,
  5049. z_move=z_move, old_point=old_point)
  5050. elif type(geometry) == Point:
  5051. gcode_single_pass = self.point2gcode(geometry, cdia, z_move=z_move, old_point=old_point)
  5052. else:
  5053. log.warning("G-code generation not implemented for %s" % (str(type(geometry))))
  5054. return
  5055. return gcode_single_pass
  5056. def create_gcode_multi_pass(self, geometry, cdia, extracut, extracut_length, tolerance, postproc, z_move,
  5057. old_point=(0, 0)):
  5058. """
  5059. :param geometry: A Shapely Geometry (LineString or LinearRing) which is the path to be cut
  5060. :type geometry: LineString, LinearRing
  5061. :param cdia: Tool diameter
  5062. :type cdia: float
  5063. :param extracut: Will add an extra cut over the point where start of the cut is met with the end cut
  5064. :type extracut: bool
  5065. :param extracut_length: The length of the extra cut: half before the meeting point, half after
  5066. :type extracut_length: float
  5067. :param tolerance: Tolerance used to simplify the paths (making them mre rough)
  5068. :type tolerance: float
  5069. :param postproc: Preprocessor class
  5070. :type postproc: class
  5071. :param z_move: Travel Z
  5072. :type z_move: float
  5073. :param old_point: Previous point
  5074. :type old_point: tuple
  5075. :return: Gcode
  5076. :rtype: str
  5077. """
  5078. p = postproc
  5079. gcode_multi_pass = ''
  5080. if isinstance(self.z_cut, Decimal):
  5081. z_cut = self.z_cut
  5082. else:
  5083. z_cut = Decimal(self.z_cut).quantize(Decimal('0.000000001'))
  5084. if self.z_depthpercut is None:
  5085. self.z_depthpercut = z_cut
  5086. elif not isinstance(self.z_depthpercut, Decimal):
  5087. self.z_depthpercut = Decimal(self.z_depthpercut).quantize(Decimal('0.000000001'))
  5088. depth = 0
  5089. reverse = False
  5090. while depth > z_cut:
  5091. # Increase depth. Limit to z_cut.
  5092. depth -= self.z_depthpercut
  5093. if depth < z_cut:
  5094. depth = z_cut
  5095. # Cut at specific depth and do not lift the tool.
  5096. # Note: linear2gcode() will use G00 to move to the first point in the path, but it should be already
  5097. # at the first point if the tool is down (in the material). So, an extra G00 should show up but
  5098. # is inconsequential.
  5099. if type(geometry) == LineString or type(geometry) == LinearRing:
  5100. if extracut is False or not geometry.is_ring:
  5101. gcode_multi_pass += self.linear2gcode(geometry, cdia, tolerance=tolerance, z_cut=depth, up=False,
  5102. z_move=z_move, old_point=old_point)
  5103. else:
  5104. gcode_multi_pass += self.linear2gcode_extra(geometry, cdia, extracut_length, tolerance=tolerance,
  5105. z_move=z_move, z_cut=depth, up=False,
  5106. old_point=old_point)
  5107. # Ignore multi-pass for points.
  5108. elif type(geometry) == Point:
  5109. gcode_multi_pass += self.point2gcode(geometry, cdia, z_move=z_move, old_point=old_point)
  5110. break # Ignoring ...
  5111. else:
  5112. log.warning("G-code generation not implemented for %s" % (str(type(geometry))))
  5113. # Reverse coordinates if not a loop so we can continue cutting without returning to the beginning.
  5114. if type(geometry) == LineString:
  5115. geometry.coords = list(geometry.coords)[::-1]
  5116. reverse = True
  5117. # If geometry is reversed, revert.
  5118. if reverse:
  5119. if type(geometry) == LineString:
  5120. geometry.coords = list(geometry.coords)[::-1]
  5121. # Lift the tool
  5122. gcode_multi_pass += self.doformat(p.lift_code, x=old_point[0], y=old_point[1])
  5123. return gcode_multi_pass
  5124. def codes_split(self, gline):
  5125. """
  5126. Parses a line of G-Code such as "G01 X1234 Y987" into
  5127. a dictionary: {'G': 1.0, 'X': 1234.0, 'Y': 987.0}
  5128. :param gline: G-Code line string
  5129. :type gline: str
  5130. :return: Dictionary with parsed line.
  5131. :rtype: dict
  5132. """
  5133. command = {}
  5134. if 'Roland' in self.pp_excellon_name or 'Roland' in self.pp_geometry_name:
  5135. match_z = re.search(r"^Z(\s*-?\d+\.\d+?),(\s*\s*-?\d+\.\d+?),(\s*\s*-?\d+\.\d+?)*;$", gline)
  5136. if match_z:
  5137. command['G'] = 0
  5138. command['X'] = float(match_z.group(1).replace(" ", "")) * 0.025
  5139. command['Y'] = float(match_z.group(2).replace(" ", "")) * 0.025
  5140. command['Z'] = float(match_z.group(3).replace(" ", "")) * 0.025
  5141. elif 'hpgl' in self.pp_excellon_name or 'hpgl' in self.pp_geometry_name:
  5142. match_pa = re.search(r"^PA(\s*-?\d+\.\d+?),(\s*\s*-?\d+\.\d+?)*;$", gline)
  5143. if match_pa:
  5144. command['G'] = 0
  5145. command['X'] = float(match_pa.group(1).replace(" ", "")) / 40
  5146. command['Y'] = float(match_pa.group(2).replace(" ", "")) / 40
  5147. match_pen = re.search(r"^(P[U|D])", gline)
  5148. if match_pen:
  5149. if match_pen.group(1) == 'PU':
  5150. # the value does not matter, only that it is positive so the gcode_parse() know it is > 0,
  5151. # therefore the move is of kind T (travel)
  5152. command['Z'] = 1
  5153. else:
  5154. command['Z'] = 0
  5155. elif 'laser' in self.pp_excellon_name.lower() or 'laser' in self.pp_geometry_name.lower() or \
  5156. (self.pp_solderpaste_name is not None and 'paste' in self.pp_solderpaste_name.lower()):
  5157. match_lsr = re.search(r"X([\+-]?\d+.[\+-]?\d+)\s*Y([\+-]?\d+.[\+-]?\d+)", gline)
  5158. if match_lsr:
  5159. command['X'] = float(match_lsr.group(1).replace(" ", ""))
  5160. command['Y'] = float(match_lsr.group(2).replace(" ", ""))
  5161. match_lsr_pos = re.search(r"^(M0?[3-5])", gline)
  5162. if match_lsr_pos:
  5163. if 'M05' in match_lsr_pos.group(1) or 'M5' in match_lsr_pos.group(1):
  5164. # the value does not matter, only that it is positive so the gcode_parse() know it is > 0,
  5165. # therefore the move is of kind T (travel)
  5166. command['Z'] = 1
  5167. else:
  5168. command['Z'] = 0
  5169. match_lsr_pos_2 = re.search(r"^(M10[6|7])", gline)
  5170. if match_lsr_pos_2:
  5171. if 'M107' in match_lsr_pos_2.group(1):
  5172. command['Z'] = 1
  5173. else:
  5174. command['Z'] = 0
  5175. elif self.pp_solderpaste_name is not None:
  5176. if 'Paste' in self.pp_solderpaste_name:
  5177. match_paste = re.search(r"X([\+-]?\d+.[\+-]?\d+)\s*Y([\+-]?\d+.[\+-]?\d+)", gline)
  5178. if match_paste:
  5179. command['X'] = float(match_paste.group(1).replace(" ", ""))
  5180. command['Y'] = float(match_paste.group(2).replace(" ", ""))
  5181. else:
  5182. match = re.search(r'^\s*([A-Z])\s*([\+\-\.\d\s]+)', gline)
  5183. while match:
  5184. command[match.group(1)] = float(match.group(2).replace(" ", ""))
  5185. gline = gline[match.end():]
  5186. match = re.search(r'^\s*([A-Z])\s*([\+\-\.\d\s]+)', gline)
  5187. return command
  5188. def gcode_parse(self, force_parsing=None):
  5189. """
  5190. G-Code parser (from self.gcode). Generates dictionary with
  5191. single-segment LineString's and "kind" indicating cut or travel,
  5192. fast or feedrate speed.
  5193. Will return a list of dict in the format:
  5194. {
  5195. "geom": LineString(path),
  5196. "kind": kind
  5197. }
  5198. where kind can be either ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  5199. :param force_parsing:
  5200. :type force_parsing:
  5201. :return:
  5202. :rtype: dict
  5203. """
  5204. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  5205. # Results go here
  5206. geometry = []
  5207. # Last known instruction
  5208. current = {'X': 0.0, 'Y': 0.0, 'Z': 0.0, 'G': 0}
  5209. # Current path: temporary storage until tool is
  5210. # lifted or lowered.
  5211. if self.toolchange_xy_type == "excellon":
  5212. if self.app.defaults["excellon_toolchangexy"] == '' or self.app.defaults["excellon_toolchangexy"] is None:
  5213. pos_xy = (0, 0)
  5214. else:
  5215. pos_xy = self.app.defaults["excellon_toolchangexy"]
  5216. try:
  5217. pos_xy = [float(eval(a)) for a in pos_xy.split(",")]
  5218. except Exception:
  5219. if len(pos_xy) != 2:
  5220. pos_xy = (0, 0)
  5221. else:
  5222. if self.app.defaults["geometry_toolchangexy"] == '' or self.app.defaults["geometry_toolchangexy"] is None:
  5223. pos_xy = (0, 0)
  5224. else:
  5225. pos_xy = self.app.defaults["geometry_toolchangexy"]
  5226. try:
  5227. pos_xy = [float(eval(a)) for a in pos_xy.split(",")]
  5228. except Exception:
  5229. if len(pos_xy) != 2:
  5230. pos_xy = (0, 0)
  5231. path = [pos_xy]
  5232. # path = [(0, 0)]
  5233. gcode_lines_list = self.gcode.splitlines()
  5234. self.app.inform.emit('%s: %d' % (_("Parsing GCode file. Number of lines"), len(gcode_lines_list)))
  5235. # Process every instruction
  5236. for line in gcode_lines_list:
  5237. if force_parsing is False or force_parsing is None:
  5238. if '%MO' in line or '%' in line or 'MOIN' in line or 'MOMM' in line:
  5239. return "fail"
  5240. gobj = self.codes_split(line)
  5241. # ## Units
  5242. if 'G' in gobj and (gobj['G'] == 20.0 or gobj['G'] == 21.0):
  5243. self.units = {20.0: "IN", 21.0: "MM"}[gobj['G']]
  5244. continue
  5245. # TODO take into consideration the tools and update the travel line thickness
  5246. if 'T' in gobj:
  5247. pass
  5248. # ## Changing height
  5249. if 'Z' in gobj:
  5250. if 'Roland' in self.pp_excellon_name or 'Roland' in self.pp_geometry_name:
  5251. pass
  5252. elif 'hpgl' in self.pp_excellon_name or 'hpgl' in self.pp_geometry_name:
  5253. pass
  5254. elif 'laser' in self.pp_excellon_name or 'laser' in self.pp_geometry_name:
  5255. pass
  5256. elif ('X' in gobj or 'Y' in gobj) and gobj['Z'] != current['Z']:
  5257. if self.pp_geometry_name == 'line_xyz' or self.pp_excellon_name == 'line_xyz':
  5258. pass
  5259. else:
  5260. log.warning("Non-orthogonal motion: From %s" % str(current))
  5261. log.warning(" To: %s" % str(gobj))
  5262. current['Z'] = gobj['Z']
  5263. # Store the path into geometry and reset path
  5264. if len(path) > 1:
  5265. geometry.append({"geom": LineString(path),
  5266. "kind": kind})
  5267. path = [path[-1]] # Start with the last point of last path.
  5268. # create the geometry for the holes created when drilling Excellon drills
  5269. if self.origin_kind == 'excellon':
  5270. if current['Z'] < 0:
  5271. current_drill_point_coords = (
  5272. float('%.*f' % (self.decimals, current['X'])),
  5273. float('%.*f' % (self.decimals, current['Y']))
  5274. )
  5275. # find the drill diameter knowing the drill coordinates
  5276. break_loop = False
  5277. for tool, tool_dict in self.exc_tools.items():
  5278. if 'drills' in tool_dict:
  5279. for drill_pt in tool_dict['drills']:
  5280. point_in_dict_coords = (
  5281. float('%.*f' % (self.decimals, drill_pt.x)),
  5282. float('%.*f' % (self.decimals, drill_pt.y))
  5283. )
  5284. if point_in_dict_coords == current_drill_point_coords:
  5285. dia = self.exc_tools[tool]['tooldia']
  5286. kind = ['C', 'F']
  5287. geometry.append(
  5288. {
  5289. "geom": Point(current_drill_point_coords).buffer(dia / 2.0).exterior,
  5290. "kind": kind
  5291. }
  5292. )
  5293. break_loop = True
  5294. break
  5295. if break_loop:
  5296. break
  5297. if 'G' in gobj:
  5298. current['G'] = int(gobj['G'])
  5299. if 'X' in gobj or 'Y' in gobj:
  5300. if 'X' in gobj:
  5301. x = gobj['X']
  5302. # current['X'] = x
  5303. else:
  5304. x = current['X']
  5305. if 'Y' in gobj:
  5306. y = gobj['Y']
  5307. else:
  5308. y = current['Y']
  5309. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  5310. if current['Z'] > 0:
  5311. kind[0] = 'T'
  5312. if current['G'] > 0:
  5313. kind[1] = 'S'
  5314. if current['G'] in [0, 1]: # line
  5315. path.append((x, y))
  5316. arcdir = [None, None, "cw", "ccw"]
  5317. if current['G'] in [2, 3]: # arc
  5318. center = [gobj['I'] + current['X'], gobj['J'] + current['Y']]
  5319. radius = np.sqrt(gobj['I'] ** 2 + gobj['J'] ** 2)
  5320. start = np.arctan2(-gobj['J'], -gobj['I'])
  5321. stop = np.arctan2(-center[1] + y, -center[0] + x)
  5322. path += arc(center, radius, start, stop, arcdir[current['G']], int(self.steps_per_circle))
  5323. current['X'] = x
  5324. current['Y'] = y
  5325. # Update current instruction
  5326. for code in gobj:
  5327. current[code] = gobj[code]
  5328. self.app.inform.emit('%s...' % _("Creating Geometry from the parsed GCode file. "))
  5329. # There might not be a change in height at the
  5330. # end, therefore, see here too if there is
  5331. # a final path.
  5332. if len(path) > 1:
  5333. geometry.append(
  5334. {
  5335. "geom": LineString(path),
  5336. "kind": kind
  5337. }
  5338. )
  5339. self.gcode_parsed = geometry
  5340. return geometry
  5341. def excellon_tool_gcode_parse(self, dia, gcode, start_pt=(0, 0), force_parsing=None):
  5342. """
  5343. G-Code parser (from self.exc_cnc_tools['tooldia']['gcode']). Generates dictionary with
  5344. single-segment LineString's and "kind" indicating cut or travel,
  5345. fast or feedrate speed.
  5346. Will return the Geometry as a list of dict in the format:
  5347. {
  5348. "geom": LineString(path),
  5349. "kind": kind
  5350. }
  5351. where kind can be either ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  5352. :param dia: the dia is a tool diameter which is the key in self.exc_cnc_tools dict
  5353. :type dia: float
  5354. :param gcode: Gcode to parse
  5355. :type gcode: str
  5356. :param start_pt: the point coordinates from where to start the parsing
  5357. :type start_pt: tuple
  5358. :param force_parsing:
  5359. :type force_parsing: bool
  5360. :return: Geometry as a list of dictionaries
  5361. :rtype: list
  5362. """
  5363. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  5364. # Results go here
  5365. geometry = []
  5366. # Last known instruction
  5367. current = {'X': 0.0, 'Y': 0.0, 'Z': 0.0, 'G': 0}
  5368. # Current path: temporary storage until tool is
  5369. # lifted or lowered.
  5370. pos_xy = start_pt
  5371. path = [pos_xy]
  5372. # path = [(0, 0)]
  5373. gcode_lines_list = gcode.splitlines()
  5374. self.app.inform.emit(
  5375. '%s: %s. %s: %d' % (_("Parsing GCode file for tool diameter"),
  5376. str(dia), _("Number of lines"),
  5377. len(gcode_lines_list))
  5378. )
  5379. # Process every instruction
  5380. for line in gcode_lines_list:
  5381. if force_parsing is False or force_parsing is None:
  5382. if '%MO' in line or '%' in line or 'MOIN' in line or 'MOMM' in line:
  5383. return "fail"
  5384. gobj = self.codes_split(line)
  5385. # ## Units
  5386. if 'G' in gobj and (gobj['G'] == 20.0 or gobj['G'] == 21.0):
  5387. self.units = {20.0: "IN", 21.0: "MM"}[gobj['G']]
  5388. continue
  5389. # TODO take into consideration the tools and update the travel line thickness
  5390. if 'T' in gobj:
  5391. pass
  5392. # ## Changing height
  5393. if 'Z' in gobj:
  5394. if 'Roland' in self.pp_excellon_name or 'Roland' in self.pp_geometry_name:
  5395. pass
  5396. elif 'hpgl' in self.pp_excellon_name or 'hpgl' in self.pp_geometry_name:
  5397. pass
  5398. elif 'laser' in self.pp_excellon_name or 'laser' in self.pp_geometry_name:
  5399. pass
  5400. elif ('X' in gobj or 'Y' in gobj) and gobj['Z'] != current['Z']:
  5401. if self.pp_geometry_name == 'line_xyz' or self.pp_excellon_name == 'line_xyz':
  5402. pass
  5403. else:
  5404. log.warning("Non-orthogonal motion: From %s" % str(current))
  5405. log.warning(" To: %s" % str(gobj))
  5406. current['Z'] = gobj['Z']
  5407. # Store the path into geometry and reset path
  5408. if len(path) > 1:
  5409. geometry.append({"geom": LineString(path),
  5410. "kind": kind})
  5411. path = [path[-1]] # Start with the last point of last path.
  5412. # create the geometry for the holes created when drilling Excellon drills
  5413. if current['Z'] < 0:
  5414. current_drill_point_coords = (
  5415. float('%.*f' % (self.decimals, current['X'])),
  5416. float('%.*f' % (self.decimals, current['Y']))
  5417. )
  5418. kind = ['C', 'F']
  5419. geometry.append(
  5420. {
  5421. "geom": Point(current_drill_point_coords).buffer(dia/2.0).exterior,
  5422. "kind": kind
  5423. }
  5424. )
  5425. if 'G' in gobj:
  5426. current['G'] = int(gobj['G'])
  5427. if 'X' in gobj or 'Y' in gobj:
  5428. x = gobj['X'] if 'X' in gobj else current['X']
  5429. y = gobj['Y'] if 'Y' in gobj else current['Y']
  5430. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  5431. if current['Z'] > 0:
  5432. kind[0] = 'T'
  5433. if current['G'] > 0:
  5434. kind[1] = 'S'
  5435. if current['G'] in [0, 1]: # line
  5436. path.append((x, y))
  5437. arcdir = [None, None, "cw", "ccw"]
  5438. if current['G'] in [2, 3]: # arc
  5439. center = [gobj['I'] + current['X'], gobj['J'] + current['Y']]
  5440. radius = np.sqrt(gobj['I'] ** 2 + gobj['J'] ** 2)
  5441. start = np.arctan2(-gobj['J'], -gobj['I'])
  5442. stop = np.arctan2(-center[1] + y, -center[0] + x)
  5443. path += arc(center, radius, start, stop, arcdir[current['G']], int(self.steps_per_circle))
  5444. current['X'] = x
  5445. current['Y'] = y
  5446. # Update current instruction
  5447. for code in gobj:
  5448. current[code] = gobj[code]
  5449. self.app.inform.emit('%s: %s' % (_("Creating Geometry from the parsed GCode file for tool diameter"), str(dia)))
  5450. # There might not be a change in height at the end, therefore, see here too if there is a final path.
  5451. if len(path) > 1:
  5452. geometry.append(
  5453. {
  5454. "geom": LineString(path),
  5455. "kind": kind
  5456. }
  5457. )
  5458. return geometry
  5459. # def plot(self, tooldia=None, dpi=75, margin=0.1,
  5460. # color={"T": ["#F0E24D", "#B5AB3A"], "C": ["#5E6CFF", "#4650BD"]},
  5461. # alpha={"T": 0.3, "C": 1.0}):
  5462. # """
  5463. # Creates a Matplotlib figure with a plot of the
  5464. # G-code job.
  5465. # """
  5466. # if tooldia is None:
  5467. # tooldia = self.tooldia
  5468. #
  5469. # fig = Figure(dpi=dpi)
  5470. # ax = fig.add_subplot(111)
  5471. # ax.set_aspect(1)
  5472. # xmin, ymin, xmax, ymax = self.input_geometry_bounds
  5473. # ax.set_xlim(xmin-margin, xmax+margin)
  5474. # ax.set_ylim(ymin-margin, ymax+margin)
  5475. #
  5476. # if tooldia == 0:
  5477. # for geo in self.gcode_parsed:
  5478. # linespec = '--'
  5479. # linecolor = color[geo['kind'][0]][1]
  5480. # if geo['kind'][0] == 'C':
  5481. # linespec = 'k-'
  5482. # x, y = geo['geom'].coords.xy
  5483. # ax.plot(x, y, linespec, color=linecolor)
  5484. # else:
  5485. # for geo in self.gcode_parsed:
  5486. # poly = geo['geom'].buffer(tooldia/2.0)
  5487. # patch = PolygonPatch(poly, facecolor=color[geo['kind'][0]][0],
  5488. # edgecolor=color[geo['kind'][0]][1],
  5489. # alpha=alpha[geo['kind'][0]], zorder=2)
  5490. # ax.add_patch(patch)
  5491. #
  5492. # return fig
  5493. def plot2(self, tooldia=None, dpi=75, margin=0.1, gcode_parsed=None,
  5494. color=None, alpha={"T": 0.3, "C": 1.0}, tool_tolerance=0.0005, obj=None, visible=False, kind='all'):
  5495. """
  5496. Plots the G-code job onto the given axes.
  5497. :param tooldia: Tool diameter.
  5498. :type tooldia: float
  5499. :param dpi: Not used!
  5500. :type dpi: float
  5501. :param margin: Not used!
  5502. :type margin: float
  5503. :param gcode_parsed: Parsed Gcode
  5504. :type gcode_parsed: str
  5505. :param color: Color specification.
  5506. :type color: str
  5507. :param alpha: Transparency specification.
  5508. :type alpha: dict
  5509. :param tool_tolerance: Tolerance when drawing the toolshape.
  5510. :type tool_tolerance: float
  5511. :param obj: The object for whih to plot
  5512. :type obj: class
  5513. :param visible: Visibility status
  5514. :type visible: bool
  5515. :param kind: Can be: "travel", "cut", "all"
  5516. :type kind: str
  5517. :return: None
  5518. :rtype:
  5519. """
  5520. # units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5521. if color is None:
  5522. color = {
  5523. "T": [self.app.defaults["cncjob_travel_fill"], self.app.defaults["cncjob_travel_line"]],
  5524. "C": [self.app.defaults["cncjob_plot_fill"], self.app.defaults["cncjob_plot_line"]]
  5525. }
  5526. gcode_parsed = gcode_parsed if gcode_parsed else self.gcode_parsed
  5527. if tooldia is None:
  5528. tooldia = self.tooldia
  5529. # this should be unlikely unless when upstream the tooldia is a tuple made by one dia and a comma like (2.4,)
  5530. if isinstance(tooldia, list):
  5531. tooldia = tooldia[0] if tooldia[0] is not None else self.tooldia
  5532. if tooldia == 0:
  5533. for geo in gcode_parsed:
  5534. if kind == 'all':
  5535. obj.add_shape(shape=geo['geom'], color=color[geo['kind'][0]][1], visible=visible)
  5536. elif kind == 'travel':
  5537. if geo['kind'][0] == 'T':
  5538. obj.add_shape(shape=geo['geom'], color=color['T'][1], visible=visible)
  5539. elif kind == 'cut':
  5540. if geo['kind'][0] == 'C':
  5541. obj.add_shape(shape=geo['geom'], color=color['C'][1], visible=visible)
  5542. else:
  5543. path_num = 0
  5544. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  5545. if self.coordinates_type == "G90":
  5546. # For Absolute coordinates type G90
  5547. for geo in gcode_parsed:
  5548. if geo['kind'][0] == 'T':
  5549. start_position = geo['geom'].coords[0]
  5550. if tooldia not in obj.annotations_dict:
  5551. obj.annotations_dict[tooldia] = {
  5552. 'pos': [],
  5553. 'text': []
  5554. }
  5555. if start_position not in obj.annotations_dict[tooldia]['pos']:
  5556. path_num += 1
  5557. obj.annotations_dict[tooldia]['pos'].append(start_position)
  5558. obj.annotations_dict[tooldia]['text'].append(str(path_num))
  5559. end_position = geo['geom'].coords[-1]
  5560. if tooldia not in obj.annotations_dict:
  5561. obj.annotations_dict[tooldia] = {
  5562. 'pos': [],
  5563. 'text': []
  5564. }
  5565. if end_position not in obj.annotations_dict[tooldia]['pos']:
  5566. path_num += 1
  5567. obj.annotations_dict[tooldia]['pos'].append(end_position)
  5568. obj.annotations_dict[tooldia]['text'].append(str(path_num))
  5569. # plot the geometry of Excellon objects
  5570. if self.origin_kind == 'excellon':
  5571. try:
  5572. # if the geos are travel lines
  5573. if geo['kind'][0] == 'T':
  5574. poly = geo['geom'].buffer(distance=(tooldia / 1.99999999),
  5575. resolution=self.steps_per_circle)
  5576. else:
  5577. poly = Polygon(geo['geom'])
  5578. poly = poly.simplify(tool_tolerance)
  5579. except Exception:
  5580. # deal here with unexpected plot errors due of LineStrings not valid
  5581. continue
  5582. else:
  5583. # plot the geometry of any objects other than Excellon
  5584. poly = geo['geom'].buffer(distance=(tooldia / 1.99999999), resolution=self.steps_per_circle)
  5585. poly = poly.simplify(tool_tolerance)
  5586. if kind == 'all':
  5587. obj.add_shape(shape=poly, color=color[geo['kind'][0]][1], face_color=color[geo['kind'][0]][0],
  5588. visible=visible, layer=1 if geo['kind'][0] == 'C' else 2)
  5589. elif kind == 'travel':
  5590. if geo['kind'][0] == 'T':
  5591. obj.add_shape(shape=poly, color=color['T'][1], face_color=color['T'][0],
  5592. visible=visible, layer=2)
  5593. elif kind == 'cut':
  5594. if geo['kind'][0] == 'C':
  5595. obj.add_shape(shape=poly, color=color['C'][1], face_color=color['C'][0],
  5596. visible=visible, layer=1)
  5597. else:
  5598. self.app.inform.emit('[ERROR_NOTCL] %s...' % _('G91 coordinates not implemented'))
  5599. return 'fail'
  5600. def plot_annotations(self, obj, visible=True):
  5601. """
  5602. Plot annotations.
  5603. :param obj: FlatCAM CNCJob object for which to plot the annotations
  5604. :type obj:
  5605. :param visible: annotaions visibility
  5606. :type visible: bool
  5607. :return: Nothing
  5608. :rtype:
  5609. """
  5610. if not obj.annotations_dict:
  5611. return
  5612. if visible is True:
  5613. obj.text_col.enabled = True
  5614. else:
  5615. obj.text_col.enabled = False
  5616. return
  5617. text = []
  5618. pos = []
  5619. for tooldia in obj.annotations_dict:
  5620. pos += obj.annotations_dict[tooldia]['pos']
  5621. text += obj.annotations_dict[tooldia]['text']
  5622. if not text or not pos:
  5623. return
  5624. try:
  5625. if self.app.defaults['global_theme'] == 'white':
  5626. obj.annotation.set(text=text, pos=pos, visible=obj.options['plot'],
  5627. font_size=self.app.defaults["cncjob_annotation_fontsize"],
  5628. color=self.app.defaults["cncjob_annotation_fontcolor"])
  5629. else:
  5630. # invert the color
  5631. old_color = self.app.defaults["cncjob_annotation_fontcolor"].lower()
  5632. new_color = ''
  5633. code = {}
  5634. l1 = "#;0123456789abcdef"
  5635. l2 = "#;fedcba9876543210"
  5636. for i in range(len(l1)):
  5637. code[l1[i]] = l2[i]
  5638. for x in range(len(old_color)):
  5639. new_color += code[old_color[x]]
  5640. obj.annotation.set(text=text, pos=pos, visible=obj.options['plot'],
  5641. font_size=self.app.defaults["cncjob_annotation_fontsize"],
  5642. color=new_color)
  5643. except Exception as e:
  5644. log.debug("CNCJob.plot2() --> annotations --> %s" % str(e))
  5645. if self.app.is_legacy is False:
  5646. obj.annotation.clear(update=True)
  5647. obj.annotation.redraw()
  5648. def create_geometry(self):
  5649. """
  5650. It is used by the Excellon objects. Will create the solid_geometry which will be an attribute of the
  5651. Excellon object class.
  5652. :return: List of Shapely geometry elements
  5653. :rtype: list
  5654. """
  5655. # TODO: This takes forever. Too much data?
  5656. # self.app.inform.emit('%s: %s' % (_("Unifying Geometry from parsed Geometry segments"),
  5657. # str(len(self.gcode_parsed))))
  5658. # self.solid_geometry = cascaded_union([geo['geom'] for geo in self.gcode_parsed])
  5659. # This is much faster but not so nice to look at as you can see different segments of the geometry
  5660. self.solid_geometry = [geo['geom'] for geo in self.gcode_parsed]
  5661. return self.solid_geometry
  5662. def segment(self, coords):
  5663. """
  5664. Break long linear lines to make it more auto level friendly.
  5665. Code snippet added by Lei Zheng in a rejected pull request on FlatCAM https://bitbucket.org/realthunder/
  5666. :param coords: List of coordinates tuples
  5667. :type coords: list
  5668. :return: A path; list with the multiple coordinates breaking a line.
  5669. :rtype: list
  5670. """
  5671. if len(coords) < 2 or self.segx <= 0 and self.segy <= 0:
  5672. return list(coords)
  5673. path = [coords[0]]
  5674. # break the line in either x or y dimension only
  5675. def linebreak_single(line, dim, dmax):
  5676. if dmax <= 0:
  5677. return None
  5678. if line[1][dim] > line[0][dim]:
  5679. sign = 1.0
  5680. d = line[1][dim] - line[0][dim]
  5681. else:
  5682. sign = -1.0
  5683. d = line[0][dim] - line[1][dim]
  5684. if d > dmax:
  5685. # make sure we don't make any new lines too short
  5686. if d > dmax * 2:
  5687. dd = dmax
  5688. else:
  5689. dd = d / 2
  5690. other = dim ^ 1
  5691. return (line[0][dim] + dd * sign, line[0][other] + \
  5692. dd * (line[1][other] - line[0][other]) / d)
  5693. return None
  5694. # recursively breaks down a given line until it is within the
  5695. # required step size
  5696. def linebreak(line):
  5697. pt_new = linebreak_single(line, 0, self.segx)
  5698. if pt_new is None:
  5699. pt_new2 = linebreak_single(line, 1, self.segy)
  5700. else:
  5701. pt_new2 = linebreak_single((line[0], pt_new), 1, self.segy)
  5702. if pt_new2 is not None:
  5703. pt_new = pt_new2[::-1]
  5704. if pt_new is None:
  5705. path.append(line[1])
  5706. else:
  5707. path.append(pt_new)
  5708. linebreak((pt_new, line[1]))
  5709. for pt in coords[1:]:
  5710. linebreak((path[-1], pt))
  5711. return path
  5712. def linear2gcode(self, linear, dia, tolerance=0, down=True, up=True, z_cut=None, z_move=None, zdownrate=None,
  5713. feedrate=None, feedrate_z=None, feedrate_rapid=None, cont=False, old_point=(0, 0)):
  5714. """
  5715. Generates G-code to cut along the linear feature.
  5716. :param linear: The path to cut along.
  5717. :type: Shapely.LinearRing or Shapely.Linear String
  5718. :param dia: The tool diameter that is going on the path
  5719. :type dia: float
  5720. :param tolerance: All points in the simplified object will be within the
  5721. tolerance distance of the original geometry.
  5722. :type tolerance: float
  5723. :param down:
  5724. :param up:
  5725. :param z_cut:
  5726. :param z_move:
  5727. :param zdownrate:
  5728. :param feedrate: speed for cut on X - Y plane
  5729. :param feedrate_z: speed for cut on Z plane
  5730. :param feedrate_rapid: speed to move between cuts; usually is G0 but some CNC require to specify it
  5731. :param cont:
  5732. :param old_point:
  5733. :return: G-code to cut along the linear feature.
  5734. """
  5735. if z_cut is None:
  5736. z_cut = self.z_cut
  5737. if z_move is None:
  5738. z_move = self.z_move
  5739. #
  5740. # if zdownrate is None:
  5741. # zdownrate = self.zdownrate
  5742. if feedrate is None:
  5743. feedrate = self.feedrate
  5744. if feedrate_z is None:
  5745. feedrate_z = self.z_feedrate
  5746. if feedrate_rapid is None:
  5747. feedrate_rapid = self.feedrate_rapid
  5748. # Simplify paths?
  5749. if tolerance > 0:
  5750. target_linear = linear.simplify(tolerance)
  5751. else:
  5752. target_linear = linear
  5753. gcode = ""
  5754. # path = list(target_linear.coords)
  5755. path = self.segment(target_linear.coords)
  5756. p = self.pp_geometry
  5757. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  5758. if self.coordinates_type == "G90":
  5759. # For Absolute coordinates type G90
  5760. first_x = path[0][0]
  5761. first_y = path[0][1]
  5762. else:
  5763. # For Incremental coordinates type G91
  5764. first_x = path[0][0] - old_point[0]
  5765. first_y = path[0][1] - old_point[1]
  5766. # Move fast to 1st point
  5767. if not cont:
  5768. current_tooldia = dia
  5769. travels = self.app.exc_areas.travel_coordinates(start_point=(old_point[0], old_point[1]),
  5770. end_point=(first_x, first_y),
  5771. tooldia=current_tooldia)
  5772. prev_z = None
  5773. for travel in travels:
  5774. locx = travel[1][0]
  5775. locy = travel[1][1]
  5776. if travel[0] is not None:
  5777. # move to next point
  5778. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  5779. # raise to safe Z (travel[0]) each time because safe Z may be different
  5780. self.z_move = travel[0]
  5781. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  5782. # restore z_move
  5783. self.z_move = z_move
  5784. else:
  5785. if prev_z is not None:
  5786. # move to next point
  5787. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  5788. # we assume that previously the z_move was altered therefore raise to
  5789. # the travel_z (z_move)
  5790. self.z_move = z_move
  5791. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  5792. else:
  5793. # move to next point
  5794. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  5795. # store prev_z
  5796. prev_z = travel[0]
  5797. # gcode += self.doformat(p.rapid_code, x=first_x, y=first_y) # Move to first point
  5798. # Move down to cutting depth
  5799. if down:
  5800. # Different feedrate for vertical cut?
  5801. gcode += self.doformat(p.z_feedrate_code)
  5802. # gcode += self.doformat(p.feedrate_code)
  5803. gcode += self.doformat(p.down_code, x=first_x, y=first_y, z_cut=z_cut)
  5804. gcode += self.doformat(p.feedrate_code, feedrate=feedrate)
  5805. # Cutting...
  5806. prev_x = first_x
  5807. prev_y = first_y
  5808. for pt in path[1:]:
  5809. if self.app.abort_flag:
  5810. # graceful abort requested by the user
  5811. raise grace
  5812. if self.coordinates_type == "G90":
  5813. # For Absolute coordinates type G90
  5814. next_x = pt[0]
  5815. next_y = pt[1]
  5816. else:
  5817. # For Incremental coordinates type G91
  5818. # next_x = pt[0] - prev_x
  5819. # next_y = pt[1] - prev_y
  5820. self.app.inform.emit('[ERROR_NOTCL] %s' % _('G91 coordinates not implemented ...'))
  5821. next_x = pt[0]
  5822. next_y = pt[1]
  5823. gcode += self.doformat(p.linear_code, x=next_x, y=next_y, z=z_cut) # Linear motion to point
  5824. prev_x = pt[0]
  5825. prev_y = pt[1]
  5826. # Up to travelling height.
  5827. if up:
  5828. gcode += self.doformat(p.lift_code, x=prev_x, y=prev_y, z_move=z_move) # Stop cutting
  5829. return gcode
  5830. def linear2gcode_extra(self, linear, dia, extracut_length, tolerance=0, down=True, up=True,
  5831. z_cut=None, z_move=None, zdownrate=None,
  5832. feedrate=None, feedrate_z=None, feedrate_rapid=None, cont=False, old_point=(0, 0)):
  5833. """
  5834. Generates G-code to cut along the linear feature.
  5835. :param linear: The path to cut along.
  5836. :type: Shapely.LinearRing or Shapely.Linear String
  5837. :param dia: The tool diameter that is going on the path
  5838. :type dia: float
  5839. :param extracut_length: how much to cut extra over the first point at the end of the path
  5840. :param tolerance: All points in the simplified object will be within the
  5841. tolerance distance of the original geometry.
  5842. :type tolerance: float
  5843. :param down:
  5844. :param up:
  5845. :param z_cut:
  5846. :param z_move:
  5847. :param zdownrate:
  5848. :param feedrate: speed for cut on X - Y plane
  5849. :param feedrate_z: speed for cut on Z plane
  5850. :param feedrate_rapid: speed to move between cuts; usually is G0 but some CNC require to specify it
  5851. :param cont:
  5852. :param old_point:
  5853. :return: G-code to cut along the linear feature.
  5854. :rtype: str
  5855. """
  5856. if z_cut is None:
  5857. z_cut = self.z_cut
  5858. if z_move is None:
  5859. z_move = self.z_move
  5860. #
  5861. # if zdownrate is None:
  5862. # zdownrate = self.zdownrate
  5863. if feedrate is None:
  5864. feedrate = self.feedrate
  5865. if feedrate_z is None:
  5866. feedrate_z = self.z_feedrate
  5867. if feedrate_rapid is None:
  5868. feedrate_rapid = self.feedrate_rapid
  5869. # Simplify paths?
  5870. if tolerance > 0:
  5871. target_linear = linear.simplify(tolerance)
  5872. else:
  5873. target_linear = linear
  5874. gcode = ""
  5875. path = list(target_linear.coords)
  5876. p = self.pp_geometry
  5877. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  5878. if self.coordinates_type == "G90":
  5879. # For Absolute coordinates type G90
  5880. first_x = path[0][0]
  5881. first_y = path[0][1]
  5882. else:
  5883. # For Incremental coordinates type G91
  5884. first_x = path[0][0] - old_point[0]
  5885. first_y = path[0][1] - old_point[1]
  5886. # Move fast to 1st point
  5887. if not cont:
  5888. current_tooldia = dia
  5889. travels = self.app.exc_areas.travel_coordinates(start_point=(old_point[0], old_point[1]),
  5890. end_point=(first_x, first_y),
  5891. tooldia=current_tooldia)
  5892. prev_z = None
  5893. for travel in travels:
  5894. locx = travel[1][0]
  5895. locy = travel[1][1]
  5896. if travel[0] is not None:
  5897. # move to next point
  5898. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  5899. # raise to safe Z (travel[0]) each time because safe Z may be different
  5900. self.z_move = travel[0]
  5901. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  5902. # restore z_move
  5903. self.z_move = z_move
  5904. else:
  5905. if prev_z is not None:
  5906. # move to next point
  5907. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  5908. # we assume that previously the z_move was altered therefore raise to
  5909. # the travel_z (z_move)
  5910. self.z_move = z_move
  5911. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  5912. else:
  5913. # move to next point
  5914. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  5915. # store prev_z
  5916. prev_z = travel[0]
  5917. # gcode += self.doformat(p.rapid_code, x=first_x, y=first_y) # Move to first point
  5918. # Move down to cutting depth
  5919. if down:
  5920. # Different feedrate for vertical cut?
  5921. if self.z_feedrate is not None:
  5922. gcode += self.doformat(p.z_feedrate_code)
  5923. # gcode += self.doformat(p.feedrate_code)
  5924. gcode += self.doformat(p.down_code, x=first_x, y=first_y, z_cut=z_cut)
  5925. gcode += self.doformat(p.feedrate_code, feedrate=feedrate)
  5926. else:
  5927. gcode += self.doformat(p.down_code, x=first_x, y=first_y, z_cut=z_cut) # Start cutting
  5928. # Cutting...
  5929. prev_x = first_x
  5930. prev_y = first_y
  5931. for pt in path[1:]:
  5932. if self.app.abort_flag:
  5933. # graceful abort requested by the user
  5934. raise grace
  5935. if self.coordinates_type == "G90":
  5936. # For Absolute coordinates type G90
  5937. next_x = pt[0]
  5938. next_y = pt[1]
  5939. else:
  5940. # For Incremental coordinates type G91
  5941. # For Incremental coordinates type G91
  5942. # next_x = pt[0] - prev_x
  5943. # next_y = pt[1] - prev_y
  5944. self.app.inform.emit('[ERROR_NOTCL] %s' % _('G91 coordinates not implemented ...'))
  5945. next_x = pt[0]
  5946. next_y = pt[1]
  5947. gcode += self.doformat(p.linear_code, x=next_x, y=next_y, z=z_cut) # Linear motion to point
  5948. prev_x = next_x
  5949. prev_y = next_y
  5950. # this line is added to create an extra cut over the first point in patch
  5951. # to make sure that we remove the copper leftovers
  5952. # Linear motion to the 1st point in the cut path
  5953. # if self.coordinates_type == "G90":
  5954. # # For Absolute coordinates type G90
  5955. # last_x = path[1][0]
  5956. # last_y = path[1][1]
  5957. # else:
  5958. # # For Incremental coordinates type G91
  5959. # last_x = path[1][0] - first_x
  5960. # last_y = path[1][1] - first_y
  5961. # gcode += self.doformat(p.linear_code, x=last_x, y=last_y)
  5962. # the first point for extracut is always mandatory if the extracut is enabled. But if the length of distance
  5963. # between point 0 and point 1 is more than the distance we set for the extra cut then make an interpolation
  5964. # along the path and find the point at the distance extracut_length
  5965. if extracut_length == 0.0:
  5966. extra_path = [path[-1], path[0], path[1]]
  5967. new_x = extra_path[0][0]
  5968. new_y = extra_path[0][1]
  5969. # this is an extra line therefore lift the milling bit
  5970. gcode += self.doformat(p.lift_code, x=prev_x, y=prev_y, z_move=z_move) # lift
  5971. # move fast to the new first point
  5972. gcode += self.doformat(p.rapid_code, x=new_x, y=new_y)
  5973. # lower the milling bit
  5974. # Different feedrate for vertical cut?
  5975. if self.z_feedrate is not None:
  5976. gcode += self.doformat(p.z_feedrate_code)
  5977. gcode += self.doformat(p.down_code, x=new_x, y=new_y, z_cut=z_cut)
  5978. gcode += self.doformat(p.feedrate_code, feedrate=feedrate)
  5979. else:
  5980. gcode += self.doformat(p.down_code, x=new_x, y=new_y, z_cut=z_cut) # Start cutting
  5981. # start cutting the extra line
  5982. last_pt = extra_path[0]
  5983. for pt in extra_path[1:]:
  5984. gcode += self.doformat(p.linear_code, x=pt[0], y=pt[1])
  5985. last_pt = pt
  5986. # go back to the original point
  5987. gcode += self.doformat(p.linear_code, x=path[0][0], y=path[0][1])
  5988. last_pt = path[0]
  5989. else:
  5990. # go to the point that is 5% in length before the end (therefore 95% length from start of the line),
  5991. # along the line to be cut
  5992. if extracut_length >= target_linear.length:
  5993. extracut_length = target_linear.length
  5994. # ---------------------------------------------
  5995. # first half
  5996. # ---------------------------------------------
  5997. start_length = target_linear.length - (extracut_length * 0.5)
  5998. extra_line = substring(target_linear, start_length, target_linear.length)
  5999. extra_path = list(extra_line.coords)
  6000. new_x = extra_path[0][0]
  6001. new_y = extra_path[0][1]
  6002. # this is an extra line therefore lift the milling bit
  6003. gcode += self.doformat(p.lift_code, x=prev_x, y=prev_y, z_move=z_move) # lift
  6004. # move fast to the new first point
  6005. gcode += self.doformat(p.rapid_code, x=new_x, y=new_y)
  6006. # lower the milling bit
  6007. # Different feedrate for vertical cut?
  6008. if self.z_feedrate is not None:
  6009. gcode += self.doformat(p.z_feedrate_code)
  6010. gcode += self.doformat(p.down_code, x=new_x, y=new_y, z_cut=z_cut)
  6011. gcode += self.doformat(p.feedrate_code, feedrate=feedrate)
  6012. else:
  6013. gcode += self.doformat(p.down_code, x=new_x, y=new_y, z_cut=z_cut) # Start cutting
  6014. # start cutting the extra line
  6015. for pt in extra_path[1:]:
  6016. gcode += self.doformat(p.linear_code, x=pt[0], y=pt[1])
  6017. # ---------------------------------------------
  6018. # second half
  6019. # ---------------------------------------------
  6020. extra_line = substring(target_linear, 0, (extracut_length * 0.5))
  6021. extra_path = list(extra_line.coords)
  6022. # start cutting the extra line
  6023. last_pt = extra_path[0]
  6024. for pt in extra_path[1:]:
  6025. gcode += self.doformat(p.linear_code, x=pt[0], y=pt[1])
  6026. last_pt = pt
  6027. # ---------------------------------------------
  6028. # back to original start point, cutting
  6029. # ---------------------------------------------
  6030. extra_line = substring(target_linear, 0, (extracut_length * 0.5))
  6031. extra_path = list(extra_line.coords)[::-1]
  6032. # start cutting the extra line
  6033. last_pt = extra_path[0]
  6034. for pt in extra_path[1:]:
  6035. gcode += self.doformat(p.linear_code, x=pt[0], y=pt[1])
  6036. last_pt = pt
  6037. # if extracut_length == 0.0:
  6038. # gcode += self.doformat(p.linear_code, x=path[1][0], y=path[1][1])
  6039. # last_pt = path[1]
  6040. # else:
  6041. # if abs(distance(path[1], path[0])) > extracut_length:
  6042. # i_point = LineString([path[0], path[1]]).interpolate(extracut_length)
  6043. # gcode += self.doformat(p.linear_code, x=i_point.x, y=i_point.y)
  6044. # last_pt = (i_point.x, i_point.y)
  6045. # else:
  6046. # last_pt = path[0]
  6047. # for pt in path[1:]:
  6048. # extracut_distance = abs(distance(pt, last_pt))
  6049. # if extracut_distance <= extracut_length:
  6050. # gcode += self.doformat(p.linear_code, x=pt[0], y=pt[1])
  6051. # last_pt = pt
  6052. # else:
  6053. # break
  6054. # Up to travelling height.
  6055. if up:
  6056. gcode += self.doformat(p.lift_code, x=last_pt[0], y=last_pt[1], z_move=z_move) # Stop cutting
  6057. return gcode
  6058. def point2gcode(self, point, dia, z_move=None, old_point=(0, 0)):
  6059. """
  6060. :param point: A Shapely Point
  6061. :type point: Point
  6062. :param dia: The tool diameter that is going on the path
  6063. :type dia: float
  6064. :param z_move: Travel Z
  6065. :type z_move: float
  6066. :param old_point: Old point coordinates from which we moved to the 'point'
  6067. :type old_point: tuple
  6068. :return: G-code to cut on the Point feature.
  6069. :rtype: str
  6070. """
  6071. gcode = ""
  6072. if self.app.abort_flag:
  6073. # graceful abort requested by the user
  6074. raise grace
  6075. path = list(point.coords)
  6076. p = self.pp_geometry
  6077. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  6078. if self.coordinates_type == "G90":
  6079. # For Absolute coordinates type G90
  6080. first_x = path[0][0]
  6081. first_y = path[0][1]
  6082. else:
  6083. # For Incremental coordinates type G91
  6084. # first_x = path[0][0] - old_point[0]
  6085. # first_y = path[0][1] - old_point[1]
  6086. self.app.inform.emit('[ERROR_NOTCL] %s' %
  6087. _('G91 coordinates not implemented ...'))
  6088. first_x = path[0][0]
  6089. first_y = path[0][1]
  6090. current_tooldia = dia
  6091. travels = self.app.exc_areas.travel_coordinates(start_point=(old_point[0], old_point[1]),
  6092. end_point=(first_x, first_y),
  6093. tooldia=current_tooldia)
  6094. prev_z = None
  6095. for travel in travels:
  6096. locx = travel[1][0]
  6097. locy = travel[1][1]
  6098. if travel[0] is not None:
  6099. # move to next point
  6100. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  6101. # raise to safe Z (travel[0]) each time because safe Z may be different
  6102. self.z_move = travel[0]
  6103. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  6104. # restore z_move
  6105. self.z_move = z_move
  6106. else:
  6107. if prev_z is not None:
  6108. # move to next point
  6109. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  6110. # we assume that previously the z_move was altered therefore raise to
  6111. # the travel_z (z_move)
  6112. self.z_move = z_move
  6113. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  6114. else:
  6115. # move to next point
  6116. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  6117. # store prev_z
  6118. prev_z = travel[0]
  6119. # gcode += self.doformat(p.linear_code, x=first_x, y=first_y) # Move to first point
  6120. if self.z_feedrate is not None:
  6121. gcode += self.doformat(p.z_feedrate_code)
  6122. gcode += self.doformat(p.down_code, x=first_x, y=first_y, z_cut=self.z_cut)
  6123. gcode += self.doformat(p.feedrate_code)
  6124. else:
  6125. gcode += self.doformat(p.down_code, x=first_x, y=first_y, z_cut=self.z_cut) # Start cutting
  6126. gcode += self.doformat(p.lift_code, x=first_x, y=first_y) # Stop cutting
  6127. return gcode
  6128. def export_svg(self, scale_stroke_factor=0.00):
  6129. """
  6130. Exports the CNC Job as a SVG Element
  6131. :param scale_stroke_factor: A factor to scale the SVG geometry
  6132. :type scale_stroke_factor: float
  6133. :return: SVG Element string
  6134. :rtype: str
  6135. """
  6136. # scale_factor is a multiplication factor for the SVG stroke-width used within shapely's svg export
  6137. # If not specified then try and use the tool diameter
  6138. # This way what is on screen will match what is outputed for the svg
  6139. # This is quite a useful feature for svg's used with visicut
  6140. if scale_stroke_factor <= 0:
  6141. scale_stroke_factor = self.options['tooldia'] / 2
  6142. # If still 0 then default to 0.05
  6143. # This value appears to work for zooming, and getting the output svg line width
  6144. # to match that viewed on screen with FlatCam
  6145. if scale_stroke_factor == 0:
  6146. scale_stroke_factor = 0.01
  6147. # Separate the list of cuts and travels into 2 distinct lists
  6148. # This way we can add different formatting / colors to both
  6149. cuts = []
  6150. travels = []
  6151. cutsgeom = ''
  6152. travelsgeom = ''
  6153. for g in self.gcode_parsed:
  6154. if self.app.abort_flag:
  6155. # graceful abort requested by the user
  6156. raise grace
  6157. if g['kind'][0] == 'C':
  6158. cuts.append(g)
  6159. if g['kind'][0] == 'T':
  6160. travels.append(g)
  6161. # Used to determine the overall board size
  6162. self.solid_geometry = cascaded_union([geo['geom'] for geo in self.gcode_parsed])
  6163. # Convert the cuts and travels into single geometry objects we can render as svg xml
  6164. if travels:
  6165. travelsgeom = cascaded_union([geo['geom'] for geo in travels])
  6166. if self.app.abort_flag:
  6167. # graceful abort requested by the user
  6168. raise grace
  6169. if cuts:
  6170. cutsgeom = cascaded_union([geo['geom'] for geo in cuts])
  6171. # Render the SVG Xml
  6172. # The scale factor affects the size of the lines, and the stroke color adds different formatting for each set
  6173. # It's better to have the travels sitting underneath the cuts for visicut
  6174. svg_elem = ""
  6175. if travels:
  6176. svg_elem = travelsgeom.svg(scale_factor=scale_stroke_factor, stroke_color="#F0E24D")
  6177. if cuts:
  6178. svg_elem += cutsgeom.svg(scale_factor=scale_stroke_factor, stroke_color="#5E6CFF")
  6179. return svg_elem
  6180. def bounds(self, flatten=None):
  6181. """
  6182. Returns coordinates of rectangular bounds of geometry: (xmin, ymin, xmax, ymax).
  6183. :param flatten: Not used, it is here for compatibility with base class method
  6184. :type flatten: bool
  6185. :return: Bounding values in format (xmin, ymin, xmax, ymax)
  6186. :rtype: tuple
  6187. """
  6188. log.debug("camlib.CNCJob.bounds()")
  6189. def bounds_rec(obj):
  6190. if type(obj) is list:
  6191. cminx = np.Inf
  6192. cminy = np.Inf
  6193. cmaxx = -np.Inf
  6194. cmaxy = -np.Inf
  6195. for k in obj:
  6196. if type(k) is dict:
  6197. for key in k:
  6198. minx_, miny_, maxx_, maxy_ = bounds_rec(k[key])
  6199. cminx = min(cminx, minx_)
  6200. cminy = min(cminy, miny_)
  6201. cmaxx = max(cmaxx, maxx_)
  6202. cmaxy = max(cmaxy, maxy_)
  6203. else:
  6204. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  6205. cminx = min(cminx, minx_)
  6206. cminy = min(cminy, miny_)
  6207. cmaxx = max(cmaxx, maxx_)
  6208. cmaxy = max(cmaxy, maxy_)
  6209. return cminx, cminy, cmaxx, cmaxy
  6210. else:
  6211. # it's a Shapely object, return it's bounds
  6212. return obj.bounds
  6213. if self.multitool is False:
  6214. log.debug("CNCJob->bounds()")
  6215. if self.solid_geometry is None:
  6216. log.debug("solid_geometry is None")
  6217. return 0, 0, 0, 0
  6218. bounds_coords = bounds_rec(self.solid_geometry)
  6219. else:
  6220. minx = np.Inf
  6221. miny = np.Inf
  6222. maxx = -np.Inf
  6223. maxy = -np.Inf
  6224. for k, v in self.cnc_tools.items():
  6225. minx = np.Inf
  6226. miny = np.Inf
  6227. maxx = -np.Inf
  6228. maxy = -np.Inf
  6229. try:
  6230. for k in v['solid_geometry']:
  6231. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  6232. minx = min(minx, minx_)
  6233. miny = min(miny, miny_)
  6234. maxx = max(maxx, maxx_)
  6235. maxy = max(maxy, maxy_)
  6236. except TypeError:
  6237. minx_, miny_, maxx_, maxy_ = bounds_rec(v['solid_geometry'])
  6238. minx = min(minx, minx_)
  6239. miny = min(miny, miny_)
  6240. maxx = max(maxx, maxx_)
  6241. maxy = max(maxy, maxy_)
  6242. bounds_coords = minx, miny, maxx, maxy
  6243. return bounds_coords
  6244. # TODO This function should be replaced at some point with a "real" function. Until then it's an ugly hack ...
  6245. def scale(self, xfactor, yfactor=None, point=None):
  6246. """
  6247. Scales all the geometry on the XY plane in the object by the
  6248. given factor. Tool sizes, feedrates, or Z-axis dimensions are
  6249. not altered.
  6250. :param factor: Number by which to scale the object.
  6251. :type factor: float
  6252. :param point: the (x,y) coords for the point of origin of scale
  6253. :type tuple of floats
  6254. :return: None
  6255. :rtype: None
  6256. """
  6257. log.debug("camlib.CNCJob.scale()")
  6258. if yfactor is None:
  6259. yfactor = xfactor
  6260. if point is None:
  6261. px = 0
  6262. py = 0
  6263. else:
  6264. px, py = point
  6265. def scale_g(g):
  6266. """
  6267. :param g: 'g' parameter it's a gcode string
  6268. :return: scaled gcode string
  6269. """
  6270. temp_gcode = ''
  6271. header_start = False
  6272. header_stop = False
  6273. units = self.app.defaults['units'].upper()
  6274. lines = StringIO(g)
  6275. for line in lines:
  6276. # this changes the GCODE header ---- UGLY HACK
  6277. if "TOOL DIAMETER" in line or "Feedrate:" in line:
  6278. header_start = True
  6279. if "G20" in line or "G21" in line:
  6280. header_start = False
  6281. header_stop = True
  6282. if header_start is True:
  6283. header_stop = False
  6284. if "in" in line:
  6285. if units == 'MM':
  6286. line = line.replace("in", "mm")
  6287. if "mm" in line:
  6288. if units == 'IN':
  6289. line = line.replace("mm", "in")
  6290. # find any float number in header (even multiple on the same line) and convert it
  6291. numbers_in_header = re.findall(self.g_nr_re, line)
  6292. if numbers_in_header:
  6293. for nr in numbers_in_header:
  6294. new_nr = float(nr) * xfactor
  6295. # replace the updated string
  6296. line = line.replace(nr, ('%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_nr))
  6297. )
  6298. # this scales all the X and Y and Z and F values and also the Tool Dia in the toolchange message
  6299. if header_stop is True:
  6300. if "G20" in line:
  6301. if units == 'MM':
  6302. line = line.replace("G20", "G21")
  6303. if "G21" in line:
  6304. if units == 'IN':
  6305. line = line.replace("G21", "G20")
  6306. # find the X group
  6307. match_x = self.g_x_re.search(line)
  6308. if match_x:
  6309. if match_x.group(1) is not None:
  6310. new_x = float(match_x.group(1)[1:]) * xfactor
  6311. # replace the updated string
  6312. line = line.replace(
  6313. match_x.group(1),
  6314. 'X%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_x)
  6315. )
  6316. # find the Y group
  6317. match_y = self.g_y_re.search(line)
  6318. if match_y:
  6319. if match_y.group(1) is not None:
  6320. new_y = float(match_y.group(1)[1:]) * yfactor
  6321. line = line.replace(
  6322. match_y.group(1),
  6323. 'Y%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_y)
  6324. )
  6325. # find the Z group
  6326. match_z = self.g_z_re.search(line)
  6327. if match_z:
  6328. if match_z.group(1) is not None:
  6329. new_z = float(match_z.group(1)[1:]) * xfactor
  6330. line = line.replace(
  6331. match_z.group(1),
  6332. 'Z%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_z)
  6333. )
  6334. # find the F group
  6335. match_f = self.g_f_re.search(line)
  6336. if match_f:
  6337. if match_f.group(1) is not None:
  6338. new_f = float(match_f.group(1)[1:]) * xfactor
  6339. line = line.replace(
  6340. match_f.group(1),
  6341. 'F%.*f' % (self.app.defaults["cncjob_fr_decimals"], new_f)
  6342. )
  6343. # find the T group (tool dia on toolchange)
  6344. match_t = self.g_t_re.search(line)
  6345. if match_t:
  6346. if match_t.group(1) is not None:
  6347. new_t = float(match_t.group(1)[1:]) * xfactor
  6348. line = line.replace(
  6349. match_t.group(1),
  6350. '= %.*f' % (self.app.defaults["cncjob_coords_decimals"], new_t)
  6351. )
  6352. temp_gcode += line
  6353. lines.close()
  6354. header_stop = False
  6355. return temp_gcode
  6356. if self.multitool is False:
  6357. # offset Gcode
  6358. self.gcode = scale_g(self.gcode)
  6359. # variables to display the percentage of work done
  6360. self.geo_len = 0
  6361. try:
  6362. self.geo_len = len(self.gcode_parsed)
  6363. except TypeError:
  6364. self.geo_len = 1
  6365. self.old_disp_number = 0
  6366. self.el_count = 0
  6367. # scale geometry
  6368. for g in self.gcode_parsed:
  6369. try:
  6370. g['geom'] = affinity.scale(g['geom'], xfactor, yfactor, origin=(px, py))
  6371. except AttributeError:
  6372. return g['geom']
  6373. self.el_count += 1
  6374. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  6375. if self.old_disp_number < disp_number <= 100:
  6376. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  6377. self.old_disp_number = disp_number
  6378. self.create_geometry()
  6379. else:
  6380. for k, v in self.cnc_tools.items():
  6381. # scale Gcode
  6382. v['gcode'] = scale_g(v['gcode'])
  6383. # variables to display the percentage of work done
  6384. self.geo_len = 0
  6385. try:
  6386. self.geo_len = len(v['gcode_parsed'])
  6387. except TypeError:
  6388. self.geo_len = 1
  6389. self.old_disp_number = 0
  6390. self.el_count = 0
  6391. # scale gcode_parsed
  6392. for g in v['gcode_parsed']:
  6393. try:
  6394. g['geom'] = affinity.scale(g['geom'], xfactor, yfactor, origin=(px, py))
  6395. except AttributeError:
  6396. return g['geom']
  6397. self.el_count += 1
  6398. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  6399. if self.old_disp_number < disp_number <= 100:
  6400. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  6401. self.old_disp_number = disp_number
  6402. v['solid_geometry'] = cascaded_union([geo['geom'] for geo in v['gcode_parsed']])
  6403. self.create_geometry()
  6404. self.app.proc_container.new_text = ''
  6405. def offset(self, vect):
  6406. """
  6407. Offsets all the geometry on the XY plane in the object by the
  6408. given vector.
  6409. Offsets all the GCODE on the XY plane in the object by the
  6410. given vector.
  6411. g_offsetx_re, g_offsety_re, multitool, cnnc_tools are attributes of FlatCAMCNCJob class in camlib
  6412. :param vect: (x, y) offset vector.
  6413. :type vect: tuple
  6414. :return: None
  6415. """
  6416. log.debug("camlib.CNCJob.offset()")
  6417. dx, dy = vect
  6418. def offset_g(g):
  6419. """
  6420. :param g: 'g' parameter it's a gcode string
  6421. :return: offseted gcode string
  6422. """
  6423. temp_gcode = ''
  6424. lines = StringIO(g)
  6425. for line in lines:
  6426. # find the X group
  6427. match_x = self.g_x_re.search(line)
  6428. if match_x:
  6429. if match_x.group(1) is not None:
  6430. # get the coordinate and add X offset
  6431. new_x = float(match_x.group(1)[1:]) + dx
  6432. # replace the updated string
  6433. line = line.replace(
  6434. match_x.group(1),
  6435. 'X%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_x)
  6436. )
  6437. match_y = self.g_y_re.search(line)
  6438. if match_y:
  6439. if match_y.group(1) is not None:
  6440. new_y = float(match_y.group(1)[1:]) + dy
  6441. line = line.replace(
  6442. match_y.group(1),
  6443. 'Y%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_y)
  6444. )
  6445. temp_gcode += line
  6446. lines.close()
  6447. return temp_gcode
  6448. if self.multitool is False:
  6449. # offset Gcode
  6450. self.gcode = offset_g(self.gcode)
  6451. # variables to display the percentage of work done
  6452. self.geo_len = 0
  6453. try:
  6454. self.geo_len = len(self.gcode_parsed)
  6455. except TypeError:
  6456. self.geo_len = 1
  6457. self.old_disp_number = 0
  6458. self.el_count = 0
  6459. # offset geometry
  6460. for g in self.gcode_parsed:
  6461. try:
  6462. g['geom'] = affinity.translate(g['geom'], xoff=dx, yoff=dy)
  6463. except AttributeError:
  6464. return g['geom']
  6465. self.el_count += 1
  6466. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  6467. if self.old_disp_number < disp_number <= 100:
  6468. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  6469. self.old_disp_number = disp_number
  6470. self.create_geometry()
  6471. else:
  6472. for k, v in self.cnc_tools.items():
  6473. # offset Gcode
  6474. v['gcode'] = offset_g(v['gcode'])
  6475. # variables to display the percentage of work done
  6476. self.geo_len = 0
  6477. try:
  6478. self.geo_len = len(v['gcode_parsed'])
  6479. except TypeError:
  6480. self.geo_len = 1
  6481. self.old_disp_number = 0
  6482. self.el_count = 0
  6483. # offset gcode_parsed
  6484. for g in v['gcode_parsed']:
  6485. try:
  6486. g['geom'] = affinity.translate(g['geom'], xoff=dx, yoff=dy)
  6487. except AttributeError:
  6488. return g['geom']
  6489. self.el_count += 1
  6490. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  6491. if self.old_disp_number < disp_number <= 100:
  6492. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  6493. self.old_disp_number = disp_number
  6494. # for the bounding box
  6495. v['solid_geometry'] = cascaded_union([geo['geom'] for geo in v['gcode_parsed']])
  6496. self.app.proc_container.new_text = ''
  6497. def mirror(self, axis, point):
  6498. """
  6499. Mirror the geometry of an object by an given axis around the coordinates of the 'point'
  6500. :param axis: Axis for Mirror
  6501. :param point: tuple of coordinates (x,y). Point of origin for Mirror
  6502. :return:
  6503. """
  6504. log.debug("camlib.CNCJob.mirror()")
  6505. px, py = point
  6506. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  6507. # variables to display the percentage of work done
  6508. self.geo_len = 0
  6509. try:
  6510. self.geo_len = len(self.gcode_parsed)
  6511. except TypeError:
  6512. self.geo_len = 1
  6513. self.old_disp_number = 0
  6514. self.el_count = 0
  6515. for g in self.gcode_parsed:
  6516. try:
  6517. g['geom'] = affinity.scale(g['geom'], xscale, yscale, origin=(px, py))
  6518. except AttributeError:
  6519. return g['geom']
  6520. self.el_count += 1
  6521. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  6522. if self.old_disp_number < disp_number <= 100:
  6523. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  6524. self.old_disp_number = disp_number
  6525. self.create_geometry()
  6526. self.app.proc_container.new_text = ''
  6527. def skew(self, angle_x, angle_y, point):
  6528. """
  6529. Shear/Skew the geometries of an object by angles along x and y dimensions.
  6530. :param angle_x:
  6531. :param angle_y:
  6532. angle_x, angle_y : float, float
  6533. The shear angle(s) for the x and y axes respectively. These can be
  6534. specified in either degrees (default) or radians by setting
  6535. use_radians=True.
  6536. :param point: tupple of coordinates (x,y)
  6537. See shapely manual for more information: http://toblerity.org/shapely/manual.html#affine-transformations
  6538. """
  6539. log.debug("camlib.CNCJob.skew()")
  6540. px, py = point
  6541. # variables to display the percentage of work done
  6542. self.geo_len = 0
  6543. try:
  6544. self.geo_len = len(self.gcode_parsed)
  6545. except TypeError:
  6546. self.geo_len = 1
  6547. self.old_disp_number = 0
  6548. self.el_count = 0
  6549. for g in self.gcode_parsed:
  6550. try:
  6551. g['geom'] = affinity.skew(g['geom'], angle_x, angle_y, origin=(px, py))
  6552. except AttributeError:
  6553. return g['geom']
  6554. self.el_count += 1
  6555. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  6556. if self.old_disp_number < disp_number <= 100:
  6557. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  6558. self.old_disp_number = disp_number
  6559. self.create_geometry()
  6560. self.app.proc_container.new_text = ''
  6561. def rotate(self, angle, point):
  6562. """
  6563. Rotate the geometry of an object by an given angle around the coordinates of the 'point'
  6564. :param angle: Angle of Rotation
  6565. :param point: tuple of coordinates (x,y). Origin point for Rotation
  6566. :return:
  6567. """
  6568. log.debug("camlib.CNCJob.rotate()")
  6569. px, py = point
  6570. # variables to display the percentage of work done
  6571. self.geo_len = 0
  6572. try:
  6573. self.geo_len = len(self.gcode_parsed)
  6574. except TypeError:
  6575. self.geo_len = 1
  6576. self.old_disp_number = 0
  6577. self.el_count = 0
  6578. for g in self.gcode_parsed:
  6579. try:
  6580. g['geom'] = affinity.rotate(g['geom'], angle, origin=(px, py))
  6581. except AttributeError:
  6582. return g['geom']
  6583. self.el_count += 1
  6584. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  6585. if self.old_disp_number < disp_number <= 100:
  6586. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  6587. self.old_disp_number = disp_number
  6588. self.create_geometry()
  6589. self.app.proc_container.new_text = ''
  6590. def get_bounds(geometry_list):
  6591. """
  6592. Will return limit values for a list of geometries
  6593. :param geometry_list: List of geometries for which to calculate the bounds limits
  6594. :return:
  6595. """
  6596. xmin = np.Inf
  6597. ymin = np.Inf
  6598. xmax = -np.Inf
  6599. ymax = -np.Inf
  6600. for gs in geometry_list:
  6601. try:
  6602. gxmin, gymin, gxmax, gymax = gs.bounds()
  6603. xmin = min([xmin, gxmin])
  6604. ymin = min([ymin, gymin])
  6605. xmax = max([xmax, gxmax])
  6606. ymax = max([ymax, gymax])
  6607. except Exception:
  6608. log.warning("DEVELOPMENT: Tried to get bounds of empty geometry.")
  6609. return [xmin, ymin, xmax, ymax]
  6610. def arc(center, radius, start, stop, direction, steps_per_circ):
  6611. """
  6612. Creates a list of point along the specified arc.
  6613. :param center: Coordinates of the center [x, y]
  6614. :type center: list
  6615. :param radius: Radius of the arc.
  6616. :type radius: float
  6617. :param start: Starting angle in radians
  6618. :type start: float
  6619. :param stop: End angle in radians
  6620. :type stop: float
  6621. :param direction: Orientation of the arc, "CW" or "CCW"
  6622. :type direction: string
  6623. :param steps_per_circ: Number of straight line segments to
  6624. represent a circle.
  6625. :type steps_per_circ: int
  6626. :return: The desired arc, as list of tuples
  6627. :rtype: list
  6628. """
  6629. # TODO: Resolution should be established by maximum error from the exact arc.
  6630. da_sign = {"cw": -1.0, "ccw": 1.0}
  6631. points = []
  6632. if direction == "ccw" and stop <= start:
  6633. stop += 2 * np.pi
  6634. if direction == "cw" and stop >= start:
  6635. stop -= 2 * np.pi
  6636. angle = abs(stop - start)
  6637. # angle = stop-start
  6638. steps = max([int(np.ceil(angle / (2 * np.pi) * steps_per_circ)), 2])
  6639. delta_angle = da_sign[direction] * angle * 1.0 / steps
  6640. for i in range(steps + 1):
  6641. theta = start + delta_angle * i
  6642. points.append((center[0] + radius * np.cos(theta), center[1] + radius * np.sin(theta)))
  6643. return points
  6644. def arc2(p1, p2, center, direction, steps_per_circ):
  6645. r = np.sqrt((center[0] - p1[0]) ** 2 + (center[1] - p1[1]) ** 2)
  6646. start = np.arctan2(p1[1] - center[1], p1[0] - center[0])
  6647. stop = np.arctan2(p2[1] - center[1], p2[0] - center[0])
  6648. return arc(center, r, start, stop, direction, steps_per_circ)
  6649. def arc_angle(start, stop, direction):
  6650. if direction == "ccw" and stop <= start:
  6651. stop += 2 * np.pi
  6652. if direction == "cw" and stop >= start:
  6653. stop -= 2 * np.pi
  6654. angle = abs(stop - start)
  6655. return angle
  6656. # def find_polygon(poly, point):
  6657. # """
  6658. # Find an object that object.contains(Point(point)) in
  6659. # poly, which can can be iterable, contain iterable of, or
  6660. # be itself an implementer of .contains().
  6661. #
  6662. # :param poly: See description
  6663. # :return: Polygon containing point or None.
  6664. # """
  6665. #
  6666. # if poly is None:
  6667. # return None
  6668. #
  6669. # try:
  6670. # for sub_poly in poly:
  6671. # p = find_polygon(sub_poly, point)
  6672. # if p is not None:
  6673. # return p
  6674. # except TypeError:
  6675. # try:
  6676. # if poly.contains(Point(point)):
  6677. # return poly
  6678. # except AttributeError:
  6679. # return None
  6680. #
  6681. # return None
  6682. def to_dict(obj):
  6683. """
  6684. Makes the following types into serializable form:
  6685. * ApertureMacro
  6686. * BaseGeometry
  6687. :param obj: Shapely geometry.
  6688. :type obj: BaseGeometry
  6689. :return: Dictionary with serializable form if ``obj`` was
  6690. BaseGeometry or ApertureMacro, otherwise returns ``obj``.
  6691. """
  6692. if isinstance(obj, ApertureMacro):
  6693. return {
  6694. "__class__": "ApertureMacro",
  6695. "__inst__": obj.to_dict()
  6696. }
  6697. if isinstance(obj, BaseGeometry):
  6698. return {
  6699. "__class__": "Shply",
  6700. "__inst__": sdumps(obj)
  6701. }
  6702. return obj
  6703. def dict2obj(d):
  6704. """
  6705. Default deserializer.
  6706. :param d: Serializable dictionary representation of an object
  6707. to be reconstructed.
  6708. :return: Reconstructed object.
  6709. """
  6710. if '__class__' in d and '__inst__' in d:
  6711. if d['__class__'] == "Shply":
  6712. return sloads(d['__inst__'])
  6713. if d['__class__'] == "ApertureMacro":
  6714. am = ApertureMacro()
  6715. am.from_dict(d['__inst__'])
  6716. return am
  6717. return d
  6718. else:
  6719. return d
  6720. # def plotg(geo, solid_poly=False, color="black"):
  6721. # try:
  6722. # __ = iter(geo)
  6723. # except:
  6724. # geo = [geo]
  6725. #
  6726. # for g in geo:
  6727. # if type(g) == Polygon:
  6728. # if solid_poly:
  6729. # patch = PolygonPatch(g,
  6730. # facecolor="#BBF268",
  6731. # edgecolor="#006E20",
  6732. # alpha=0.75,
  6733. # zorder=2)
  6734. # ax = subplot(111)
  6735. # ax.add_patch(patch)
  6736. # else:
  6737. # x, y = g.exterior.coords.xy
  6738. # plot(x, y, color=color)
  6739. # for ints in g.interiors:
  6740. # x, y = ints.coords.xy
  6741. # plot(x, y, color=color)
  6742. # continue
  6743. #
  6744. # if type(g) == LineString or type(g) == LinearRing:
  6745. # x, y = g.coords.xy
  6746. # plot(x, y, color=color)
  6747. # continue
  6748. #
  6749. # if type(g) == Point:
  6750. # x, y = g.coords.xy
  6751. # plot(x, y, 'o')
  6752. # continue
  6753. #
  6754. # try:
  6755. # __ = iter(g)
  6756. # plotg(g, color=color)
  6757. # except:
  6758. # log.error("Cannot plot: " + str(type(g)))
  6759. # continue
  6760. # def alpha_shape(points, alpha):
  6761. # """
  6762. # Compute the alpha shape (concave hull) of a set of points.
  6763. #
  6764. # @param points: Iterable container of points.
  6765. # @param alpha: alpha value to influence the gooeyness of the border. Smaller
  6766. # numbers don't fall inward as much as larger numbers. Too large,
  6767. # and you lose everything!
  6768. # """
  6769. # if len(points) < 4:
  6770. # # When you have a triangle, there is no sense in computing an alpha
  6771. # # shape.
  6772. # return MultiPoint(list(points)).convex_hull
  6773. #
  6774. # def add_edge(edges, edge_points, coords, i, j):
  6775. # """Add a line between the i-th and j-th points, if not in the list already"""
  6776. # if (i, j) in edges or (j, i) in edges:
  6777. # # already added
  6778. # return
  6779. # edges.add( (i, j) )
  6780. # edge_points.append(coords[ [i, j] ])
  6781. #
  6782. # coords = np.array([point.coords[0] for point in points])
  6783. #
  6784. # tri = Delaunay(coords)
  6785. # edges = set()
  6786. # edge_points = []
  6787. # # loop over triangles:
  6788. # # ia, ib, ic = indices of corner points of the triangle
  6789. # for ia, ib, ic in tri.vertices:
  6790. # pa = coords[ia]
  6791. # pb = coords[ib]
  6792. # pc = coords[ic]
  6793. #
  6794. # # Lengths of sides of triangle
  6795. # a = math.sqrt((pa[0]-pb[0])**2 + (pa[1]-pb[1])**2)
  6796. # b = math.sqrt((pb[0]-pc[0])**2 + (pb[1]-pc[1])**2)
  6797. # c = math.sqrt((pc[0]-pa[0])**2 + (pc[1]-pa[1])**2)
  6798. #
  6799. # # Semiperimeter of triangle
  6800. # s = (a + b + c)/2.0
  6801. #
  6802. # # Area of triangle by Heron's formula
  6803. # area = math.sqrt(s*(s-a)*(s-b)*(s-c))
  6804. # circum_r = a*b*c/(4.0*area)
  6805. #
  6806. # # Here's the radius filter.
  6807. # #print circum_r
  6808. # if circum_r < 1.0/alpha:
  6809. # add_edge(edges, edge_points, coords, ia, ib)
  6810. # add_edge(edges, edge_points, coords, ib, ic)
  6811. # add_edge(edges, edge_points, coords, ic, ia)
  6812. #
  6813. # m = MultiLineString(edge_points)
  6814. # triangles = list(polygonize(m))
  6815. # return cascaded_union(triangles), edge_points
  6816. # def voronoi(P):
  6817. # """
  6818. # Returns a list of all edges of the voronoi diagram for the given input points.
  6819. # """
  6820. # delauny = Delaunay(P)
  6821. # triangles = delauny.points[delauny.vertices]
  6822. #
  6823. # circum_centers = np.array([triangle_csc(tri) for tri in triangles])
  6824. # long_lines_endpoints = []
  6825. #
  6826. # lineIndices = []
  6827. # for i, triangle in enumerate(triangles):
  6828. # circum_center = circum_centers[i]
  6829. # for j, neighbor in enumerate(delauny.neighbors[i]):
  6830. # if neighbor != -1:
  6831. # lineIndices.append((i, neighbor))
  6832. # else:
  6833. # ps = triangle[(j+1)%3] - triangle[(j-1)%3]
  6834. # ps = np.array((ps[1], -ps[0]))
  6835. #
  6836. # middle = (triangle[(j+1)%3] + triangle[(j-1)%3]) * 0.5
  6837. # di = middle - triangle[j]
  6838. #
  6839. # ps /= np.linalg.norm(ps)
  6840. # di /= np.linalg.norm(di)
  6841. #
  6842. # if np.dot(di, ps) < 0.0:
  6843. # ps *= -1000.0
  6844. # else:
  6845. # ps *= 1000.0
  6846. #
  6847. # long_lines_endpoints.append(circum_center + ps)
  6848. # lineIndices.append((i, len(circum_centers) + len(long_lines_endpoints)-1))
  6849. #
  6850. # vertices = np.vstack((circum_centers, long_lines_endpoints))
  6851. #
  6852. # # filter out any duplicate lines
  6853. # lineIndicesSorted = np.sort(lineIndices) # make (1,2) and (2,1) both (1,2)
  6854. # lineIndicesTupled = [tuple(row) for row in lineIndicesSorted]
  6855. # lineIndicesUnique = np.unique(lineIndicesTupled)
  6856. #
  6857. # return vertices, lineIndicesUnique
  6858. #
  6859. #
  6860. # def triangle_csc(pts):
  6861. # rows, cols = pts.shape
  6862. #
  6863. # A = np.bmat([[2 * np.dot(pts, pts.T), np.ones((rows, 1))],
  6864. # [np.ones((1, rows)), np.zeros((1, 1))]])
  6865. #
  6866. # b = np.hstack((np.sum(pts * pts, axis=1), np.ones((1))))
  6867. # x = np.linalg.solve(A,b)
  6868. # bary_coords = x[:-1]
  6869. # return np.sum(pts * np.tile(bary_coords.reshape((pts.shape[0], 1)), (1, pts.shape[1])), axis=0)
  6870. #
  6871. #
  6872. # def voronoi_cell_lines(points, vertices, lineIndices):
  6873. # """
  6874. # Returns a mapping from a voronoi cell to its edges.
  6875. #
  6876. # :param points: shape (m,2)
  6877. # :param vertices: shape (n,2)
  6878. # :param lineIndices: shape (o,2)
  6879. # :rtype: dict point index -> list of shape (n,2) with vertex indices
  6880. # """
  6881. # kd = KDTree(points)
  6882. #
  6883. # cells = collections.defaultdict(list)
  6884. # for i1, i2 in lineIndices:
  6885. # v1, v2 = vertices[i1], vertices[i2]
  6886. # mid = (v1+v2)/2
  6887. # _, (p1Idx, p2Idx) = kd.query(mid, 2)
  6888. # cells[p1Idx].append((i1, i2))
  6889. # cells[p2Idx].append((i1, i2))
  6890. #
  6891. # return cells
  6892. #
  6893. #
  6894. # def voronoi_edges2polygons(cells):
  6895. # """
  6896. # Transforms cell edges into polygons.
  6897. #
  6898. # :param cells: as returned from voronoi_cell_lines
  6899. # :rtype: dict point index -> list of vertex indices which form a polygon
  6900. # """
  6901. #
  6902. # # first, close the outer cells
  6903. # for pIdx, lineIndices_ in cells.items():
  6904. # dangling_lines = []
  6905. # for i1, i2 in lineIndices_:
  6906. # p = (i1, i2)
  6907. # connections = filter(lambda k: p != k and
  6908. # (p[0] == k[0] or p[0] == k[1] or p[1] == k[0] or p[1] == k[1]), lineIndices_)
  6909. # # connections = filter(lambda (i1_, i2_): (i1, i2) != (i1_, i2_) and
  6910. # (i1 == i1_ or i1 == i2_ or i2 == i1_ or i2 == i2_), lineIndices_)
  6911. # assert 1 <= len(connections) <= 2
  6912. # if len(connections) == 1:
  6913. # dangling_lines.append((i1, i2))
  6914. # assert len(dangling_lines) in [0, 2]
  6915. # if len(dangling_lines) == 2:
  6916. # (i11, i12), (i21, i22) = dangling_lines
  6917. # s = (i11, i12)
  6918. # t = (i21, i22)
  6919. #
  6920. # # determine which line ends are unconnected
  6921. # connected = filter(lambda k: k != s and (k[0] == s[0] or k[1] == s[0]), lineIndices_)
  6922. # # connected = filter(lambda (i1,i2): (i1,i2) != (i11,i12) and (i1 == i11 or i2 == i11), lineIndices_)
  6923. # i11Unconnected = len(connected) == 0
  6924. #
  6925. # connected = filter(lambda k: k != t and (k[0] == t[0] or k[1] == t[0]), lineIndices_)
  6926. # # connected = filter(lambda (i1,i2): (i1,i2) != (i21,i22) and (i1 == i21 or i2 == i21), lineIndices_)
  6927. # i21Unconnected = len(connected) == 0
  6928. #
  6929. # startIdx = i11 if i11Unconnected else i12
  6930. # endIdx = i21 if i21Unconnected else i22
  6931. #
  6932. # cells[pIdx].append((startIdx, endIdx))
  6933. #
  6934. # # then, form polygons by storing vertex indices in (counter-)clockwise order
  6935. # polys = {}
  6936. # for pIdx, lineIndices_ in cells.items():
  6937. # # get a directed graph which contains both directions and arbitrarily follow one of both
  6938. # directedGraph = lineIndices_ + [(i2, i1) for (i1, i2) in lineIndices_]
  6939. # directedGraphMap = collections.defaultdict(list)
  6940. # for (i1, i2) in directedGraph:
  6941. # directedGraphMap[i1].append(i2)
  6942. # orderedEdges = []
  6943. # currentEdge = directedGraph[0]
  6944. # while len(orderedEdges) < len(lineIndices_):
  6945. # i1 = currentEdge[1]
  6946. # i2 = directedGraphMap[i1][0] if directedGraphMap[i1][0] != currentEdge[0] else directedGraphMap[i1][1]
  6947. # nextEdge = (i1, i2)
  6948. # orderedEdges.append(nextEdge)
  6949. # currentEdge = nextEdge
  6950. #
  6951. # polys[pIdx] = [i1 for (i1, i2) in orderedEdges]
  6952. #
  6953. # return polys
  6954. #
  6955. #
  6956. # def voronoi_polygons(points):
  6957. # """
  6958. # Returns the voronoi polygon for each input point.
  6959. #
  6960. # :param points: shape (n,2)
  6961. # :rtype: list of n polygons where each polygon is an array of vertices
  6962. # """
  6963. # vertices, lineIndices = voronoi(points)
  6964. # cells = voronoi_cell_lines(points, vertices, lineIndices)
  6965. # polys = voronoi_edges2polygons(cells)
  6966. # polylist = []
  6967. # for i in range(len(points)):
  6968. # poly = vertices[np.asarray(polys[i])]
  6969. # polylist.append(poly)
  6970. # return polylist
  6971. #
  6972. #
  6973. # class Zprofile:
  6974. # def __init__(self):
  6975. #
  6976. # # data contains lists of [x, y, z]
  6977. # self.data = []
  6978. #
  6979. # # Computed voronoi polygons (shapely)
  6980. # self.polygons = []
  6981. # pass
  6982. #
  6983. # # def plot_polygons(self):
  6984. # # axes = plt.subplot(1, 1, 1)
  6985. # #
  6986. # # plt.axis([-0.05, 1.05, -0.05, 1.05])
  6987. # #
  6988. # # for poly in self.polygons:
  6989. # # p = PolygonPatch(poly, facecolor=np.random.rand(3, 1), alpha=0.3)
  6990. # # axes.add_patch(p)
  6991. #
  6992. # def init_from_csv(self, filename):
  6993. # pass
  6994. #
  6995. # def init_from_string(self, zpstring):
  6996. # pass
  6997. #
  6998. # def init_from_list(self, zplist):
  6999. # self.data = zplist
  7000. #
  7001. # def generate_polygons(self):
  7002. # self.polygons = [Polygon(p) for p in voronoi_polygons(array([[x[0], x[1]] for x in self.data]))]
  7003. #
  7004. # def normalize(self, origin):
  7005. # pass
  7006. #
  7007. # def paste(self, path):
  7008. # """
  7009. # Return a list of dictionaries containing the parts of the original
  7010. # path and their z-axis offset.
  7011. # """
  7012. #
  7013. # # At most one region/polygon will contain the path
  7014. # containing = [i for i in range(len(self.polygons)) if self.polygons[i].contains(path)]
  7015. #
  7016. # if len(containing) > 0:
  7017. # return [{"path": path, "z": self.data[containing[0]][2]}]
  7018. #
  7019. # # All region indexes that intersect with the path
  7020. # crossing = [i for i in range(len(self.polygons)) if self.polygons[i].intersects(path)]
  7021. #
  7022. # return [{"path": path.intersection(self.polygons[i]),
  7023. # "z": self.data[i][2]} for i in crossing]
  7024. def autolist(obj):
  7025. try:
  7026. __ = iter(obj)
  7027. return obj
  7028. except TypeError:
  7029. return [obj]
  7030. def three_point_circle(p1, p2, p3):
  7031. """
  7032. Computes the center and radius of a circle from
  7033. 3 points on its circumference.
  7034. :param p1: Point 1
  7035. :param p2: Point 2
  7036. :param p3: Point 3
  7037. :return: center, radius
  7038. """
  7039. # Midpoints
  7040. a1 = (p1 + p2) / 2.0
  7041. a2 = (p2 + p3) / 2.0
  7042. # Normals
  7043. b1 = np.dot((p2 - p1), np.array([[0, -1], [1, 0]], dtype=np.float32))
  7044. b2 = np.dot((p3 - p2), np.array([[0, 1], [-1, 0]], dtype=np.float32))
  7045. # Params
  7046. try:
  7047. T = solve(np.transpose(np.array([-b1, b2])), a1 - a2)
  7048. except Exception as e:
  7049. log.debug("camlib.three_point_circle() --> %s" % str(e))
  7050. return
  7051. # Center
  7052. center = a1 + b1 * T[0]
  7053. # Radius
  7054. radius = np.linalg.norm(center - p1)
  7055. return center, radius, T[0]
  7056. def distance(pt1, pt2):
  7057. return np.sqrt((pt1[0] - pt2[0]) ** 2 + (pt1[1] - pt2[1]) ** 2)
  7058. def distance_euclidian(x1, y1, x2, y2):
  7059. return np.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
  7060. class FlatCAMRTree(object):
  7061. """
  7062. Indexes geometry (Any object with "cooords" property containing
  7063. a list of tuples with x, y values). Objects are indexed by
  7064. all their points by default. To index by arbitrary points,
  7065. override self.points2obj.
  7066. """
  7067. def __init__(self):
  7068. # Python RTree Index
  7069. self.rti = rtindex.Index()
  7070. # ## Track object-point relationship
  7071. # Each is list of points in object.
  7072. self.obj2points = []
  7073. # Index is index in rtree, value is index of
  7074. # object in obj2points.
  7075. self.points2obj = []
  7076. self.get_points = lambda go: go.coords
  7077. def grow_obj2points(self, idx):
  7078. """
  7079. Increases the size of self.obj2points to fit
  7080. idx + 1 items.
  7081. :param idx: Index to fit into list.
  7082. :return: None
  7083. """
  7084. if len(self.obj2points) > idx:
  7085. # len == 2, idx == 1, ok.
  7086. return
  7087. else:
  7088. # len == 2, idx == 2, need 1 more.
  7089. # range(2, 3)
  7090. for i in range(len(self.obj2points), idx + 1):
  7091. self.obj2points.append([])
  7092. def insert(self, objid, obj):
  7093. self.grow_obj2points(objid)
  7094. self.obj2points[objid] = []
  7095. for pt in self.get_points(obj):
  7096. self.rti.insert(len(self.points2obj), (pt[0], pt[1], pt[0], pt[1]), obj=objid)
  7097. self.obj2points[objid].append(len(self.points2obj))
  7098. self.points2obj.append(objid)
  7099. def remove_obj(self, objid, obj):
  7100. # Use all ptids to delete from index
  7101. for i, pt in enumerate(self.get_points(obj)):
  7102. try:
  7103. self.rti.delete(self.obj2points[objid][i], (pt[0], pt[1], pt[0], pt[1]))
  7104. except IndexError:
  7105. pass
  7106. def nearest(self, pt):
  7107. """
  7108. Will raise StopIteration if no items are found.
  7109. :param pt:
  7110. :return:
  7111. """
  7112. return next(self.rti.nearest(pt, objects=True))
  7113. class FlatCAMRTreeStorage(FlatCAMRTree):
  7114. """
  7115. Just like FlatCAMRTree it indexes geometry, but also serves
  7116. as storage for the geometry.
  7117. """
  7118. def __init__(self):
  7119. # super(FlatCAMRTreeStorage, self).__init__()
  7120. super().__init__()
  7121. self.objects = []
  7122. # Optimization attempt!
  7123. self.indexes = {}
  7124. def insert(self, obj):
  7125. self.objects.append(obj)
  7126. idx = len(self.objects) - 1
  7127. # Note: Shapely objects are not hashable any more, although
  7128. # there seem to be plans to re-introduce the feature in
  7129. # version 2.0. For now, we will index using the object's id,
  7130. # but it's important to remember that shapely geometry is
  7131. # mutable, ie. it can be modified to a totally different shape
  7132. # and continue to have the same id.
  7133. # self.indexes[obj] = idx
  7134. self.indexes[id(obj)] = idx
  7135. # super(FlatCAMRTreeStorage, self).insert(idx, obj)
  7136. super().insert(idx, obj)
  7137. # @profile
  7138. def remove(self, obj):
  7139. # See note about self.indexes in insert().
  7140. # objidx = self.indexes[obj]
  7141. objidx = self.indexes[id(obj)]
  7142. # Remove from list
  7143. self.objects[objidx] = None
  7144. # Remove from index
  7145. self.remove_obj(objidx, obj)
  7146. def get_objects(self):
  7147. return (o for o in self.objects if o is not None)
  7148. def nearest(self, pt):
  7149. """
  7150. Returns the nearest matching points and the object
  7151. it belongs to.
  7152. :param pt: Query point.
  7153. :return: (match_x, match_y), Object owner of
  7154. matching point.
  7155. :rtype: tuple
  7156. """
  7157. tidx = super(FlatCAMRTreeStorage, self).nearest(pt)
  7158. return (tidx.bbox[0], tidx.bbox[1]), self.objects[tidx.object]
  7159. # class myO:
  7160. # def __init__(self, coords):
  7161. # self.coords = coords
  7162. #
  7163. #
  7164. # def test_rti():
  7165. #
  7166. # o1 = myO([(0, 0), (0, 1), (1, 1)])
  7167. # o2 = myO([(2, 0), (2, 1), (2, 1)])
  7168. # o3 = myO([(2, 0), (2, 1), (3, 1)])
  7169. #
  7170. # os = [o1, o2]
  7171. #
  7172. # idx = FlatCAMRTree()
  7173. #
  7174. # for o in range(len(os)):
  7175. # idx.insert(o, os[o])
  7176. #
  7177. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  7178. #
  7179. # idx.remove_obj(0, o1)
  7180. #
  7181. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  7182. #
  7183. # idx.remove_obj(1, o2)
  7184. #
  7185. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  7186. #
  7187. #
  7188. # def test_rtis():
  7189. #
  7190. # o1 = myO([(0, 0), (0, 1), (1, 1)])
  7191. # o2 = myO([(2, 0), (2, 1), (2, 1)])
  7192. # o3 = myO([(2, 0), (2, 1), (3, 1)])
  7193. #
  7194. # os = [o1, o2]
  7195. #
  7196. # idx = FlatCAMRTreeStorage()
  7197. #
  7198. # for o in range(len(os)):
  7199. # idx.insert(os[o])
  7200. #
  7201. # #os = None
  7202. # #o1 = None
  7203. # #o2 = None
  7204. #
  7205. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  7206. #
  7207. # idx.remove(idx.nearest((2,0))[1])
  7208. #
  7209. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  7210. #
  7211. # idx.remove(idx.nearest((0,0))[1])
  7212. #
  7213. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]