camlib.py 358 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674
  1. # ########################################################## ##
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # ########################################################## ##
  8. from PyQt5 import QtWidgets, QtCore
  9. from io import StringIO
  10. from numpy.linalg import solve, norm
  11. import platform
  12. from copy import deepcopy
  13. import traceback
  14. from decimal import Decimal
  15. from rtree import index as rtindex
  16. from lxml import etree as ET
  17. # See: http://toblerity.org/shapely/manual.html
  18. from shapely.geometry import Polygon, Point, LinearRing
  19. from shapely.geometry import box as shply_box
  20. from shapely.ops import cascaded_union, unary_union, substring, linemerge
  21. import shapely.affinity as affinity
  22. from shapely.wkt import loads as sloads
  23. from shapely.wkt import dumps as sdumps
  24. from shapely.geometry.base import BaseGeometry
  25. from shapely.geometry import shape
  26. # ---------------------------------------
  27. # NEEDED for Legacy mode
  28. # Used for solid polygons in Matplotlib
  29. from descartes.patch import PolygonPatch
  30. # ---------------------------------------
  31. from collections import Iterable
  32. import rasterio
  33. from rasterio.features import shapes
  34. import ezdxf
  35. from appCommon.Common import GracefulException as grace
  36. # Commented for FlatCAM packaging with cx_freeze
  37. # from scipy.spatial import KDTree, Delaunay
  38. # from scipy.spatial import Delaunay
  39. from appParsers.ParseSVG import *
  40. from appParsers.ParseDXF import *
  41. if platform.architecture()[0] == '64bit':
  42. from ortools.constraint_solver import pywrapcp
  43. from ortools.constraint_solver import routing_enums_pb2
  44. import logging
  45. import gettext
  46. import appTranslation as fcTranslate
  47. import builtins
  48. fcTranslate.apply_language('strings')
  49. log = logging.getLogger('base2')
  50. log.setLevel(logging.DEBUG)
  51. formatter = logging.Formatter('[%(levelname)s] %(message)s')
  52. handler = logging.StreamHandler()
  53. handler.setFormatter(formatter)
  54. log.addHandler(handler)
  55. if '_' not in builtins.__dict__:
  56. _ = gettext.gettext
  57. class ParseError(Exception):
  58. pass
  59. class ApertureMacro:
  60. """
  61. Syntax of aperture macros.
  62. <AM command>: AM<Aperture macro name>*<Macro content>
  63. <Macro content>: {{<Variable definition>*}{<Primitive>*}}
  64. <Variable definition>: $K=<Arithmetic expression>
  65. <Primitive>: <Primitive code>,<Modifier>{,<Modifier>}|<Comment>
  66. <Modifier>: $M|< Arithmetic expression>
  67. <Comment>: 0 <Text>
  68. """
  69. # ## Regular expressions
  70. am1_re = re.compile(r'^%AM([^\*]+)\*(.+)?(%)?$')
  71. am2_re = re.compile(r'(.*)%$')
  72. amcomm_re = re.compile(r'^0(.*)')
  73. amprim_re = re.compile(r'^[1-9].*')
  74. amvar_re = re.compile(r'^\$([0-9a-zA-z]+)=(.*)')
  75. def __init__(self, name=None):
  76. self.name = name
  77. self.raw = ""
  78. # ## These below are recomputed for every aperture
  79. # ## definition, in other words, are temporary variables.
  80. self.primitives = []
  81. self.locvars = {}
  82. self.geometry = None
  83. def to_dict(self):
  84. """
  85. Returns the object in a serializable form. Only the name and
  86. raw are required.
  87. :return: Dictionary representing the object. JSON ready.
  88. :rtype: dict
  89. """
  90. return {
  91. 'name': self.name,
  92. 'raw': self.raw
  93. }
  94. def from_dict(self, d):
  95. """
  96. Populates the object from a serial representation created
  97. with ``self.to_dict()``.
  98. :param d: Serial representation of an ApertureMacro object.
  99. :return: None
  100. """
  101. for attr in ['name', 'raw']:
  102. setattr(self, attr, d[attr])
  103. def parse_content(self):
  104. """
  105. Creates numerical lists for all primitives in the aperture
  106. macro (in ``self.raw``) by replacing all variables by their
  107. values iteratively and evaluating expressions. Results
  108. are stored in ``self.primitives``.
  109. :return: None
  110. """
  111. # Cleanup
  112. self.raw = self.raw.replace('\n', '').replace('\r', '').strip(" *")
  113. self.primitives = []
  114. # Separate parts
  115. parts = self.raw.split('*')
  116. # ### Every part in the macro ####
  117. for part in parts:
  118. # ## Comments. Ignored.
  119. match = ApertureMacro.amcomm_re.search(part)
  120. if match:
  121. continue
  122. # ## Variables
  123. # These are variables defined locally inside the macro. They can be
  124. # numerical constant or defined in terms of previously define
  125. # variables, which can be defined locally or in an aperture
  126. # definition. All replacements occur here.
  127. match = ApertureMacro.amvar_re.search(part)
  128. if match:
  129. var = match.group(1)
  130. val = match.group(2)
  131. # Replace variables in value
  132. for v in self.locvars:
  133. # replaced the following line with the next to fix Mentor custom apertures not parsed OK
  134. # val = re.sub((r'\$'+str(v)+r'(?![0-9a-zA-Z])'), str(self.locvars[v]), val)
  135. val = val.replace('$' + str(v), str(self.locvars[v]))
  136. # Make all others 0
  137. val = re.sub(r'\$[0-9a-zA-Z](?![0-9a-zA-Z])', "0", val)
  138. # Change x with *
  139. val = re.sub(r'[xX]', "*", val)
  140. # Eval() and store.
  141. self.locvars[var] = eval(val)
  142. continue
  143. # ## Primitives
  144. # Each is an array. The first identifies the primitive, while the
  145. # rest depend on the primitive. All are strings representing a
  146. # number and may contain variable definition. The values of these
  147. # variables are defined in an aperture definition.
  148. match = ApertureMacro.amprim_re.search(part)
  149. if match:
  150. # ## Replace all variables
  151. for v in self.locvars:
  152. # replaced the following line with the next to fix Mentor custom apertures not parsed OK
  153. # part = re.sub(r'\$' + str(v) + r'(?![0-9a-zA-Z])', str(self.locvars[v]), part)
  154. part = part.replace('$' + str(v), str(self.locvars[v]))
  155. # Make all others 0
  156. part = re.sub(r'\$[0-9a-zA-Z](?![0-9a-zA-Z])', "0", part)
  157. # Change x with *
  158. part = re.sub(r'[xX]', "*", part)
  159. # ## Store
  160. elements = part.split(",")
  161. self.primitives.append([eval(x) for x in elements])
  162. continue
  163. log.warning("Unknown syntax of aperture macro part: %s" % str(part))
  164. def append(self, data):
  165. """
  166. Appends a string to the raw macro.
  167. :param data: Part of the macro.
  168. :type data: str
  169. :return: None
  170. """
  171. self.raw += data
  172. @staticmethod
  173. def default2zero(n, mods):
  174. """
  175. Pads the ``mods`` list with zeros resulting in an
  176. list of length n.
  177. :param n: Length of the resulting list.
  178. :type n: int
  179. :param mods: List to be padded.
  180. :type mods: list
  181. :return: Zero-padded list.
  182. :rtype: list
  183. """
  184. x = [0.0] * n
  185. na = len(mods)
  186. x[0:na] = mods
  187. return x
  188. @staticmethod
  189. def make_circle(mods):
  190. """
  191. :param mods: (Exposure 0/1, Diameter >=0, X-coord, Y-coord)
  192. :return:
  193. """
  194. 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 = cascaded_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 = cascaded_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 = cascaded_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 cascaded_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 cascaded_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(cascaded_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 = cascaded_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 cascaded union on the list of objects in
  1862. solid_geometry.
  1863. :return: None
  1864. """
  1865. self.solid_geometry = [cascaded_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 = cascaded_union(flat_geo)
  1882. else:
  1883. geom_svg = cascaded_union(self.flatten())
  1884. else:
  1885. geom_svg = cascaded_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(_("Finished G-Code generation for tool: %s" % 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. self.exc_cnc_tools[it[1]] = {}
  2953. self.exc_cnc_tools[it[1]]['tool'] = it[0]
  2954. self.exc_cnc_tools[it[1]]['nr_drills'] = drill_no
  2955. self.exc_cnc_tools[it[1]]['nr_slots'] = slot_no
  2956. self.exc_cnc_tools[it[1]]['offset_z'] = z_off
  2957. self.exc_cnc_tools[it[1]]['data'] = default_data
  2958. self.exc_cnc_tools[it[1]]['solid_geometry'] = deepcopy(sol_geo)
  2959. # build a self.options['Tools_in_use'] list from scratch if we don't have one like in the case of
  2960. # running this method from a Tcl Command
  2961. if build_tools_in_use_list is True:
  2962. self.options['Tools_in_use'].append(
  2963. [it[0], it[1], drill_no, slot_no]
  2964. )
  2965. self.app.inform.emit(_("Creating a list of points to drill..."))
  2966. # #############################################################################################################
  2967. # #############################################################################################################
  2968. # Points (Group by tool): a dictionary of shapely Point geo elements grouped by tool number
  2969. # #############################################################################################################
  2970. # #############################################################################################################
  2971. points = {}
  2972. for tool, tool_dict in self.exc_tools.items():
  2973. if tool in tools:
  2974. if self.app.abort_flag:
  2975. # graceful abort requested by the user
  2976. raise grace
  2977. if 'drills' in tool_dict and tool_dict['drills']:
  2978. for drill_pt in tool_dict['drills']:
  2979. try:
  2980. points[tool].append(drill_pt)
  2981. except KeyError:
  2982. points[tool] = [drill_pt]
  2983. log.debug("Found %d TOOLS with drills." % len(points))
  2984. # check if there are drill points in the exclusion areas.
  2985. # If we find any within the exclusion areas return 'fail'
  2986. for tool in points:
  2987. for pt in points[tool]:
  2988. for area in self.app.exc_areas.exclusion_areas_storage:
  2989. pt_buf = pt.buffer(self.exc_tools[tool]['tooldia'] / 2.0)
  2990. if pt_buf.within(area['shape']) or pt_buf.intersects(area['shape']):
  2991. self.app.inform.emit("[ERROR_NOTCL] %s" % _("Failed. Drill points inside the exclusion zones."))
  2992. return 'fail'
  2993. # this holds the resulting GCode
  2994. self.gcode = []
  2995. # #############################################################################################################
  2996. # #############################################################################################################
  2997. # Initialization
  2998. # #############################################################################################################
  2999. # #############################################################################################################
  3000. gcode = self.doformat(p.start_code)
  3001. if use_ui is False:
  3002. gcode += self.doformat(p.z_feedrate_code)
  3003. if self.toolchange is False:
  3004. if self.xy_toolchange is not None:
  3005. gcode += self.doformat(p.lift_code, x=self.xy_toolchange[0], y=self.xy_toolchange[1])
  3006. gcode += self.doformat(p.startz_code, x=self.xy_toolchange[0], y=self.xy_toolchange[1])
  3007. else:
  3008. gcode += self.doformat(p.lift_code, x=0.0, y=0.0)
  3009. gcode += self.doformat(p.startz_code, x=0.0, y=0.0)
  3010. if self.xy_toolchange is not None:
  3011. self.oldx = self.xy_toolchange[0]
  3012. self.oldy = self.xy_toolchange[1]
  3013. else:
  3014. self.oldx = 0.0
  3015. self.oldy = 0.0
  3016. measured_distance = 0.0
  3017. measured_down_distance = 0.0
  3018. measured_up_to_zero_distance = 0.0
  3019. measured_lift_distance = 0.0
  3020. # #############################################################################################################
  3021. # #############################################################################################################
  3022. # GCODE creation
  3023. # #############################################################################################################
  3024. # #############################################################################################################
  3025. self.app.inform.emit('%s...' % _("Starting G-Code"))
  3026. has_drills = None
  3027. for tool, tool_dict in self.exc_tools.items():
  3028. if 'drills' in tool_dict and tool_dict['drills']:
  3029. has_drills = True
  3030. break
  3031. if not has_drills:
  3032. log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> "
  3033. "The loaded Excellon file has no drills ...")
  3034. self.app.inform.emit('[ERROR_NOTCL] %s...' % _('The loaded Excellon file has no drills'))
  3035. return 'fail'
  3036. current_platform = platform.architecture()[0]
  3037. if current_platform == '64bit':
  3038. used_excellon_optimization_type = self.excellon_optimization_type
  3039. else:
  3040. used_excellon_optimization_type = 'T'
  3041. # #############################################################################################################
  3042. # #############################################################################################################
  3043. # ################################## DRILLING !!! #########################################################
  3044. # #############################################################################################################
  3045. # #############################################################################################################
  3046. if used_excellon_optimization_type == 'M':
  3047. log.debug("Using OR-Tools Metaheuristic Guided Local Search drill path optimization.")
  3048. elif used_excellon_optimization_type == 'B':
  3049. log.debug("Using OR-Tools Basic drill path optimization.")
  3050. elif used_excellon_optimization_type == 'T':
  3051. log.debug("Using Travelling Salesman drill path optimization.")
  3052. else:
  3053. log.debug("Using no path optimization.")
  3054. if self.toolchange is True:
  3055. for tool in tools:
  3056. # check if it has drills
  3057. if not self.exc_tools[tool]['drills']:
  3058. continue
  3059. if self.app.abort_flag:
  3060. # graceful abort requested by the user
  3061. raise grace
  3062. self.tool = tool
  3063. self.tooldia = self.exc_tools[tool]["tooldia"]
  3064. self.postdata['toolC'] = self.tooldia
  3065. if self.use_ui:
  3066. self.z_feedrate = self.exc_tools[tool]['data']['tools_drill_feedrate_z']
  3067. self.feedrate = self.exc_tools[tool]['data']['tools_drill_feedrate_z']
  3068. self.z_cut = self.exc_tools[tool]['data']['tools_drill_cutz']
  3069. gcode += self.doformat(p.z_feedrate_code)
  3070. if self.machinist_setting == 0:
  3071. if self.z_cut > 0:
  3072. self.app.inform.emit('[WARNING] %s' %
  3073. _("The Cut Z parameter has positive value. "
  3074. "It is the depth value to drill into material.\n"
  3075. "The Cut Z parameter needs to have a negative value, "
  3076. "assuming it is a typo "
  3077. "therefore the app will convert the value to negative. "
  3078. "Check the resulting CNC code (Gcode etc)."))
  3079. self.z_cut = -self.z_cut
  3080. elif self.z_cut == 0:
  3081. self.app.inform.emit('[WARNING] %s: %s' %
  3082. (_(
  3083. "The Cut Z parameter is zero. There will be no cut, "
  3084. "skipping file"),
  3085. exobj.options['name']))
  3086. return 'fail'
  3087. old_zcut = deepcopy(self.z_cut)
  3088. self.z_move = self.exc_tools[tool]['data']['tools_drill_travelz']
  3089. self.spindlespeed = self.exc_tools[tool]['data']['tools_drill_spindlespeed']
  3090. self.dwell = self.exc_tools[tool]['data']['tools_drill_dwell']
  3091. self.dwelltime = self.exc_tools[tool]['data']['tools_drill_dwelltime']
  3092. self.multidepth = self.exc_tools[tool]['data']['tools_drill_multidepth']
  3093. self.z_depthpercut = self.exc_tools[tool]['data']['tools_drill_depthperpass']
  3094. else:
  3095. old_zcut = deepcopy(self.z_cut)
  3096. # #########################################################################################################
  3097. # ############ Create the data. #################
  3098. # #########################################################################################################
  3099. locations = []
  3100. altPoints = []
  3101. optimized_path = []
  3102. if used_excellon_optimization_type == 'M':
  3103. if tool in points:
  3104. locations = self.create_tool_data_array(points=points[tool])
  3105. # if there are no locations then go to the next tool
  3106. if not locations:
  3107. continue
  3108. opt_time = self.app.defaults["excellon_search_time"]
  3109. optimized_path = self.optimized_ortools_meta(locations=locations, opt_time=opt_time)
  3110. elif used_excellon_optimization_type == 'B':
  3111. if tool in points:
  3112. locations = self.create_tool_data_array(points=points[tool])
  3113. # if there are no locations then go to the next tool
  3114. if not locations:
  3115. continue
  3116. optimized_path = self.optimized_ortools_basic(locations=locations)
  3117. elif used_excellon_optimization_type == 'T':
  3118. for point in points[tool]:
  3119. altPoints.append((point.coords.xy[0][0], point.coords.xy[1][0]))
  3120. optimized_path = self.optimized_travelling_salesman(altPoints)
  3121. else:
  3122. # it's actually not optimized path but here we build a list of (x,y) coordinates
  3123. # out of the tool's drills
  3124. for drill in self.exc_tools[tool]['drills']:
  3125. unoptimized_coords = (
  3126. drill.x,
  3127. drill.y
  3128. )
  3129. optimized_path.append(unoptimized_coords)
  3130. # #########################################################################################################
  3131. # #########################################################################################################
  3132. # Only if there are locations to drill
  3133. if not optimized_path:
  3134. continue
  3135. if self.app.abort_flag:
  3136. # graceful abort requested by the user
  3137. raise grace
  3138. # Tool change sequence (optional)
  3139. if self.toolchange:
  3140. gcode += self.doformat(p.toolchange_code, toolchangexy=(self.oldx, self.oldy))
  3141. # Spindle start
  3142. gcode += self.doformat(p.spindle_code)
  3143. # Dwell time
  3144. if self.dwell is True:
  3145. gcode += self.doformat(p.dwell_code)
  3146. current_tooldia = float('%.*f' % (self.decimals, float(self.exc_tools[tool]["tooldia"])))
  3147. self.app.inform.emit(
  3148. '%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  3149. str(current_tooldia),
  3150. str(self.units))
  3151. )
  3152. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  3153. # APPLY Offset only when using the appGUI, for TclCommand this will create an error
  3154. # because the values for Z offset are created in build_ui()
  3155. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  3156. try:
  3157. z_offset = float(self.exc_tools[tool]['data']['tools_drill_offset']) * (-1)
  3158. except KeyError:
  3159. z_offset = 0
  3160. self.z_cut = z_offset + old_zcut
  3161. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  3162. if self.coordinates_type == "G90":
  3163. # Drillling! for Absolute coordinates type G90
  3164. # variables to display the percentage of work done
  3165. geo_len = len(optimized_path)
  3166. old_disp_number = 0
  3167. log.warning("Number of drills for which to generate GCode: %s" % str(geo_len))
  3168. loc_nr = 0
  3169. for point in optimized_path:
  3170. if self.app.abort_flag:
  3171. # graceful abort requested by the user
  3172. raise grace
  3173. if used_excellon_optimization_type == 'T':
  3174. locx = point[0]
  3175. locy = point[1]
  3176. else:
  3177. locx = locations[point][0]
  3178. locy = locations[point][1]
  3179. travels = self.app.exc_areas.travel_coordinates(start_point=(self.oldx, self.oldy),
  3180. end_point=(locx, locy),
  3181. tooldia=current_tooldia)
  3182. prev_z = None
  3183. for travel in travels:
  3184. locx = travel[1][0]
  3185. locy = travel[1][1]
  3186. if travel[0] is not None:
  3187. # move to next point
  3188. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3189. # raise to safe Z (travel[0]) each time because safe Z may be different
  3190. self.z_move = travel[0]
  3191. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3192. # restore z_move
  3193. self.z_move = self.exc_tools[tool]['data']['tools_drill_travelz']
  3194. else:
  3195. if prev_z is not None:
  3196. # move to next point
  3197. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3198. # we assume that previously the z_move was altered therefore raise to
  3199. # the travel_z (z_move)
  3200. self.z_move = self.exc_tools[tool]['data']['tools_drill_travelz']
  3201. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3202. else:
  3203. # move to next point
  3204. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3205. # store prev_z
  3206. prev_z = travel[0]
  3207. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3208. if self.multidepth and abs(self.z_cut) > abs(self.z_depthpercut):
  3209. doc = deepcopy(self.z_cut)
  3210. self.z_cut = 0.0
  3211. while abs(self.z_cut) < abs(doc):
  3212. self.z_cut -= self.z_depthpercut
  3213. if abs(doc) < abs(self.z_cut) < (abs(doc) + self.z_depthpercut):
  3214. self.z_cut = doc
  3215. gcode += self.doformat(p.down_code, x=locx, y=locy)
  3216. measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  3217. if self.f_retract is False:
  3218. gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  3219. measured_up_to_zero_distance += abs(self.z_cut)
  3220. measured_lift_distance += abs(self.z_move)
  3221. else:
  3222. measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  3223. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3224. else:
  3225. gcode += self.doformat(p.down_code, x=locx, y=locy)
  3226. measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  3227. if self.f_retract is False:
  3228. gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  3229. measured_up_to_zero_distance += abs(self.z_cut)
  3230. measured_lift_distance += abs(self.z_move)
  3231. else:
  3232. measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  3233. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3234. measured_distance += abs(distance_euclidian(locx, locy, self.oldx, self.oldy))
  3235. self.oldx = locx
  3236. self.oldy = locy
  3237. loc_nr += 1
  3238. disp_number = int(np.interp(loc_nr, [0, geo_len], [0, 100]))
  3239. if old_disp_number < disp_number <= 100:
  3240. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  3241. old_disp_number = disp_number
  3242. else:
  3243. self.app.inform.emit('[ERROR_NOTCL] %s...' % _('G91 coordinates not implemented'))
  3244. return 'fail'
  3245. self.z_cut = deepcopy(old_zcut)
  3246. else:
  3247. # We are not using Toolchange therefore we need to decide which tool properties to use
  3248. one_tool = 1
  3249. all_points = []
  3250. for tool in points:
  3251. # check if it has drills
  3252. if not points[tool]:
  3253. continue
  3254. all_points += points[tool]
  3255. if self.app.abort_flag:
  3256. # graceful abort requested by the user
  3257. raise grace
  3258. self.tool = one_tool
  3259. self.tooldia = self.exc_tools[one_tool]["tooldia"]
  3260. self.postdata['toolC'] = self.tooldia
  3261. if self.use_ui:
  3262. self.z_feedrate = self.exc_tools[one_tool]['data']['tools_drill_feedrate_z']
  3263. self.feedrate = self.exc_tools[one_tool]['data']['tools_drill_feedrate_z']
  3264. self.z_cut = self.exc_tools[one_tool]['data']['tools_drill_cutz']
  3265. gcode += self.doformat(p.z_feedrate_code)
  3266. if self.machinist_setting == 0:
  3267. if self.z_cut > 0:
  3268. self.app.inform.emit('[WARNING] %s' %
  3269. _("The Cut Z parameter has positive value. "
  3270. "It is the depth value to drill into material.\n"
  3271. "The Cut Z parameter needs to have a negative value, "
  3272. "assuming it is a typo "
  3273. "therefore the app will convert the value to negative. "
  3274. "Check the resulting CNC code (Gcode etc)."))
  3275. self.z_cut = -self.z_cut
  3276. elif self.z_cut == 0:
  3277. self.app.inform.emit('[WARNING] %s: %s' %
  3278. (_(
  3279. "The Cut Z parameter is zero. There will be no cut, "
  3280. "skipping file"),
  3281. exobj.options['name']))
  3282. return 'fail'
  3283. old_zcut = deepcopy(self.z_cut)
  3284. self.z_move = self.exc_tools[one_tool]['data']['tools_drill_travelz']
  3285. self.spindlespeed = self.exc_tools[one_tool]['data']['tools_drill_spindlespeed']
  3286. self.dwell = self.exc_tools[one_tool]['data']['tools_drill_dwell']
  3287. self.dwelltime = self.exc_tools[one_tool]['data']['tools_drill_dwelltime']
  3288. self.multidepth = self.exc_tools[one_tool]['data']['tools_drill_multidepth']
  3289. self.z_depthpercut = self.exc_tools[one_tool]['data']['tools_drill_depthperpass']
  3290. else:
  3291. old_zcut = deepcopy(self.z_cut)
  3292. # #########################################################################################################
  3293. # ############ Create the data. #################
  3294. # #########################################################################################################
  3295. locations = []
  3296. altPoints = []
  3297. optimized_path = []
  3298. if used_excellon_optimization_type == 'M':
  3299. if all_points:
  3300. locations = self.create_tool_data_array(points=all_points)
  3301. # if there are no locations then go to the next tool
  3302. if not locations:
  3303. return 'fail'
  3304. opt_time = self.app.defaults["excellon_search_time"]
  3305. optimized_path = self.optimized_ortools_meta(locations=locations, opt_time=opt_time)
  3306. elif used_excellon_optimization_type == 'B':
  3307. if all_points:
  3308. locations = self.create_tool_data_array(points=all_points)
  3309. # if there are no locations then go to the next tool
  3310. if not locations:
  3311. return 'fail'
  3312. optimized_path = self.optimized_ortools_basic(locations=locations)
  3313. elif used_excellon_optimization_type == 'T':
  3314. for point in all_points:
  3315. altPoints.append((point.coords.xy[0][0], point.coords.xy[1][0]))
  3316. optimized_path = self.optimized_travelling_salesman(altPoints)
  3317. else:
  3318. # it's actually not optimized path but here we build a list of (x,y) coordinates
  3319. # out of the tool's drills
  3320. for pt in all_points:
  3321. unoptimized_coords = (
  3322. pt.x,
  3323. pt.y
  3324. )
  3325. optimized_path.append(unoptimized_coords)
  3326. # #########################################################################################################
  3327. # #########################################################################################################
  3328. # Only if there are locations to drill
  3329. if not optimized_path:
  3330. return 'fail'
  3331. if self.app.abort_flag:
  3332. # graceful abort requested by the user
  3333. raise grace
  3334. # Spindle start
  3335. gcode += self.doformat(p.spindle_code)
  3336. # Dwell time
  3337. if self.dwell is True:
  3338. gcode += self.doformat(p.dwell_code)
  3339. current_tooldia = float('%.*f' % (self.decimals, float(self.exc_tools[one_tool]["tooldia"])))
  3340. self.app.inform.emit(
  3341. '%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  3342. str(current_tooldia),
  3343. str(self.units))
  3344. )
  3345. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  3346. # APPLY Offset only when using the appGUI, for TclCommand this will create an error
  3347. # because the values for Z offset are created in build_ui()
  3348. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  3349. try:
  3350. z_offset = float(self.exc_tools[one_tool]['data']['tools_drill_offset']) * (-1)
  3351. except KeyError:
  3352. z_offset = 0
  3353. self.z_cut = z_offset + old_zcut
  3354. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  3355. if self.coordinates_type == "G90":
  3356. # Drillling! for Absolute coordinates type G90
  3357. # variables to display the percentage of work done
  3358. geo_len = len(optimized_path)
  3359. old_disp_number = 0
  3360. log.warning("Number of drills for which to generate GCode: %s" % str(geo_len))
  3361. loc_nr = 0
  3362. for point in optimized_path:
  3363. if self.app.abort_flag:
  3364. # graceful abort requested by the user
  3365. raise grace
  3366. if used_excellon_optimization_type == 'T':
  3367. locx = point[0]
  3368. locy = point[1]
  3369. else:
  3370. locx = locations[point][0]
  3371. locy = locations[point][1]
  3372. travels = self.app.exc_areas.travel_coordinates(start_point=(self.oldx, self.oldy),
  3373. end_point=(locx, locy),
  3374. tooldia=current_tooldia)
  3375. prev_z = None
  3376. for travel in travels:
  3377. locx = travel[1][0]
  3378. locy = travel[1][1]
  3379. if travel[0] is not None:
  3380. # move to next point
  3381. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3382. # raise to safe Z (travel[0]) each time because safe Z may be different
  3383. self.z_move = travel[0]
  3384. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3385. # restore z_move
  3386. self.z_move = self.exc_tools[one_tool]['data']['tools_drill_travelz']
  3387. else:
  3388. if prev_z is not None:
  3389. # move to next point
  3390. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3391. # we assume that previously the z_move was altered therefore raise to
  3392. # the travel_z (z_move)
  3393. self.z_move = self.exc_tools[one_tool]['data']['tools_drill_travelz']
  3394. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3395. else:
  3396. # move to next point
  3397. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3398. # store prev_z
  3399. prev_z = travel[0]
  3400. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3401. if self.multidepth and abs(self.z_cut) > abs(self.z_depthpercut):
  3402. doc = deepcopy(self.z_cut)
  3403. self.z_cut = 0.0
  3404. while abs(self.z_cut) < abs(doc):
  3405. self.z_cut -= self.z_depthpercut
  3406. if abs(doc) < abs(self.z_cut) < (abs(doc) + self.z_depthpercut):
  3407. self.z_cut = doc
  3408. gcode += self.doformat(p.down_code, x=locx, y=locy)
  3409. measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  3410. if self.f_retract is False:
  3411. gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  3412. measured_up_to_zero_distance += abs(self.z_cut)
  3413. measured_lift_distance += abs(self.z_move)
  3414. else:
  3415. measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  3416. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3417. else:
  3418. gcode += self.doformat(p.down_code, x=locx, y=locy)
  3419. measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  3420. if self.f_retract is False:
  3421. gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  3422. measured_up_to_zero_distance += abs(self.z_cut)
  3423. measured_lift_distance += abs(self.z_move)
  3424. else:
  3425. measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  3426. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3427. measured_distance += abs(distance_euclidian(locx, locy, self.oldx, self.oldy))
  3428. self.oldx = locx
  3429. self.oldy = locy
  3430. loc_nr += 1
  3431. disp_number = int(np.interp(loc_nr, [0, geo_len], [0, 100]))
  3432. if old_disp_number < disp_number <= 100:
  3433. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  3434. old_disp_number = disp_number
  3435. else:
  3436. self.app.inform.emit('[ERROR_NOTCL] %s...' % _('G91 coordinates not implemented'))
  3437. return 'fail'
  3438. self.z_cut = deepcopy(old_zcut)
  3439. if used_excellon_optimization_type == 'M':
  3440. log.debug("The total travel distance with OR-TOOLS Metaheuristics is: %s" % str(measured_distance))
  3441. elif used_excellon_optimization_type == 'B':
  3442. log.debug("The total travel distance with OR-TOOLS Basic Algorithm is: %s" % str(measured_distance))
  3443. elif used_excellon_optimization_type == 'T':
  3444. log.debug("The total travel distance with Travelling Salesman Algorithm is: %s" % str(measured_distance))
  3445. else:
  3446. log.debug("The total travel distance with with no optimization is: %s" % str(measured_distance))
  3447. # if used_excellon_optimization_type == 'M':
  3448. # log.debug("Using OR-Tools Metaheuristic Guided Local Search drill path optimization.")
  3449. #
  3450. # if has_drills:
  3451. # for tool in tools:
  3452. # if self.app.abort_flag:
  3453. # # graceful abort requested by the user
  3454. # raise grace
  3455. #
  3456. # self.tool = tool
  3457. # self.tooldia = self.exc_tools[tool]["tooldia"]
  3458. # self.postdata['toolC'] = self.tooldia
  3459. #
  3460. # if self.use_ui:
  3461. # self.z_feedrate = self.exc_tools[tool]['data']['feedrate_z']
  3462. # self.feedrate = self.exc_tools[tool]['data']['feedrate']
  3463. # gcode += self.doformat(p.z_feedrate_code)
  3464. # self.z_cut = self.exc_tools[tool]['data']['cutz']
  3465. #
  3466. # if self.machinist_setting == 0:
  3467. # if self.z_cut > 0:
  3468. # self.app.inform.emit('[WARNING] %s' %
  3469. # _("The Cut Z parameter has positive value. "
  3470. # "It is the depth value to drill into material.\n"
  3471. # "The Cut Z parameter needs to have a negative value, "
  3472. # "assuming it is a typo "
  3473. # "therefore the app will convert the value to negative. "
  3474. # "Check the resulting CNC code (Gcode etc)."))
  3475. # self.z_cut = -self.z_cut
  3476. # elif self.z_cut == 0:
  3477. # self.app.inform.emit('[WARNING] %s: %s' %
  3478. # (_(
  3479. # "The Cut Z parameter is zero. There will be no cut, "
  3480. # "skipping file"),
  3481. # exobj.options['name']))
  3482. # return 'fail'
  3483. #
  3484. # old_zcut = deepcopy(self.z_cut)
  3485. #
  3486. # self.z_move = self.exc_tools[tool]['data']['travelz']
  3487. # self.spindlespeed = self.exc_tools[tool]['data']['spindlespeed']
  3488. # self.dwell = self.exc_tools[tool]['data']['dwell']
  3489. # self.dwelltime = self.exc_tools[tool]['data']['dwelltime']
  3490. # self.multidepth = self.exc_tools[tool]['data']['multidepth']
  3491. # self.z_depthpercut = self.exc_tools[tool]['data']['depthperpass']
  3492. # else:
  3493. # old_zcut = deepcopy(self.z_cut)
  3494. #
  3495. # # ###############################################
  3496. # # ############ Create the data. #################
  3497. # # ###############################################
  3498. # locations = self.create_tool_data_array(tool=tool, points=points)
  3499. # # if there are no locations then go to the next tool
  3500. # if not locations:
  3501. # continue
  3502. # optimized_path = self.optimized_ortools_meta(locations=locations)
  3503. #
  3504. # # Only if tool has points.
  3505. # if tool in points:
  3506. # if self.app.abort_flag:
  3507. # # graceful abort requested by the user
  3508. # raise grace
  3509. #
  3510. # # Tool change sequence (optional)
  3511. # if self.toolchange:
  3512. # gcode += self.doformat(p.toolchange_code, toolchangexy=(self.oldx, self.oldy))
  3513. # # Spindle start
  3514. # gcode += self.doformat(p.spindle_code)
  3515. # # Dwell time
  3516. # if self.dwell is True:
  3517. # gcode += self.doformat(p.dwell_code)
  3518. #
  3519. # current_tooldia = float('%.*f' % (self.decimals, float(self.exc_tools[tool]["tooldia"])))
  3520. #
  3521. # self.app.inform.emit(
  3522. # '%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  3523. # str(current_tooldia),
  3524. # str(self.units))
  3525. # )
  3526. #
  3527. # # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  3528. # # APPLY Offset only when using the appGUI, for TclCommand this will create an error
  3529. # # because the values for Z offset are created in build_ui()
  3530. # # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  3531. # try:
  3532. # z_offset = float(self.exc_tools[tool]['data']['offset']) * (-1)
  3533. # except KeyError:
  3534. # z_offset = 0
  3535. # self.z_cut = z_offset + old_zcut
  3536. #
  3537. # self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  3538. # if self.coordinates_type == "G90":
  3539. # # Drillling! for Absolute coordinates type G90
  3540. # # variables to display the percentage of work done
  3541. # geo_len = len(optimized_path)
  3542. #
  3543. # old_disp_number = 0
  3544. # log.warning("Number of drills for which to generate GCode: %s" % str(geo_len))
  3545. #
  3546. # loc_nr = 0
  3547. # for k in optimized_path:
  3548. # if self.app.abort_flag:
  3549. # # graceful abort requested by the user
  3550. # raise grace
  3551. #
  3552. # locx = locations[k][0]
  3553. # locy = locations[k][1]
  3554. #
  3555. # travels = self.app.exc_areas.travel_coordinates(start_point=(self.oldx, self.oldy),
  3556. # end_point=(locx, locy),
  3557. # tooldia=current_tooldia)
  3558. # prev_z = None
  3559. # for travel in travels:
  3560. # locx = travel[1][0]
  3561. # locy = travel[1][1]
  3562. #
  3563. # if travel[0] is not None:
  3564. # # move to next point
  3565. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3566. #
  3567. # # raise to safe Z (travel[0]) each time because safe Z may be different
  3568. # self.z_move = travel[0]
  3569. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3570. #
  3571. # # restore z_move
  3572. # self.z_move = self.exc_tools[tool]['data']['travelz']
  3573. # else:
  3574. # if prev_z is not None:
  3575. # # move to next point
  3576. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3577. #
  3578. # # we assume that previously the z_move was altered therefore raise to
  3579. # # the travel_z (z_move)
  3580. # self.z_move = self.exc_tools[tool]['data']['travelz']
  3581. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3582. # else:
  3583. # # move to next point
  3584. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3585. #
  3586. # # store prev_z
  3587. # prev_z = travel[0]
  3588. #
  3589. # # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3590. #
  3591. # if self.multidepth and abs(self.z_cut) > abs(self.z_depthpercut):
  3592. # doc = deepcopy(self.z_cut)
  3593. # self.z_cut = 0.0
  3594. #
  3595. # while abs(self.z_cut) < abs(doc):
  3596. #
  3597. # self.z_cut -= self.z_depthpercut
  3598. # if abs(doc) < abs(self.z_cut) < (abs(doc) + self.z_depthpercut):
  3599. # self.z_cut = doc
  3600. # gcode += self.doformat(p.down_code, x=locx, y=locy)
  3601. #
  3602. # measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  3603. #
  3604. # if self.f_retract is False:
  3605. # gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  3606. # measured_up_to_zero_distance += abs(self.z_cut)
  3607. # measured_lift_distance += abs(self.z_move)
  3608. # else:
  3609. # measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  3610. #
  3611. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3612. #
  3613. # else:
  3614. # gcode += self.doformat(p.down_code, x=locx, y=locy)
  3615. #
  3616. # measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  3617. #
  3618. # if self.f_retract is False:
  3619. # gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  3620. # measured_up_to_zero_distance += abs(self.z_cut)
  3621. # measured_lift_distance += abs(self.z_move)
  3622. # else:
  3623. # measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  3624. #
  3625. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3626. #
  3627. # measured_distance += abs(distance_euclidian(locx, locy, self.oldx, self.oldy))
  3628. # self.oldx = locx
  3629. # self.oldy = locy
  3630. #
  3631. # loc_nr += 1
  3632. # disp_number = int(np.interp(loc_nr, [0, geo_len], [0, 100]))
  3633. #
  3634. # if old_disp_number < disp_number <= 100:
  3635. # self.app.proc_container.update_view_text(' %d%%' % disp_number)
  3636. # old_disp_number = disp_number
  3637. #
  3638. # else:
  3639. # self.app.inform.emit('[ERROR_NOTCL] %s...' % _('G91 coordinates not implemented'))
  3640. # return 'fail'
  3641. # self.z_cut = deepcopy(old_zcut)
  3642. # else:
  3643. # log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> "
  3644. # "The loaded Excellon file has no drills ...")
  3645. # self.app.inform.emit('[ERROR_NOTCL] %s...' % _('The loaded Excellon file has no drills'))
  3646. # return 'fail'
  3647. #
  3648. # log.debug("The total travel distance with OR-TOOLS Metaheuristics is: %s" % str(measured_distance))
  3649. #
  3650. # elif used_excellon_optimization_type == 'B':
  3651. # log.debug("Using OR-Tools Basic drill path optimization.")
  3652. #
  3653. # if has_drills:
  3654. # for tool in tools:
  3655. # if self.app.abort_flag:
  3656. # # graceful abort requested by the user
  3657. # raise grace
  3658. #
  3659. # self.tool = tool
  3660. # self.tooldia = self.exc_tools[tool]["tooldia"]
  3661. # self.postdata['toolC'] = self.tooldia
  3662. #
  3663. # if self.use_ui:
  3664. # self.z_feedrate = self.exc_tools[tool]['data']['feedrate_z']
  3665. # self.feedrate = self.exc_tools[tool]['data']['feedrate']
  3666. # gcode += self.doformat(p.z_feedrate_code)
  3667. # self.z_cut = self.exc_tools[tool]['data']['cutz']
  3668. #
  3669. # if self.machinist_setting == 0:
  3670. # if self.z_cut > 0:
  3671. # self.app.inform.emit('[WARNING] %s' %
  3672. # _("The Cut Z parameter has positive value. "
  3673. # "It is the depth value to drill into material.\n"
  3674. # "The Cut Z parameter needs to have a negative value, "
  3675. # "assuming it is a typo "
  3676. # "therefore the app will convert the value to negative. "
  3677. # "Check the resulting CNC code (Gcode etc)."))
  3678. # self.z_cut = -self.z_cut
  3679. # elif self.z_cut == 0:
  3680. # self.app.inform.emit('[WARNING] %s: %s' %
  3681. # (_(
  3682. # "The Cut Z parameter is zero. There will be no cut, "
  3683. # "skipping file"),
  3684. # exobj.options['name']))
  3685. # return 'fail'
  3686. #
  3687. # old_zcut = deepcopy(self.z_cut)
  3688. #
  3689. # self.z_move = self.exc_tools[tool]['data']['travelz']
  3690. #
  3691. # self.spindlespeed = self.exc_tools[tool]['data']['spindlespeed']
  3692. # self.dwell = self.exc_tools[tool]['data']['dwell']
  3693. # self.dwelltime = self.exc_tools[tool]['data']['dwelltime']
  3694. # self.multidepth = self.exc_tools[tool]['data']['multidepth']
  3695. # self.z_depthpercut = self.exc_tools[tool]['data']['depthperpass']
  3696. # else:
  3697. # old_zcut = deepcopy(self.z_cut)
  3698. #
  3699. # # ###############################################
  3700. # # ############ Create the data. #################
  3701. # # ###############################################
  3702. # locations = self.create_tool_data_array(tool=tool, points=points)
  3703. # # if there are no locations then go to the next tool
  3704. # if not locations:
  3705. # continue
  3706. # optimized_path = self.optimized_ortools_basic(locations=locations)
  3707. #
  3708. # # Only if tool has points.
  3709. # if tool in points:
  3710. # if self.app.abort_flag:
  3711. # # graceful abort requested by the user
  3712. # raise grace
  3713. #
  3714. # # Tool change sequence (optional)
  3715. # if self.toolchange:
  3716. # gcode += self.doformat(p.toolchange_code, toolchangexy=(self.oldx, self.oldy))
  3717. # gcode += self.doformat(p.spindle_code) # Spindle start)
  3718. # if self.dwell is True:
  3719. # gcode += self.doformat(p.dwell_code) # Dwell time
  3720. # else:
  3721. # gcode += self.doformat(p.spindle_code)
  3722. # if self.dwell is True:
  3723. # gcode += self.doformat(p.dwell_code) # Dwell time
  3724. #
  3725. # current_tooldia = float('%.*f' % (self.decimals, float(self.exc_tools[tool]["tooldia"])))
  3726. #
  3727. # self.app.inform.emit(
  3728. # '%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  3729. # str(current_tooldia),
  3730. # str(self.units))
  3731. # )
  3732. #
  3733. # # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  3734. # # APPLY Offset only when using the appGUI, for TclCommand this will create an error
  3735. # # because the values for Z offset are created in build_ui()
  3736. # # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  3737. # try:
  3738. # z_offset = float(self.exc_tools[tool]['data']['offset']) * (-1)
  3739. # except KeyError:
  3740. # z_offset = 0
  3741. # self.z_cut = z_offset + old_zcut
  3742. #
  3743. # self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  3744. # if self.coordinates_type == "G90":
  3745. # # Drillling! for Absolute coordinates type G90
  3746. # # variables to display the percentage of work done
  3747. # geo_len = len(optimized_path)
  3748. # old_disp_number = 0
  3749. # log.warning("Number of drills for which to generate GCode: %s" % str(geo_len))
  3750. #
  3751. # loc_nr = 0
  3752. # for k in optimized_path:
  3753. # if self.app.abort_flag:
  3754. # # graceful abort requested by the user
  3755. # raise grace
  3756. #
  3757. # locx = locations[k][0]
  3758. # locy = locations[k][1]
  3759. #
  3760. # travels = self.app.exc_areas.travel_coordinates(start_point=(self.oldx, self.oldy),
  3761. # end_point=(locx, locy),
  3762. # tooldia=current_tooldia)
  3763. # prev_z = None
  3764. # for travel in travels:
  3765. # locx = travel[1][0]
  3766. # locy = travel[1][1]
  3767. #
  3768. # if travel[0] is not None:
  3769. # # move to next point
  3770. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3771. #
  3772. # # raise to safe Z (travel[0]) each time because safe Z may be different
  3773. # self.z_move = travel[0]
  3774. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3775. #
  3776. # # restore z_move
  3777. # self.z_move = self.exc_tools[tool]['data']['travelz']
  3778. # else:
  3779. # if prev_z is not None:
  3780. # # move to next point
  3781. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3782. #
  3783. # # we assume that previously the z_move was altered therefore raise to
  3784. # # the travel_z (z_move)
  3785. # self.z_move = self.exc_tools[tool]['data']['travelz']
  3786. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3787. # else:
  3788. # # move to next point
  3789. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3790. #
  3791. # # store prev_z
  3792. # prev_z = travel[0]
  3793. #
  3794. # # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3795. #
  3796. # if self.multidepth and abs(self.z_cut) > abs(self.z_depthpercut):
  3797. # doc = deepcopy(self.z_cut)
  3798. # self.z_cut = 0.0
  3799. #
  3800. # while abs(self.z_cut) < abs(doc):
  3801. #
  3802. # self.z_cut -= self.z_depthpercut
  3803. # if abs(doc) < abs(self.z_cut) < (abs(doc) + self.z_depthpercut):
  3804. # self.z_cut = doc
  3805. # gcode += self.doformat(p.down_code, x=locx, y=locy)
  3806. #
  3807. # measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  3808. #
  3809. # if self.f_retract is False:
  3810. # gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  3811. # measured_up_to_zero_distance += abs(self.z_cut)
  3812. # measured_lift_distance += abs(self.z_move)
  3813. # else:
  3814. # measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  3815. #
  3816. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3817. #
  3818. # else:
  3819. # gcode += self.doformat(p.down_code, x=locx, y=locy)
  3820. #
  3821. # measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  3822. #
  3823. # if self.f_retract is False:
  3824. # gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  3825. # measured_up_to_zero_distance += abs(self.z_cut)
  3826. # measured_lift_distance += abs(self.z_move)
  3827. # else:
  3828. # measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  3829. #
  3830. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3831. #
  3832. # measured_distance += abs(distance_euclidian(locx, locy, self.oldx, self.oldy))
  3833. # self.oldx = locx
  3834. # self.oldy = locy
  3835. #
  3836. # loc_nr += 1
  3837. # disp_number = int(np.interp(loc_nr, [0, geo_len], [0, 100]))
  3838. #
  3839. # if old_disp_number < disp_number <= 100:
  3840. # self.app.proc_container.update_view_text(' %d%%' % disp_number)
  3841. # old_disp_number = disp_number
  3842. #
  3843. # else:
  3844. # self.app.inform.emit('[ERROR_NOTCL] %s...' % _('G91 coordinates not implemented'))
  3845. # return 'fail'
  3846. # self.z_cut = deepcopy(old_zcut)
  3847. # else:
  3848. # log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> "
  3849. # "The loaded Excellon file has no drills ...")
  3850. # self.app.inform.emit('[ERROR_NOTCL] %s...' % _('The loaded Excellon file has no drills'))
  3851. # return 'fail'
  3852. #
  3853. # log.debug("The total travel distance with OR-TOOLS Basic Algorithm is: %s" % str(measured_distance))
  3854. #
  3855. # elif used_excellon_optimization_type == 'T':
  3856. # log.debug("Using Travelling Salesman drill path optimization.")
  3857. #
  3858. # for tool in tools:
  3859. # if self.app.abort_flag:
  3860. # # graceful abort requested by the user
  3861. # raise grace
  3862. #
  3863. # if has_drills:
  3864. # self.tool = tool
  3865. # self.tooldia = self.exc_tools[tool]["tooldia"]
  3866. # self.postdata['toolC'] = self.tooldia
  3867. #
  3868. # if self.use_ui:
  3869. # self.z_feedrate = self.exc_tools[tool]['data']['feedrate_z']
  3870. # self.feedrate = self.exc_tools[tool]['data']['feedrate']
  3871. # gcode += self.doformat(p.z_feedrate_code)
  3872. #
  3873. # self.z_cut = self.exc_tools[tool]['data']['cutz']
  3874. #
  3875. # if self.machinist_setting == 0:
  3876. # if self.z_cut > 0:
  3877. # self.app.inform.emit('[WARNING] %s' %
  3878. # _("The Cut Z parameter has positive value. "
  3879. # "It is the depth value to drill into material.\n"
  3880. # "The Cut Z parameter needs to have a negative value, "
  3881. # "assuming it is a typo "
  3882. # "therefore the app will convert the value to negative. "
  3883. # "Check the resulting CNC code (Gcode etc)."))
  3884. # self.z_cut = -self.z_cut
  3885. # elif self.z_cut == 0:
  3886. # self.app.inform.emit('[WARNING] %s: %s' %
  3887. # (_(
  3888. # "The Cut Z parameter is zero. There will be no cut, "
  3889. # "skipping file"),
  3890. # exobj.options['name']))
  3891. # return 'fail'
  3892. #
  3893. # old_zcut = deepcopy(self.z_cut)
  3894. #
  3895. # self.z_move = self.exc_tools[tool]['data']['travelz']
  3896. # self.spindlespeed = self.exc_tools[tool]['data']['spindlespeed']
  3897. # self.dwell = self.exc_tools[tool]['data']['dwell']
  3898. # self.dwelltime = self.exc_tools[tool]['data']['dwelltime']
  3899. # self.multidepth = self.exc_tools[tool]['data']['multidepth']
  3900. # self.z_depthpercut = self.exc_tools[tool]['data']['depthperpass']
  3901. # else:
  3902. # old_zcut = deepcopy(self.z_cut)
  3903. #
  3904. # # ###############################################
  3905. # # ############ Create the data. #################
  3906. # # ###############################################
  3907. # altPoints = []
  3908. # for point in points[tool]:
  3909. # altPoints.append((point.coords.xy[0][0], point.coords.xy[1][0]))
  3910. # optimized_path = self.optimized_travelling_salesman(altPoints)
  3911. #
  3912. # # Only if tool has points.
  3913. # if tool in points:
  3914. # if self.app.abort_flag:
  3915. # # graceful abort requested by the user
  3916. # raise grace
  3917. #
  3918. # # Tool change sequence (optional)
  3919. # if self.toolchange:
  3920. # gcode += self.doformat(p.toolchange_code, toolchangexy=(self.oldx, self.oldy))
  3921. # gcode += self.doformat(p.spindle_code) # Spindle start)
  3922. # if self.dwell is True:
  3923. # gcode += self.doformat(p.dwell_code) # Dwell time
  3924. # else:
  3925. # gcode += self.doformat(p.spindle_code)
  3926. # if self.dwell is True:
  3927. # gcode += self.doformat(p.dwell_code) # Dwell time
  3928. #
  3929. # current_tooldia = float('%.*f' % (self.decimals, float(self.exc_tools[tool]["tooldia"])))
  3930. #
  3931. # self.app.inform.emit(
  3932. # '%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  3933. # str(current_tooldia),
  3934. # str(self.units))
  3935. # )
  3936. #
  3937. # # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  3938. # # APPLY Offset only when using the appGUI, for TclCommand this will create an error
  3939. # # because the values for Z offset are created in build_ui()
  3940. # # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  3941. # try:
  3942. # z_offset = float(self.exc_tools[tool]['data']['offset']) * (-1)
  3943. # except KeyError:
  3944. # z_offset = 0
  3945. # self.z_cut = z_offset + old_zcut
  3946. #
  3947. # self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  3948. # if self.coordinates_type == "G90":
  3949. # # Drillling! for Absolute coordinates type G90
  3950. # # variables to display the percentage of work done
  3951. # geo_len = len(optimized_path)
  3952. # old_disp_number = 0
  3953. # log.warning("Number of drills for which to generate GCode: %s" % str(geo_len))
  3954. #
  3955. # loc_nr = 0
  3956. # for point in optimized_path:
  3957. # if self.app.abort_flag:
  3958. # # graceful abort requested by the user
  3959. # raise grace
  3960. #
  3961. # locx = point[0]
  3962. # locy = point[1]
  3963. #
  3964. # travels = self.app.exc_areas.travel_coordinates(start_point=(self.oldx, self.oldy),
  3965. # end_point=(locx, locy),
  3966. # tooldia=current_tooldia)
  3967. # prev_z = None
  3968. # for travel in travels:
  3969. # locx = travel[1][0]
  3970. # locy = travel[1][1]
  3971. #
  3972. # if travel[0] is not None:
  3973. # # move to next point
  3974. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3975. #
  3976. # # raise to safe Z (travel[0]) each time because safe Z may be different
  3977. # self.z_move = travel[0]
  3978. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3979. #
  3980. # # restore z_move
  3981. # self.z_move = self.exc_tools[tool]['data']['travelz']
  3982. # else:
  3983. # if prev_z is not None:
  3984. # # move to next point
  3985. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3986. #
  3987. # # we assume that previously the z_move was altered therefore raise to
  3988. # # the travel_z (z_move)
  3989. # self.z_move = self.exc_tools[tool]['data']['travelz']
  3990. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3991. # else:
  3992. # # move to next point
  3993. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3994. #
  3995. # # store prev_z
  3996. # prev_z = travel[0]
  3997. #
  3998. # # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3999. #
  4000. # if self.multidepth and abs(self.z_cut) > abs(self.z_depthpercut):
  4001. # doc = deepcopy(self.z_cut)
  4002. # self.z_cut = 0.0
  4003. #
  4004. # while abs(self.z_cut) < abs(doc):
  4005. #
  4006. # self.z_cut -= self.z_depthpercut
  4007. # if abs(doc) < abs(self.z_cut) < (abs(doc) + self.z_depthpercut):
  4008. # self.z_cut = doc
  4009. # gcode += self.doformat(p.down_code, x=locx, y=locy)
  4010. #
  4011. # measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  4012. #
  4013. # if self.f_retract is False:
  4014. # gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  4015. # measured_up_to_zero_distance += abs(self.z_cut)
  4016. # measured_lift_distance += abs(self.z_move)
  4017. # else:
  4018. # measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  4019. #
  4020. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  4021. #
  4022. # else:
  4023. # gcode += self.doformat(p.down_code, x=locx, y=locy)
  4024. #
  4025. # measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  4026. #
  4027. # if self.f_retract is False:
  4028. # gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  4029. # measured_up_to_zero_distance += abs(self.z_cut)
  4030. # measured_lift_distance += abs(self.z_move)
  4031. # else:
  4032. # measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  4033. #
  4034. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  4035. #
  4036. # measured_distance += abs(distance_euclidian(locx, locy, self.oldx, self.oldy))
  4037. # self.oldx = locx
  4038. # self.oldy = locy
  4039. #
  4040. # loc_nr += 1
  4041. # disp_number = int(np.interp(loc_nr, [0, geo_len], [0, 100]))
  4042. #
  4043. # if old_disp_number < disp_number <= 100:
  4044. # self.app.proc_container.update_view_text(' %d%%' % disp_number)
  4045. # old_disp_number = disp_number
  4046. # else:
  4047. # self.app.inform.emit('[ERROR_NOTCL] %s...' % _('G91 coordinates not implemented'))
  4048. # return 'fail'
  4049. # else:
  4050. # log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> "
  4051. # "The loaded Excellon file has no drills ...")
  4052. # self.app.inform.emit('[ERROR_NOTCL] %s...' % _('The loaded Excellon file has no drills'))
  4053. # return 'fail'
  4054. # self.z_cut = deepcopy(old_zcut)
  4055. # log.debug("The total travel distance with Travelling Salesman Algorithm is: %s" % str(measured_distance))
  4056. #
  4057. # else:
  4058. # log.debug("camlib.CNCJob.generate_from_excellon_by_tool(): Chosen drill optimization doesn't exist.")
  4059. # return 'fail'
  4060. # Spindle stop
  4061. gcode += self.doformat(p.spindle_stop_code)
  4062. # Move to End position
  4063. gcode += self.doformat(p.end_code, x=0, y=0)
  4064. # #############################################################################################################
  4065. # ############################# Calculate DISTANCE and ESTIMATED TIME #########################################
  4066. # #############################################################################################################
  4067. measured_distance += abs(distance_euclidian(self.oldx, self.oldy, 0, 0))
  4068. log.debug("The total travel distance including travel to end position is: %s" %
  4069. str(measured_distance) + '\n')
  4070. self.travel_distance = measured_distance
  4071. # I use the value of self.feedrate_rapid for the feadrate in case of the measure_lift_distance and for
  4072. # traveled_time because it is not always possible to determine the feedrate that the CNC machine uses
  4073. # for G0 move (the fastest speed available to the CNC router). Although self.feedrate_rapids is used only with
  4074. # Marlin preprocessor and derivatives.
  4075. self.routing_time = (measured_down_distance + measured_up_to_zero_distance) / self.feedrate
  4076. lift_time = measured_lift_distance / self.feedrate_rapid
  4077. traveled_time = measured_distance / self.feedrate_rapid
  4078. self.routing_time += lift_time + traveled_time
  4079. # #############################################################################################################
  4080. # ############################# Store the GCODE for further usage ############################################
  4081. # #############################################################################################################
  4082. self.gcode = gcode
  4083. self.app.inform.emit(_("Finished G-Code generation..."))
  4084. return 'OK'
  4085. def generate_from_multitool_geometry(self, geometry, append=True, tooldia=None, offset=0.0, tolerance=0, z_cut=1.0,
  4086. z_move=2.0, feedrate=2.0, feedrate_z=2.0, feedrate_rapid=30,
  4087. spindlespeed=None, spindledir='CW', dwell=False, dwelltime=1.0,
  4088. multidepth=False, depthpercut=None, toolchange=False, toolchangez=1.0,
  4089. toolchangexy="0.0, 0.0", extracut=False, extracut_length=0.2,
  4090. startz=None, endz=2.0, endxy='', pp_geometry_name=None, tool_no=1):
  4091. """
  4092. Algorithm to generate from multitool Geometry.
  4093. Algorithm description:
  4094. ----------------------
  4095. Uses RTree to find the nearest path to follow.
  4096. :param geometry:
  4097. :param append:
  4098. :param tooldia:
  4099. :param offset:
  4100. :param tolerance:
  4101. :param z_cut:
  4102. :param z_move:
  4103. :param feedrate:
  4104. :param feedrate_z:
  4105. :param feedrate_rapid:
  4106. :param spindlespeed:
  4107. :param spindledir: Direction of rotation for the spindle. If using GRBL laser mode will
  4108. adjust the laser mode
  4109. :param dwell:
  4110. :param dwelltime:
  4111. :param multidepth: If True, use multiple passes to reach the desired depth.
  4112. :param depthpercut: Maximum depth in each pass.
  4113. :param toolchange:
  4114. :param toolchangez:
  4115. :param toolchangexy:
  4116. :param extracut: Adds (or not) an extra cut at the end of each path overlapping the
  4117. first point in path to ensure complete copper removal
  4118. :param extracut_length: Extra cut legth at the end of the path
  4119. :param startz:
  4120. :param endz:
  4121. :param endxy:
  4122. :param pp_geometry_name:
  4123. :param tool_no:
  4124. :return: GCode - string
  4125. """
  4126. log.debug("generate_from_multitool_geometry()")
  4127. temp_solid_geometry = []
  4128. if offset != 0.0:
  4129. for it in geometry:
  4130. # if the geometry is a closed shape then create a Polygon out of it
  4131. if isinstance(it, LineString):
  4132. c = it.coords
  4133. if c[0] == c[-1]:
  4134. it = Polygon(it)
  4135. temp_solid_geometry.append(it.buffer(offset, join_style=2))
  4136. else:
  4137. temp_solid_geometry = geometry
  4138. # ## Flatten the geometry. Only linear elements (no polygons) remain.
  4139. flat_geometry = self.flatten(temp_solid_geometry, pathonly=True)
  4140. log.debug("%d paths" % len(flat_geometry))
  4141. try:
  4142. self.tooldia = float(tooldia)
  4143. except Exception as e:
  4144. self.app.inform.emit('[ERROR] %s\n%s' % (_("Failed."), str(e)))
  4145. return 'fail'
  4146. self.z_cut = float(z_cut) if z_cut else None
  4147. self.z_move = float(z_move) if z_move is not None else None
  4148. self.feedrate = float(feedrate) if feedrate else self.app.defaults["geometry_feedrate"]
  4149. self.z_feedrate = float(feedrate_z) if feedrate_z is not None else self.app.defaults["geometry_feedrate_z"]
  4150. self.feedrate_rapid = float(feedrate_rapid) if feedrate_rapid else self.app.defaults["geometry_feedrate_rapid"]
  4151. self.spindlespeed = int(spindlespeed) if spindlespeed != 0 else None
  4152. self.spindledir = spindledir
  4153. self.dwell = dwell
  4154. self.dwelltime = float(dwelltime) if dwelltime else self.app.defaults["geometry_dwelltime"]
  4155. self.startz = float(startz) if startz is not None else self.app.defaults["geometry_startz"]
  4156. self.z_end = float(endz) if endz is not None else self.app.defaults["geometry_endz"]
  4157. self.xy_end = re.sub('[()\[\]]', '', str(endxy)) if endxy else self.app.defaults["geometry_endxy"]
  4158. if self.xy_end and self.xy_end != '':
  4159. self.xy_end = [float(eval(a)) for a in self.xy_end.split(",")]
  4160. if self.xy_end and len(self.xy_end) < 2:
  4161. self.app.inform.emit('[ERROR] %s' % _("The End Move X,Y field in Edit -> Preferences has to be "
  4162. "in the format (x, y) but now there is only one value, not two."))
  4163. return 'fail'
  4164. self.z_depthpercut = float(depthpercut) if depthpercut else self.app.defaults["geometry_depthperpass"]
  4165. self.multidepth = multidepth
  4166. self.z_toolchange = float(toolchangez) if toolchangez is not None else self.app.defaults["geometry_toolchangez"]
  4167. # it servers in the preprocessor file
  4168. self.tool = tool_no
  4169. try:
  4170. if toolchangexy == '':
  4171. self.xy_toolchange = None
  4172. else:
  4173. self.xy_toolchange = re.sub('[()\[\]]', '', str(toolchangexy)) \
  4174. if toolchangexy else self.app.defaults["geometry_toolchangexy"]
  4175. if self.xy_toolchange and self.xy_toolchange != '':
  4176. self.xy_toolchange = [float(eval(a)) for a in self.xy_toolchange.split(",")]
  4177. if len(self.xy_toolchange) < 2:
  4178. self.app.inform.emit('[ERROR] %s' % _("The Toolchange X,Y field in Edit -> Preferences has to be "
  4179. "in the format (x, y) \n"
  4180. "but now there is only one value, not two."))
  4181. return 'fail'
  4182. except Exception as e:
  4183. log.debug("camlib.CNCJob.generate_from_multitool_geometry() --> %s" % str(e))
  4184. pass
  4185. self.pp_geometry_name = pp_geometry_name if pp_geometry_name else 'default'
  4186. self.f_plunge = self.app.defaults["geometry_f_plunge"]
  4187. if self.z_cut is None:
  4188. if 'laser' not in self.pp_geometry_name:
  4189. self.app.inform.emit(
  4190. '[ERROR_NOTCL] %s' % _("Cut_Z parameter is None or zero. Most likely a bad combinations of "
  4191. "other parameters."))
  4192. return 'fail'
  4193. else:
  4194. self.z_cut = 0
  4195. if self.machinist_setting == 0:
  4196. if self.z_cut > 0:
  4197. self.app.inform.emit('[WARNING] %s' %
  4198. _("The Cut Z parameter has positive value. "
  4199. "It is the depth value to cut into material.\n"
  4200. "The Cut Z parameter needs to have a negative value, assuming it is a typo "
  4201. "therefore the app will convert the value to negative."
  4202. "Check the resulting CNC code (Gcode etc)."))
  4203. self.z_cut = -self.z_cut
  4204. elif self.z_cut == 0 and 'laser' not in self.pp_geometry_name:
  4205. self.app.inform.emit('[WARNING] %s: %s' %
  4206. (_("The Cut Z parameter is zero. There will be no cut, skipping file"),
  4207. self.options['name']))
  4208. return 'fail'
  4209. if self.z_move is None:
  4210. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Travel Z parameter is None or zero."))
  4211. return 'fail'
  4212. if self.z_move < 0:
  4213. self.app.inform.emit('[WARNING] %s' %
  4214. _("The Travel Z parameter has negative value. "
  4215. "It is the height value to travel between cuts.\n"
  4216. "The Z Travel parameter needs to have a positive value, assuming it is a typo "
  4217. "therefore the app will convert the value to positive."
  4218. "Check the resulting CNC code (Gcode etc)."))
  4219. self.z_move = -self.z_move
  4220. elif self.z_move == 0:
  4221. self.app.inform.emit('[WARNING] %s: %s' %
  4222. (_("The Z Travel parameter is zero. This is dangerous, skipping file"),
  4223. self.options['name']))
  4224. return 'fail'
  4225. # made sure that depth_per_cut is no more then the z_cut
  4226. if abs(self.z_cut) < self.z_depthpercut:
  4227. self.z_depthpercut = abs(self.z_cut)
  4228. # ## Index first and last points in paths
  4229. # What points to index.
  4230. def get_pts(o):
  4231. return [o.coords[0], o.coords[-1]]
  4232. # Create the indexed storage.
  4233. storage = FlatCAMRTreeStorage()
  4234. storage.get_points = get_pts
  4235. # Store the geometry
  4236. log.debug("Indexing geometry before generating G-Code...")
  4237. self.app.inform.emit(_("Indexing geometry before generating G-Code..."))
  4238. for geo_shape in flat_geometry:
  4239. if self.app.abort_flag:
  4240. # graceful abort requested by the user
  4241. raise grace
  4242. if geo_shape is not None:
  4243. storage.insert(geo_shape)
  4244. # self.input_geometry_bounds = geometry.bounds()
  4245. if not append:
  4246. self.gcode = ""
  4247. # tell preprocessor the number of tool (for toolchange)
  4248. self.tool = tool_no
  4249. # this is the tool diameter, it is used as such to accommodate the preprocessor who need the tool diameter
  4250. # given under the name 'toolC'
  4251. self.postdata['toolC'] = self.tooldia
  4252. # Initial G-Code
  4253. self.pp_geometry = self.app.preprocessors[self.pp_geometry_name]
  4254. p = self.pp_geometry
  4255. self.gcode = self.doformat(p.start_code)
  4256. self.gcode += self.doformat(p.feedrate_code) # sets the feed rate
  4257. if toolchange is False:
  4258. self.gcode += self.doformat(p.lift_code, x=0, y=0) # Move (up) to travel height
  4259. self.gcode += self.doformat(p.startz_code, x=0, y=0)
  4260. if toolchange:
  4261. # if "line_xyz" in self.pp_geometry_name:
  4262. # self.gcode += self.doformat(p.toolchange_code, x=self.xy_toolchange[0], y=self.xy_toolchange[1])
  4263. # else:
  4264. # self.gcode += self.doformat(p.toolchange_code)
  4265. self.gcode += self.doformat(p.toolchange_code)
  4266. if 'laser' not in self.pp_geometry_name:
  4267. self.gcode += self.doformat(p.spindle_code) # Spindle start
  4268. else:
  4269. # for laser this will disable the laser
  4270. self.gcode += self.doformat(p.lift_code, x=self.oldx, y=self.oldy) # Move (up) to travel height
  4271. if self.dwell is True:
  4272. self.gcode += self.doformat(p.dwell_code) # Dwell time
  4273. else:
  4274. if 'laser' not in self.pp_geometry_name:
  4275. self.gcode += self.doformat(p.spindle_code) # Spindle start
  4276. if self.dwell is True:
  4277. self.gcode += self.doformat(p.dwell_code) # Dwell time
  4278. total_travel = 0.0
  4279. total_cut = 0.0
  4280. # ## Iterate over geometry paths getting the nearest each time.
  4281. log.debug("Starting G-Code...")
  4282. self.app.inform.emit('%s...' % _("Starting G-Code"))
  4283. path_count = 0
  4284. current_pt = (0, 0)
  4285. # variables to display the percentage of work done
  4286. geo_len = len(flat_geometry)
  4287. old_disp_number = 0
  4288. log.warning("Number of paths for which to generate GCode: %s" % str(geo_len))
  4289. current_tooldia = float('%.*f' % (self.decimals, float(self.tooldia)))
  4290. self.app.inform.emit('%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  4291. str(current_tooldia),
  4292. str(self.units)))
  4293. pt, geo = storage.nearest(current_pt)
  4294. try:
  4295. while True:
  4296. if self.app.abort_flag:
  4297. # graceful abort requested by the user
  4298. raise grace
  4299. path_count += 1
  4300. # Remove before modifying, otherwise deletion will fail.
  4301. storage.remove(geo)
  4302. # If last point in geometry is the nearest but prefer the first one if last point == first point
  4303. # then reverse coordinates.
  4304. if pt != geo.coords[0] and pt == geo.coords[-1]:
  4305. # geo.coords = list(geo.coords)[::-1] # Shapley 2.0
  4306. geo = LineString(list(geo.coords)[::-1])
  4307. # ---------- Single depth/pass --------
  4308. if not multidepth:
  4309. # calculate the cut distance
  4310. total_cut = total_cut + geo.length
  4311. self.gcode += self.create_gcode_single_pass(geo, current_tooldia, extracut, extracut_length,
  4312. tolerance, z_move=z_move, old_point=current_pt)
  4313. # --------- Multi-pass ---------
  4314. else:
  4315. # calculate the cut distance
  4316. # due of the number of cuts (multi depth) it has to multiplied by the number of cuts
  4317. nr_cuts = 0
  4318. depth = abs(self.z_cut)
  4319. while depth > 0:
  4320. nr_cuts += 1
  4321. depth -= float(self.z_depthpercut)
  4322. total_cut += (geo.length * nr_cuts)
  4323. gc, geo = self.create_gcode_multi_pass(geo, current_tooldia, extracut, extracut_length,
  4324. tolerance, z_move=z_move, postproc=p,
  4325. old_point=current_pt)
  4326. self.gcode += gc
  4327. # calculate the total distance
  4328. total_travel = total_travel + abs(distance(pt1=current_pt, pt2=pt))
  4329. current_pt = geo.coords[-1]
  4330. pt, geo = storage.nearest(current_pt) # Next
  4331. disp_number = int(np.interp(path_count, [0, geo_len], [0, 100]))
  4332. if old_disp_number < disp_number <= 100:
  4333. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  4334. old_disp_number = disp_number
  4335. except StopIteration: # Nothing found in storage.
  4336. pass
  4337. log.debug("Finished G-Code... %s paths traced." % path_count)
  4338. # add move to end position
  4339. total_travel += abs(distance_euclidian(current_pt[0], current_pt[1], 0, 0))
  4340. self.travel_distance += total_travel + total_cut
  4341. self.routing_time += total_cut / self.feedrate
  4342. # Finish
  4343. self.gcode += self.doformat(p.spindle_stop_code)
  4344. self.gcode += self.doformat(p.lift_code, x=current_pt[0], y=current_pt[1])
  4345. self.gcode += self.doformat(p.end_code, x=0, y=0)
  4346. self.app.inform.emit(
  4347. '%s... %s %s.' % (_("Finished G-Code generation"), str(path_count), _("paths traced"))
  4348. )
  4349. return self.gcode
  4350. def geometry_tool_gcode_gen(self, tool, tools, first_pt, tolerance, is_first=False, is_last=False,
  4351. toolchange=False):
  4352. """
  4353. Algorithm to generate GCode from multitool Geometry.
  4354. :param tool: tool number for which to generate GCode
  4355. :type tool: int
  4356. :param tools: a dictionary holding all the tools and data
  4357. :type tools: dict
  4358. :param first_pt: a tuple of coordinates for the first point of the current tool
  4359. :type first_pt: tuple
  4360. :param tolerance: geometry tolerance
  4361. :type tolerance:
  4362. :param is_first: if the current tool is the first tool (for this we need to add start GCode)
  4363. :type is_first: bool
  4364. :param is_last: if the current tool is the last tool (for this we need to add the end GCode)
  4365. :type is_last: bool
  4366. :param toolchange: add toolchange event
  4367. :type toolchange: bool
  4368. :return: GCode
  4369. :rtype: str
  4370. """
  4371. log.debug("geometry_tool_gcode_gen()")
  4372. t_gcode = ''
  4373. temp_solid_geometry = []
  4374. # The Geometry from which we create GCode
  4375. geometry = tools[tool]['solid_geometry']
  4376. # ## Flatten the geometry. Only linear elements (no polygons) remain.
  4377. flat_geometry = self.flatten(geometry, reset=True, pathonly=True)
  4378. log.debug("%d paths" % len(flat_geometry))
  4379. # #########################################################################################################
  4380. # #########################################################################################################
  4381. # ############# PARAMETERS used in PREPROCESSORS so they need to be updated ###############################
  4382. # #########################################################################################################
  4383. # #########################################################################################################
  4384. self.tool = str(tool)
  4385. tool_dict = tools[tool]['data']
  4386. # this is the tool diameter, it is used as such to accommodate the preprocessor who need the tool diameter
  4387. # given under the name 'toolC'
  4388. self.postdata['toolC'] = float(tools[tool]['tooldia'])
  4389. self.tooldia = float(tools[tool]['tooldia'])
  4390. self.use_ui = True
  4391. self.tolerance = tolerance
  4392. # Optimization type. Can be: 'M', 'B', 'T', 'R', 'No'
  4393. opt_type = tool_dict['optimization_type']
  4394. opt_time = tool_dict['search_time'] if 'search_time' in tool_dict else 'R'
  4395. if opt_type == 'M':
  4396. log.debug("Using OR-Tools Metaheuristic Guided Local Search path optimization.")
  4397. elif opt_type == 'B':
  4398. log.debug("Using OR-Tools Basic path optimization.")
  4399. elif opt_type == 'T':
  4400. log.debug("Using Travelling Salesman path optimization.")
  4401. elif opt_type == 'R':
  4402. log.debug("Using RTree path optimization.")
  4403. else:
  4404. log.debug("Using no path optimization.")
  4405. # Preprocessor
  4406. self.pp_geometry_name = tool_dict['ppname_g']
  4407. self.pp_geometry = self.app.preprocessors[self.pp_geometry_name]
  4408. p = self.pp_geometry
  4409. # Offset the Geometry if it is the case
  4410. # FIXME need to test if in ["Path", "In", "Out", "Custom"]. For now only 'Custom' is somehow done
  4411. offset = tools[tool]['offset_value']
  4412. if offset != 0.0:
  4413. for it in flat_geometry:
  4414. # if the geometry is a closed shape then create a Polygon out of it
  4415. if isinstance(it, LineString):
  4416. if it.is_ring:
  4417. it = Polygon(it)
  4418. temp_solid_geometry.append(it.buffer(offset, join_style=2))
  4419. temp_solid_geometry = self.flatten(temp_solid_geometry, reset=True, pathonly=True)
  4420. else:
  4421. temp_solid_geometry = flat_geometry
  4422. if self.z_cut is None:
  4423. if 'laser' not in self.pp_geometry_name:
  4424. self.app.inform.emit(
  4425. '[ERROR_NOTCL] %s' % _("Cut_Z parameter is None or zero. Most likely a bad combinations of "
  4426. "other parameters."))
  4427. return 'fail'
  4428. else:
  4429. self.z_cut = 0
  4430. if self.machinist_setting == 0:
  4431. if self.z_cut > 0:
  4432. self.app.inform.emit('[WARNING] %s' %
  4433. _("The Cut Z parameter has positive value. "
  4434. "It is the depth value to cut into material.\n"
  4435. "The Cut Z parameter needs to have a negative value, assuming it is a typo "
  4436. "therefore the app will convert the value to negative."
  4437. "Check the resulting CNC code (Gcode etc)."))
  4438. self.z_cut = -self.z_cut
  4439. elif self.z_cut == 0 and 'laser' not in self.pp_geometry_name:
  4440. self.app.inform.emit('[WARNING] %s: %s' %
  4441. (_("The Cut Z parameter is zero. There will be no cut, skipping file"),
  4442. self.options['name']))
  4443. return 'fail'
  4444. if self.z_move is None:
  4445. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Travel Z parameter is None or zero."))
  4446. return 'fail'
  4447. if self.z_move < 0:
  4448. self.app.inform.emit('[WARNING] %s' %
  4449. _("The Travel Z parameter has negative value. "
  4450. "It is the height value to travel between cuts.\n"
  4451. "The Z Travel parameter needs to have a positive value, assuming it is a typo "
  4452. "therefore the app will convert the value to positive."
  4453. "Check the resulting CNC code (Gcode etc)."))
  4454. self.z_move = -self.z_move
  4455. elif self.z_move == 0:
  4456. self.app.inform.emit('[WARNING] %s: %s' %
  4457. (_("The Z Travel parameter is zero. This is dangerous, skipping file"),
  4458. self.options['name']))
  4459. return 'fail'
  4460. # made sure that depth_per_cut is no more then the z_cut
  4461. if abs(self.z_cut) < self.z_depthpercut:
  4462. self.z_depthpercut = abs(self.z_cut)
  4463. # Depth parameters
  4464. self.z_cut = float(tool_dict['cutz'])
  4465. self.multidepth = tool_dict['multidepth']
  4466. self.z_depthpercut = float(tool_dict['depthperpass'])
  4467. self.z_move = float(tool_dict['travelz'])
  4468. self.f_plunge = self.app.defaults["geometry_f_plunge"]
  4469. self.feedrate = float(tool_dict['feedrate'])
  4470. self.z_feedrate = float(tool_dict['feedrate_z'])
  4471. self.feedrate_rapid = float(tool_dict['feedrate_rapid'])
  4472. self.spindlespeed = float(tool_dict['spindlespeed'])
  4473. self.spindledir = tool_dict['spindledir']
  4474. self.dwell = tool_dict['dwell']
  4475. self.dwelltime = float(tool_dict['dwelltime'])
  4476. self.startz = float(tool_dict['startz']) if tool_dict['startz'] else None
  4477. if self.startz == '':
  4478. self.startz = None
  4479. self.z_end = float(tool_dict['endz'])
  4480. self.xy_end = tool_dict['endxy']
  4481. try:
  4482. if self.xy_end == '' or self.xy_end is None:
  4483. self.xy_end = None
  4484. else:
  4485. # either originally it was a string or not, xy_end will be made string
  4486. self.xy_end = re.sub('[()\[\]]', '', str(self.xy_end)) if self.xy_end else None
  4487. # and now, xy_end is made into a list of floats in format [x, y]
  4488. if self.xy_end:
  4489. self.xy_end = [float(eval(a)) for a in self.xy_end.split(",")]
  4490. if self.xy_end and len(self.xy_end) != 2:
  4491. self.app.inform.emit('[ERROR]%s' % _("The End X,Y format has to be (x, y)."))
  4492. return 'fail'
  4493. except Exception as e:
  4494. log.debug("camlib.CNCJob.geometry_from_excellon_by_tool() xy_end --> %s" % str(e))
  4495. self.xy_end = [0, 0]
  4496. self.z_toolchange = tool_dict['toolchangez']
  4497. self.xy_toolchange = tool_dict["toolchangexy"]
  4498. try:
  4499. if self.xy_toolchange == '':
  4500. self.xy_toolchange = None
  4501. else:
  4502. # either originally it was a string or not, xy_toolchange will be made string
  4503. self.xy_toolchange = re.sub('[()\[\]]', '', str(self.xy_toolchange)) if self.xy_toolchange else None
  4504. # and now, xy_toolchange is made into a list of floats in format [x, y]
  4505. if self.xy_toolchange:
  4506. self.xy_toolchange = [float(eval(a)) for a in self.xy_toolchange.split(",")]
  4507. if self.xy_toolchange and len(self.xy_toolchange) != 2:
  4508. self.app.inform.emit('[ERROR] %s' % _("The Toolchange X,Y format has to be (x, y)."))
  4509. return 'fail'
  4510. except Exception as e:
  4511. log.debug("camlib.CNCJob.geometry_from_excellon_by_tool() --> %s" % str(e))
  4512. pass
  4513. self.extracut = tool_dict['extracut']
  4514. self.extracut_length = tool_dict['extracut_length']
  4515. # Probe parameters
  4516. # self.z_pdepth = tool_dict["tools_drill_z_pdepth"]
  4517. # self.feedrate_probe = tool_dict["tools_drill_feedrate_probe"]
  4518. # #########################################################################################################
  4519. # ############ Create the data. ###########################################################################
  4520. # #########################################################################################################
  4521. optimized_path = []
  4522. geo_storage = {}
  4523. for geo in temp_solid_geometry:
  4524. if not geo is None:
  4525. geo_storage[geo.coords[0]] = geo
  4526. locations = list(geo_storage.keys())
  4527. if opt_type == 'M':
  4528. # if there are no locations then go to the next tool
  4529. if not locations:
  4530. return 'fail'
  4531. optimized_locations = self.optimized_ortools_meta(locations=locations, opt_time=opt_time)
  4532. optimized_path = [(locations[loc], geo_storage[locations[loc]]) for loc in optimized_locations]
  4533. elif opt_type == 'B':
  4534. # if there are no locations then go to the next tool
  4535. if not locations:
  4536. return 'fail'
  4537. optimized_locations = self.optimized_ortools_basic(locations=locations)
  4538. optimized_path = [(locations[loc], geo_storage[locations[loc]]) for loc in optimized_locations]
  4539. elif opt_type == 'T':
  4540. # if there are no locations then go to the next tool
  4541. if not locations:
  4542. return 'fail'
  4543. optimized_locations = self.optimized_travelling_salesman(locations)
  4544. optimized_path = [(loc, geo_storage[loc]) for loc in optimized_locations]
  4545. elif opt_type == 'R':
  4546. optimized_path = self.geo_optimized_rtree(temp_solid_geometry)
  4547. if optimized_path == 'fail':
  4548. return 'fail'
  4549. else:
  4550. # it's actually not optimized path but here we build a list of (x,y) coordinates
  4551. # out of the tool's drills
  4552. for geo in temp_solid_geometry:
  4553. optimized_path.append(geo.coords[0])
  4554. # #########################################################################################################
  4555. # #########################################################################################################
  4556. # Only if there are locations to mill
  4557. if not optimized_path:
  4558. log.debug("camlib.CNCJob.geometry_tool_gcode_gen() -> Optimized path is empty.")
  4559. return 'fail'
  4560. if self.app.abort_flag:
  4561. # graceful abort requested by the user
  4562. raise grace
  4563. # #############################################################################################################
  4564. # #############################################################################################################
  4565. # ################# MILLING !!! ##############################################################################
  4566. # #############################################################################################################
  4567. # #############################################################################################################
  4568. log.debug("Starting G-Code...")
  4569. current_tooldia = float('%.*f' % (self.decimals, float(self.tooldia)))
  4570. self.app.inform.emit('%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  4571. str(current_tooldia),
  4572. str(self.units)))
  4573. # Measurements
  4574. total_travel = 0.0
  4575. total_cut = 0.0
  4576. # Start GCode
  4577. start_gcode = ''
  4578. if is_first:
  4579. start_gcode = self.doformat(p.start_code)
  4580. t_gcode += start_gcode
  4581. # Toolchange code
  4582. t_gcode += self.doformat(p.feedrate_code) # sets the feed rate
  4583. if toolchange:
  4584. t_gcode += self.doformat(p.toolchange_code)
  4585. if 'laser' not in self.pp_geometry_name.lower():
  4586. t_gcode += self.doformat(p.spindle_code) # Spindle start
  4587. else:
  4588. # for laser this will disable the laser
  4589. t_gcode += self.doformat(p.lift_code, x=self.oldx, y=self.oldy) # Move (up) to travel height
  4590. if self.dwell:
  4591. t_gcode += self.doformat(p.dwell_code) # Dwell time
  4592. else:
  4593. t_gcode += self.doformat(p.lift_code, x=0, y=0) # Move (up) to travel height
  4594. t_gcode += self.doformat(p.startz_code, x=0, y=0)
  4595. if 'laser' not in self.pp_geometry_name.lower():
  4596. t_gcode += self.doformat(p.spindle_code) # Spindle start
  4597. if self.dwell is True:
  4598. t_gcode += self.doformat(p.dwell_code) # Dwell time
  4599. t_gcode += self.doformat(p.feedrate_code) # sets the feed rate
  4600. # ## Iterate over geometry paths getting the nearest each time.
  4601. path_count = 0
  4602. # variables to display the percentage of work done
  4603. geo_len = len(flat_geometry)
  4604. log.warning("Number of paths for which to generate GCode: %s" % str(geo_len))
  4605. old_disp_number = 0
  4606. current_pt = (0, 0)
  4607. for pt, geo in optimized_path:
  4608. if self.app.abort_flag:
  4609. # graceful abort requested by the user
  4610. raise grace
  4611. path_count += 1
  4612. # If last point in geometry is the nearest but prefer the first one if last point == first point
  4613. # then reverse coordinates.
  4614. if pt != geo.coords[0] and pt == geo.coords[-1]:
  4615. geo = LineString(list(geo.coords)[::-1])
  4616. # ---------- Single depth/pass --------
  4617. if not self.multidepth:
  4618. # calculate the cut distance
  4619. total_cut = total_cut + geo.length
  4620. t_gcode += self.create_gcode_single_pass(geo, current_tooldia, self.extracut,
  4621. self.extracut_length, self.tolerance,
  4622. z_move=self.z_move, old_point=current_pt)
  4623. # --------- Multi-pass ---------
  4624. else:
  4625. # calculate the cut distance
  4626. # due of the number of cuts (multi depth) it has to multiplied by the number of cuts
  4627. nr_cuts = 0
  4628. depth = abs(self.z_cut)
  4629. while depth > 0:
  4630. nr_cuts += 1
  4631. depth -= float(self.z_depthpercut)
  4632. total_cut += (geo.length * nr_cuts)
  4633. gc, geo = self.create_gcode_multi_pass(geo, current_tooldia, self.extracut,
  4634. self.extracut_length, self.tolerance,
  4635. z_move=self.z_move, postproc=p, old_point=current_pt)
  4636. t_gcode += gc
  4637. # calculate the total distance
  4638. total_travel = total_travel + abs(distance(pt1=current_pt, pt2=pt))
  4639. current_pt = geo.coords[-1]
  4640. disp_number = int(np.interp(path_count, [0, geo_len], [0, 100]))
  4641. if old_disp_number < disp_number <= 100:
  4642. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  4643. old_disp_number = disp_number
  4644. log.debug("Finished G-Code... %s paths traced." % path_count)
  4645. # add move to end position
  4646. total_travel += abs(distance_euclidian(current_pt[0], current_pt[1], 0, 0))
  4647. self.travel_distance += total_travel + total_cut
  4648. self.routing_time += total_cut / self.feedrate
  4649. # Finish
  4650. if is_last:
  4651. t_gcode += self.doformat(p.spindle_stop_code)
  4652. t_gcode += self.doformat(p.lift_code, x=current_pt[0], y=current_pt[1])
  4653. t_gcode += self.doformat(p.end_code, x=0, y=0)
  4654. self.app.inform.emit(
  4655. '%s... %s %s.' % (_("Finished G-Code generation"), str(path_count), _("paths traced"))
  4656. )
  4657. self.gcode = t_gcode
  4658. return self.gcode, start_gcode
  4659. def generate_from_geometry_2(self, geometry, append=True, tooldia=None, offset=0.0, tolerance=0, z_cut=None,
  4660. z_move=None, feedrate=None, feedrate_z=None, feedrate_rapid=None, spindlespeed=None,
  4661. spindledir='CW', dwell=False, dwelltime=None, multidepth=False, depthpercut=None,
  4662. toolchange=False, toolchangez=None, toolchangexy="0.0, 0.0", extracut=False,
  4663. extracut_length=None, startz=None, endz=None, endxy='', pp_geometry_name=None,
  4664. tool_no=1):
  4665. """
  4666. Second algorithm to generate from Geometry.
  4667. Algorithm description:
  4668. ----------------------
  4669. Uses RTree to find the nearest path to follow.
  4670. :param geometry:
  4671. :param append:
  4672. :param tooldia:
  4673. :param offset:
  4674. :param tolerance:
  4675. :param z_cut:
  4676. :param z_move:
  4677. :param feedrate:
  4678. :param feedrate_z:
  4679. :param feedrate_rapid:
  4680. :param spindlespeed:
  4681. :param spindledir:
  4682. :param dwell:
  4683. :param dwelltime:
  4684. :param multidepth: If True, use multiple passes to reach the desired depth.
  4685. :param depthpercut: Maximum depth in each pass.
  4686. :param toolchange:
  4687. :param toolchangez:
  4688. :param toolchangexy:
  4689. :param extracut: Adds (or not) an extra cut at the end of each path overlapping the first point in
  4690. path to ensure complete copper removal
  4691. :param extracut_length: The extra cut length
  4692. :param startz:
  4693. :param endz:
  4694. :param endxy:
  4695. :param pp_geometry_name:
  4696. :param tool_no:
  4697. :return: None
  4698. """
  4699. log.debug("Executing camlib.CNCJob.generate_from_geometry_2()")
  4700. # if solid_geometry is empty raise an exception
  4701. if not geometry.solid_geometry:
  4702. self.app.inform.emit(
  4703. '[ERROR_NOTCL] %s' % _("Trying to generate a CNC Job from a Geometry object without solid_geometry.")
  4704. )
  4705. return 'fail'
  4706. def bounds_rec(obj):
  4707. if type(obj) is list:
  4708. minx = np.Inf
  4709. miny = np.Inf
  4710. maxx = -np.Inf
  4711. maxy = -np.Inf
  4712. for k in obj:
  4713. if type(k) is dict:
  4714. for key in k:
  4715. minx_, miny_, maxx_, maxy_ = bounds_rec(k[key])
  4716. minx = min(minx, minx_)
  4717. miny = min(miny, miny_)
  4718. maxx = max(maxx, maxx_)
  4719. maxy = max(maxy, maxy_)
  4720. else:
  4721. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  4722. minx = min(minx, minx_)
  4723. miny = min(miny, miny_)
  4724. maxx = max(maxx, maxx_)
  4725. maxy = max(maxy, maxy_)
  4726. return minx, miny, maxx, maxy
  4727. else:
  4728. # it's a Shapely object, return it's bounds
  4729. return obj.bounds
  4730. # Create the solid geometry which will be used to generate GCode
  4731. temp_solid_geometry = []
  4732. if offset != 0.0:
  4733. offset_for_use = offset
  4734. if offset < 0:
  4735. a, b, c, d = bounds_rec(geometry.solid_geometry)
  4736. # if the offset is less than half of the total length or less than half of the total width of the
  4737. # solid geometry it's obvious we can't do the offset
  4738. if -offset > ((c - a) / 2) or -offset > ((d - b) / 2):
  4739. self.app.inform.emit(
  4740. '[ERROR_NOTCL] %s' %
  4741. _("The Tool Offset value is too negative to use for the current_geometry.\n"
  4742. "Raise the value (in module) and try again.")
  4743. )
  4744. return 'fail'
  4745. # hack: make offset smaller by 0.0000000001 which is insignificant difference but allow the job
  4746. # to continue
  4747. elif -offset == ((c - a) / 2) or -offset == ((d - b) / 2):
  4748. offset_for_use = offset - 0.0000000001
  4749. for it in geometry.solid_geometry:
  4750. # if the geometry is a closed shape then create a Polygon out of it
  4751. if isinstance(it, LineString):
  4752. c = it.coords
  4753. if c[0] == c[-1]:
  4754. it = Polygon(it)
  4755. temp_solid_geometry.append(it.buffer(offset_for_use, join_style=2))
  4756. else:
  4757. temp_solid_geometry = geometry.solid_geometry
  4758. # ## Flatten the geometry. Only linear elements (no polygons) remain.
  4759. flat_geometry = self.flatten(temp_solid_geometry, pathonly=True)
  4760. log.debug("%d paths" % len(flat_geometry))
  4761. default_dia = None
  4762. if isinstance(self.app.defaults["geometry_cnctooldia"], float):
  4763. default_dia = self.app.defaults["geometry_cnctooldia"]
  4764. else:
  4765. try:
  4766. tools_string = self.app.defaults["geometry_cnctooldia"].split(",")
  4767. tools_diameters = [eval(a) for a in tools_string if a != '']
  4768. default_dia = tools_diameters[0] if tools_diameters else 0.0
  4769. except Exception as e:
  4770. self.app.log.debug("camlib.CNCJob.generate_from_geometry_2() --> %s" % str(e))
  4771. try:
  4772. self.tooldia = float(tooldia) if tooldia else default_dia
  4773. except ValueError:
  4774. self.tooldia = [float(el) for el in tooldia.split(',') if el != ''] if tooldia is not None else default_dia
  4775. if self.tooldia is None:
  4776. self.app.inform.emit('[ERROR] %s' % _("Failed."))
  4777. return 'fail'
  4778. self.z_cut = float(z_cut) if z_cut is not None else self.app.defaults["geometry_cutz"]
  4779. self.z_move = float(z_move) if z_move is not None else self.app.defaults["geometry_travelz"]
  4780. self.feedrate = float(feedrate) if feedrate is not None else self.app.defaults["geometry_feedrate"]
  4781. self.z_feedrate = float(feedrate_z) if feedrate_z is not None else self.app.defaults["geometry_feedrate_z"]
  4782. self.feedrate_rapid = float(feedrate_rapid) if feedrate_rapid is not None else \
  4783. self.app.defaults["geometry_feedrate_rapid"]
  4784. self.spindlespeed = int(spindlespeed) if spindlespeed != 0 and spindlespeed is not None else None
  4785. self.spindledir = spindledir
  4786. self.dwell = dwell
  4787. self.dwelltime = float(dwelltime) if dwelltime is not None else self.app.defaults["geometry_dwelltime"]
  4788. self.startz = float(startz) if startz is not None and startz != '' else self.app.defaults["geometry_startz"]
  4789. self.z_end = float(endz) if endz is not None else self.app.defaults["geometry_endz"]
  4790. self.xy_end = endxy if endxy != '' and endxy else self.app.defaults["geometry_endxy"]
  4791. self.xy_end = re.sub('[()\[\]]', '', str(self.xy_end)) if self.xy_end else None
  4792. if self.xy_end is not None and self.xy_end != '':
  4793. self.xy_end = [float(eval(a)) for a in self.xy_end.split(",")]
  4794. if self.xy_end and len(self.xy_end) < 2:
  4795. self.app.inform.emit('[ERROR] %s' % _("The End Move X,Y field in Edit -> Preferences has to be "
  4796. "in the format (x, y) but now there is only one value, not two."))
  4797. return 'fail'
  4798. self.z_depthpercut = float(depthpercut) if depthpercut is not None and depthpercut != 0 else abs(self.z_cut)
  4799. self.multidepth = multidepth
  4800. self.z_toolchange = float(toolchangez) if toolchangez is not None else self.app.defaults["geometry_toolchangez"]
  4801. self.extracut_length = float(extracut_length) if extracut_length is not None else \
  4802. self.app.defaults["geometry_extracut_length"]
  4803. try:
  4804. if toolchangexy == '':
  4805. self.xy_toolchange = None
  4806. else:
  4807. self.xy_toolchange = re.sub('[()\[\]]', '', str(toolchangexy)) if self.xy_toolchange else None
  4808. if self.xy_toolchange and self.xy_toolchange != '':
  4809. self.xy_toolchange = [float(eval(a)) for a in self.xy_toolchange.split(",")]
  4810. if len(self.xy_toolchange) < 2:
  4811. self.app.inform.emit('[ERROR] %s' % _("The Toolchange X,Y format has to be (x, y)."))
  4812. return 'fail'
  4813. except Exception as e:
  4814. log.debug("camlib.CNCJob.generate_from_geometry_2() --> %s" % str(e))
  4815. pass
  4816. self.pp_geometry_name = pp_geometry_name if pp_geometry_name else 'default'
  4817. self.f_plunge = self.app.defaults["geometry_f_plunge"]
  4818. if self.machinist_setting == 0:
  4819. if self.z_cut is None:
  4820. if 'laser' not in self.pp_geometry_name:
  4821. self.app.inform.emit(
  4822. '[ERROR_NOTCL] %s' % _("Cut_Z parameter is None or zero. Most likely a bad combinations of "
  4823. "other parameters.")
  4824. )
  4825. return 'fail'
  4826. else:
  4827. self.z_cut = 0.0
  4828. if self.z_cut > 0:
  4829. self.app.inform.emit('[WARNING] %s' %
  4830. _("The Cut Z parameter has positive value. "
  4831. "It is the depth value to cut into material.\n"
  4832. "The Cut Z parameter needs to have a negative value, assuming it is a typo "
  4833. "therefore the app will convert the value to negative."
  4834. "Check the resulting CNC code (Gcode etc)."))
  4835. self.z_cut = -self.z_cut
  4836. elif self.z_cut == 0 and 'laser' not in self.pp_geometry_name:
  4837. self.app.inform.emit(
  4838. '[WARNING] %s: %s' % (_("The Cut Z parameter is zero. There will be no cut, skipping file"),
  4839. geometry.options['name'])
  4840. )
  4841. return 'fail'
  4842. if self.z_move is None:
  4843. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Travel Z parameter is None or zero."))
  4844. return 'fail'
  4845. if self.z_move < 0:
  4846. self.app.inform.emit('[WARNING] %s' %
  4847. _("The Travel Z parameter has negative value. "
  4848. "It is the height value to travel between cuts.\n"
  4849. "The Z Travel parameter needs to have a positive value, assuming it is a typo "
  4850. "therefore the app will convert the value to positive."
  4851. "Check the resulting CNC code (Gcode etc)."))
  4852. self.z_move = -self.z_move
  4853. elif self.z_move == 0:
  4854. self.app.inform.emit(
  4855. '[WARNING] %s: %s' % (_("The Z Travel parameter is zero. This is dangerous, skipping file"),
  4856. self.options['name'])
  4857. )
  4858. return 'fail'
  4859. # made sure that depth_per_cut is no more then the z_cut
  4860. try:
  4861. if abs(self.z_cut) < self.z_depthpercut:
  4862. self.z_depthpercut = abs(self.z_cut)
  4863. except TypeError:
  4864. self.z_depthpercut = abs(self.z_cut)
  4865. # ## Index first and last points in paths
  4866. # What points to index.
  4867. def get_pts(o):
  4868. return [o.coords[0], o.coords[-1]]
  4869. # Create the indexed storage.
  4870. storage = FlatCAMRTreeStorage()
  4871. storage.get_points = get_pts
  4872. # Store the geometry
  4873. log.debug("Indexing geometry before generating G-Code...")
  4874. self.app.inform.emit(_("Indexing geometry before generating G-Code..."))
  4875. for geo_shape in flat_geometry:
  4876. if self.app.abort_flag:
  4877. # graceful abort requested by the user
  4878. raise grace
  4879. if geo_shape is not None:
  4880. storage.insert(geo_shape)
  4881. if not append:
  4882. self.gcode = ""
  4883. # tell preprocessor the number of tool (for toolchange)
  4884. self.tool = tool_no
  4885. # this is the tool diameter, it is used as such to accommodate the preprocessor who need the tool diameter
  4886. # given under the name 'toolC'
  4887. # this is a fancy way of adding a class attribute (which should be added in the __init__ method) without doing
  4888. # it there :)
  4889. self.postdata['toolC'] = self.tooldia
  4890. # Initial G-Code
  4891. self.pp_geometry = self.app.preprocessors[self.pp_geometry_name]
  4892. # the 'p' local attribute is a reference to the current preprocessor class
  4893. p = self.pp_geometry
  4894. self.oldx = 0.0
  4895. self.oldy = 0.0
  4896. self.gcode = self.doformat(p.start_code)
  4897. self.gcode += self.doformat(p.feedrate_code) # sets the feed rate
  4898. if toolchange is False:
  4899. # all the x and y parameters in self.doformat() are used only by some preprocessors not by all
  4900. self.gcode += self.doformat(p.lift_code, x=self.oldx, y=self.oldy) # Move (up) to travel height
  4901. self.gcode += self.doformat(p.startz_code, x=self.oldx, y=self.oldy)
  4902. if toolchange:
  4903. # if "line_xyz" in self.pp_geometry_name:
  4904. # self.gcode += self.doformat(p.toolchange_code, x=self.xy_toolchange[0], y=self.xy_toolchange[1])
  4905. # else:
  4906. # self.gcode += self.doformat(p.toolchange_code)
  4907. self.gcode += self.doformat(p.toolchange_code)
  4908. if 'laser' not in self.pp_geometry_name:
  4909. self.gcode += self.doformat(p.spindle_code) # Spindle start
  4910. else:
  4911. # for laser this will disable the laser
  4912. self.gcode += self.doformat(p.lift_code, x=self.oldx, y=self.oldy) # Move (up) to travel height
  4913. if self.dwell is True:
  4914. self.gcode += self.doformat(p.dwell_code) # Dwell time
  4915. else:
  4916. if 'laser' not in self.pp_geometry_name:
  4917. self.gcode += self.doformat(p.spindle_code) # Spindle start
  4918. if self.dwell is True:
  4919. self.gcode += self.doformat(p.dwell_code) # Dwell time
  4920. total_travel = 0.0
  4921. total_cut = 0.0
  4922. # Iterate over geometry paths getting the nearest each time.
  4923. log.debug("Starting G-Code...")
  4924. self.app.inform.emit('%s...' % _("Starting G-Code"))
  4925. # variables to display the percentage of work done
  4926. geo_len = len(flat_geometry)
  4927. old_disp_number = 0
  4928. log.warning("Number of paths for which to generate GCode: %s" % str(geo_len))
  4929. current_tooldia = float('%.*f' % (self.decimals, float(self.tooldia)))
  4930. self.app.inform.emit(
  4931. '%s: %s%s.' % (_("Starting G-Code for tool with diameter"), str(current_tooldia), str(self.units))
  4932. )
  4933. path_count = 0
  4934. current_pt = (0, 0)
  4935. pt, geo = storage.nearest(current_pt)
  4936. # when nothing is left in the storage a StopIteration exception will be raised therefore stopping
  4937. # the whole process including the infinite loop while True below.
  4938. try:
  4939. while True:
  4940. if self.app.abort_flag:
  4941. # graceful abort requested by the user
  4942. raise grace
  4943. path_count += 1
  4944. # Remove before modifying, otherwise deletion will fail.
  4945. storage.remove(geo)
  4946. # If last point in geometry is the nearest but prefer the first one if last point == first point
  4947. # then reverse coordinates.
  4948. if pt != geo.coords[0] and pt == geo.coords[-1]:
  4949. # geo.coords = list(geo.coords)[::-1] # Shapely 2.0
  4950. geo = LineString(list(geo.coords)[::-1])
  4951. # ---------- Single depth/pass --------
  4952. if not multidepth:
  4953. # calculate the cut distance
  4954. total_cut += geo.length
  4955. self.gcode += self.create_gcode_single_pass(geo, current_tooldia, extracut, self.extracut_length,
  4956. tolerance, z_move=z_move, old_point=current_pt)
  4957. # --------- Multi-pass ---------
  4958. else:
  4959. # calculate the cut distance
  4960. # due of the number of cuts (multi depth) it has to multiplied by the number of cuts
  4961. nr_cuts = 0
  4962. depth = abs(self.z_cut)
  4963. while depth > 0:
  4964. nr_cuts += 1
  4965. depth -= float(self.z_depthpercut)
  4966. total_cut += (geo.length * nr_cuts)
  4967. gc, geo = self.create_gcode_multi_pass(geo, current_tooldia, extracut, self.extracut_length,
  4968. tolerance, z_move=z_move, postproc=p,
  4969. old_point=current_pt)
  4970. self.gcode += gc
  4971. # calculate the travel distance
  4972. total_travel += abs(distance(pt1=current_pt, pt2=pt))
  4973. current_pt = geo.coords[-1]
  4974. pt, geo = storage.nearest(current_pt) # Next
  4975. # update the activity counter (lower left side of the app, status bar)
  4976. disp_number = int(np.interp(path_count, [0, geo_len], [0, 100]))
  4977. if old_disp_number < disp_number <= 100:
  4978. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  4979. old_disp_number = disp_number
  4980. except StopIteration: # Nothing found in storage.
  4981. pass
  4982. log.debug("Finishing G-Code... %s paths traced." % path_count)
  4983. # add move to end position
  4984. total_travel += abs(distance_euclidian(current_pt[0], current_pt[1], 0, 0))
  4985. self.travel_distance += total_travel + total_cut
  4986. self.routing_time += total_cut / self.feedrate
  4987. # Finish
  4988. self.gcode += self.doformat(p.spindle_stop_code)
  4989. self.gcode += self.doformat(p.lift_code, x=current_pt[0], y=current_pt[1])
  4990. self.gcode += self.doformat(p.end_code, x=0, y=0)
  4991. self.app.inform.emit(
  4992. '%s... %s %s' % (_("Finished G-Code generation"), str(path_count), _(" paths traced."))
  4993. )
  4994. return self.gcode
  4995. def generate_gcode_from_solderpaste_geo(self, **kwargs):
  4996. """
  4997. Algorithm to generate from multitool Geometry.
  4998. Algorithm description:
  4999. ----------------------
  5000. Uses RTree to find the nearest path to follow.
  5001. :return: Gcode string
  5002. """
  5003. log.debug("Generate_from_solderpaste_geometry()")
  5004. # ## Index first and last points in paths
  5005. # What points to index.
  5006. def get_pts(o):
  5007. return [o.coords[0], o.coords[-1]]
  5008. self.gcode = ""
  5009. if not kwargs:
  5010. log.debug("camlib.generate_from_solderpaste_geo() --> No tool in the solderpaste geometry.")
  5011. self.app.inform.emit('[ERROR_NOTCL] %s' %
  5012. _("There is no tool data in the SolderPaste geometry."))
  5013. # this is the tool diameter, it is used as such to accommodate the preprocessor who need the tool diameter
  5014. # given under the name 'toolC'
  5015. self.postdata['z_start'] = kwargs['data']['tools_solderpaste_z_start']
  5016. self.postdata['z_dispense'] = kwargs['data']['tools_solderpaste_z_dispense']
  5017. self.postdata['z_stop'] = kwargs['data']['tools_solderpaste_z_stop']
  5018. self.postdata['z_travel'] = kwargs['data']['tools_solderpaste_z_travel']
  5019. self.postdata['z_toolchange'] = kwargs['data']['tools_solderpaste_z_toolchange']
  5020. self.postdata['xy_toolchange'] = kwargs['data']['tools_solderpaste_xy_toolchange']
  5021. self.postdata['frxy'] = kwargs['data']['tools_solderpaste_frxy']
  5022. self.postdata['frz'] = kwargs['data']['tools_solderpaste_frz']
  5023. self.postdata['frz_dispense'] = kwargs['data']['tools_solderpaste_frz_dispense']
  5024. self.postdata['speedfwd'] = kwargs['data']['tools_solderpaste_speedfwd']
  5025. self.postdata['dwellfwd'] = kwargs['data']['tools_solderpaste_dwellfwd']
  5026. self.postdata['speedrev'] = kwargs['data']['tools_solderpaste_speedrev']
  5027. self.postdata['dwellrev'] = kwargs['data']['tools_solderpaste_dwellrev']
  5028. self.postdata['pp_solderpaste_name'] = kwargs['data']['tools_solderpaste_pp']
  5029. self.postdata['toolC'] = kwargs['tooldia']
  5030. self.pp_solderpaste_name = kwargs['data']['tools_solderpaste_pp'] if kwargs['data']['tools_solderpaste_pp'] \
  5031. else self.app.defaults['tools_solderpaste_pp']
  5032. p = self.app.preprocessors[self.pp_solderpaste_name]
  5033. # ## Flatten the geometry. Only linear elements (no polygons) remain.
  5034. flat_geometry = self.flatten(kwargs['solid_geometry'], pathonly=True)
  5035. log.debug("%d paths" % len(flat_geometry))
  5036. # Create the indexed storage.
  5037. storage = FlatCAMRTreeStorage()
  5038. storage.get_points = get_pts
  5039. # Store the geometry
  5040. log.debug("Indexing geometry before generating G-Code...")
  5041. for geo_shape in flat_geometry:
  5042. if self.app.abort_flag:
  5043. # graceful abort requested by the user
  5044. raise grace
  5045. if geo_shape is not None:
  5046. storage.insert(geo_shape)
  5047. # Initial G-Code
  5048. self.gcode = self.doformat(p.start_code)
  5049. self.gcode += self.doformat(p.spindle_off_code)
  5050. self.gcode += self.doformat(p.toolchange_code)
  5051. # ## Iterate over geometry paths getting the nearest each time.
  5052. log.debug("Starting SolderPaste G-Code...")
  5053. path_count = 0
  5054. current_pt = (0, 0)
  5055. # variables to display the percentage of work done
  5056. geo_len = len(flat_geometry)
  5057. old_disp_number = 0
  5058. pt, geo = storage.nearest(current_pt)
  5059. try:
  5060. while True:
  5061. if self.app.abort_flag:
  5062. # graceful abort requested by the user
  5063. raise grace
  5064. path_count += 1
  5065. # Remove before modifying, otherwise deletion will fail.
  5066. storage.remove(geo)
  5067. # If last point in geometry is the nearest but prefer the first one if last point == first point
  5068. # then reverse coordinates.
  5069. if pt != geo.coords[0] and pt == geo.coords[-1]:
  5070. # geo.coords = list(geo.coords)[::-1] # Shapely 2.0
  5071. geo = LineString(list(geo.coords)[::-1])
  5072. self.gcode += self.create_soldepaste_gcode(geo, p=p, old_point=current_pt)
  5073. current_pt = geo.coords[-1]
  5074. pt, geo = storage.nearest(current_pt) # Next
  5075. disp_number = int(np.interp(path_count, [0, geo_len], [0, 100]))
  5076. if old_disp_number < disp_number <= 100:
  5077. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  5078. old_disp_number = disp_number
  5079. except StopIteration: # Nothing found in storage.
  5080. pass
  5081. log.debug("Finishing SolderPste G-Code... %s paths traced." % path_count)
  5082. self.app.inform.emit(
  5083. '%s... %s %s' % (_("Finished SolderPaste G-Code generation"), str(path_count), _("paths traced."))
  5084. )
  5085. # Finish
  5086. self.gcode += self.doformat(p.lift_code)
  5087. self.gcode += self.doformat(p.end_code)
  5088. return self.gcode
  5089. def create_soldepaste_gcode(self, geometry, p, old_point=(0, 0)):
  5090. gcode = ''
  5091. path = geometry.coords
  5092. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  5093. if self.coordinates_type == "G90":
  5094. # For Absolute coordinates type G90
  5095. first_x = path[0][0]
  5096. first_y = path[0][1]
  5097. else:
  5098. # For Incremental coordinates type G91
  5099. first_x = path[0][0] - old_point[0]
  5100. first_y = path[0][1] - old_point[1]
  5101. if type(geometry) == LineString or type(geometry) == LinearRing:
  5102. # Move fast to 1st point
  5103. gcode += self.doformat(p.rapid_code, x=first_x, y=first_y) # Move to first point
  5104. # Move down to cutting depth
  5105. gcode += self.doformat(p.z_feedrate_code)
  5106. gcode += self.doformat(p.down_z_start_code)
  5107. gcode += self.doformat(p.spindle_fwd_code) # Start dispensing
  5108. gcode += self.doformat(p.dwell_fwd_code)
  5109. gcode += self.doformat(p.feedrate_z_dispense_code)
  5110. gcode += self.doformat(p.lift_z_dispense_code)
  5111. gcode += self.doformat(p.feedrate_xy_code)
  5112. # Cutting...
  5113. prev_x = first_x
  5114. prev_y = first_y
  5115. for pt in path[1:]:
  5116. if self.coordinates_type == "G90":
  5117. # For Absolute coordinates type G90
  5118. next_x = pt[0]
  5119. next_y = pt[1]
  5120. else:
  5121. # For Incremental coordinates type G91
  5122. next_x = pt[0] - prev_x
  5123. next_y = pt[1] - prev_y
  5124. gcode += self.doformat(p.linear_code, x=next_x, y=next_y) # Linear motion to point
  5125. prev_x = next_x
  5126. prev_y = next_y
  5127. # Up to travelling height.
  5128. gcode += self.doformat(p.spindle_off_code) # Stop dispensing
  5129. gcode += self.doformat(p.spindle_rev_code)
  5130. gcode += self.doformat(p.down_z_stop_code)
  5131. gcode += self.doformat(p.spindle_off_code)
  5132. gcode += self.doformat(p.dwell_rev_code)
  5133. gcode += self.doformat(p.z_feedrate_code)
  5134. gcode += self.doformat(p.lift_code)
  5135. elif type(geometry) == Point:
  5136. gcode += self.doformat(p.linear_code, x=first_x, y=first_y) # Move to first point
  5137. gcode += self.doformat(p.feedrate_z_dispense_code)
  5138. gcode += self.doformat(p.down_z_start_code)
  5139. gcode += self.doformat(p.spindle_fwd_code) # Start dispensing
  5140. gcode += self.doformat(p.dwell_fwd_code)
  5141. gcode += self.doformat(p.lift_z_dispense_code)
  5142. gcode += self.doformat(p.spindle_off_code) # Stop dispensing
  5143. gcode += self.doformat(p.spindle_rev_code)
  5144. gcode += self.doformat(p.spindle_off_code)
  5145. gcode += self.doformat(p.down_z_stop_code)
  5146. gcode += self.doformat(p.dwell_rev_code)
  5147. gcode += self.doformat(p.z_feedrate_code)
  5148. gcode += self.doformat(p.lift_code)
  5149. return gcode
  5150. def create_gcode_single_pass(self, geometry, cdia, extracut, extracut_length, tolerance, z_move, old_point=(0, 0)):
  5151. """
  5152. # G-code. Note: self.linear2gcode() and self.point2gcode() will lower and raise the tool every time.
  5153. :param geometry: A Shapely Geometry (LineString or LinearRing) which is the path to be cut
  5154. :type geometry: LineString, LinearRing
  5155. :param cdia: Tool diameter
  5156. :type cdia: float
  5157. :param extracut: Will add an extra cut over the point where start of the cut is met with the end cut
  5158. :type extracut: bool
  5159. :param extracut_length: The length of the extra cut: half before the meeting point, half after
  5160. :type extracut_length: float
  5161. :param tolerance: Tolerance used to simplify the paths (making them mre rough)
  5162. :type tolerance: float
  5163. :param z_move: Travel Z
  5164. :type z_move: float
  5165. :param old_point: Previous point
  5166. :type old_point: tuple
  5167. :return: Gcode
  5168. :rtype: str
  5169. """
  5170. # p = postproc
  5171. if type(geometry) == LineString or type(geometry) == LinearRing:
  5172. if extracut is False or not geometry.is_ring:
  5173. gcode_single_pass = self.linear2gcode(geometry, cdia, z_move=z_move, tolerance=tolerance,
  5174. old_point=old_point)
  5175. else:
  5176. gcode_single_pass = self.linear2gcode_extra(geometry, cdia, extracut_length, tolerance=tolerance,
  5177. z_move=z_move, old_point=old_point)
  5178. elif type(geometry) == Point:
  5179. gcode_single_pass = self.point2gcode(geometry, cdia, z_move=z_move, old_point=old_point)
  5180. else:
  5181. log.warning("G-code generation not implemented for %s" % (str(type(geometry))))
  5182. return
  5183. return gcode_single_pass
  5184. def create_gcode_multi_pass(self, geometry, cdia, extracut, extracut_length, tolerance, postproc, z_move,
  5185. old_point=(0, 0)):
  5186. """
  5187. :param geometry: A Shapely Geometry (LineString or LinearRing) which is the path to be cut
  5188. :type geometry: LineString, LinearRing
  5189. :param cdia: Tool diameter
  5190. :type cdia: float
  5191. :param extracut: Will add an extra cut over the point where start of the cut is met with the end cut
  5192. :type extracut: bool
  5193. :param extracut_length: The length of the extra cut: half before the meeting point, half after
  5194. :type extracut_length: float
  5195. :param tolerance: Tolerance used to simplify the paths (making them mre rough)
  5196. :type tolerance: float
  5197. :param postproc: Preprocessor class
  5198. :type postproc: class
  5199. :param z_move: Travel Z
  5200. :type z_move: float
  5201. :param old_point: Previous point
  5202. :type old_point: tuple
  5203. :return: Gcode
  5204. :rtype: str
  5205. """
  5206. p = postproc
  5207. gcode_multi_pass = ''
  5208. if isinstance(self.z_cut, Decimal):
  5209. z_cut = self.z_cut
  5210. else:
  5211. z_cut = Decimal(self.z_cut).quantize(Decimal('0.000000001'))
  5212. if self.z_depthpercut is None:
  5213. self.z_depthpercut = z_cut
  5214. elif not isinstance(self.z_depthpercut, Decimal):
  5215. self.z_depthpercut = Decimal(self.z_depthpercut).quantize(Decimal('0.000000001'))
  5216. depth = 0
  5217. reverse = False
  5218. while depth > z_cut:
  5219. # Increase depth. Limit to z_cut.
  5220. depth -= self.z_depthpercut
  5221. if depth < z_cut:
  5222. depth = z_cut
  5223. # Cut at specific depth and do not lift the tool.
  5224. # Note: linear2gcode() will use G00 to move to the first point in the path, but it should be already
  5225. # at the first point if the tool is down (in the material). So, an extra G00 should show up but
  5226. # is inconsequential.
  5227. if type(geometry) == LineString or type(geometry) == LinearRing:
  5228. if extracut is False or not geometry.is_ring:
  5229. gcode_multi_pass += self.linear2gcode(geometry, cdia, tolerance=tolerance, z_cut=depth, up=False,
  5230. z_move=z_move, old_point=old_point)
  5231. else:
  5232. gcode_multi_pass += self.linear2gcode_extra(geometry, cdia, extracut_length, tolerance=tolerance,
  5233. z_move=z_move, z_cut=depth, up=False,
  5234. old_point=old_point)
  5235. # Ignore multi-pass for points.
  5236. elif type(geometry) == Point:
  5237. gcode_multi_pass += self.point2gcode(geometry, cdia, z_move=z_move, old_point=old_point)
  5238. break # Ignoring ...
  5239. else:
  5240. log.warning("G-code generation not implemented for %s" % (str(type(geometry))))
  5241. # Reverse coordinates if not a loop so we can continue cutting without returning to the beginning.
  5242. if type(geometry) == LineString:
  5243. geometry = LineString(list(geometry.coords)[::-1])
  5244. reverse = True
  5245. # If geometry is reversed, revert.
  5246. if reverse:
  5247. if type(geometry) == LineString:
  5248. geometry = LineString(list(geometry.coords)[::-1])
  5249. # Lift the tool
  5250. gcode_multi_pass += self.doformat(p.lift_code, x=old_point[0], y=old_point[1])
  5251. return gcode_multi_pass, geometry
  5252. def codes_split(self, gline):
  5253. """
  5254. Parses a line of G-Code such as "G01 X1234 Y987" into
  5255. a dictionary: {'G': 1.0, 'X': 1234.0, 'Y': 987.0}
  5256. :param gline: G-Code line string
  5257. :type gline: str
  5258. :return: Dictionary with parsed line.
  5259. :rtype: dict
  5260. """
  5261. command = {}
  5262. if 'Roland' in self.pp_excellon_name or 'Roland' in self.pp_geometry_name:
  5263. match_z = re.search(r"^Z(\s*-?\d+\.\d+?),(\s*\s*-?\d+\.\d+?),(\s*\s*-?\d+\.\d+?)*;$", gline)
  5264. if match_z:
  5265. command['G'] = 0
  5266. command['X'] = float(match_z.group(1).replace(" ", "")) * 0.025
  5267. command['Y'] = float(match_z.group(2).replace(" ", "")) * 0.025
  5268. command['Z'] = float(match_z.group(3).replace(" ", "")) * 0.025
  5269. elif 'hpgl' in self.pp_excellon_name or 'hpgl' in self.pp_geometry_name:
  5270. match_pa = re.search(r"^PA(\s*-?\d+\.\d+?),(\s*\s*-?\d+\.\d+?)*;$", gline)
  5271. if match_pa:
  5272. command['G'] = 0
  5273. command['X'] = float(match_pa.group(1).replace(" ", "")) / 40
  5274. command['Y'] = float(match_pa.group(2).replace(" ", "")) / 40
  5275. match_pen = re.search(r"^(P[U|D])", gline)
  5276. if match_pen:
  5277. if match_pen.group(1) == 'PU':
  5278. # the value does not matter, only that it is positive so the gcode_parse() know it is > 0,
  5279. # therefore the move is of kind T (travel)
  5280. command['Z'] = 1
  5281. else:
  5282. command['Z'] = 0
  5283. elif 'laser' in self.pp_excellon_name.lower() or 'laser' in self.pp_geometry_name.lower() or \
  5284. (self.pp_solderpaste_name is not None and 'paste' in self.pp_solderpaste_name.lower()):
  5285. match_lsr = re.search(r"X([\+-]?\d+.[\+-]?\d+)\s*Y([\+-]?\d+.[\+-]?\d+)", gline)
  5286. if match_lsr:
  5287. command['X'] = float(match_lsr.group(1).replace(" ", ""))
  5288. command['Y'] = float(match_lsr.group(2).replace(" ", ""))
  5289. match_lsr_pos = re.search(r"^(M0?[3-5])", gline)
  5290. if match_lsr_pos:
  5291. if 'M05' in match_lsr_pos.group(1) or 'M5' in match_lsr_pos.group(1):
  5292. # the value does not matter, only that it is positive so the gcode_parse() know it is > 0,
  5293. # therefore the move is of kind T (travel)
  5294. command['Z'] = 1
  5295. else:
  5296. command['Z'] = 0
  5297. match_lsr_pos_2 = re.search(r"^(M10[6|7])", gline)
  5298. if match_lsr_pos_2:
  5299. if 'M107' in match_lsr_pos_2.group(1):
  5300. command['Z'] = 1
  5301. else:
  5302. command['Z'] = 0
  5303. elif self.pp_solderpaste_name is not None:
  5304. if 'Paste' in self.pp_solderpaste_name:
  5305. match_paste = re.search(r"X([\+-]?\d+.[\+-]?\d+)\s*Y([\+-]?\d+.[\+-]?\d+)", gline)
  5306. if match_paste:
  5307. command['X'] = float(match_paste.group(1).replace(" ", ""))
  5308. command['Y'] = float(match_paste.group(2).replace(" ", ""))
  5309. else:
  5310. match = re.search(r'^\s*([A-Z])\s*([\+\-\.\d\s]+)', gline)
  5311. while match:
  5312. command[match.group(1)] = float(match.group(2).replace(" ", ""))
  5313. gline = gline[match.end():]
  5314. match = re.search(r'^\s*([A-Z])\s*([\+\-\.\d\s]+)', gline)
  5315. return command
  5316. def gcode_parse(self, force_parsing=None):
  5317. """
  5318. G-Code parser (from self.gcode). Generates dictionary with
  5319. single-segment LineString's and "kind" indicating cut or travel,
  5320. fast or feedrate speed.
  5321. Will return a list of dict in the format:
  5322. {
  5323. "geom": LineString(path),
  5324. "kind": kind
  5325. }
  5326. where kind can be either ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  5327. :param force_parsing:
  5328. :type force_parsing:
  5329. :return:
  5330. :rtype: dict
  5331. """
  5332. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  5333. # Results go here
  5334. geometry = []
  5335. # Last known instruction
  5336. current = {'X': 0.0, 'Y': 0.0, 'Z': 0.0, 'G': 0}
  5337. # Current path: temporary storage until tool is
  5338. # lifted or lowered.
  5339. if self.toolchange_xy_type == "excellon":
  5340. if self.app.defaults["excellon_toolchangexy"] == '' or self.app.defaults["excellon_toolchangexy"] is None:
  5341. pos_xy = (0, 0)
  5342. else:
  5343. pos_xy = self.app.defaults["excellon_toolchangexy"]
  5344. try:
  5345. pos_xy = [float(eval(a)) for a in pos_xy.split(",")]
  5346. except Exception:
  5347. if len(pos_xy) != 2:
  5348. pos_xy = (0, 0)
  5349. else:
  5350. if self.app.defaults["geometry_toolchangexy"] == '' or self.app.defaults["geometry_toolchangexy"] is None:
  5351. pos_xy = (0, 0)
  5352. else:
  5353. pos_xy = self.app.defaults["geometry_toolchangexy"]
  5354. try:
  5355. pos_xy = [float(eval(a)) for a in pos_xy.split(",")]
  5356. except Exception:
  5357. if len(pos_xy) != 2:
  5358. pos_xy = (0, 0)
  5359. path = [pos_xy]
  5360. # path = [(0, 0)]
  5361. gcode_lines_list = self.gcode.splitlines()
  5362. self.app.inform.emit('%s: %d' % (_("Parsing GCode file. Number of lines"), len(gcode_lines_list)))
  5363. # Process every instruction
  5364. for line in gcode_lines_list:
  5365. if force_parsing is False or force_parsing is None:
  5366. if '%MO' in line or '%' in line or 'MOIN' in line or 'MOMM' in line:
  5367. return "fail"
  5368. gobj = self.codes_split(line)
  5369. # ## Units
  5370. if 'G' in gobj and (gobj['G'] == 20.0 or gobj['G'] == 21.0):
  5371. self.units = {20.0: "IN", 21.0: "MM"}[gobj['G']]
  5372. continue
  5373. # TODO take into consideration the tools and update the travel line thickness
  5374. if 'T' in gobj:
  5375. pass
  5376. # ## Changing height
  5377. if 'Z' in gobj:
  5378. if 'Roland' in self.pp_excellon_name or 'Roland' in self.pp_geometry_name:
  5379. pass
  5380. elif 'hpgl' in self.pp_excellon_name or 'hpgl' in self.pp_geometry_name:
  5381. pass
  5382. elif 'laser' in self.pp_excellon_name or 'laser' in self.pp_geometry_name:
  5383. pass
  5384. elif ('X' in gobj or 'Y' in gobj) and gobj['Z'] != current['Z']:
  5385. if self.pp_geometry_name == 'line_xyz' or self.pp_excellon_name == 'line_xyz':
  5386. pass
  5387. else:
  5388. log.warning("Non-orthogonal motion: From %s" % str(current))
  5389. log.warning(" To: %s" % str(gobj))
  5390. current['Z'] = gobj['Z']
  5391. # Store the path into geometry and reset path
  5392. if len(path) > 1:
  5393. geometry.append({"geom": LineString(path),
  5394. "kind": kind})
  5395. path = [path[-1]] # Start with the last point of last path.
  5396. # create the geometry for the holes created when drilling Excellon drills
  5397. if self.origin_kind == 'excellon':
  5398. if current['Z'] < 0:
  5399. current_drill_point_coords = (
  5400. float('%.*f' % (self.decimals, current['X'])),
  5401. float('%.*f' % (self.decimals, current['Y']))
  5402. )
  5403. # find the drill diameter knowing the drill coordinates
  5404. break_loop = False
  5405. for tool, tool_dict in self.exc_tools.items():
  5406. if 'drills' in tool_dict:
  5407. for drill_pt in tool_dict['drills']:
  5408. point_in_dict_coords = (
  5409. float('%.*f' % (self.decimals, drill_pt.x)),
  5410. float('%.*f' % (self.decimals, drill_pt.y))
  5411. )
  5412. if point_in_dict_coords == current_drill_point_coords:
  5413. dia = self.exc_tools[tool]['tooldia']
  5414. kind = ['C', 'F']
  5415. geometry.append(
  5416. {
  5417. "geom": Point(current_drill_point_coords).buffer(dia / 2.0).exterior,
  5418. "kind": kind
  5419. }
  5420. )
  5421. break_loop = True
  5422. break
  5423. if break_loop:
  5424. break
  5425. if 'G' in gobj:
  5426. current['G'] = int(gobj['G'])
  5427. if 'X' in gobj or 'Y' in gobj:
  5428. if 'X' in gobj:
  5429. x = gobj['X']
  5430. # current['X'] = x
  5431. else:
  5432. x = current['X']
  5433. if 'Y' in gobj:
  5434. y = gobj['Y']
  5435. else:
  5436. y = current['Y']
  5437. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  5438. if current['Z'] > 0:
  5439. kind[0] = 'T'
  5440. if current['G'] > 0:
  5441. kind[1] = 'S'
  5442. if current['G'] in [0, 1]: # line
  5443. path.append((x, y))
  5444. arcdir = [None, None, "cw", "ccw"]
  5445. if current['G'] in [2, 3]: # arc
  5446. center = [gobj['I'] + current['X'], gobj['J'] + current['Y']]
  5447. radius = np.sqrt(gobj['I'] ** 2 + gobj['J'] ** 2)
  5448. start = np.arctan2(-gobj['J'], -gobj['I'])
  5449. stop = np.arctan2(-center[1] + y, -center[0] + x)
  5450. path += arc(center, radius, start, stop, arcdir[current['G']], int(self.steps_per_circle))
  5451. current['X'] = x
  5452. current['Y'] = y
  5453. # Update current instruction
  5454. for code in gobj:
  5455. current[code] = gobj[code]
  5456. self.app.inform.emit('%s...' % _("Creating Geometry from the parsed GCode file. "))
  5457. # There might not be a change in height at the
  5458. # end, therefore, see here too if there is
  5459. # a final path.
  5460. if len(path) > 1:
  5461. geometry.append(
  5462. {
  5463. "geom": LineString(path),
  5464. "kind": kind
  5465. }
  5466. )
  5467. self.gcode_parsed = geometry
  5468. return geometry
  5469. def excellon_tool_gcode_parse(self, dia, gcode, start_pt=(0, 0), force_parsing=None):
  5470. """
  5471. G-Code parser (from self.exc_cnc_tools['tooldia']['gcode']). Generates dictionary with
  5472. single-segment LineString's and "kind" indicating cut or travel,
  5473. fast or feedrate speed.
  5474. Will return the Geometry as a list of dict in the format:
  5475. {
  5476. "geom": LineString(path),
  5477. "kind": kind
  5478. }
  5479. where kind can be either ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  5480. :param dia: the dia is a tool diameter which is the key in self.exc_cnc_tools dict
  5481. :type dia: float
  5482. :param gcode: Gcode to parse
  5483. :type gcode: str
  5484. :param start_pt: the point coordinates from where to start the parsing
  5485. :type start_pt: tuple
  5486. :param force_parsing:
  5487. :type force_parsing: bool
  5488. :return: Geometry as a list of dictionaries
  5489. :rtype: list
  5490. """
  5491. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  5492. # Results go here
  5493. geometry = []
  5494. # Last known instruction
  5495. current = {'X': 0.0, 'Y': 0.0, 'Z': 0.0, 'G': 0}
  5496. # Current path: temporary storage until tool is
  5497. # lifted or lowered.
  5498. pos_xy = start_pt
  5499. path = [pos_xy]
  5500. # path = [(0, 0)]
  5501. gcode_lines_list = gcode.splitlines()
  5502. self.app.inform.emit(
  5503. '%s: %s. %s: %d' % (_("Parsing GCode file for tool diameter"),
  5504. str(dia), _("Number of lines"),
  5505. len(gcode_lines_list))
  5506. )
  5507. # Process every instruction
  5508. for line in gcode_lines_list:
  5509. if force_parsing is False or force_parsing is None:
  5510. if '%MO' in line or '%' in line or 'MOIN' in line or 'MOMM' in line:
  5511. return "fail"
  5512. gobj = self.codes_split(line)
  5513. # ## Units
  5514. if 'G' in gobj and (gobj['G'] == 20.0 or gobj['G'] == 21.0):
  5515. self.units = {20.0: "IN", 21.0: "MM"}[gobj['G']]
  5516. continue
  5517. # TODO take into consideration the tools and update the travel line thickness
  5518. if 'T' in gobj:
  5519. pass
  5520. # ## Changing height
  5521. if 'Z' in gobj:
  5522. if 'Roland' in self.pp_excellon_name or 'Roland' in self.pp_geometry_name:
  5523. pass
  5524. elif 'hpgl' in self.pp_excellon_name or 'hpgl' in self.pp_geometry_name:
  5525. pass
  5526. elif 'laser' in self.pp_excellon_name or 'laser' in self.pp_geometry_name:
  5527. pass
  5528. elif ('X' in gobj or 'Y' in gobj) and gobj['Z'] != current['Z']:
  5529. if self.pp_geometry_name == 'line_xyz' or self.pp_excellon_name == 'line_xyz':
  5530. pass
  5531. else:
  5532. log.warning("Non-orthogonal motion: From %s" % str(current))
  5533. log.warning(" To: %s" % str(gobj))
  5534. current['Z'] = gobj['Z']
  5535. # Store the path into geometry and reset path
  5536. if len(path) > 1:
  5537. geometry.append({"geom": LineString(path),
  5538. "kind": kind})
  5539. path = [path[-1]] # Start with the last point of last path.
  5540. # create the geometry for the holes created when drilling Excellon drills
  5541. if current['Z'] < 0:
  5542. current_drill_point_coords = (
  5543. float('%.*f' % (self.decimals, current['X'])),
  5544. float('%.*f' % (self.decimals, current['Y']))
  5545. )
  5546. kind = ['C', 'F']
  5547. geometry.append(
  5548. {
  5549. "geom": Point(current_drill_point_coords).buffer(dia/2.0).exterior,
  5550. "kind": kind
  5551. }
  5552. )
  5553. if 'G' in gobj:
  5554. current['G'] = int(gobj['G'])
  5555. if 'X' in gobj or 'Y' in gobj:
  5556. x = gobj['X'] if 'X' in gobj else current['X']
  5557. y = gobj['Y'] if 'Y' in gobj else current['Y']
  5558. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  5559. if current['Z'] > 0:
  5560. kind[0] = 'T'
  5561. if current['G'] > 0:
  5562. kind[1] = 'S'
  5563. if current['G'] in [0, 1]: # line
  5564. path.append((x, y))
  5565. arcdir = [None, None, "cw", "ccw"]
  5566. if current['G'] in [2, 3]: # arc
  5567. center = [gobj['I'] + current['X'], gobj['J'] + current['Y']]
  5568. radius = np.sqrt(gobj['I'] ** 2 + gobj['J'] ** 2)
  5569. start = np.arctan2(-gobj['J'], -gobj['I'])
  5570. stop = np.arctan2(-center[1] + y, -center[0] + x)
  5571. path += arc(center, radius, start, stop, arcdir[current['G']], int(self.steps_per_circle))
  5572. current['X'] = x
  5573. current['Y'] = y
  5574. # Update current instruction
  5575. for code in gobj:
  5576. current[code] = gobj[code]
  5577. self.app.inform.emit('%s: %s' % (_("Creating Geometry from the parsed GCode file for tool diameter"), str(dia)))
  5578. # There might not be a change in height at the end, therefore, see here too if there is a final path.
  5579. if len(path) > 1:
  5580. geometry.append(
  5581. {
  5582. "geom": LineString(path),
  5583. "kind": kind
  5584. }
  5585. )
  5586. return geometry
  5587. # def plot(self, tooldia=None, dpi=75, margin=0.1,
  5588. # color={"T": ["#F0E24D", "#B5AB3A"], "C": ["#5E6CFF", "#4650BD"]},
  5589. # alpha={"T": 0.3, "C": 1.0}):
  5590. # """
  5591. # Creates a Matplotlib figure with a plot of the
  5592. # G-code job.
  5593. # """
  5594. # if tooldia is None:
  5595. # tooldia = self.tooldia
  5596. #
  5597. # fig = Figure(dpi=dpi)
  5598. # ax = fig.add_subplot(111)
  5599. # ax.set_aspect(1)
  5600. # xmin, ymin, xmax, ymax = self.input_geometry_bounds
  5601. # ax.set_xlim(xmin-margin, xmax+margin)
  5602. # ax.set_ylim(ymin-margin, ymax+margin)
  5603. #
  5604. # if tooldia == 0:
  5605. # for geo in self.gcode_parsed:
  5606. # linespec = '--'
  5607. # linecolor = color[geo['kind'][0]][1]
  5608. # if geo['kind'][0] == 'C':
  5609. # linespec = 'k-'
  5610. # x, y = geo['geom'].coords.xy
  5611. # ax.plot(x, y, linespec, color=linecolor)
  5612. # else:
  5613. # for geo in self.gcode_parsed:
  5614. # poly = geo['geom'].buffer(tooldia/2.0)
  5615. # patch = PolygonPatch(poly, facecolor=color[geo['kind'][0]][0],
  5616. # edgecolor=color[geo['kind'][0]][1],
  5617. # alpha=alpha[geo['kind'][0]], zorder=2)
  5618. # ax.add_patch(patch)
  5619. #
  5620. # return fig
  5621. def plot2(self, tooldia=None, dpi=75, margin=0.1, gcode_parsed=None,
  5622. color=None, alpha={"T": 0.3, "C": 1.0}, tool_tolerance=0.0005, obj=None, visible=False, kind='all'):
  5623. """
  5624. Plots the G-code job onto the given axes.
  5625. :param tooldia: Tool diameter.
  5626. :type tooldia: float
  5627. :param dpi: Not used!
  5628. :type dpi: float
  5629. :param margin: Not used!
  5630. :type margin: float
  5631. :param gcode_parsed: Parsed Gcode
  5632. :type gcode_parsed: str
  5633. :param color: Color specification.
  5634. :type color: str
  5635. :param alpha: Transparency specification.
  5636. :type alpha: dict
  5637. :param tool_tolerance: Tolerance when drawing the toolshape.
  5638. :type tool_tolerance: float
  5639. :param obj: The object for whih to plot
  5640. :type obj: class
  5641. :param visible: Visibility status
  5642. :type visible: bool
  5643. :param kind: Can be: "travel", "cut", "all"
  5644. :type kind: str
  5645. :return: None
  5646. :rtype:
  5647. """
  5648. # units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5649. if color is None:
  5650. color = {
  5651. "T": [self.app.defaults["cncjob_travel_fill"], self.app.defaults["cncjob_travel_line"]],
  5652. "C": [self.app.defaults["cncjob_plot_fill"], self.app.defaults["cncjob_plot_line"]]
  5653. }
  5654. gcode_parsed = gcode_parsed if gcode_parsed else self.gcode_parsed
  5655. if tooldia is None:
  5656. tooldia = self.tooldia
  5657. # this should be unlikely unless when upstream the tooldia is a tuple made by one dia and a comma like (2.4,)
  5658. if isinstance(tooldia, list):
  5659. tooldia = tooldia[0] if tooldia[0] is not None else self.tooldia
  5660. if tooldia == 0:
  5661. for geo in gcode_parsed:
  5662. if kind == 'all':
  5663. obj.add_shape(shape=geo['geom'], color=color[geo['kind'][0]][1], visible=visible)
  5664. elif kind == 'travel':
  5665. if geo['kind'][0] == 'T':
  5666. obj.add_shape(shape=geo['geom'], color=color['T'][1], visible=visible)
  5667. elif kind == 'cut':
  5668. if geo['kind'][0] == 'C':
  5669. obj.add_shape(shape=geo['geom'], color=color['C'][1], visible=visible)
  5670. else:
  5671. path_num = 0
  5672. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  5673. if self.coordinates_type == "G90":
  5674. # For Absolute coordinates type G90
  5675. for geo in gcode_parsed:
  5676. if geo['kind'][0] == 'T':
  5677. start_position = geo['geom'].coords[0]
  5678. if tooldia not in obj.annotations_dict:
  5679. obj.annotations_dict[tooldia] = {
  5680. 'pos': [],
  5681. 'text': []
  5682. }
  5683. if start_position not in obj.annotations_dict[tooldia]['pos']:
  5684. path_num += 1
  5685. obj.annotations_dict[tooldia]['pos'].append(start_position)
  5686. obj.annotations_dict[tooldia]['text'].append(str(path_num))
  5687. end_position = geo['geom'].coords[-1]
  5688. if tooldia not in obj.annotations_dict:
  5689. obj.annotations_dict[tooldia] = {
  5690. 'pos': [],
  5691. 'text': []
  5692. }
  5693. if end_position not in obj.annotations_dict[tooldia]['pos']:
  5694. path_num += 1
  5695. obj.annotations_dict[tooldia]['pos'].append(end_position)
  5696. obj.annotations_dict[tooldia]['text'].append(str(path_num))
  5697. # plot the geometry of Excellon objects
  5698. if self.origin_kind == 'excellon':
  5699. try:
  5700. # if the geos are travel lines
  5701. if geo['kind'][0] == 'T':
  5702. poly = geo['geom'].buffer(distance=(tooldia / 1.99999999),
  5703. resolution=self.steps_per_circle)
  5704. else:
  5705. poly = Polygon(geo['geom'])
  5706. poly = poly.simplify(tool_tolerance)
  5707. except Exception:
  5708. # deal here with unexpected plot errors due of LineStrings not valid
  5709. continue
  5710. else:
  5711. # plot the geometry of any objects other than Excellon
  5712. poly = geo['geom'].buffer(distance=(tooldia / 1.99999999), resolution=self.steps_per_circle)
  5713. poly = poly.simplify(tool_tolerance)
  5714. if kind == 'all':
  5715. obj.add_shape(shape=poly, color=color[geo['kind'][0]][1], face_color=color[geo['kind'][0]][0],
  5716. visible=visible, layer=1 if geo['kind'][0] == 'C' else 2)
  5717. elif kind == 'travel':
  5718. if geo['kind'][0] == 'T':
  5719. obj.add_shape(shape=poly, color=color['T'][1], face_color=color['T'][0],
  5720. visible=visible, layer=2)
  5721. elif kind == 'cut':
  5722. if geo['kind'][0] == 'C':
  5723. obj.add_shape(shape=poly, color=color['C'][1], face_color=color['C'][0],
  5724. visible=visible, layer=1)
  5725. else:
  5726. self.app.inform.emit('[ERROR_NOTCL] %s...' % _('G91 coordinates not implemented'))
  5727. return 'fail'
  5728. def plot_annotations(self, obj, visible=True):
  5729. """
  5730. Plot annotations.
  5731. :param obj: FlatCAM CNCJob object for which to plot the annotations
  5732. :type obj:
  5733. :param visible: annotaions visibility
  5734. :type visible: bool
  5735. :return: Nothing
  5736. :rtype:
  5737. """
  5738. if not obj.annotations_dict:
  5739. return
  5740. if visible is True:
  5741. obj.text_col.enabled = True
  5742. else:
  5743. obj.text_col.enabled = False
  5744. return
  5745. text = []
  5746. pos = []
  5747. for tooldia in obj.annotations_dict:
  5748. pos += obj.annotations_dict[tooldia]['pos']
  5749. text += obj.annotations_dict[tooldia]['text']
  5750. if not text or not pos:
  5751. return
  5752. try:
  5753. if self.app.defaults['global_theme'] == 'white':
  5754. obj.annotation.set(text=text, pos=pos, visible=obj.options['plot'],
  5755. font_size=self.app.defaults["cncjob_annotation_fontsize"],
  5756. color=self.app.defaults["cncjob_annotation_fontcolor"])
  5757. else:
  5758. # invert the color
  5759. old_color = self.app.defaults["cncjob_annotation_fontcolor"].lower()
  5760. new_color = ''
  5761. code = {}
  5762. l1 = "#;0123456789abcdef"
  5763. l2 = "#;fedcba9876543210"
  5764. for i in range(len(l1)):
  5765. code[l1[i]] = l2[i]
  5766. for x in range(len(old_color)):
  5767. new_color += code[old_color[x]]
  5768. obj.annotation.set(text=text, pos=pos, visible=obj.options['plot'],
  5769. font_size=self.app.defaults["cncjob_annotation_fontsize"],
  5770. color=new_color)
  5771. except Exception as e:
  5772. log.debug("CNCJob.plot2() --> annotations --> %s" % str(e))
  5773. if self.app.is_legacy is False:
  5774. obj.annotation.clear(update=True)
  5775. obj.annotation.redraw()
  5776. def create_geometry(self):
  5777. """
  5778. It is used by the Excellon objects. Will create the solid_geometry which will be an attribute of the
  5779. Excellon object class.
  5780. :return: List of Shapely geometry elements
  5781. :rtype: list
  5782. """
  5783. # This takes forever. Too much data?
  5784. # self.app.inform.emit('%s: %s' % (_("Unifying Geometry from parsed Geometry segments"),
  5785. # str(len(self.gcode_parsed))))
  5786. # self.solid_geometry = cascaded_union([geo['geom'] for geo in self.gcode_parsed])
  5787. # This is much faster but not so nice to look at as you can see different segments of the geometry
  5788. self.solid_geometry = [geo['geom'] for geo in self.gcode_parsed]
  5789. return self.solid_geometry
  5790. def segment(self, coords):
  5791. """
  5792. Break long linear lines to make it more auto level friendly.
  5793. Code snippet added by Lei Zheng in a rejected pull request on FlatCAM https://bitbucket.org/realthunder/
  5794. :param coords: List of coordinates tuples
  5795. :type coords: list
  5796. :return: A path; list with the multiple coordinates breaking a line.
  5797. :rtype: list
  5798. """
  5799. if len(coords) < 2 or self.segx <= 0 and self.segy <= 0:
  5800. return list(coords)
  5801. path = [coords[0]]
  5802. # break the line in either x or y dimension only
  5803. def linebreak_single(line, dim, dmax):
  5804. if dmax <= 0:
  5805. return None
  5806. if line[1][dim] > line[0][dim]:
  5807. sign = 1.0
  5808. d = line[1][dim] - line[0][dim]
  5809. else:
  5810. sign = -1.0
  5811. d = line[0][dim] - line[1][dim]
  5812. if d > dmax:
  5813. # make sure we don't make any new lines too short
  5814. if d > dmax * 2:
  5815. dd = dmax
  5816. else:
  5817. dd = d / 2
  5818. other = dim ^ 1
  5819. return (line[0][dim] + dd * sign, line[0][other] + \
  5820. dd * (line[1][other] - line[0][other]) / d)
  5821. return None
  5822. # recursively breaks down a given line until it is within the
  5823. # required step size
  5824. def linebreak(line):
  5825. pt_new = linebreak_single(line, 0, self.segx)
  5826. if pt_new is None:
  5827. pt_new2 = linebreak_single(line, 1, self.segy)
  5828. else:
  5829. pt_new2 = linebreak_single((line[0], pt_new), 1, self.segy)
  5830. if pt_new2 is not None:
  5831. pt_new = pt_new2[::-1]
  5832. if pt_new is None:
  5833. path.append(line[1])
  5834. else:
  5835. path.append(pt_new)
  5836. linebreak((pt_new, line[1]))
  5837. for pt in coords[1:]:
  5838. linebreak((path[-1], pt))
  5839. return path
  5840. def linear2gcode(self, linear, dia, tolerance=0, down=True, up=True, z_cut=None, z_move=None, zdownrate=None,
  5841. feedrate=None, feedrate_z=None, feedrate_rapid=None, cont=False, old_point=(0, 0)):
  5842. """
  5843. Generates G-code to cut along the linear feature.
  5844. :param linear: The path to cut along.
  5845. :type: Shapely.LinearRing or Shapely.Linear String
  5846. :param dia: The tool diameter that is going on the path
  5847. :type dia: float
  5848. :param tolerance: All points in the simplified object will be within the
  5849. tolerance distance of the original geometry.
  5850. :type tolerance: float
  5851. :param down:
  5852. :param up:
  5853. :param z_cut:
  5854. :param z_move:
  5855. :param zdownrate:
  5856. :param feedrate: speed for cut on X - Y plane
  5857. :param feedrate_z: speed for cut on Z plane
  5858. :param feedrate_rapid: speed to move between cuts; usually is G0 but some CNC require to specify it
  5859. :param cont:
  5860. :param old_point:
  5861. :return: G-code to cut along the linear feature.
  5862. """
  5863. if z_cut is None:
  5864. z_cut = self.z_cut
  5865. if z_move is None:
  5866. z_move = self.z_move
  5867. #
  5868. # if zdownrate is None:
  5869. # zdownrate = self.zdownrate
  5870. if feedrate is None:
  5871. feedrate = self.feedrate
  5872. if feedrate_z is None:
  5873. feedrate_z = self.z_feedrate
  5874. if feedrate_rapid is None:
  5875. feedrate_rapid = self.feedrate_rapid
  5876. # Simplify paths?
  5877. if tolerance > 0:
  5878. target_linear = linear.simplify(tolerance)
  5879. else:
  5880. target_linear = linear
  5881. gcode = ""
  5882. # path = list(target_linear.coords)
  5883. path = self.segment(target_linear.coords)
  5884. p = self.pp_geometry
  5885. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  5886. if self.coordinates_type == "G90":
  5887. # For Absolute coordinates type G90
  5888. first_x = path[0][0]
  5889. first_y = path[0][1]
  5890. else:
  5891. # For Incremental coordinates type G91
  5892. first_x = path[0][0] - old_point[0]
  5893. first_y = path[0][1] - old_point[1]
  5894. # Move fast to 1st point
  5895. if not cont:
  5896. current_tooldia = dia
  5897. travels = self.app.exc_areas.travel_coordinates(start_point=(old_point[0], old_point[1]),
  5898. end_point=(first_x, first_y),
  5899. tooldia=current_tooldia)
  5900. prev_z = None
  5901. for travel in travels:
  5902. locx = travel[1][0]
  5903. locy = travel[1][1]
  5904. if travel[0] is not None:
  5905. # move to next point
  5906. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  5907. # raise to safe Z (travel[0]) each time because safe Z may be different
  5908. self.z_move = travel[0]
  5909. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  5910. # restore z_move
  5911. self.z_move = z_move
  5912. else:
  5913. if prev_z is not None:
  5914. # move to next point
  5915. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  5916. # we assume that previously the z_move was altered therefore raise to
  5917. # the travel_z (z_move)
  5918. self.z_move = z_move
  5919. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  5920. else:
  5921. # move to next point
  5922. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  5923. # store prev_z
  5924. prev_z = travel[0]
  5925. # gcode += self.doformat(p.rapid_code, x=first_x, y=first_y) # Move to first point
  5926. # Move down to cutting depth
  5927. if down:
  5928. # Different feedrate for vertical cut?
  5929. gcode += self.doformat(p.z_feedrate_code)
  5930. # gcode += self.doformat(p.feedrate_code)
  5931. gcode += self.doformat(p.down_code, x=first_x, y=first_y, z_cut=z_cut)
  5932. gcode += self.doformat(p.feedrate_code, feedrate=feedrate)
  5933. # Cutting...
  5934. prev_x = first_x
  5935. prev_y = first_y
  5936. for pt in path[1:]:
  5937. if self.app.abort_flag:
  5938. # graceful abort requested by the user
  5939. raise grace
  5940. if self.coordinates_type == "G90":
  5941. # For Absolute coordinates type G90
  5942. next_x = pt[0]
  5943. next_y = pt[1]
  5944. else:
  5945. # For Incremental coordinates type G91
  5946. # next_x = pt[0] - prev_x
  5947. # next_y = pt[1] - prev_y
  5948. self.app.inform.emit('[ERROR_NOTCL] %s' % _('G91 coordinates not implemented ...'))
  5949. next_x = pt[0]
  5950. next_y = pt[1]
  5951. gcode += self.doformat(p.linear_code, x=next_x, y=next_y, z=z_cut) # Linear motion to point
  5952. prev_x = pt[0]
  5953. prev_y = pt[1]
  5954. # Up to travelling height.
  5955. if up:
  5956. gcode += self.doformat(p.lift_code, x=prev_x, y=prev_y, z_move=z_move) # Stop cutting
  5957. return gcode
  5958. def linear2gcode_extra(self, linear, dia, extracut_length, tolerance=0, down=True, up=True,
  5959. z_cut=None, z_move=None, zdownrate=None,
  5960. feedrate=None, feedrate_z=None, feedrate_rapid=None, cont=False, old_point=(0, 0)):
  5961. """
  5962. Generates G-code to cut along the linear feature.
  5963. :param linear: The path to cut along.
  5964. :type: Shapely.LinearRing or Shapely.Linear String
  5965. :param dia: The tool diameter that is going on the path
  5966. :type dia: float
  5967. :param extracut_length: how much to cut extra over the first point at the end of the path
  5968. :param tolerance: All points in the simplified object will be within the
  5969. tolerance distance of the original geometry.
  5970. :type tolerance: float
  5971. :param down:
  5972. :param up:
  5973. :param z_cut:
  5974. :param z_move:
  5975. :param zdownrate:
  5976. :param feedrate: speed for cut on X - Y plane
  5977. :param feedrate_z: speed for cut on Z plane
  5978. :param feedrate_rapid: speed to move between cuts; usually is G0 but some CNC require to specify it
  5979. :param cont:
  5980. :param old_point:
  5981. :return: G-code to cut along the linear feature.
  5982. :rtype: str
  5983. """
  5984. if z_cut is None:
  5985. z_cut = self.z_cut
  5986. if z_move is None:
  5987. z_move = self.z_move
  5988. #
  5989. # if zdownrate is None:
  5990. # zdownrate = self.zdownrate
  5991. if feedrate is None:
  5992. feedrate = self.feedrate
  5993. if feedrate_z is None:
  5994. feedrate_z = self.z_feedrate
  5995. if feedrate_rapid is None:
  5996. feedrate_rapid = self.feedrate_rapid
  5997. # Simplify paths?
  5998. if tolerance > 0:
  5999. target_linear = linear.simplify(tolerance)
  6000. else:
  6001. target_linear = linear
  6002. gcode = ""
  6003. path = list(target_linear.coords)
  6004. p = self.pp_geometry
  6005. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  6006. if self.coordinates_type == "G90":
  6007. # For Absolute coordinates type G90
  6008. first_x = path[0][0]
  6009. first_y = path[0][1]
  6010. else:
  6011. # For Incremental coordinates type G91
  6012. first_x = path[0][0] - old_point[0]
  6013. first_y = path[0][1] - old_point[1]
  6014. # Move fast to 1st point
  6015. if not cont:
  6016. current_tooldia = dia
  6017. travels = self.app.exc_areas.travel_coordinates(start_point=(old_point[0], old_point[1]),
  6018. end_point=(first_x, first_y),
  6019. tooldia=current_tooldia)
  6020. prev_z = None
  6021. for travel in travels:
  6022. locx = travel[1][0]
  6023. locy = travel[1][1]
  6024. if travel[0] is not None:
  6025. # move to next point
  6026. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  6027. # raise to safe Z (travel[0]) each time because safe Z may be different
  6028. self.z_move = travel[0]
  6029. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  6030. # restore z_move
  6031. self.z_move = z_move
  6032. else:
  6033. if prev_z is not None:
  6034. # move to next point
  6035. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  6036. # we assume that previously the z_move was altered therefore raise to
  6037. # the travel_z (z_move)
  6038. self.z_move = z_move
  6039. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  6040. else:
  6041. # move to next point
  6042. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  6043. # store prev_z
  6044. prev_z = travel[0]
  6045. # gcode += self.doformat(p.rapid_code, x=first_x, y=first_y) # Move to first point
  6046. # Move down to cutting depth
  6047. if down:
  6048. # Different feedrate for vertical cut?
  6049. if self.z_feedrate is not None:
  6050. gcode += self.doformat(p.z_feedrate_code)
  6051. # gcode += self.doformat(p.feedrate_code)
  6052. gcode += self.doformat(p.down_code, x=first_x, y=first_y, z_cut=z_cut)
  6053. gcode += self.doformat(p.feedrate_code, feedrate=feedrate)
  6054. else:
  6055. gcode += self.doformat(p.down_code, x=first_x, y=first_y, z_cut=z_cut) # Start cutting
  6056. # Cutting...
  6057. prev_x = first_x
  6058. prev_y = first_y
  6059. for pt in path[1:]:
  6060. if self.app.abort_flag:
  6061. # graceful abort requested by the user
  6062. raise grace
  6063. if self.coordinates_type == "G90":
  6064. # For Absolute coordinates type G90
  6065. next_x = pt[0]
  6066. next_y = pt[1]
  6067. else:
  6068. # For Incremental coordinates type G91
  6069. # For Incremental coordinates type G91
  6070. # next_x = pt[0] - prev_x
  6071. # next_y = pt[1] - prev_y
  6072. self.app.inform.emit('[ERROR_NOTCL] %s' % _('G91 coordinates not implemented ...'))
  6073. next_x = pt[0]
  6074. next_y = pt[1]
  6075. gcode += self.doformat(p.linear_code, x=next_x, y=next_y, z=z_cut) # Linear motion to point
  6076. prev_x = next_x
  6077. prev_y = next_y
  6078. # this line is added to create an extra cut over the first point in patch
  6079. # to make sure that we remove the copper leftovers
  6080. # Linear motion to the 1st point in the cut path
  6081. # if self.coordinates_type == "G90":
  6082. # # For Absolute coordinates type G90
  6083. # last_x = path[1][0]
  6084. # last_y = path[1][1]
  6085. # else:
  6086. # # For Incremental coordinates type G91
  6087. # last_x = path[1][0] - first_x
  6088. # last_y = path[1][1] - first_y
  6089. # gcode += self.doformat(p.linear_code, x=last_x, y=last_y)
  6090. # the first point for extracut is always mandatory if the extracut is enabled. But if the length of distance
  6091. # between point 0 and point 1 is more than the distance we set for the extra cut then make an interpolation
  6092. # along the path and find the point at the distance extracut_length
  6093. if extracut_length == 0.0:
  6094. extra_path = [path[-1], path[0], path[1]]
  6095. new_x = extra_path[0][0]
  6096. new_y = extra_path[0][1]
  6097. # this is an extra line therefore lift the milling bit
  6098. gcode += self.doformat(p.lift_code, x=prev_x, y=prev_y, z_move=z_move) # lift
  6099. # move fast to the new first point
  6100. gcode += self.doformat(p.rapid_code, x=new_x, y=new_y)
  6101. # lower the milling bit
  6102. # Different feedrate for vertical cut?
  6103. if self.z_feedrate is not None:
  6104. gcode += self.doformat(p.z_feedrate_code)
  6105. gcode += self.doformat(p.down_code, x=new_x, y=new_y, z_cut=z_cut)
  6106. gcode += self.doformat(p.feedrate_code, feedrate=feedrate)
  6107. else:
  6108. gcode += self.doformat(p.down_code, x=new_x, y=new_y, z_cut=z_cut) # Start cutting
  6109. # start cutting the extra line
  6110. last_pt = extra_path[0]
  6111. for pt in extra_path[1:]:
  6112. gcode += self.doformat(p.linear_code, x=pt[0], y=pt[1])
  6113. last_pt = pt
  6114. # go back to the original point
  6115. gcode += self.doformat(p.linear_code, x=path[0][0], y=path[0][1])
  6116. last_pt = path[0]
  6117. else:
  6118. # go to the point that is 5% in length before the end (therefore 95% length from start of the line),
  6119. # along the line to be cut
  6120. if extracut_length >= target_linear.length:
  6121. extracut_length = target_linear.length
  6122. # ---------------------------------------------
  6123. # first half
  6124. # ---------------------------------------------
  6125. start_length = target_linear.length - (extracut_length * 0.5)
  6126. extra_line = substring(target_linear, start_length, target_linear.length)
  6127. extra_path = list(extra_line.coords)
  6128. new_x = extra_path[0][0]
  6129. new_y = extra_path[0][1]
  6130. # this is an extra line therefore lift the milling bit
  6131. gcode += self.doformat(p.lift_code, x=prev_x, y=prev_y, z_move=z_move) # lift
  6132. # move fast to the new first point
  6133. gcode += self.doformat(p.rapid_code, x=new_x, y=new_y)
  6134. # lower the milling bit
  6135. # Different feedrate for vertical cut?
  6136. if self.z_feedrate is not None:
  6137. gcode += self.doformat(p.z_feedrate_code)
  6138. gcode += self.doformat(p.down_code, x=new_x, y=new_y, z_cut=z_cut)
  6139. gcode += self.doformat(p.feedrate_code, feedrate=feedrate)
  6140. else:
  6141. gcode += self.doformat(p.down_code, x=new_x, y=new_y, z_cut=z_cut) # Start cutting
  6142. # start cutting the extra line
  6143. for pt in extra_path[1:]:
  6144. gcode += self.doformat(p.linear_code, x=pt[0], y=pt[1])
  6145. # ---------------------------------------------
  6146. # second half
  6147. # ---------------------------------------------
  6148. extra_line = substring(target_linear, 0, (extracut_length * 0.5))
  6149. extra_path = list(extra_line.coords)
  6150. # start cutting the extra line
  6151. last_pt = extra_path[0]
  6152. for pt in extra_path[1:]:
  6153. gcode += self.doformat(p.linear_code, x=pt[0], y=pt[1])
  6154. last_pt = pt
  6155. # ---------------------------------------------
  6156. # back to original start point, cutting
  6157. # ---------------------------------------------
  6158. extra_line = substring(target_linear, 0, (extracut_length * 0.5))
  6159. extra_path = list(extra_line.coords)[::-1]
  6160. # start cutting the extra line
  6161. last_pt = extra_path[0]
  6162. for pt in extra_path[1:]:
  6163. gcode += self.doformat(p.linear_code, x=pt[0], y=pt[1])
  6164. last_pt = pt
  6165. # if extracut_length == 0.0:
  6166. # gcode += self.doformat(p.linear_code, x=path[1][0], y=path[1][1])
  6167. # last_pt = path[1]
  6168. # else:
  6169. # if abs(distance(path[1], path[0])) > extracut_length:
  6170. # i_point = LineString([path[0], path[1]]).interpolate(extracut_length)
  6171. # gcode += self.doformat(p.linear_code, x=i_point.x, y=i_point.y)
  6172. # last_pt = (i_point.x, i_point.y)
  6173. # else:
  6174. # last_pt = path[0]
  6175. # for pt in path[1:]:
  6176. # extracut_distance = abs(distance(pt, last_pt))
  6177. # if extracut_distance <= extracut_length:
  6178. # gcode += self.doformat(p.linear_code, x=pt[0], y=pt[1])
  6179. # last_pt = pt
  6180. # else:
  6181. # break
  6182. # Up to travelling height.
  6183. if up:
  6184. gcode += self.doformat(p.lift_code, x=last_pt[0], y=last_pt[1], z_move=z_move) # Stop cutting
  6185. return gcode
  6186. def point2gcode(self, point, dia, z_move=None, old_point=(0, 0)):
  6187. """
  6188. :param point: A Shapely Point
  6189. :type point: Point
  6190. :param dia: The tool diameter that is going on the path
  6191. :type dia: float
  6192. :param z_move: Travel Z
  6193. :type z_move: float
  6194. :param old_point: Old point coordinates from which we moved to the 'point'
  6195. :type old_point: tuple
  6196. :return: G-code to cut on the Point feature.
  6197. :rtype: str
  6198. """
  6199. gcode = ""
  6200. if self.app.abort_flag:
  6201. # graceful abort requested by the user
  6202. raise grace
  6203. path = list(point.coords)
  6204. p = self.pp_geometry
  6205. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  6206. if self.coordinates_type == "G90":
  6207. # For Absolute coordinates type G90
  6208. first_x = path[0][0]
  6209. first_y = path[0][1]
  6210. else:
  6211. # For Incremental coordinates type G91
  6212. # first_x = path[0][0] - old_point[0]
  6213. # first_y = path[0][1] - old_point[1]
  6214. self.app.inform.emit('[ERROR_NOTCL] %s' %
  6215. _('G91 coordinates not implemented ...'))
  6216. first_x = path[0][0]
  6217. first_y = path[0][1]
  6218. current_tooldia = dia
  6219. travels = self.app.exc_areas.travel_coordinates(start_point=(old_point[0], old_point[1]),
  6220. end_point=(first_x, first_y),
  6221. tooldia=current_tooldia)
  6222. prev_z = None
  6223. for travel in travels:
  6224. locx = travel[1][0]
  6225. locy = travel[1][1]
  6226. if travel[0] is not None:
  6227. # move to next point
  6228. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  6229. # raise to safe Z (travel[0]) each time because safe Z may be different
  6230. self.z_move = travel[0]
  6231. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  6232. # restore z_move
  6233. self.z_move = z_move
  6234. else:
  6235. if prev_z is not None:
  6236. # move to next point
  6237. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  6238. # we assume that previously the z_move was altered therefore raise to
  6239. # the travel_z (z_move)
  6240. self.z_move = z_move
  6241. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  6242. else:
  6243. # move to next point
  6244. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  6245. # store prev_z
  6246. prev_z = travel[0]
  6247. # gcode += self.doformat(p.linear_code, x=first_x, y=first_y) # Move to first point
  6248. if self.z_feedrate is not None:
  6249. gcode += self.doformat(p.z_feedrate_code)
  6250. gcode += self.doformat(p.down_code, x=first_x, y=first_y, z_cut=self.z_cut)
  6251. gcode += self.doformat(p.feedrate_code)
  6252. else:
  6253. gcode += self.doformat(p.down_code, x=first_x, y=first_y, z_cut=self.z_cut) # Start cutting
  6254. gcode += self.doformat(p.lift_code, x=first_x, y=first_y) # Stop cutting
  6255. return gcode
  6256. def export_svg(self, scale_stroke_factor=0.00):
  6257. """
  6258. Exports the CNC Job as a SVG Element
  6259. :param scale_stroke_factor: A factor to scale the SVG geometry
  6260. :type scale_stroke_factor: float
  6261. :return: SVG Element string
  6262. :rtype: str
  6263. """
  6264. # scale_factor is a multiplication factor for the SVG stroke-width used within shapely's svg export
  6265. # If not specified then try and use the tool diameter
  6266. # This way what is on screen will match what is outputed for the svg
  6267. # This is quite a useful feature for svg's used with visicut
  6268. if scale_stroke_factor <= 0:
  6269. scale_stroke_factor = self.options['tooldia'] / 2
  6270. # If still 0 then default to 0.05
  6271. # This value appears to work for zooming, and getting the output svg line width
  6272. # to match that viewed on screen with FlatCam
  6273. if scale_stroke_factor == 0:
  6274. scale_stroke_factor = 0.01
  6275. # Separate the list of cuts and travels into 2 distinct lists
  6276. # This way we can add different formatting / colors to both
  6277. cuts = []
  6278. travels = []
  6279. cutsgeom = ''
  6280. travelsgeom = ''
  6281. for g in self.gcode_parsed:
  6282. if self.app.abort_flag:
  6283. # graceful abort requested by the user
  6284. raise grace
  6285. if g['kind'][0] == 'C':
  6286. cuts.append(g)
  6287. if g['kind'][0] == 'T':
  6288. travels.append(g)
  6289. # Used to determine the overall board size
  6290. self.solid_geometry = cascaded_union([geo['geom'] for geo in self.gcode_parsed])
  6291. # Convert the cuts and travels into single geometry objects we can render as svg xml
  6292. if travels:
  6293. travelsgeom = cascaded_union([geo['geom'] for geo in travels])
  6294. if self.app.abort_flag:
  6295. # graceful abort requested by the user
  6296. raise grace
  6297. if cuts:
  6298. cutsgeom = cascaded_union([geo['geom'] for geo in cuts])
  6299. # Render the SVG Xml
  6300. # The scale factor affects the size of the lines, and the stroke color adds different formatting for each set
  6301. # It's better to have the travels sitting underneath the cuts for visicut
  6302. svg_elem = ""
  6303. if travels:
  6304. svg_elem = travelsgeom.svg(scale_factor=scale_stroke_factor, stroke_color="#F0E24D")
  6305. if cuts:
  6306. svg_elem += cutsgeom.svg(scale_factor=scale_stroke_factor, stroke_color="#5E6CFF")
  6307. return svg_elem
  6308. def bounds(self, flatten=None):
  6309. """
  6310. Returns coordinates of rectangular bounds of geometry: (xmin, ymin, xmax, ymax).
  6311. :param flatten: Not used, it is here for compatibility with base class method
  6312. :type flatten: bool
  6313. :return: Bounding values in format (xmin, ymin, xmax, ymax)
  6314. :rtype: tuple
  6315. """
  6316. log.debug("camlib.CNCJob.bounds()")
  6317. def bounds_rec(obj):
  6318. if type(obj) is list:
  6319. cminx = np.Inf
  6320. cminy = np.Inf
  6321. cmaxx = -np.Inf
  6322. cmaxy = -np.Inf
  6323. for k in obj:
  6324. if type(k) is dict:
  6325. for key in k:
  6326. minx_, miny_, maxx_, maxy_ = bounds_rec(k[key])
  6327. cminx = min(cminx, minx_)
  6328. cminy = min(cminy, miny_)
  6329. cmaxx = max(cmaxx, maxx_)
  6330. cmaxy = max(cmaxy, maxy_)
  6331. else:
  6332. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  6333. cminx = min(cminx, minx_)
  6334. cminy = min(cminy, miny_)
  6335. cmaxx = max(cmaxx, maxx_)
  6336. cmaxy = max(cmaxy, maxy_)
  6337. return cminx, cminy, cmaxx, cmaxy
  6338. else:
  6339. # it's a Shapely object, return it's bounds
  6340. return obj.bounds
  6341. if self.multitool is False:
  6342. log.debug("CNCJob->bounds()")
  6343. if self.solid_geometry is None:
  6344. log.debug("solid_geometry is None")
  6345. return 0, 0, 0, 0
  6346. bounds_coords = bounds_rec(self.solid_geometry)
  6347. else:
  6348. minx = np.Inf
  6349. miny = np.Inf
  6350. maxx = -np.Inf
  6351. maxy = -np.Inf
  6352. for k, v in self.cnc_tools.items():
  6353. minx = np.Inf
  6354. miny = np.Inf
  6355. maxx = -np.Inf
  6356. maxy = -np.Inf
  6357. try:
  6358. for k in v['solid_geometry']:
  6359. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  6360. minx = min(minx, minx_)
  6361. miny = min(miny, miny_)
  6362. maxx = max(maxx, maxx_)
  6363. maxy = max(maxy, maxy_)
  6364. except TypeError:
  6365. minx_, miny_, maxx_, maxy_ = bounds_rec(v['solid_geometry'])
  6366. minx = min(minx, minx_)
  6367. miny = min(miny, miny_)
  6368. maxx = max(maxx, maxx_)
  6369. maxy = max(maxy, maxy_)
  6370. bounds_coords = minx, miny, maxx, maxy
  6371. return bounds_coords
  6372. # TODO This function should be replaced at some point with a "real" function. Until then it's an ugly hack ...
  6373. def scale(self, xfactor, yfactor=None, point=None):
  6374. """
  6375. Scales all the geometry on the XY plane in the object by the
  6376. given factor. Tool sizes, feedrates, or Z-axis dimensions are
  6377. not altered.
  6378. :param factor: Number by which to scale the object.
  6379. :type factor: float
  6380. :param point: the (x,y) coords for the point of origin of scale
  6381. :type tuple of floats
  6382. :return: None
  6383. :rtype: None
  6384. """
  6385. log.debug("camlib.CNCJob.scale()")
  6386. if yfactor is None:
  6387. yfactor = xfactor
  6388. if point is None:
  6389. px = 0
  6390. py = 0
  6391. else:
  6392. px, py = point
  6393. def scale_g(g):
  6394. """
  6395. :param g: 'g' parameter it's a gcode string
  6396. :return: scaled gcode string
  6397. """
  6398. temp_gcode = ''
  6399. header_start = False
  6400. header_stop = False
  6401. units = self.app.defaults['units'].upper()
  6402. lines = StringIO(g)
  6403. for line in lines:
  6404. # this changes the GCODE header ---- UGLY HACK
  6405. if "TOOL DIAMETER" in line or "Feedrate:" in line:
  6406. header_start = True
  6407. if "G20" in line or "G21" in line:
  6408. header_start = False
  6409. header_stop = True
  6410. if header_start is True:
  6411. header_stop = False
  6412. if "in" in line:
  6413. if units == 'MM':
  6414. line = line.replace("in", "mm")
  6415. if "mm" in line:
  6416. if units == 'IN':
  6417. line = line.replace("mm", "in")
  6418. # find any float number in header (even multiple on the same line) and convert it
  6419. numbers_in_header = re.findall(self.g_nr_re, line)
  6420. if numbers_in_header:
  6421. for nr in numbers_in_header:
  6422. new_nr = float(nr) * xfactor
  6423. # replace the updated string
  6424. line = line.replace(nr, ('%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_nr))
  6425. )
  6426. # this scales all the X and Y and Z and F values and also the Tool Dia in the toolchange message
  6427. if header_stop is True:
  6428. if "G20" in line:
  6429. if units == 'MM':
  6430. line = line.replace("G20", "G21")
  6431. if "G21" in line:
  6432. if units == 'IN':
  6433. line = line.replace("G21", "G20")
  6434. # find the X group
  6435. match_x = self.g_x_re.search(line)
  6436. if match_x:
  6437. if match_x.group(1) is not None:
  6438. new_x = float(match_x.group(1)[1:]) * xfactor
  6439. # replace the updated string
  6440. line = line.replace(
  6441. match_x.group(1),
  6442. 'X%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_x)
  6443. )
  6444. # find the Y group
  6445. match_y = self.g_y_re.search(line)
  6446. if match_y:
  6447. if match_y.group(1) is not None:
  6448. new_y = float(match_y.group(1)[1:]) * yfactor
  6449. line = line.replace(
  6450. match_y.group(1),
  6451. 'Y%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_y)
  6452. )
  6453. # find the Z group
  6454. match_z = self.g_z_re.search(line)
  6455. if match_z:
  6456. if match_z.group(1) is not None:
  6457. new_z = float(match_z.group(1)[1:]) * xfactor
  6458. line = line.replace(
  6459. match_z.group(1),
  6460. 'Z%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_z)
  6461. )
  6462. # find the F group
  6463. match_f = self.g_f_re.search(line)
  6464. if match_f:
  6465. if match_f.group(1) is not None:
  6466. new_f = float(match_f.group(1)[1:]) * xfactor
  6467. line = line.replace(
  6468. match_f.group(1),
  6469. 'F%.*f' % (self.app.defaults["cncjob_fr_decimals"], new_f)
  6470. )
  6471. # find the T group (tool dia on toolchange)
  6472. match_t = self.g_t_re.search(line)
  6473. if match_t:
  6474. if match_t.group(1) is not None:
  6475. new_t = float(match_t.group(1)[1:]) * xfactor
  6476. line = line.replace(
  6477. match_t.group(1),
  6478. '= %.*f' % (self.app.defaults["cncjob_coords_decimals"], new_t)
  6479. )
  6480. temp_gcode += line
  6481. lines.close()
  6482. header_stop = False
  6483. return temp_gcode
  6484. if self.multitool is False:
  6485. # offset Gcode
  6486. self.gcode = scale_g(self.gcode)
  6487. # variables to display the percentage of work done
  6488. self.geo_len = 0
  6489. try:
  6490. self.geo_len = len(self.gcode_parsed)
  6491. except TypeError:
  6492. self.geo_len = 1
  6493. self.old_disp_number = 0
  6494. self.el_count = 0
  6495. # scale geometry
  6496. for g in self.gcode_parsed:
  6497. try:
  6498. g['geom'] = affinity.scale(g['geom'], xfactor, yfactor, origin=(px, py))
  6499. except AttributeError:
  6500. return g['geom']
  6501. self.el_count += 1
  6502. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  6503. if self.old_disp_number < disp_number <= 100:
  6504. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  6505. self.old_disp_number = disp_number
  6506. self.create_geometry()
  6507. else:
  6508. for k, v in self.cnc_tools.items():
  6509. # scale Gcode
  6510. v['gcode'] = scale_g(v['gcode'])
  6511. # variables to display the percentage of work done
  6512. self.geo_len = 0
  6513. try:
  6514. self.geo_len = len(v['gcode_parsed'])
  6515. except TypeError:
  6516. self.geo_len = 1
  6517. self.old_disp_number = 0
  6518. self.el_count = 0
  6519. # scale gcode_parsed
  6520. for g in v['gcode_parsed']:
  6521. try:
  6522. g['geom'] = affinity.scale(g['geom'], xfactor, yfactor, origin=(px, py))
  6523. except AttributeError:
  6524. return g['geom']
  6525. self.el_count += 1
  6526. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  6527. if self.old_disp_number < disp_number <= 100:
  6528. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  6529. self.old_disp_number = disp_number
  6530. v['solid_geometry'] = cascaded_union([geo['geom'] for geo in v['gcode_parsed']])
  6531. self.create_geometry()
  6532. self.app.proc_container.new_text = ''
  6533. def offset(self, vect):
  6534. """
  6535. Offsets all the geometry on the XY plane in the object by the
  6536. given vector.
  6537. Offsets all the GCODE on the XY plane in the object by the
  6538. given vector.
  6539. g_offsetx_re, g_offsety_re, multitool, cnnc_tools are attributes of FlatCAMCNCJob class in camlib
  6540. :param vect: (x, y) offset vector.
  6541. :type vect: tuple
  6542. :return: None
  6543. """
  6544. log.debug("camlib.CNCJob.offset()")
  6545. dx, dy = vect
  6546. def offset_g(g):
  6547. """
  6548. :param g: 'g' parameter it's a gcode string
  6549. :return: offseted gcode string
  6550. """
  6551. temp_gcode = ''
  6552. lines = StringIO(g)
  6553. for line in lines:
  6554. # find the X group
  6555. match_x = self.g_x_re.search(line)
  6556. if match_x:
  6557. if match_x.group(1) is not None:
  6558. # get the coordinate and add X offset
  6559. new_x = float(match_x.group(1)[1:]) + dx
  6560. # replace the updated string
  6561. line = line.replace(
  6562. match_x.group(1),
  6563. 'X%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_x)
  6564. )
  6565. match_y = self.g_y_re.search(line)
  6566. if match_y:
  6567. if match_y.group(1) is not None:
  6568. new_y = float(match_y.group(1)[1:]) + dy
  6569. line = line.replace(
  6570. match_y.group(1),
  6571. 'Y%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_y)
  6572. )
  6573. temp_gcode += line
  6574. lines.close()
  6575. return temp_gcode
  6576. if self.multitool is False:
  6577. # offset Gcode
  6578. self.gcode = offset_g(self.gcode)
  6579. # variables to display the percentage of work done
  6580. self.geo_len = 0
  6581. try:
  6582. self.geo_len = len(self.gcode_parsed)
  6583. except TypeError:
  6584. self.geo_len = 1
  6585. self.old_disp_number = 0
  6586. self.el_count = 0
  6587. # offset geometry
  6588. for g in self.gcode_parsed:
  6589. try:
  6590. g['geom'] = affinity.translate(g['geom'], xoff=dx, yoff=dy)
  6591. except AttributeError:
  6592. return g['geom']
  6593. self.el_count += 1
  6594. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  6595. if self.old_disp_number < disp_number <= 100:
  6596. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  6597. self.old_disp_number = disp_number
  6598. self.create_geometry()
  6599. else:
  6600. for k, v in self.cnc_tools.items():
  6601. # offset Gcode
  6602. v['gcode'] = offset_g(v['gcode'])
  6603. # variables to display the percentage of work done
  6604. self.geo_len = 0
  6605. try:
  6606. self.geo_len = len(v['gcode_parsed'])
  6607. except TypeError:
  6608. self.geo_len = 1
  6609. self.old_disp_number = 0
  6610. self.el_count = 0
  6611. # offset gcode_parsed
  6612. for g in v['gcode_parsed']:
  6613. try:
  6614. g['geom'] = affinity.translate(g['geom'], xoff=dx, yoff=dy)
  6615. except AttributeError:
  6616. return g['geom']
  6617. self.el_count += 1
  6618. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  6619. if self.old_disp_number < disp_number <= 100:
  6620. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  6621. self.old_disp_number = disp_number
  6622. # for the bounding box
  6623. v['solid_geometry'] = cascaded_union([geo['geom'] for geo in v['gcode_parsed']])
  6624. self.app.proc_container.new_text = ''
  6625. def mirror(self, axis, point):
  6626. """
  6627. Mirror the geometry of an object by an given axis around the coordinates of the 'point'
  6628. :param axis: Axis for Mirror
  6629. :param point: tuple of coordinates (x,y). Point of origin for Mirror
  6630. :return:
  6631. """
  6632. log.debug("camlib.CNCJob.mirror()")
  6633. px, py = point
  6634. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  6635. # variables to display the percentage of work done
  6636. self.geo_len = 0
  6637. try:
  6638. self.geo_len = len(self.gcode_parsed)
  6639. except TypeError:
  6640. self.geo_len = 1
  6641. self.old_disp_number = 0
  6642. self.el_count = 0
  6643. for g in self.gcode_parsed:
  6644. try:
  6645. g['geom'] = affinity.scale(g['geom'], xscale, yscale, origin=(px, py))
  6646. except AttributeError:
  6647. return g['geom']
  6648. self.el_count += 1
  6649. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  6650. if self.old_disp_number < disp_number <= 100:
  6651. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  6652. self.old_disp_number = disp_number
  6653. self.create_geometry()
  6654. self.app.proc_container.new_text = ''
  6655. def skew(self, angle_x, angle_y, point):
  6656. """
  6657. Shear/Skew the geometries of an object by angles along x and y dimensions.
  6658. :param angle_x:
  6659. :param angle_y:
  6660. angle_x, angle_y : float, float
  6661. The shear angle(s) for the x and y axes respectively. These can be
  6662. specified in either degrees (default) or radians by setting
  6663. use_radians=True.
  6664. :param point: tupple of coordinates (x,y)
  6665. See shapely manual for more information: http://toblerity.org/shapely/manual.html#affine-transformations
  6666. """
  6667. log.debug("camlib.CNCJob.skew()")
  6668. px, py = point
  6669. # variables to display the percentage of work done
  6670. self.geo_len = 0
  6671. try:
  6672. self.geo_len = len(self.gcode_parsed)
  6673. except TypeError:
  6674. self.geo_len = 1
  6675. self.old_disp_number = 0
  6676. self.el_count = 0
  6677. for g in self.gcode_parsed:
  6678. try:
  6679. g['geom'] = affinity.skew(g['geom'], angle_x, angle_y, origin=(px, py))
  6680. except AttributeError:
  6681. return g['geom']
  6682. self.el_count += 1
  6683. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  6684. if self.old_disp_number < disp_number <= 100:
  6685. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  6686. self.old_disp_number = disp_number
  6687. self.create_geometry()
  6688. self.app.proc_container.new_text = ''
  6689. def rotate(self, angle, point):
  6690. """
  6691. Rotate the geometry of an object by an given angle around the coordinates of the 'point'
  6692. :param angle: Angle of Rotation
  6693. :param point: tuple of coordinates (x,y). Origin point for Rotation
  6694. :return:
  6695. """
  6696. log.debug("camlib.CNCJob.rotate()")
  6697. px, py = point
  6698. # variables to display the percentage of work done
  6699. self.geo_len = 0
  6700. try:
  6701. self.geo_len = len(self.gcode_parsed)
  6702. except TypeError:
  6703. self.geo_len = 1
  6704. self.old_disp_number = 0
  6705. self.el_count = 0
  6706. for g in self.gcode_parsed:
  6707. try:
  6708. g['geom'] = affinity.rotate(g['geom'], angle, origin=(px, py))
  6709. except AttributeError:
  6710. return g['geom']
  6711. self.el_count += 1
  6712. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  6713. if self.old_disp_number < disp_number <= 100:
  6714. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  6715. self.old_disp_number = disp_number
  6716. self.create_geometry()
  6717. self.app.proc_container.new_text = ''
  6718. def get_bounds(geometry_list):
  6719. """
  6720. Will return limit values for a list of geometries
  6721. :param geometry_list: List of geometries for which to calculate the bounds limits
  6722. :return:
  6723. """
  6724. xmin = np.Inf
  6725. ymin = np.Inf
  6726. xmax = -np.Inf
  6727. ymax = -np.Inf
  6728. for gs in geometry_list:
  6729. try:
  6730. gxmin, gymin, gxmax, gymax = gs.bounds()
  6731. xmin = min([xmin, gxmin])
  6732. ymin = min([ymin, gymin])
  6733. xmax = max([xmax, gxmax])
  6734. ymax = max([ymax, gymax])
  6735. except Exception:
  6736. log.warning("DEVELOPMENT: Tried to get bounds of empty geometry.")
  6737. return [xmin, ymin, xmax, ymax]
  6738. def arc(center, radius, start, stop, direction, steps_per_circ):
  6739. """
  6740. Creates a list of point along the specified arc.
  6741. :param center: Coordinates of the center [x, y]
  6742. :type center: list
  6743. :param radius: Radius of the arc.
  6744. :type radius: float
  6745. :param start: Starting angle in radians
  6746. :type start: float
  6747. :param stop: End angle in radians
  6748. :type stop: float
  6749. :param direction: Orientation of the arc, "CW" or "CCW"
  6750. :type direction: string
  6751. :param steps_per_circ: Number of straight line segments to
  6752. represent a circle.
  6753. :type steps_per_circ: int
  6754. :return: The desired arc, as list of tuples
  6755. :rtype: list
  6756. """
  6757. # TODO: Resolution should be established by maximum error from the exact arc.
  6758. da_sign = {"cw": -1.0, "ccw": 1.0}
  6759. points = []
  6760. if direction == "ccw" and stop <= start:
  6761. stop += 2 * np.pi
  6762. if direction == "cw" and stop >= start:
  6763. stop -= 2 * np.pi
  6764. angle = abs(stop - start)
  6765. # angle = stop-start
  6766. steps = max([int(np.ceil(angle / (2 * np.pi) * steps_per_circ)), 2])
  6767. delta_angle = da_sign[direction] * angle * 1.0 / steps
  6768. for i in range(steps + 1):
  6769. theta = start + delta_angle * i
  6770. points.append((center[0] + radius * np.cos(theta), center[1] + radius * np.sin(theta)))
  6771. return points
  6772. def arc2(p1, p2, center, direction, steps_per_circ):
  6773. r = np.sqrt((center[0] - p1[0]) ** 2 + (center[1] - p1[1]) ** 2)
  6774. start = np.arctan2(p1[1] - center[1], p1[0] - center[0])
  6775. stop = np.arctan2(p2[1] - center[1], p2[0] - center[0])
  6776. return arc(center, r, start, stop, direction, steps_per_circ)
  6777. def arc_angle(start, stop, direction):
  6778. if direction == "ccw" and stop <= start:
  6779. stop += 2 * np.pi
  6780. if direction == "cw" and stop >= start:
  6781. stop -= 2 * np.pi
  6782. angle = abs(stop - start)
  6783. return angle
  6784. # def find_polygon(poly, point):
  6785. # """
  6786. # Find an object that object.contains(Point(point)) in
  6787. # poly, which can can be iterable, contain iterable of, or
  6788. # be itself an implementer of .contains().
  6789. #
  6790. # :param poly: See description
  6791. # :return: Polygon containing point or None.
  6792. # """
  6793. #
  6794. # if poly is None:
  6795. # return None
  6796. #
  6797. # try:
  6798. # for sub_poly in poly:
  6799. # p = find_polygon(sub_poly, point)
  6800. # if p is not None:
  6801. # return p
  6802. # except TypeError:
  6803. # try:
  6804. # if poly.contains(Point(point)):
  6805. # return poly
  6806. # except AttributeError:
  6807. # return None
  6808. #
  6809. # return None
  6810. def to_dict(obj):
  6811. """
  6812. Makes the following types into serializable form:
  6813. * ApertureMacro
  6814. * BaseGeometry
  6815. :param obj: Shapely geometry.
  6816. :type obj: BaseGeometry
  6817. :return: Dictionary with serializable form if ``obj`` was
  6818. BaseGeometry or ApertureMacro, otherwise returns ``obj``.
  6819. """
  6820. if isinstance(obj, ApertureMacro):
  6821. return {
  6822. "__class__": "ApertureMacro",
  6823. "__inst__": obj.to_dict()
  6824. }
  6825. if isinstance(obj, BaseGeometry):
  6826. return {
  6827. "__class__": "Shply",
  6828. "__inst__": sdumps(obj)
  6829. }
  6830. return obj
  6831. def dict2obj(d):
  6832. """
  6833. Default deserializer.
  6834. :param d: Serializable dictionary representation of an object
  6835. to be reconstructed.
  6836. :return: Reconstructed object.
  6837. """
  6838. if '__class__' in d and '__inst__' in d:
  6839. if d['__class__'] == "Shply":
  6840. return sloads(d['__inst__'])
  6841. if d['__class__'] == "ApertureMacro":
  6842. am = ApertureMacro()
  6843. am.from_dict(d['__inst__'])
  6844. return am
  6845. return d
  6846. else:
  6847. return d
  6848. # def plotg(geo, solid_poly=False, color="black"):
  6849. # try:
  6850. # __ = iter(geo)
  6851. # except:
  6852. # geo = [geo]
  6853. #
  6854. # for g in geo:
  6855. # if type(g) == Polygon:
  6856. # if solid_poly:
  6857. # patch = PolygonPatch(g,
  6858. # facecolor="#BBF268",
  6859. # edgecolor="#006E20",
  6860. # alpha=0.75,
  6861. # zorder=2)
  6862. # ax = subplot(111)
  6863. # ax.add_patch(patch)
  6864. # else:
  6865. # x, y = g.exterior.coords.xy
  6866. # plot(x, y, color=color)
  6867. # for ints in g.interiors:
  6868. # x, y = ints.coords.xy
  6869. # plot(x, y, color=color)
  6870. # continue
  6871. #
  6872. # if type(g) == LineString or type(g) == LinearRing:
  6873. # x, y = g.coords.xy
  6874. # plot(x, y, color=color)
  6875. # continue
  6876. #
  6877. # if type(g) == Point:
  6878. # x, y = g.coords.xy
  6879. # plot(x, y, 'o')
  6880. # continue
  6881. #
  6882. # try:
  6883. # __ = iter(g)
  6884. # plotg(g, color=color)
  6885. # except:
  6886. # log.error("Cannot plot: " + str(type(g)))
  6887. # continue
  6888. # def alpha_shape(points, alpha):
  6889. # """
  6890. # Compute the alpha shape (concave hull) of a set of points.
  6891. #
  6892. # @param points: Iterable container of points.
  6893. # @param alpha: alpha value to influence the gooeyness of the border. Smaller
  6894. # numbers don't fall inward as much as larger numbers. Too large,
  6895. # and you lose everything!
  6896. # """
  6897. # if len(points) < 4:
  6898. # # When you have a triangle, there is no sense in computing an alpha
  6899. # # shape.
  6900. # return MultiPoint(list(points)).convex_hull
  6901. #
  6902. # def add_edge(edges, edge_points, coords, i, j):
  6903. # """Add a line between the i-th and j-th points, if not in the list already"""
  6904. # if (i, j) in edges or (j, i) in edges:
  6905. # # already added
  6906. # return
  6907. # edges.add( (i, j) )
  6908. # edge_points.append(coords[ [i, j] ])
  6909. #
  6910. # coords = np.array([point.coords[0] for point in points])
  6911. #
  6912. # tri = Delaunay(coords)
  6913. # edges = set()
  6914. # edge_points = []
  6915. # # loop over triangles:
  6916. # # ia, ib, ic = indices of corner points of the triangle
  6917. # for ia, ib, ic in tri.vertices:
  6918. # pa = coords[ia]
  6919. # pb = coords[ib]
  6920. # pc = coords[ic]
  6921. #
  6922. # # Lengths of sides of triangle
  6923. # a = math.sqrt((pa[0]-pb[0])**2 + (pa[1]-pb[1])**2)
  6924. # b = math.sqrt((pb[0]-pc[0])**2 + (pb[1]-pc[1])**2)
  6925. # c = math.sqrt((pc[0]-pa[0])**2 + (pc[1]-pa[1])**2)
  6926. #
  6927. # # Semiperimeter of triangle
  6928. # s = (a + b + c)/2.0
  6929. #
  6930. # # Area of triangle by Heron's formula
  6931. # area = math.sqrt(s*(s-a)*(s-b)*(s-c))
  6932. # circum_r = a*b*c/(4.0*area)
  6933. #
  6934. # # Here's the radius filter.
  6935. # #print circum_r
  6936. # if circum_r < 1.0/alpha:
  6937. # add_edge(edges, edge_points, coords, ia, ib)
  6938. # add_edge(edges, edge_points, coords, ib, ic)
  6939. # add_edge(edges, edge_points, coords, ic, ia)
  6940. #
  6941. # m = MultiLineString(edge_points)
  6942. # triangles = list(polygonize(m))
  6943. # return cascaded_union(triangles), edge_points
  6944. # def voronoi(P):
  6945. # """
  6946. # Returns a list of all edges of the voronoi diagram for the given input points.
  6947. # """
  6948. # delauny = Delaunay(P)
  6949. # triangles = delauny.points[delauny.vertices]
  6950. #
  6951. # circum_centers = np.array([triangle_csc(tri) for tri in triangles])
  6952. # long_lines_endpoints = []
  6953. #
  6954. # lineIndices = []
  6955. # for i, triangle in enumerate(triangles):
  6956. # circum_center = circum_centers[i]
  6957. # for j, neighbor in enumerate(delauny.neighbors[i]):
  6958. # if neighbor != -1:
  6959. # lineIndices.append((i, neighbor))
  6960. # else:
  6961. # ps = triangle[(j+1)%3] - triangle[(j-1)%3]
  6962. # ps = np.array((ps[1], -ps[0]))
  6963. #
  6964. # middle = (triangle[(j+1)%3] + triangle[(j-1)%3]) * 0.5
  6965. # di = middle - triangle[j]
  6966. #
  6967. # ps /= np.linalg.norm(ps)
  6968. # di /= np.linalg.norm(di)
  6969. #
  6970. # if np.dot(di, ps) < 0.0:
  6971. # ps *= -1000.0
  6972. # else:
  6973. # ps *= 1000.0
  6974. #
  6975. # long_lines_endpoints.append(circum_center + ps)
  6976. # lineIndices.append((i, len(circum_centers) + len(long_lines_endpoints)-1))
  6977. #
  6978. # vertices = np.vstack((circum_centers, long_lines_endpoints))
  6979. #
  6980. # # filter out any duplicate lines
  6981. # lineIndicesSorted = np.sort(lineIndices) # make (1,2) and (2,1) both (1,2)
  6982. # lineIndicesTupled = [tuple(row) for row in lineIndicesSorted]
  6983. # lineIndicesUnique = np.unique(lineIndicesTupled)
  6984. #
  6985. # return vertices, lineIndicesUnique
  6986. #
  6987. #
  6988. # def triangle_csc(pts):
  6989. # rows, cols = pts.shape
  6990. #
  6991. # A = np.bmat([[2 * np.dot(pts, pts.T), np.ones((rows, 1))],
  6992. # [np.ones((1, rows)), np.zeros((1, 1))]])
  6993. #
  6994. # b = np.hstack((np.sum(pts * pts, axis=1), np.ones((1))))
  6995. # x = np.linalg.solve(A,b)
  6996. # bary_coords = x[:-1]
  6997. # return np.sum(pts * np.tile(bary_coords.reshape((pts.shape[0], 1)), (1, pts.shape[1])), axis=0)
  6998. #
  6999. #
  7000. # def voronoi_cell_lines(points, vertices, lineIndices):
  7001. # """
  7002. # Returns a mapping from a voronoi cell to its edges.
  7003. #
  7004. # :param points: shape (m,2)
  7005. # :param vertices: shape (n,2)
  7006. # :param lineIndices: shape (o,2)
  7007. # :rtype: dict point index -> list of shape (n,2) with vertex indices
  7008. # """
  7009. # kd = KDTree(points)
  7010. #
  7011. # cells = collections.defaultdict(list)
  7012. # for i1, i2 in lineIndices:
  7013. # v1, v2 = vertices[i1], vertices[i2]
  7014. # mid = (v1+v2)/2
  7015. # _, (p1Idx, p2Idx) = kd.query(mid, 2)
  7016. # cells[p1Idx].append((i1, i2))
  7017. # cells[p2Idx].append((i1, i2))
  7018. #
  7019. # return cells
  7020. #
  7021. #
  7022. # def voronoi_edges2polygons(cells):
  7023. # """
  7024. # Transforms cell edges into polygons.
  7025. #
  7026. # :param cells: as returned from voronoi_cell_lines
  7027. # :rtype: dict point index -> list of vertex indices which form a polygon
  7028. # """
  7029. #
  7030. # # first, close the outer cells
  7031. # for pIdx, lineIndices_ in cells.items():
  7032. # dangling_lines = []
  7033. # for i1, i2 in lineIndices_:
  7034. # p = (i1, i2)
  7035. # connections = filter(lambda k: p != k and
  7036. # (p[0] == k[0] or p[0] == k[1] or p[1] == k[0] or p[1] == k[1]), lineIndices_)
  7037. # # connections = filter(lambda (i1_, i2_): (i1, i2) != (i1_, i2_) and
  7038. # (i1 == i1_ or i1 == i2_ or i2 == i1_ or i2 == i2_), lineIndices_)
  7039. # assert 1 <= len(connections) <= 2
  7040. # if len(connections) == 1:
  7041. # dangling_lines.append((i1, i2))
  7042. # assert len(dangling_lines) in [0, 2]
  7043. # if len(dangling_lines) == 2:
  7044. # (i11, i12), (i21, i22) = dangling_lines
  7045. # s = (i11, i12)
  7046. # t = (i21, i22)
  7047. #
  7048. # # determine which line ends are unconnected
  7049. # connected = filter(lambda k: k != s and (k[0] == s[0] or k[1] == s[0]), lineIndices_)
  7050. # # connected = filter(lambda (i1,i2): (i1,i2) != (i11,i12) and (i1 == i11 or i2 == i11), lineIndices_)
  7051. # i11Unconnected = len(connected) == 0
  7052. #
  7053. # connected = filter(lambda k: k != t and (k[0] == t[0] or k[1] == t[0]), lineIndices_)
  7054. # # connected = filter(lambda (i1,i2): (i1,i2) != (i21,i22) and (i1 == i21 or i2 == i21), lineIndices_)
  7055. # i21Unconnected = len(connected) == 0
  7056. #
  7057. # startIdx = i11 if i11Unconnected else i12
  7058. # endIdx = i21 if i21Unconnected else i22
  7059. #
  7060. # cells[pIdx].append((startIdx, endIdx))
  7061. #
  7062. # # then, form polygons by storing vertex indices in (counter-)clockwise order
  7063. # polys = {}
  7064. # for pIdx, lineIndices_ in cells.items():
  7065. # # get a directed graph which contains both directions and arbitrarily follow one of both
  7066. # directedGraph = lineIndices_ + [(i2, i1) for (i1, i2) in lineIndices_]
  7067. # directedGraphMap = collections.defaultdict(list)
  7068. # for (i1, i2) in directedGraph:
  7069. # directedGraphMap[i1].append(i2)
  7070. # orderedEdges = []
  7071. # currentEdge = directedGraph[0]
  7072. # while len(orderedEdges) < len(lineIndices_):
  7073. # i1 = currentEdge[1]
  7074. # i2 = directedGraphMap[i1][0] if directedGraphMap[i1][0] != currentEdge[0] else directedGraphMap[i1][1]
  7075. # nextEdge = (i1, i2)
  7076. # orderedEdges.append(nextEdge)
  7077. # currentEdge = nextEdge
  7078. #
  7079. # polys[pIdx] = [i1 for (i1, i2) in orderedEdges]
  7080. #
  7081. # return polys
  7082. #
  7083. #
  7084. # def voronoi_polygons(points):
  7085. # """
  7086. # Returns the voronoi polygon for each input point.
  7087. #
  7088. # :param points: shape (n,2)
  7089. # :rtype: list of n polygons where each polygon is an array of vertices
  7090. # """
  7091. # vertices, lineIndices = voronoi(points)
  7092. # cells = voronoi_cell_lines(points, vertices, lineIndices)
  7093. # polys = voronoi_edges2polygons(cells)
  7094. # polylist = []
  7095. # for i in range(len(points)):
  7096. # poly = vertices[np.asarray(polys[i])]
  7097. # polylist.append(poly)
  7098. # return polylist
  7099. #
  7100. #
  7101. # class Zprofile:
  7102. # def __init__(self):
  7103. #
  7104. # # data contains lists of [x, y, z]
  7105. # self.data = []
  7106. #
  7107. # # Computed voronoi polygons (shapely)
  7108. # self.polygons = []
  7109. # pass
  7110. #
  7111. # # def plot_polygons(self):
  7112. # # axes = plt.subplot(1, 1, 1)
  7113. # #
  7114. # # plt.axis([-0.05, 1.05, -0.05, 1.05])
  7115. # #
  7116. # # for poly in self.polygons:
  7117. # # p = PolygonPatch(poly, facecolor=np.random.rand(3, 1), alpha=0.3)
  7118. # # axes.add_patch(p)
  7119. #
  7120. # def init_from_csv(self, filename):
  7121. # pass
  7122. #
  7123. # def init_from_string(self, zpstring):
  7124. # pass
  7125. #
  7126. # def init_from_list(self, zplist):
  7127. # self.data = zplist
  7128. #
  7129. # def generate_polygons(self):
  7130. # self.polygons = [Polygon(p) for p in voronoi_polygons(array([[x[0], x[1]] for x in self.data]))]
  7131. #
  7132. # def normalize(self, origin):
  7133. # pass
  7134. #
  7135. # def paste(self, path):
  7136. # """
  7137. # Return a list of dictionaries containing the parts of the original
  7138. # path and their z-axis offset.
  7139. # """
  7140. #
  7141. # # At most one region/polygon will contain the path
  7142. # containing = [i for i in range(len(self.polygons)) if self.polygons[i].contains(path)]
  7143. #
  7144. # if len(containing) > 0:
  7145. # return [{"path": path, "z": self.data[containing[0]][2]}]
  7146. #
  7147. # # All region indexes that intersect with the path
  7148. # crossing = [i for i in range(len(self.polygons)) if self.polygons[i].intersects(path)]
  7149. #
  7150. # return [{"path": path.intersection(self.polygons[i]),
  7151. # "z": self.data[i][2]} for i in crossing]
  7152. def autolist(obj):
  7153. try:
  7154. __ = iter(obj)
  7155. return obj
  7156. except TypeError:
  7157. return [obj]
  7158. def three_point_circle(p1, p2, p3):
  7159. """
  7160. Computes the center and radius of a circle from
  7161. 3 points on its circumference.
  7162. :param p1: Point 1
  7163. :param p2: Point 2
  7164. :param p3: Point 3
  7165. :return: center, radius
  7166. """
  7167. # Midpoints
  7168. a1 = (p1 + p2) / 2.0
  7169. a2 = (p2 + p3) / 2.0
  7170. # Normals
  7171. b1 = np.dot((p2 - p1), np.array([[0, -1], [1, 0]], dtype=np.float32))
  7172. b2 = np.dot((p3 - p2), np.array([[0, 1], [-1, 0]], dtype=np.float32))
  7173. # Params
  7174. try:
  7175. T = solve(np.transpose(np.array([-b1, b2])), a1 - a2)
  7176. except Exception as e:
  7177. log.debug("camlib.three_point_circle() --> %s" % str(e))
  7178. return
  7179. # Center
  7180. center = a1 + b1 * T[0]
  7181. # Radius
  7182. radius = np.linalg.norm(center - p1)
  7183. return center, radius, T[0]
  7184. def distance(pt1, pt2):
  7185. return np.sqrt((pt1[0] - pt2[0]) ** 2 + (pt1[1] - pt2[1]) ** 2)
  7186. def distance_euclidian(x1, y1, x2, y2):
  7187. return np.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
  7188. class FlatCAMRTree(object):
  7189. """
  7190. Indexes geometry (Any object with "cooords" property containing
  7191. a list of tuples with x, y values). Objects are indexed by
  7192. all their points by default. To index by arbitrary points,
  7193. override self.points2obj.
  7194. """
  7195. def __init__(self):
  7196. # Python RTree Index
  7197. self.rti = rtindex.Index()
  7198. # ## Track object-point relationship
  7199. # Each is list of points in object.
  7200. self.obj2points = []
  7201. # Index is index in rtree, value is index of
  7202. # object in obj2points.
  7203. self.points2obj = []
  7204. self.get_points = lambda go: go.coords
  7205. def grow_obj2points(self, idx):
  7206. """
  7207. Increases the size of self.obj2points to fit
  7208. idx + 1 items.
  7209. :param idx: Index to fit into list.
  7210. :return: None
  7211. """
  7212. if len(self.obj2points) > idx:
  7213. # len == 2, idx == 1, ok.
  7214. return
  7215. else:
  7216. # len == 2, idx == 2, need 1 more.
  7217. # range(2, 3)
  7218. for i in range(len(self.obj2points), idx + 1):
  7219. self.obj2points.append([])
  7220. def insert(self, objid, obj):
  7221. self.grow_obj2points(objid)
  7222. self.obj2points[objid] = []
  7223. for pt in self.get_points(obj):
  7224. self.rti.insert(len(self.points2obj), (pt[0], pt[1], pt[0], pt[1]), obj=objid)
  7225. self.obj2points[objid].append(len(self.points2obj))
  7226. self.points2obj.append(objid)
  7227. def remove_obj(self, objid, obj):
  7228. # Use all ptids to delete from index
  7229. for i, pt in enumerate(self.get_points(obj)):
  7230. try:
  7231. self.rti.delete(self.obj2points[objid][i], (pt[0], pt[1], pt[0], pt[1]))
  7232. except IndexError:
  7233. pass
  7234. def nearest(self, pt):
  7235. """
  7236. Will raise StopIteration if no items are found.
  7237. :param pt:
  7238. :return:
  7239. """
  7240. return next(self.rti.nearest(pt, objects=True))
  7241. class FlatCAMRTreeStorage(FlatCAMRTree):
  7242. """
  7243. Just like FlatCAMRTree it indexes geometry, but also serves
  7244. as storage for the geometry.
  7245. """
  7246. def __init__(self):
  7247. # super(FlatCAMRTreeStorage, self).__init__()
  7248. super().__init__()
  7249. self.objects = []
  7250. # Optimization attempt!
  7251. self.indexes = {}
  7252. def insert(self, obj):
  7253. self.objects.append(obj)
  7254. idx = len(self.objects) - 1
  7255. # Note: Shapely objects are not hashable any more, although
  7256. # there seem to be plans to re-introduce the feature in
  7257. # version 2.0. For now, we will index using the object's id,
  7258. # but it's important to remember that shapely geometry is
  7259. # mutable, ie. it can be modified to a totally different shape
  7260. # and continue to have the same id.
  7261. # self.indexes[obj] = idx
  7262. self.indexes[id(obj)] = idx
  7263. # super(FlatCAMRTreeStorage, self).insert(idx, obj)
  7264. super().insert(idx, obj)
  7265. # @profile
  7266. def remove(self, obj):
  7267. # See note about self.indexes in insert().
  7268. # objidx = self.indexes[obj]
  7269. objidx = self.indexes[id(obj)]
  7270. # Remove from list
  7271. self.objects[objidx] = None
  7272. # Remove from index
  7273. self.remove_obj(objidx, obj)
  7274. def get_objects(self):
  7275. return (o for o in self.objects if o is not None)
  7276. def nearest(self, pt):
  7277. """
  7278. Returns the nearest matching points and the object
  7279. it belongs to.
  7280. :param pt: Query point.
  7281. :return: (match_x, match_y), Object owner of
  7282. matching point.
  7283. :rtype: tuple
  7284. """
  7285. tidx = super(FlatCAMRTreeStorage, self).nearest(pt)
  7286. return (tidx.bbox[0], tidx.bbox[1]), self.objects[tidx.object]
  7287. # class myO:
  7288. # def __init__(self, coords):
  7289. # self.coords = coords
  7290. #
  7291. #
  7292. # def test_rti():
  7293. #
  7294. # o1 = myO([(0, 0), (0, 1), (1, 1)])
  7295. # o2 = myO([(2, 0), (2, 1), (2, 1)])
  7296. # o3 = myO([(2, 0), (2, 1), (3, 1)])
  7297. #
  7298. # os = [o1, o2]
  7299. #
  7300. # idx = FlatCAMRTree()
  7301. #
  7302. # for o in range(len(os)):
  7303. # idx.insert(o, os[o])
  7304. #
  7305. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  7306. #
  7307. # idx.remove_obj(0, o1)
  7308. #
  7309. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  7310. #
  7311. # idx.remove_obj(1, o2)
  7312. #
  7313. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  7314. #
  7315. #
  7316. # def test_rtis():
  7317. #
  7318. # o1 = myO([(0, 0), (0, 1), (1, 1)])
  7319. # o2 = myO([(2, 0), (2, 1), (2, 1)])
  7320. # o3 = myO([(2, 0), (2, 1), (3, 1)])
  7321. #
  7322. # os = [o1, o2]
  7323. #
  7324. # idx = FlatCAMRTreeStorage()
  7325. #
  7326. # for o in range(len(os)):
  7327. # idx.insert(os[o])
  7328. #
  7329. # #os = None
  7330. # #o1 = None
  7331. # #o2 = None
  7332. #
  7333. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  7334. #
  7335. # idx.remove(idx.nearest((2,0))[1])
  7336. #
  7337. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  7338. #
  7339. # idx.remove(idx.nearest((0,0))[1])
  7340. #
  7341. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]