camlib.py 358 KB

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