camlib.py 351 KB

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