| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013 |
- /**
- * Name: Metaverse
- * Date: 2022/4/11
- * Author: https://www.4dkankan.com
- * Copyright © 2022 4DAGE Co., Ltd. All rights reserved.
- * Licensed under the GLP license
- */
- (function (factory) {
- typeof define === 'function' && define.amd ? define(factory) :
- factory();
- })((function () { 'use strict';
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
- try {
- var info = gen[key](arg);
- var value = info.value;
- } catch (error) {
- reject(error);
- return;
- }
- if (info.done) {
- resolve(value);
- } else {
- Promise.resolve(value).then(_next, _throw);
- }
- }
- function _asyncToGenerator(fn) {
- return function () {
- var self = this,
- args = arguments;
- return new Promise(function (resolve, reject) {
- var gen = fn.apply(self, args);
- function _next(value) {
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
- }
- function _throw(err) {
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
- }
- _next(undefined);
- });
- };
- }
- function createCommonjsModule(fn) {
- var module = { exports: {} };
- return fn(module, module.exports), module.exports;
- }
- /**
- * Copyright (c) 2014-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- */
- var runtime_1 = createCommonjsModule(function (module) {
- var runtime = (function (exports) {
- var Op = Object.prototype;
- var hasOwn = Op.hasOwnProperty;
- var undefined$1; // More compressible than void 0.
- var $Symbol = typeof Symbol === "function" ? Symbol : {};
- var iteratorSymbol = $Symbol.iterator || "@@iterator";
- var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
- var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
- function define(obj, key, value) {
- Object.defineProperty(obj, key, {
- value: value,
- enumerable: true,
- configurable: true,
- writable: true
- });
- return obj[key];
- }
- try {
- // IE 8 has a broken Object.defineProperty that only works on DOM objects.
- define({}, "");
- } catch (err) {
- define = function(obj, key, value) {
- return obj[key] = value;
- };
- }
- function wrap(innerFn, outerFn, self, tryLocsList) {
- // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
- var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
- var generator = Object.create(protoGenerator.prototype);
- var context = new Context(tryLocsList || []);
- // The ._invoke method unifies the implementations of the .next,
- // .throw, and .return methods.
- generator._invoke = makeInvokeMethod(innerFn, self, context);
- return generator;
- }
- exports.wrap = wrap;
- // Try/catch helper to minimize deoptimizations. Returns a completion
- // record like context.tryEntries[i].completion. This interface could
- // have been (and was previously) designed to take a closure to be
- // invoked without arguments, but in all the cases we care about we
- // already have an existing method we want to call, so there's no need
- // to create a new function object. We can even get away with assuming
- // the method takes exactly one argument, since that happens to be true
- // in every case, so we don't have to touch the arguments object. The
- // only additional allocation required is the completion record, which
- // has a stable shape and so hopefully should be cheap to allocate.
- function tryCatch(fn, obj, arg) {
- try {
- return { type: "normal", arg: fn.call(obj, arg) };
- } catch (err) {
- return { type: "throw", arg: err };
- }
- }
- var GenStateSuspendedStart = "suspendedStart";
- var GenStateSuspendedYield = "suspendedYield";
- var GenStateExecuting = "executing";
- var GenStateCompleted = "completed";
- // Returning this object from the innerFn has the same effect as
- // breaking out of the dispatch switch statement.
- var ContinueSentinel = {};
- // Dummy constructor functions that we use as the .constructor and
- // .constructor.prototype properties for functions that return Generator
- // objects. For full spec compliance, you may wish to configure your
- // minifier not to mangle the names of these two functions.
- function Generator() {}
- function GeneratorFunction() {}
- function GeneratorFunctionPrototype() {}
- // This is a polyfill for %IteratorPrototype% for environments that
- // don't natively support it.
- var IteratorPrototype = {};
- define(IteratorPrototype, iteratorSymbol, function () {
- return this;
- });
- var getProto = Object.getPrototypeOf;
- var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
- if (NativeIteratorPrototype &&
- NativeIteratorPrototype !== Op &&
- hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
- // This environment has a native %IteratorPrototype%; use it instead
- // of the polyfill.
- IteratorPrototype = NativeIteratorPrototype;
- }
- var Gp = GeneratorFunctionPrototype.prototype =
- Generator.prototype = Object.create(IteratorPrototype);
- GeneratorFunction.prototype = GeneratorFunctionPrototype;
- define(Gp, "constructor", GeneratorFunctionPrototype);
- define(GeneratorFunctionPrototype, "constructor", GeneratorFunction);
- GeneratorFunction.displayName = define(
- GeneratorFunctionPrototype,
- toStringTagSymbol,
- "GeneratorFunction"
- );
- // Helper for defining the .next, .throw, and .return methods of the
- // Iterator interface in terms of a single ._invoke method.
- function defineIteratorMethods(prototype) {
- ["next", "throw", "return"].forEach(function(method) {
- define(prototype, method, function(arg) {
- return this._invoke(method, arg);
- });
- });
- }
- exports.isGeneratorFunction = function(genFun) {
- var ctor = typeof genFun === "function" && genFun.constructor;
- return ctor
- ? ctor === GeneratorFunction ||
- // For the native GeneratorFunction constructor, the best we can
- // do is to check its .name property.
- (ctor.displayName || ctor.name) === "GeneratorFunction"
- : false;
- };
- exports.mark = function(genFun) {
- if (Object.setPrototypeOf) {
- Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
- } else {
- genFun.__proto__ = GeneratorFunctionPrototype;
- define(genFun, toStringTagSymbol, "GeneratorFunction");
- }
- genFun.prototype = Object.create(Gp);
- return genFun;
- };
- // Within the body of any async function, `await x` is transformed to
- // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
- // `hasOwn.call(value, "__await")` to determine if the yielded value is
- // meant to be awaited.
- exports.awrap = function(arg) {
- return { __await: arg };
- };
- function AsyncIterator(generator, PromiseImpl) {
- function invoke(method, arg, resolve, reject) {
- var record = tryCatch(generator[method], generator, arg);
- if (record.type === "throw") {
- reject(record.arg);
- } else {
- var result = record.arg;
- var value = result.value;
- if (value &&
- typeof value === "object" &&
- hasOwn.call(value, "__await")) {
- return PromiseImpl.resolve(value.__await).then(function(value) {
- invoke("next", value, resolve, reject);
- }, function(err) {
- invoke("throw", err, resolve, reject);
- });
- }
- return PromiseImpl.resolve(value).then(function(unwrapped) {
- // When a yielded Promise is resolved, its final value becomes
- // the .value of the Promise<{value,done}> result for the
- // current iteration.
- result.value = unwrapped;
- resolve(result);
- }, function(error) {
- // If a rejected Promise was yielded, throw the rejection back
- // into the async generator function so it can be handled there.
- return invoke("throw", error, resolve, reject);
- });
- }
- }
- var previousPromise;
- function enqueue(method, arg) {
- function callInvokeWithMethodAndArg() {
- return new PromiseImpl(function(resolve, reject) {
- invoke(method, arg, resolve, reject);
- });
- }
- return previousPromise =
- // If enqueue has been called before, then we want to wait until
- // all previous Promises have been resolved before calling invoke,
- // so that results are always delivered in the correct order. If
- // enqueue has not been called before, then it is important to
- // call invoke immediately, without waiting on a callback to fire,
- // so that the async generator function has the opportunity to do
- // any necessary setup in a predictable way. This predictability
- // is why the Promise constructor synchronously invokes its
- // executor callback, and why async functions synchronously
- // execute code before the first await. Since we implement simple
- // async functions in terms of async generators, it is especially
- // important to get this right, even though it requires care.
- previousPromise ? previousPromise.then(
- callInvokeWithMethodAndArg,
- // Avoid propagating failures to Promises returned by later
- // invocations of the iterator.
- callInvokeWithMethodAndArg
- ) : callInvokeWithMethodAndArg();
- }
- // Define the unified helper method that is used to implement .next,
- // .throw, and .return (see defineIteratorMethods).
- this._invoke = enqueue;
- }
- defineIteratorMethods(AsyncIterator.prototype);
- define(AsyncIterator.prototype, asyncIteratorSymbol, function () {
- return this;
- });
- exports.AsyncIterator = AsyncIterator;
- // Note that simple async functions are implemented on top of
- // AsyncIterator objects; they just return a Promise for the value of
- // the final result produced by the iterator.
- exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) {
- if (PromiseImpl === void 0) PromiseImpl = Promise;
- var iter = new AsyncIterator(
- wrap(innerFn, outerFn, self, tryLocsList),
- PromiseImpl
- );
- return exports.isGeneratorFunction(outerFn)
- ? iter // If outerFn is a generator, return the full iterator.
- : iter.next().then(function(result) {
- return result.done ? result.value : iter.next();
- });
- };
- function makeInvokeMethod(innerFn, self, context) {
- var state = GenStateSuspendedStart;
- return function invoke(method, arg) {
- if (state === GenStateExecuting) {
- throw new Error("Generator is already running");
- }
- if (state === GenStateCompleted) {
- if (method === "throw") {
- throw arg;
- }
- // Be forgiving, per 25.3.3.3.3 of the spec:
- // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
- return doneResult();
- }
- context.method = method;
- context.arg = arg;
- while (true) {
- var delegate = context.delegate;
- if (delegate) {
- var delegateResult = maybeInvokeDelegate(delegate, context);
- if (delegateResult) {
- if (delegateResult === ContinueSentinel) continue;
- return delegateResult;
- }
- }
- if (context.method === "next") {
- // Setting context._sent for legacy support of Babel's
- // function.sent implementation.
- context.sent = context._sent = context.arg;
- } else if (context.method === "throw") {
- if (state === GenStateSuspendedStart) {
- state = GenStateCompleted;
- throw context.arg;
- }
- context.dispatchException(context.arg);
- } else if (context.method === "return") {
- context.abrupt("return", context.arg);
- }
- state = GenStateExecuting;
- var record = tryCatch(innerFn, self, context);
- if (record.type === "normal") {
- // If an exception is thrown from innerFn, we leave state ===
- // GenStateExecuting and loop back for another invocation.
- state = context.done
- ? GenStateCompleted
- : GenStateSuspendedYield;
- if (record.arg === ContinueSentinel) {
- continue;
- }
- return {
- value: record.arg,
- done: context.done
- };
- } else if (record.type === "throw") {
- state = GenStateCompleted;
- // Dispatch the exception by looping back around to the
- // context.dispatchException(context.arg) call above.
- context.method = "throw";
- context.arg = record.arg;
- }
- }
- };
- }
- // Call delegate.iterator[context.method](context.arg) and handle the
- // result, either by returning a { value, done } result from the
- // delegate iterator, or by modifying context.method and context.arg,
- // setting context.delegate to null, and returning the ContinueSentinel.
- function maybeInvokeDelegate(delegate, context) {
- var method = delegate.iterator[context.method];
- if (method === undefined$1) {
- // A .throw or .return when the delegate iterator has no .throw
- // method always terminates the yield* loop.
- context.delegate = null;
- if (context.method === "throw") {
- // Note: ["return"] must be used for ES3 parsing compatibility.
- if (delegate.iterator["return"]) {
- // If the delegate iterator has a return method, give it a
- // chance to clean up.
- context.method = "return";
- context.arg = undefined$1;
- maybeInvokeDelegate(delegate, context);
- if (context.method === "throw") {
- // If maybeInvokeDelegate(context) changed context.method from
- // "return" to "throw", let that override the TypeError below.
- return ContinueSentinel;
- }
- }
- context.method = "throw";
- context.arg = new TypeError(
- "The iterator does not provide a 'throw' method");
- }
- return ContinueSentinel;
- }
- var record = tryCatch(method, delegate.iterator, context.arg);
- if (record.type === "throw") {
- context.method = "throw";
- context.arg = record.arg;
- context.delegate = null;
- return ContinueSentinel;
- }
- var info = record.arg;
- if (! info) {
- context.method = "throw";
- context.arg = new TypeError("iterator result is not an object");
- context.delegate = null;
- return ContinueSentinel;
- }
- if (info.done) {
- // Assign the result of the finished delegate to the temporary
- // variable specified by delegate.resultName (see delegateYield).
- context[delegate.resultName] = info.value;
- // Resume execution at the desired location (see delegateYield).
- context.next = delegate.nextLoc;
- // If context.method was "throw" but the delegate handled the
- // exception, let the outer generator proceed normally. If
- // context.method was "next", forget context.arg since it has been
- // "consumed" by the delegate iterator. If context.method was
- // "return", allow the original .return call to continue in the
- // outer generator.
- if (context.method !== "return") {
- context.method = "next";
- context.arg = undefined$1;
- }
- } else {
- // Re-yield the result returned by the delegate method.
- return info;
- }
- // The delegate iterator is finished, so forget it and continue with
- // the outer generator.
- context.delegate = null;
- return ContinueSentinel;
- }
- // Define Generator.prototype.{next,throw,return} in terms of the
- // unified ._invoke helper method.
- defineIteratorMethods(Gp);
- define(Gp, toStringTagSymbol, "Generator");
- // A Generator should always return itself as the iterator object when the
- // @@iterator function is called on it. Some browsers' implementations of the
- // iterator prototype chain incorrectly implement this, causing the Generator
- // object to not be returned from this call. This ensures that doesn't happen.
- // See https://github.com/facebook/regenerator/issues/274 for more details.
- define(Gp, iteratorSymbol, function() {
- return this;
- });
- define(Gp, "toString", function() {
- return "[object Generator]";
- });
- function pushTryEntry(locs) {
- var entry = { tryLoc: locs[0] };
- if (1 in locs) {
- entry.catchLoc = locs[1];
- }
- if (2 in locs) {
- entry.finallyLoc = locs[2];
- entry.afterLoc = locs[3];
- }
- this.tryEntries.push(entry);
- }
- function resetTryEntry(entry) {
- var record = entry.completion || {};
- record.type = "normal";
- delete record.arg;
- entry.completion = record;
- }
- function Context(tryLocsList) {
- // The root entry object (effectively a try statement without a catch
- // or a finally block) gives us a place to store values thrown from
- // locations where there is no enclosing try statement.
- this.tryEntries = [{ tryLoc: "root" }];
- tryLocsList.forEach(pushTryEntry, this);
- this.reset(true);
- }
- exports.keys = function(object) {
- var keys = [];
- for (var key in object) {
- keys.push(key);
- }
- keys.reverse();
- // Rather than returning an object with a next method, we keep
- // things simple and return the next function itself.
- return function next() {
- while (keys.length) {
- var key = keys.pop();
- if (key in object) {
- next.value = key;
- next.done = false;
- return next;
- }
- }
- // To avoid creating an additional object, we just hang the .value
- // and .done properties off the next function object itself. This
- // also ensures that the minifier will not anonymize the function.
- next.done = true;
- return next;
- };
- };
- function values(iterable) {
- if (iterable) {
- var iteratorMethod = iterable[iteratorSymbol];
- if (iteratorMethod) {
- return iteratorMethod.call(iterable);
- }
- if (typeof iterable.next === "function") {
- return iterable;
- }
- if (!isNaN(iterable.length)) {
- var i = -1, next = function next() {
- while (++i < iterable.length) {
- if (hasOwn.call(iterable, i)) {
- next.value = iterable[i];
- next.done = false;
- return next;
- }
- }
- next.value = undefined$1;
- next.done = true;
- return next;
- };
- return next.next = next;
- }
- }
- // Return an iterator with no values.
- return { next: doneResult };
- }
- exports.values = values;
- function doneResult() {
- return { value: undefined$1, done: true };
- }
- Context.prototype = {
- constructor: Context,
- reset: function(skipTempReset) {
- this.prev = 0;
- this.next = 0;
- // Resetting context._sent for legacy support of Babel's
- // function.sent implementation.
- this.sent = this._sent = undefined$1;
- this.done = false;
- this.delegate = null;
- this.method = "next";
- this.arg = undefined$1;
- this.tryEntries.forEach(resetTryEntry);
- if (!skipTempReset) {
- for (var name in this) {
- // Not sure about the optimal order of these conditions:
- if (name.charAt(0) === "t" &&
- hasOwn.call(this, name) &&
- !isNaN(+name.slice(1))) {
- this[name] = undefined$1;
- }
- }
- }
- },
- stop: function() {
- this.done = true;
- var rootEntry = this.tryEntries[0];
- var rootRecord = rootEntry.completion;
- if (rootRecord.type === "throw") {
- throw rootRecord.arg;
- }
- return this.rval;
- },
- dispatchException: function(exception) {
- if (this.done) {
- throw exception;
- }
- var context = this;
- function handle(loc, caught) {
- record.type = "throw";
- record.arg = exception;
- context.next = loc;
- if (caught) {
- // If the dispatched exception was caught by a catch block,
- // then let that catch block handle the exception normally.
- context.method = "next";
- context.arg = undefined$1;
- }
- return !! caught;
- }
- for (var i = this.tryEntries.length - 1; i >= 0; --i) {
- var entry = this.tryEntries[i];
- var record = entry.completion;
- if (entry.tryLoc === "root") {
- // Exception thrown outside of any try block that could handle
- // it, so set the completion value of the entire function to
- // throw the exception.
- return handle("end");
- }
- if (entry.tryLoc <= this.prev) {
- var hasCatch = hasOwn.call(entry, "catchLoc");
- var hasFinally = hasOwn.call(entry, "finallyLoc");
- if (hasCatch && hasFinally) {
- if (this.prev < entry.catchLoc) {
- return handle(entry.catchLoc, true);
- } else if (this.prev < entry.finallyLoc) {
- return handle(entry.finallyLoc);
- }
- } else if (hasCatch) {
- if (this.prev < entry.catchLoc) {
- return handle(entry.catchLoc, true);
- }
- } else if (hasFinally) {
- if (this.prev < entry.finallyLoc) {
- return handle(entry.finallyLoc);
- }
- } else {
- throw new Error("try statement without catch or finally");
- }
- }
- }
- },
- abrupt: function(type, arg) {
- for (var i = this.tryEntries.length - 1; i >= 0; --i) {
- var entry = this.tryEntries[i];
- if (entry.tryLoc <= this.prev &&
- hasOwn.call(entry, "finallyLoc") &&
- this.prev < entry.finallyLoc) {
- var finallyEntry = entry;
- break;
- }
- }
- if (finallyEntry &&
- (type === "break" ||
- type === "continue") &&
- finallyEntry.tryLoc <= arg &&
- arg <= finallyEntry.finallyLoc) {
- // Ignore the finally entry if control is not jumping to a
- // location outside the try/catch block.
- finallyEntry = null;
- }
- var record = finallyEntry ? finallyEntry.completion : {};
- record.type = type;
- record.arg = arg;
- if (finallyEntry) {
- this.method = "next";
- this.next = finallyEntry.finallyLoc;
- return ContinueSentinel;
- }
- return this.complete(record);
- },
- complete: function(record, afterLoc) {
- if (record.type === "throw") {
- throw record.arg;
- }
- if (record.type === "break" ||
- record.type === "continue") {
- this.next = record.arg;
- } else if (record.type === "return") {
- this.rval = this.arg = record.arg;
- this.method = "return";
- this.next = "end";
- } else if (record.type === "normal" && afterLoc) {
- this.next = afterLoc;
- }
- return ContinueSentinel;
- },
- finish: function(finallyLoc) {
- for (var i = this.tryEntries.length - 1; i >= 0; --i) {
- var entry = this.tryEntries[i];
- if (entry.finallyLoc === finallyLoc) {
- this.complete(entry.completion, entry.afterLoc);
- resetTryEntry(entry);
- return ContinueSentinel;
- }
- }
- },
- "catch": function(tryLoc) {
- for (var i = this.tryEntries.length - 1; i >= 0; --i) {
- var entry = this.tryEntries[i];
- if (entry.tryLoc === tryLoc) {
- var record = entry.completion;
- if (record.type === "throw") {
- var thrown = record.arg;
- resetTryEntry(entry);
- }
- return thrown;
- }
- }
- // The context.catch method must only be called with a location
- // argument that corresponds to a known catch block.
- throw new Error("illegal catch attempt");
- },
- delegateYield: function(iterable, resultName, nextLoc) {
- this.delegate = {
- iterator: values(iterable),
- resultName: resultName,
- nextLoc: nextLoc
- };
- if (this.method === "next") {
- // Deliberately forget the last sent value so that we don't
- // accidentally pass it on to the delegate.
- this.arg = undefined$1;
- }
- return ContinueSentinel;
- }
- };
- // Regardless of whether this script is executing as a CommonJS module
- // or not, return the runtime object so that we can declare the variable
- // regeneratorRuntime in the outer scope, which allows this module to be
- // injected easily by `bin/regenerator --include-runtime script.js`.
- return exports;
- }(
- // If this script is executing as a CommonJS module, use module.exports
- // as the regeneratorRuntime namespace. Otherwise create a new empty
- // object. Either way, the resulting object will be used to initialize
- // the regeneratorRuntime variable at the top of this file.
- module.exports
- ));
- try {
- regeneratorRuntime = runtime;
- } catch (accidentalStrictMode) {
- // This module should not be running in strict mode, so the above
- // assignment should always work unless something is misconfigured. Just
- // in case runtime.js accidentally runs in strict mode, in modern engines
- // we can explicitly access globalThis. In older engines we can escape
- // strict mode using a global Function call. This could conceivably fail
- // if a Content Security Policy forbids using Function, but in that case
- // the proper solution is to fix the accidental strict mode problem. If
- // you've misconfigured your bundler to force strict mode and applied a
- // CSP to forbid Function, and you're not willing to fix either of those
- // problems, please detail your unique predicament in a GitHub issue.
- if (typeof globalThis === "object") {
- globalThis.regeneratorRuntime = runtime;
- } else {
- Function("r", "regeneratorRuntime = r")(runtime);
- }
- }
- });
- var regenerator = runtime_1;
- function _classCallCheck(instance, Constructor) {
- if (!(instance instanceof Constructor)) {
- throw new TypeError("Cannot call a class as a function");
- }
- }
- function _defineProperties(target, props) {
- for (var i = 0; i < props.length; i++) {
- var descriptor = props[i];
- descriptor.enumerable = descriptor.enumerable || false;
- descriptor.configurable = true;
- if ("value" in descriptor) descriptor.writable = true;
- Object.defineProperty(target, descriptor.key, descriptor);
- }
- }
- function _createClass(Constructor, protoProps, staticProps) {
- if (protoProps) _defineProperties(Constructor.prototype, protoProps);
- if (staticProps) _defineProperties(Constructor, staticProps);
- Object.defineProperty(Constructor, "prototype", {
- writable: false
- });
- return Constructor;
- }
- var util = {
- uuid() {
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (i) {
- var e = Math.random() * 16 | 0;
- return (i === "x" ? e : e & 3 | 8).toString(16);
- });
- },
- getFormattedDate(i) {
- var e = i.getMonth() + 1,
- t = i.getDate(),
- r = i.getHours(),
- n = i.getMinutes(),
- o = i.getSeconds(),
- a = i.getMilliseconds(),
- s = (e < 10 ? "0" : "") + e,
- l = (t < 10 ? "0" : "") + t,
- u = (r < 10 ? "0" : "") + r,
- c = (n < 10 ? "0" : "") + n,
- h = (o < 10 ? "0" : "") + o;
- return i.getFullYear() + "-" + s + "-" + l + " " + u + ":" + c + ":" + h + "." + a;
- },
- createInstance(i) {
- var e = new Axios(i),
- t = bind(Axios.prototype.request, e);
- return utils.extend(t, Axios.prototype, e), utils.extend(t, e), t.create = function (n) {
- return createInstance(mergeConfig(i, n));
- }, t;
- },
- mapLimit(i, e, t) {
- return new Promise(function (r, n) {
- var o = i.length;
- var a = e - 1,
- s = 0;
- var l = function l(u) {
- u.forEach(function (c) {
- t(c).then(function () {
- if (s++, s === o) {
- r();
- return;
- }
- a++;
- var h = i[a];
- h && l([h]);
- }, function (h) {
- n(h);
- });
- });
- };
- l(i.slice(0, e));
- });
- },
- isWebAssemblySupported() {
- try {
- if (typeof WebAssembly == "object" && typeof WebAssembly.instantiate == "function") {
- var i = new WebAssembly.Module(Uint8Array.of(0, 97, 115, 109, 1, 0, 0, 0));
- if (i instanceof WebAssembly.Module) return new WebAssembly.Instance(i) instanceof WebAssembly.Instance;
- }
- } catch (_unused) {}
- return console.log("wasm is not supported"), !1;
- },
- isSupported() {
- return typeof RTCPeerConnection == "function" && this.isWebAssemblySupported();
- }
- };
- function _setPrototypeOf(o, p) {
- _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
- o.__proto__ = p;
- return o;
- };
- return _setPrototypeOf(o, p);
- }
- function _inherits(subClass, superClass) {
- if (typeof superClass !== "function" && superClass !== null) {
- throw new TypeError("Super expression must either be null or a function");
- }
- subClass.prototype = Object.create(superClass && superClass.prototype, {
- constructor: {
- value: subClass,
- writable: true,
- configurable: true
- }
- });
- Object.defineProperty(subClass, "prototype", {
- writable: false
- });
- if (superClass) _setPrototypeOf(subClass, superClass);
- }
- function _typeof(obj) {
- "@babel/helpers - typeof";
- return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
- return typeof obj;
- } : function (obj) {
- return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
- }, _typeof(obj);
- }
- function _assertThisInitialized(self) {
- if (self === void 0) {
- throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
- }
- return self;
- }
- function _possibleConstructorReturn(self, call) {
- if (call && (_typeof(call) === "object" || typeof call === "function")) {
- return call;
- } else if (call !== void 0) {
- throw new TypeError("Derived constructors may only return object or undefined");
- }
- return _assertThisInitialized(self);
- }
- function _getPrototypeOf(o) {
- _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
- return o.__proto__ || Object.getPrototypeOf(o);
- };
- return _getPrototypeOf(o);
- }
- function _createSuper$h(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$i(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
- function _isNativeReflectConstruct$i() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
- var Reporter = /*#__PURE__*/function (_EventEmitter) {
- _inherits(Reporter, _EventEmitter);
- var _super = _createSuper$h(Reporter);
- function Reporter() {
- var _this;
- _classCallCheck(this, Reporter);
- _this = _super.call(this);
- _this._header = {};
- _this._body = {};
- _this._queue = [];
- _this._disabled = !1;
- _this._interval = null;
- _this._reportUrl = null;
- _this.isDocumentLoaded = function () {
- return document.readyState === "complete";
- };
- _this._header.logModuleId = REPORT_MODULE_TYPE, _this._header.url = location.href, _this._header.enviroment = ENV, _this._header.networkType = window.navigator.connection ? window.navigator.connection.type : "unknown", _this._interval = window.setInterval(function () {
- _this._flushReport();
- }, 10 * 1e3);
- return _this;
- }
- _createClass(Reporter, [{
- key: "disable",
- value: function disable() {
- this._disabled = !0, this._interval && window.clearInterval(this._interval);
- }
- }, {
- key: "updateHeader",
- value: function updateHeader(e) {
- Object.assign(this._header, e);
- }
- }, {
- key: "updateBody",
- value: function updateBody(e) {
- Object.assign(this._body, e);
- }
- }, {
- key: "updateReportUrl",
- value: function updateReportUrl(e) {
- this._reportUrl = e;
- }
- }, {
- key: "report",
- value: function report(e, t, r) {
- var _this2 = this;
- if (this._disabled) return;
- r || (r = {});
- var _r = r,
- n = _r.immediate,
- o = _r.sampleRate;
- if (o && o > Math.random()) return;
- this.updateBody({
- logTime: util.getFormattedDate(new Date()),
- logTimestamp: Date.now()
- });
- var a = function a(s) {
- var l = oe(le(oe({}, _this2._body), {
- type: e
- }), s);
- _this2._queue.push(l), e === "measurement" && _this2.emit("report", s);
- };
- Array.isArray(t) ? t.forEach(function (s) {
- return a(s);
- }) : a(t), (n || this._queue.length >= REPORT_NUM_PER_REQUEST) && this._flushReport();
- }
- }, {
- key: "_flushReport",
- value: function _flushReport() {
- if (this._disabled || !this._queue.length || !this.isDocumentLoaded()) return;
- var e = {
- header: this._header,
- body: this._queue.splice(0, REPORT_NUM_PER_REQUEST)
- };
- this._post(e);
- }
- }, {
- key: "_post",
- value: function _post(e) {
- var t = this._reportUrl || REPORT_URL.DEV;
- return new Promise(function (r, n) {
- var o = new XMLHttpRequest();
- o.open("POST", t), o.setRequestHeader("Content-Type", "application/json");
- try {
- o.send(JSON.stringify(e));
- } catch (a) {
- console.error(a);
- }
- o.addEventListener("readystatechange", function () {
- if (o.readyState == 4) return o.status == 200 ? r(o) : n("Unable to send log");
- });
- });
- }
- }]);
- return Reporter;
- }(EventEmitter);
- var reporter$1 = new Reporter();
- function _arrayLikeToArray$1(arr, len) {
- if (len == null || len > arr.length) len = arr.length;
- for (var i = 0, arr2 = new Array(len); i < len; i++) {
- arr2[i] = arr[i];
- }
- return arr2;
- }
- function _arrayWithoutHoles(arr) {
- if (Array.isArray(arr)) return _arrayLikeToArray$1(arr);
- }
- function _iterableToArray(iter) {
- if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
- }
- function _unsupportedIterableToArray$1(o, minLen) {
- if (!o) return;
- if (typeof o === "string") return _arrayLikeToArray$1(o, minLen);
- var n = Object.prototype.toString.call(o).slice(8, -1);
- if (n === "Object" && o.constructor) n = o.constructor.name;
- if (n === "Map" || n === "Set") return Array.from(o);
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$1(o, minLen);
- }
- function _nonIterableSpread() {
- throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
- }
- function _toConsumableArray(arr) {
- return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray$1(arr) || _nonIterableSpread();
- }
- var Codes = {
- Success: 0,
- Param: 1001,
- Internal: 1002,
- Timeout: 1003,
- Authentication: 1004,
- TokenExpired: 1005,
- Unsupported: 1006,
- InitNetworkTimeout: 1007,
- InitDecoderTimeout: 1008,
- InitConfigTimeout: 1009,
- InitEngineTimeout: 1010,
- InitEngine: 1011,
- ActionBlocked: 1012,
- PreloadCanceled: 1013,
- FrequencyLimit: 1014,
- UsersUpperLimit: 2e3,
- RoomsUpperLimit: 2001,
- ServerParam: 2002,
- LackOfToken: 2003,
- LoginFailed: 2004,
- VerifyServiceDown: 2005,
- CreateSessionFailed: 2006,
- RtcConnection: 2008,
- DoActionFailed: 2009,
- StateSyncFailed: 2010,
- BroadcastFailed: 2011,
- DataAbnormal: 2012,
- GetOnVehicle: 2015,
- RepeatLogin: 2017,
- RoomDoseNotExist: 2018,
- TicketExpire: 2019,
- ServerRateLimit: 2020,
- DoActionBlocked: 2333,
- ActionMaybeDelay: 2334,
- ActionResponseTimeout: 2999
- };
- var Logger = /*#__PURE__*/function () {
- function Logger(e) {
- _classCallCheck(this, Logger);
- this.level = 3;
- this.module = e;
- }
- _createClass(Logger, [{
- key: "setLevel",
- value: function setLevel(e) {
- this.level = e;
- }
- }, {
- key: "atleast",
- value: function atleast(e) {
- return e >= this.level && e >= this.level;
- }
- }, {
- key: "print",
- value: function print(e, t) {
- for (var _len = arguments.length, r = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
- r[_key - 2] = arguments[_key];
- }
- if (this.atleast(t)) {
- var _console$n;
- var n = e == "debug" ? "info" : e,
- o = this.prefix(e);
- (_console$n = console[n]).call.apply(_console$n, [null, o].concat(r));
- }
- if (e !== "debug" && e !== "info") {
- var _n = r.map(function (o) {
- if (o instanceof Object) try {
- return JSON.stringify(o);
- } catch (_unused) {
- return o;
- } else return o;
- }).join(",");
- reporter$1.report("log", {
- message: _n,
- level: e,
- module: this.module
- });
- }
- }
- }, {
- key: "debug",
- value: function debug() {
- for (var _len2 = arguments.length, e = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
- e[_key2] = arguments[_key2];
- }
- return this.print.apply(this, ["debug", 1].concat(e));
- }
- }, {
- key: "info",
- value: function info() {
- for (var _len3 = arguments.length, e = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
- e[_key3] = arguments[_key3];
- }
- return this.print.apply(this, ["info", 2].concat(e));
- }
- }, {
- key: "infoAndReportLog",
- value: function infoAndReportLog(e) {
- for (var _len4 = arguments.length, t = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
- t[_key4 - 1] = arguments[_key4];
- }
- var r = e.reportOptions;
- delete e.reportOptions, reporter$1.report("log", e, r), t.length || (t = [e.message]), this.debug.apply(this, _toConsumableArray(t));
- }
- }, {
- key: "infoAndReportMeasurement",
- value: function infoAndReportMeasurement(e) {
- for (var _len5 = arguments.length, t = new Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) {
- t[_key5 - 1] = arguments[_key5];
- }
- var n;
- var r = e.reportOptions;
- if (e.startTime) {
- var o = Date.now();
- e.value === void 0 && (e.endTime = o), e.value === void 0 && (e.value = o - e.startTime);
- }
- if (e.error ? e.code = ((n = e.error) == null ? void 0 : n.code) || Codes.Internal : e.code = Codes.Success, reporter$1.report("measurement", e, r), t.length || (t = [e]), e.level === 4 || e.error) {
- this.error.apply(this, _toConsumableArray(t));
- return;
- }
- this.warn.apply(this, _toConsumableArray(t));
- }
- }, {
- key: "warn",
- value: function warn() {
- for (var _len6 = arguments.length, e = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
- e[_key6] = arguments[_key6];
- }
- return this.print.apply(this, ["warn", 3].concat(e));
- }
- }, {
- key: "error",
- value: function error() {
- for (var _len7 = arguments.length, e = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) {
- e[_key7] = arguments[_key7];
- }
- return this.print.apply(this, ["error", 4].concat(e));
- }
- }, {
- key: "prefix",
- value: function prefix(e) {
- return "[".concat(this.module, "][").concat(e, "] ").concat(util.getFormattedDate(new Date()), ":");
- }
- }], [{
- key: "setLevel",
- value: function setLevel(e) {
- this.level = e;
- }
- }]);
- return Logger;
- }();
- var logger = new Logger();
- var AxiosCanceler = /*#__PURE__*/function () {
- function AxiosCanceler() {
- _classCallCheck(this, AxiosCanceler);
- this.pendingMap = new Map();
- }
- _createClass(AxiosCanceler, [{
- key: "addPending",
- value: function addPending(e) {
- var _this = this;
- return new axios.CancelToken(function (t) {
- _this.pendingMap.has(e) || _this.pendingMap.set(e, t);
- });
- }
- }, {
- key: "removeAllPending",
- value: function removeAllPending() {
- this.pendingMap.forEach(function (e) {
- e && isFunction(e) && e();
- }), this.pendingMap.clear();
- }
- }, {
- key: "removePending",
- value: function removePending(e) {
- if (this.pendingMap.has(e)) {
- var t = this.pendingMap.get(e);
- t && t(e), this.pendingMap.delete(e);
- }
- }
- }, {
- key: "removeCancelToken",
- value: function removeCancelToken(e) {
- this.pendingMap.has(e) && this.pendingMap.delete(e);
- }
- }, {
- key: "reset",
- value: function reset() {
- this.pendingMap = new Map();
- }
- }]);
- return AxiosCanceler;
- }();
- function _createSuper$g(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$h(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
- function _isNativeReflectConstruct$h() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
- var Http1 = /*#__PURE__*/function (_EventEmitter) {
- _inherits(Http1, _EventEmitter);
- var _super = _createSuper$g(Http1);
- function Http1() {
- var _this;
- _classCallCheck(this, Http1);
- _this = _super.call(this);
- _this.instatnce = axios.create(), _this.canceler = new AxiosCanceler();
- return _this;
- }
- _createClass(Http1, [{
- key: "requestConstant",
- value: function requestConstant() {
- return {
- x_nounce: this.randomString(),
- x_timestamp: new Date().getTime(),
- x_os: "web"
- };
- }
- }, {
- key: "requestParams",
- value: function requestParams(e) {
- return oe({}, e.params);
- }
- }, {
- key: "get",
- value: function get(e) {
- return this.request(le(oe({}, e), {
- method: "GET"
- }));
- }
- }, {
- key: "post",
- value: function post(e) {
- return this.request(le(oe({}, e), {
- method: "POST"
- }));
- }
- }, {
- key: "request",
- value: function request(e) {
- var _this2 = this;
- var t = e.url,
- _e$timeout = e.timeout,
- r = _e$timeout === void 0 ? 1e4 : _e$timeout,
- n = e.method,
- o = e.key,
- a = e.beforeRequest,
- s = e.responseType,
- l = e.data;
- var _e$retry = e.retry,
- u = _e$retry === void 0 ? 0 : _e$retry;
- var c = this.patchUrl(t),
- h = this.canceler.addPending(t);
- a && isFunction(a) && a(e);
- var f = this.requestParams(e);
- var d = {
- url: c,
- method: n,
- timeout: r,
- cancelToken: h,
- responseType: s,
- params: f
- };
- n === "POST" && (d = oe({
- data: l
- }, d));
- var _ = Date.now(),
- g = function g() {
- return _this2.instatnce.request(d).then(function (m) {
- return o && logger.infoAndReportMeasurement({
- metric: "http",
- startTime: _,
- extra: t,
- group: "http",
- tag: o
- }), _this2.canceler.removeCancelToken(t), m;
- }).catch(function (m) {
- var v = axios.isCancel(m);
- return u > 0 && !v ? (u--, logger.warn("request ".concat(t, " retry, left retry count"), u), g()) : (logger.infoAndReportMeasurement({
- metric: "http",
- startTime: _,
- error: m,
- extra: {
- url: t,
- isCanceled: v
- },
- tag: o,
- group: "http"
- }), _this2.canceler.removeCancelToken(t), Promise.reject(m));
- });
- };
- return g();
- }
- }, {
- key: "patchUrl",
- value: function patchUrl(e) {
- return e;
- }
- }, {
- key: "randomString",
- value: function randomString() {
- var e = "";
- var t = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
- r = t.length;
- for (var n = 0; n < 8; n++) {
- e += t.charAt(Math.floor(Math.random() * r));
- }
- return e;
- }
- }]);
- return Http1;
- }(EventEmitter);
- var http1 = new Http1();
- var ModelManager = /*#__PURE__*/function () {
- function ModelManager(e, t) {
- _classCallCheck(this, ModelManager);
- this.avatarModelList = [];
- this.skinList = [];
- this.applicationConfig = null;
- this.config = null;
- this.appId = e, this.releaseId = t;
- }
- _createClass(ModelManager, [{
- key: "findSkinConfig",
- value: function () {
- var _findSkinConfig = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee(e) {
- var t, n;
- return regenerator.wrap(function _callee$(_context) {
- while (1) {
- switch (_context.prev = _context.next) {
- case 0:
- t = null;
- _context.next = 3;
- return this.getSkinsList();
- case 3:
- t = (this.skinList = _context.sent).find(function (n) {
- return n.id === e;
- });
- if (!t) {
- _context.next = 6;
- break;
- }
- return _context.abrupt("return", t);
- case 6:
- n = "skin is invalid: skinId: ".concat(e);
- return _context.abrupt("return", Promise.reject(new ParamError(n)));
- case 8:
- case "end":
- return _context.stop();
- }
- }
- }, _callee, this);
- }));
- function findSkinConfig(_x) {
- return _findSkinConfig.apply(this, arguments);
- }
- return findSkinConfig;
- }()
- }, {
- key: "findRoute",
- value: function () {
- var _findRoute = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee2(e, t) {
- var n, o;
- return regenerator.wrap(function _callee2$(_context2) {
- while (1) {
- switch (_context2.prev = _context2.next) {
- case 0:
- _context2.next = 2;
- return this.findSkinConfig(e);
- case 2:
- n = _context2.sent.routeList.find(function (o) {
- return o.pathName === t;
- });
- if (n) {
- _context2.next = 6;
- break;
- }
- o = "find path failed: skinId: ".concat(e, ", pathName: ").concat(t);
- return _context2.abrupt("return", Promise.reject(new ParamError(o)));
- case 6:
- return _context2.abrupt("return", (logger.debug("find route success", n), n));
- case 7:
- case "end":
- return _context2.stop();
- }
- }
- }, _callee2, this);
- }));
- function findRoute(_x2, _x3) {
- return _findRoute.apply(this, arguments);
- }
- return findRoute;
- }()
- }, {
- key: "findAssetList",
- value: function () {
- var _findAssetList = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee3(e) {
- var r, n;
- return regenerator.wrap(function _callee3$(_context3) {
- while (1) {
- switch (_context3.prev = _context3.next) {
- case 0:
- _context3.next = 2;
- return this.findSkinConfig(e);
- case 2:
- r = _context3.sent.assetList;
- if (r) {
- _context3.next = 6;
- break;
- }
- n = "find path failed: skinId: ".concat(e);
- return _context3.abrupt("return", Promise.reject(new ParamError(n)));
- case 6:
- return _context3.abrupt("return", (logger.debug("find route success", r), r));
- case 7:
- case "end":
- return _context3.stop();
- }
- }
- }, _callee3, this);
- }));
- function findAssetList(_x4) {
- return _findAssetList.apply(this, arguments);
- }
- return findAssetList;
- }()
- }, {
- key: "findAsset",
- value: function () {
- var _findAsset = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee4(e, t) {
- var r,
- n,
- o,
- a,
- _args4 = arguments;
- return regenerator.wrap(function _callee4$(_context4) {
- while (1) {
- switch (_context4.prev = _context4.next) {
- case 0:
- r = _args4.length > 2 && _args4[2] !== undefined ? _args4[2] : "id";
- _context4.next = 3;
- return this.findSkinConfig(e);
- case 3:
- n = _context4.sent;
- if (!Array.isArray(t)) {
- _context4.next = 6;
- break;
- }
- return _context4.abrupt("return", t.map(function (a) {
- return n.models.find(function (s) {
- return s[r] === a;
- });
- }).filter(Boolean));
- case 6:
- o = n.models.find(function (a) {
- return a[r] === t;
- });
- if (o) {
- _context4.next = 10;
- break;
- }
- a = "find asset failed: skinId: ".concat(e, ", keyValue: ").concat(t);
- return _context4.abrupt("return", Promise.reject(new ParamError(a)));
- case 10:
- return _context4.abrupt("return", (logger.debug("find asset success", o), o));
- case 11:
- case "end":
- return _context4.stop();
- }
- }
- }, _callee4, this);
- }));
- function findAsset(_x5, _x6) {
- return _findAsset.apply(this, arguments);
- }
- return findAsset;
- }()
- }, {
- key: "findPoint",
- value: function () {
- var _findPoint = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee5(e, t) {
- var n, o;
- return regenerator.wrap(function _callee5$(_context5) {
- while (1) {
- switch (_context5.prev = _context5.next) {
- case 0:
- _context5.next = 2;
- return this.findSkinConfig(e);
- case 2:
- n = _context5.sent.pointList.find(function (o) {
- return o.id === t;
- });
- if (n) {
- _context5.next = 6;
- break;
- }
- o = "find point failed: skinId: ".concat(e, ", id: ").concat(t);
- return _context5.abrupt("return", Promise.reject(new ParamError(o)));
- case 6:
- return _context5.abrupt("return", (logger.debug("find point success", n), n));
- case 7:
- case "end":
- return _context5.stop();
- }
- }
- }, _callee5, this);
- }));
- function findPoint(_x7, _x8) {
- return _findPoint.apply(this, arguments);
- }
- return findPoint;
- }()
- }, {
- key: "requestConfig",
- value: function () {
- var _requestConfig = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee6() {
- var t, r, _ref, n, o;
- return regenerator.wrap(function _callee6$(_context6) {
- while (1) {
- switch (_context6.prev = _context6.next) {
- case 0:
- if (!this.config) {
- _context6.next = 2;
- break;
- }
- return _context6.abrupt("return", this.config);
- case 2:
- // let e = `https://static.xverse.cn/console/config/${this.appId}/config.json`;
- // this.releaseId && (e = `https://static.xverse.cn/console/config/${this.appId}/${this.releaseId}/config.json`);
- // const t = Xverse.USE_TME_CDN ? "https://static.xverse.cn/tmeland/config/tme_config.json" : e;
- t = './assets/config.json';
- _context6.prev = 3;
- _context6.next = 6;
- return http1.get({
- url: "".concat(t, "?t=").concat(Date.now()),
- key: "config",
- timeout: 6e3,
- retry: 2
- });
- case 6:
- r = _context6.sent;
- _ref = r.data.data || {}, n = _ref.config, o = _ref.preload;
- if (n) {
- _context6.next = 10;
- break;
- }
- throw new Error("config data parse error" + r.data);
- case 10:
- return _context6.abrupt("return", (this.config = {
- config: n,
- preload: o
- }, logger.debug("get config success", this.config), this.config));
- case 13:
- _context6.prev = 13;
- _context6.t0 = _context6["catch"](3);
- return _context6.abrupt("return", Promise.reject(_context6.t0));
- case 16:
- case "end":
- return _context6.stop();
- }
- }
- }, _callee6, this, [[3, 13]]);
- }));
- function requestConfig() {
- return _requestConfig.apply(this, arguments);
- }
- return requestConfig;
- }()
- }, {
- key: "getApplicationConfig",
- value: function () {
- var _getApplicationConfig = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee7() {
- var e;
- return regenerator.wrap(function _callee7$(_context7) {
- while (1) {
- switch (_context7.prev = _context7.next) {
- case 0:
- if (!this.applicationConfig) {
- _context7.next = 2;
- break;
- }
- return _context7.abrupt("return", this.applicationConfig);
- case 2:
- _context7.prev = 2;
- _context7.next = 5;
- return this.requestConfig();
- case 5:
- e = _context7.sent;
- return _context7.abrupt("return", (this.applicationConfig = e.config, this.applicationConfig));
- case 9:
- _context7.prev = 9;
- _context7.t0 = _context7["catch"](2);
- return _context7.abrupt("return", Promise.reject(_context7.t0));
- case 12:
- case "end":
- return _context7.stop();
- }
- }
- }, _callee7, this, [[2, 9]]);
- }));
- function getApplicationConfig() {
- return _getApplicationConfig.apply(this, arguments);
- }
- return getApplicationConfig;
- }()
- }, {
- key: "getAvatarModelList",
- value: function () {
- var _getAvatarModelList = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee8() {
- var _yield$this$getApplic, e;
- return regenerator.wrap(function _callee8$(_context8) {
- while (1) {
- switch (_context8.prev = _context8.next) {
- case 0:
- if (!this.avatarModelList.length) {
- _context8.next = 2;
- break;
- }
- return _context8.abrupt("return", this.avatarModelList);
- case 2:
- _context8.prev = 2;
- _context8.next = 5;
- return this.getApplicationConfig();
- case 5:
- _yield$this$getApplic = _context8.sent;
- e = _yield$this$getApplic.avatars;
- return _context8.abrupt("return", (this.avatarModelList = e.map(function (t) {
- return {
- name: t.name,
- id: t.id,
- modelUrl: t.url,
- gender: t.gender,
- components: t.components
- };
- }), this.avatarModelList));
- case 10:
- _context8.prev = 10;
- _context8.t0 = _context8["catch"](2);
- return _context8.abrupt("return", (logger.error(_context8.t0), []));
- case 13:
- case "end":
- return _context8.stop();
- }
- }
- }, _callee8, this, [[2, 10]]);
- }));
- function getAvatarModelList() {
- return _getAvatarModelList.apply(this, arguments);
- }
- return getAvatarModelList;
- }()
- }, {
- key: "getSkinsList",
- value: function () {
- var _getSkinsList = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee9() {
- var _yield$this$getApplic2, e;
- return regenerator.wrap(function _callee9$(_context9) {
- while (1) {
- switch (_context9.prev = _context9.next) {
- case 0:
- if (!this.skinList.length) {
- _context9.next = 2;
- break;
- }
- return _context9.abrupt("return", this.skinList);
- case 2:
- _context9.prev = 2;
- _context9.next = 5;
- return this.getApplicationConfig();
- case 5:
- _yield$this$getApplic2 = _context9.sent;
- e = _yield$this$getApplic2.skins;
- return _context9.abrupt("return", (this.skinList = e.map(function (t) {
- var r;
- return {
- name: t.name,
- dataVersion: t.id + t.versionId,
- id: t.id,
- fov: parseInt(t.fov || 90),
- models: t.assetList.map(function (n) {
- var o = n.assetId,
- a = n.url,
- s = n.thumbnailUrl,
- l = n.typeName,
- u = n.className;
- return {
- id: o,
- modelUrl: a,
- name: n.name,
- thumbnailUrl: s,
- typeName: l,
- className: u === "\u4F4E\u6A21" ? "\u7C97\u6A21" : u
- };
- }),
- routeList: (r = t.routeList) == null ? void 0 : r.map(function (n) {
- var o = n.areaName,
- a = n.attitude,
- s = n.id,
- l = n.pathName,
- u = n.step,
- c = n.birthPointList;
- return {
- areaName: o,
- attitude: a,
- id: s,
- pathName: l,
- step: u,
- birthPointList: c.map(function (h) {
- return {
- camera: h.camera && {
- position: objectParseFloat(h.camera.position),
- angle: objectParseFloat(h.camera.rotation)
- },
- player: h.player && {
- position: objectParseFloat(h.player.position),
- angle: objectParseFloat(h.player.rotation)
- }
- };
- })
- };
- }),
- pointList: t.pointList.map(function (n) {
- return le(oe({}, n), {
- position: objectParseFloat(n.position),
- rotation: objectParseFloat(n.rotation)
- });
- }),
- versionId: t.versionId,
- isEnable: t.isEnable,
- assetList: t.assetList,
- visibleRules: t.visibleRules,
- animationList: t.animationList
- };
- }), this.skinList));
- case 10:
- _context9.prev = 10;
- _context9.t0 = _context9["catch"](2);
- return _context9.abrupt("return", (logger.error(_context9.t0), []));
- case 13:
- case "end":
- return _context9.stop();
- }
- }
- }, _callee9, this, [[2, 10]]);
- }));
- function getSkinsList() {
- return _getSkinsList.apply(this, arguments);
- }
- return getSkinsList;
- }()
- }, {
- key: "getBreathPointTextrueList",
- value: function () {
- var _getBreathPointTextrueList = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee10() {
- return regenerator.wrap(function _callee10$(_context10) {
- while (1) {
- switch (_context10.prev = _context10.next) {
- case 0:
- return _context10.abrupt("return", [{
- url: TEXTURE_URL
- }]);
- case 1:
- case "end":
- return _context10.stop();
- }
- }
- }, _callee10);
- }));
- function getBreathPointTextrueList() {
- return _getBreathPointTextrueList.apply(this, arguments);
- }
- return getBreathPointTextrueList;
- }()
- }], [{
- key: "getInstance",
- value: function getInstance(e, t) {
- //getInstance(e, t) {
- return this.instance || (this.instance = new ModelManager(e, t)), this.instance;
- }
- }, {
- key: "findModels",
- value: function findModels(e, t, r) {
- //findModels(e, t, r) {
- return e.filter(function (o) {
- return o.typeName === t && o.className === r;
- });
- }
- }, {
- key: "findModel",
- value: function findModel(e, t, r) {
- //findModel(e, t, r) {
- var n = e.filter(function (o) {
- return o.typeName === t && o.className === r;
- })[0];
- return n || null;
- }
- }]);
- return ModelManager;
- }();
- // export { modelManager };
- var JoyStick = /*#__PURE__*/function () {
- function JoyStick(e) {
- _classCallCheck(this, JoyStick);
- this._zone = document.createElement("div");
- this._joystick = null;
- this._room = e;
- }
- _createClass(JoyStick, [{
- key: "init",
- value: function init(e) {
- var _this = this;
- var _e$interval = e.interval,
- t = _e$interval === void 0 ? 33 : _e$interval,
- _e$triggerDistance = e.triggerDistance,
- r = _e$triggerDistance === void 0 ? 25 : _e$triggerDistance,
- _e$style = e.style,
- n = _e$style === void 0 ? {
- left: 0,
- bottom: 0
- } : _e$style,
- o = function o(u, c) {
- _this._room.actionsHandler.joystick({
- degree: Math.floor(u),
- level: Math.floor(c / 5)
- });
- },
- a = this._zone;
- document.body.appendChild(a), a.style.position = "absolute", a.style.width = "200px", a.style.height = "200px", a.style.left = String(n.left), a.style.bottom = String(n.bottom), a.style.zIndex = "999", a.style.userSelect = "none", a.style.webkitUserSelect = "none", this._joystick = nipplejs.create({
- zone: a,
- mode: "static",
- position: {
- left: "50%",
- top: "50%"
- },
- color: "white"
- });
- var s, l;
- return this._joystick.on("move", function (u, c) {
- s = c;
- }), this._joystick.on("start", function () {
- l = window.setInterval(function () {
- s && s.distance > r && o && o(s.angle.degree, s.distance);
- }, t);
- }), this._joystick.on("end", function () {
- l && window.clearInterval(l), l = void 0;
- }), this._joystick;
- }
- }, {
- key: "show",
- value: function show() {
- if (!this._joystick) throw new Error("joystick is not created");
- this._zone.style.display = "block";
- }
- }, {
- key: "hide",
- value: function hide() {
- if (!this._joystick) throw new Error("joystick is not created");
- this._zone.style.display = "none";
- }
- }]);
- return JoyStick;
- }();
- var CoreBroadcastType = {
- PlayAnimation: 'PlayAnimation'
- };
- var AvatarGroup = {
- Npc: 'npc',
- User: 'user'
- };
- var MessageHandleType$1 = {
- MHT_Undefined: 0,
- MHT_RoomMulticast: 1,
- MHT_FollowListMulticast: 2,
- MHT_CustomTargetSync: 3
- };
- var Broadcast$1 = /*#__PURE__*/function () {
- function Broadcast(e, t) {
- _classCallCheck(this, Broadcast);
- this.room = e;
- this.handlers = [];
- this.init(t);
- }
- _createClass(Broadcast, [{
- key: "init",
- value: function init(t) {
- this.handlers.push(t);
- }
- }, {
- key: "handleBroadcast",
- value: function () {
- var _handleBroadcast = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee(e) {
- return regenerator.wrap(function _callee$(_context) {
- while (1) {
- switch (_context.prev = _context.next) {
- case 0:
- _context.prev = 1;
- JSON.parse(e.broadcastAction.data);
- _context.next = 9;
- break;
- case 5:
- _context.prev = 5;
- _context.t0 = _context["catch"](1);
- logger.error(_context.t0);
- return _context.abrupt("return");
- case 9:
- case "end":
- return _context.stop();
- }
- }
- }, _callee, null, [[1, 5]]);
- }));
- function handleBroadcast(_x) {
- return _handleBroadcast.apply(this, arguments);
- }
- return handleBroadcast;
- }()
- }, {
- key: "broadcast",
- value: function broadcast(e) {
- var t = e.data,
- _e$msgType = e.msgType,
- r = _e$msgType === void 0 ? MessageHandleType$1.MHT_FollowListMulticast : _e$msgType,
- n = e.targetUserIds;
- return this.room.actionsHandler.broadcast({
- data: t,
- msgType: r,
- targetUserIds: n
- });
- }
- }]);
- return Broadcast;
- }();
- function _isNativeFunction(fn) {
- return Function.toString.call(fn).indexOf("[native code]") !== -1;
- }
- function _isNativeReflectConstruct$g() {
- if (typeof Reflect === "undefined" || !Reflect.construct) return false;
- if (Reflect.construct.sham) return false;
- if (typeof Proxy === "function") return true;
- try {
- Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
- return true;
- } catch (e) {
- return false;
- }
- }
- function _construct(Parent, args, Class) {
- if (_isNativeReflectConstruct$g()) {
- _construct = Reflect.construct;
- } else {
- _construct = function _construct(Parent, args, Class) {
- var a = [null];
- a.push.apply(a, args);
- var Constructor = Function.bind.apply(Parent, a);
- var instance = new Constructor();
- if (Class) _setPrototypeOf(instance, Class.prototype);
- return instance;
- };
- }
- return _construct.apply(null, arguments);
- }
- function _wrapNativeSuper(Class) {
- var _cache = typeof Map === "function" ? new Map() : undefined;
- _wrapNativeSuper = function _wrapNativeSuper(Class) {
- if (Class === null || !_isNativeFunction(Class)) return Class;
- if (typeof Class !== "function") {
- throw new TypeError("Super expression must either be null or a function");
- }
- if (typeof _cache !== "undefined") {
- if (_cache.has(Class)) return _cache.get(Class);
- _cache.set(Class, Wrapper);
- }
- function Wrapper() {
- return _construct(Class, arguments, _getPrototypeOf(this).constructor);
- }
- Wrapper.prototype = Object.create(Class.prototype, {
- constructor: {
- value: Wrapper,
- enumerable: false,
- writable: true,
- configurable: true
- }
- });
- return _setPrototypeOf(Wrapper, Class);
- };
- return _wrapNativeSuper(Class);
- }
- function _createSuper$f(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$f(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
- function _isNativeReflectConstruct$f() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
- var XverseError = /*#__PURE__*/function (_Error) {
- _inherits(XverseError, _Error);
- var _super = _createSuper$f(XverseError);
- function XverseError(e, t) {
- var _this;
- _classCallCheck(this, XverseError);
- _this = _super.call(this, t);
- _this.code = e;
- return _this;
- }
- _createClass(XverseError, [{
- key: "toJSON",
- value: function toJSON() {
- return {
- code: this.code,
- message: this.message
- };
- }
- }, {
- key: "toString",
- value: function toString() {
- if (Object(this) !== this) throw new TypeError();
- var t = this.name;
- t = t === void 0 ? "Error" : String(t);
- var r = this.message;
- r = r === void 0 ? "" : String(r);
- var n = this.code;
- return r = n === void 0 ? r : n + "," + r, t === "" ? r : r === "" ? t : t + ": " + r;
- }
- }]);
- return XverseError;
- }( /*#__PURE__*/_wrapNativeSuper(Error));
- function _createSuper$e(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$e(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
- function _isNativeReflectConstruct$e() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
- var TimeoutError = /*#__PURE__*/function (_XverseError) {
- _inherits(TimeoutError, _XverseError);
- var _super = _createSuper$e(TimeoutError);
- function TimeoutError(e) {
- _classCallCheck(this, TimeoutError);
- return _super.call(this, 1003, e || "\u8D85\u65F6");
- }
- return _createClass(TimeoutError);
- }(XverseError);
- function _createSuper$d(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$d(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
- function _isNativeReflectConstruct$d() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
- var XverseAvatarManager = /*#__PURE__*/function (_EventEmitter) {
- _inherits(XverseAvatarManager, _EventEmitter);
- var _super = _createSuper$d(XverseAvatarManager);
- function XverseAvatarManager(e) {
- var _this;
- _classCallCheck(this, XverseAvatarManager);
- _this = _super.call(this);
- _this.xAvatarManager = null;
- _this.avatars = new Map();
- _this.syncAvatarsLength = 0;
- _this._room = e;
- _this._usersStatistics();
- _this.broadcast = _this.setupBroadcast();
- e.on("skinChanged", function () {
- _this.avatars.forEach(function (t) {
- t.disconnected && _this.removeAvatar(t.userId, !0);
- });
- });
- return _this;
- }
- _createClass(XverseAvatarManager, [{
- key: "setupBroadcast",
- value: function setupBroadcast() {
- var _this2 = this;
- return new Broadcast$1(this._room, /*#__PURE__*/function () {
- var _ref = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee(e) {
- var t, r, n, o, a, _r$loop, s, l;
- return regenerator.wrap(function _callee$(_context) {
- while (1) {
- switch (_context.prev = _context.next) {
- case 0:
- t = e.broadcastType, r = e.info;
- if (!(t !== CoreBroadcastType.PlayAnimation)) {
- _context.next = 3;
- break;
- }
- return _context.abrupt("return");
- case 3:
- n = r.userId, o = r.animation, a = r.extra, _r$loop = r.loop, s = _r$loop === void 0 ? !1 : _r$loop, l = _this2.avatars.get(n);
- _context.t0 = l && !l.isSelf;
- if (!_context.t0) {
- _context.next = 10;
- break;
- }
- l.emit("animationStart", {
- animationName: o,
- extra: decodeURIComponent(a)
- });
- _context.next = 9;
- return l == null ? void 0 : l._playAnimation(o, s);
- case 9:
- l.emit("animationEnd", {
- animationName: o,
- extra: decodeURIComponent(a)
- });
- case 10:
- case "end":
- return _context.stop();
- }
- }
- }, _callee);
- }));
- return function (_x) {
- return _ref.apply(this, arguments);
- };
- }());
- }
- }, {
- key: "hideAll",
- value: function hideAll() {
- var e = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : !0;
- this.xAvatarManager.hideAll(e);
- }
- }, {
- key: "showAll",
- value: function showAll() {
- var e = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : !0;
- this.xAvatarManager.showAll(e);
- }
- }, {
- key: "init",
- value: function () {
- var _init = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee2() {
- var e, t;
- return regenerator.wrap(function _callee2$(_context2) {
- while (1) {
- switch (_context2.prev = _context2.next) {
- case 0:
- this.xAvatarManager = this._room.sceneManager.avatarComponent;
- _context2.prev = 1;
- _context2.next = 4;
- return this._room.modelManager.getApplicationConfig();
- case 4:
- e = _context2.sent;
- t = e.avatars;
- if (!t) {
- _context2.next = 10;
- break;
- }
- _context2.next = 9;
- return avatarLoader.parse(this._room.sceneManager, t);
- case 9:
- return _context2.abrupt("return");
- case 10:
- return _context2.abrupt("return", Promise.reject("cannot find avatar config list"));
- case 13:
- _context2.prev = 13;
- _context2.t0 = _context2["catch"](1);
- return _context2.abrupt("return", (logger.error(_context2.t0), Promise.reject("avatar mananger init error!")));
- case 16:
- case "end":
- return _context2.stop();
- }
- }
- }, _callee2, this, [[1, 13]]);
- }));
- function init() {
- return _init.apply(this, arguments);
- }
- return init;
- }()
- }, {
- key: "handleAvatar",
- value: function () {
- var _handleAvatar2 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee3(e) {
- var _this3 = this;
- var r, t, n, o, _n, a;
- return regenerator.wrap(function _callee3$(_context3) {
- while (1) {
- switch (_context3.prev = _context3.next) {
- case 0:
- if (!(this._room.viewMode === "simple" || !this._room.joined || !e.newUserStates)) {
- _context3.next = 2;
- break;
- }
- return _context3.abrupt("return");
- case 2:
- t = e.newUserStates;
- if (((r = this._room._userAvatar) == null ? void 0 : r.isMoving) && this._room._userAvatar.motionType === MotionType.Run) {
- n = t.filter(function (a) {
- return a.userId === _this3._room.userId;
- }), o = t.filter(function (a) {
- return a.userId !== _this3._room.userId;
- }).slice(0, 2);
- t = n.concat(o);
- }
- if (e.getStateType === GetStateTypes.Event) {
- this.syncAvatarsLength = (t || []).length;
- _n = this._room.avatars.filter(function (s) {
- return s.group == AvatarGroup.User;
- });
- _n.filter(function (s) {
- return !(t != null && t.find(function (l) {
- return l.userId == s.userId;
- }));
- }).forEach(function (s) {
- _this3.removeAvatar(s.userId);
- });
- a = t.filter(function (s) {
- return !_n.find(function (l) {
- return l.userId == s.userId;
- });
- });
- this._handleAvatar(a);
- }
- this._handleAvatar(t);
- case 6:
- case "end":
- return _context3.stop();
- }
- }
- }, _callee3, this);
- }));
- function handleAvatar(_x2) {
- return _handleAvatar2.apply(this, arguments);
- }
- return handleAvatar;
- }()
- }, {
- key: "_handleAvatar",
- value: function () {
- var _handleAvatar3 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee4(e) {
- var _this4 = this;
- return regenerator.wrap(function _callee4$(_context4) {
- while (1) {
- switch (_context4.prev = _context4.next) {
- case 0:
- e == null || e.forEach(function (t) {
- var n, o, a, s, l, u, c, h, f;
- var r = _this4._room.userId === t.userId;
- if (((n = t.event) == null ? void 0 : n.type) === SyncEventType.ET_RemoveVisitor) {
- var d = (a = (o = t.event) == null ? void 0 : o.removeVisitorEvent) == null ? void 0 : a.removeVisitorEvent,
- _ = JSON.parse(safeDecodeURIComponent(((l = (s = t.event) == null ? void 0 : s.removeVisitorEvent) == null ? void 0 : l.extraInfo) || "")),
- g = _.code,
- m = _.msg;
- d === RemoveVisitorType.RVT_ChangeToObserver ? _this4._room.audienceViewModeHook() : d === RemoveVisitorType.RVT_MoveOutOfTheRoom && _this4._room.leave(), _this4._room.emit("visitorStatusChanged", {
- code: g,
- msg: m
- });
- }
- if (t.event && [SyncEventType.Appear, SyncEventType.Reset].includes(t.event.type) || !t.event) {
- var _d = _this4.avatars.get(t.userId);
- if (t.playerState.avatarId && (_d == null ? void 0 : _d.avatarId) !== t.playerState.avatarId && (_d = void 0, _this4.removeAvatar(t.userId)), _d) {
- if (_d.disconnected && _d.setConnectionStatus(!1), (u = t.event) != null && u.id && _this4._room.actionsHandler.confirmEvent(t.event.id), t.playerState.nickName && (_d == null || _d._setNickname(t.playerState.nickName)), t.playerState.avatarComponents && !_d.isSelf && _d.xAvatar) {
- var _2 = safeParseComponents(t.playerState.avatarComponents);
- _d._changeComponents({
- avatarComponents: _2,
- mode: ChangeComponentsMode.Preview
- });
- }
- } else {
- var _t$playerState$player = t.playerState.player,
- _3 = _t$playerState$player.position,
- _g = _t$playerState$player.angle,
- _m = t.playerState.avatarId,
- v = t.playerState.prioritySync,
- y = safelyJsonParse(t.playerState.extra);
- if (!_m) return;
- var b = safeParseComponents(t.playerState.avatarComponents),
- T = safeDecodeURIComponent(t.playerState.nickName),
- C = _this4.calculatePriority(t.userId, y);
- _this4.addAvatar({
- userId: t.userId,
- isHost: t.playerState.isHost,
- nickname: T,
- avatarPosition: _3,
- avatarRotation: _g,
- avatarScale: t.playerState.avatarSize,
- avatarId: _m,
- avatarComponents: t.playerState.person === Person.First ? [] : b,
- priority: C,
- group: AvatarGroup.User,
- prioritySync: v,
- extraInfo: y
- }).then(function () {
- var A;
- (A = t.event) != null && A.id && _this4._room.actionsHandler.confirmEvent(t.event.id), _this4.updateAvatarPositionAndRotation(t), r && (_this4.xAvatarManager.setMainAvatar(t.userId), _this4._room.emit("userAvatarLoaded"), logger.info("userAvatarLoaded"));
- }).catch(function (A) {
- r && (_this4.xAvatarManager.setMainAvatar(t.userId), _this4._room.emit("userAvatarFailed", {
- error: A
- }), logger.error("userAvatarFailed", A));
- });
- }
- }
- if (t.event && SyncEventType.Disappear === t.event.type && ((c = t == null ? void 0 : t.event) != null && c.id && _this4._room.actionsHandler.confirmEvent(t.event.id), _this4.removeAvatar(t.userId)), t.event && [SyncEventType.Move, SyncEventType.ChangeRenderInfo].includes(t.event.type) || !t.event) {
- (h = t == null ? void 0 : t.event) != null && h.id && _this4._room.actionsHandler.confirmEvent(t.event.id);
- var _d2 = _this4.avatars.get(t.userId);
- _d2 && _d2.withModel && !_d2.isLoading && _this4.updateAvatarPositionAndRotation(t);
- }
- if (!r && ((f = t.event) == null ? void 0 : f.type) === SyncEventType.Rotate) {
- var _d3 = _this4.avatars.get(t.userId);
- _d3.statusSyncQueue.append({
- type: QueueType.Rotate,
- action: function action() {
- return _d3.statusSync(t);
- }
- });
- }
- });
- case 1:
- case "end":
- return _context4.stop();
- }
- }
- }, _callee4);
- }));
- function _handleAvatar(_x3) {
- return _handleAvatar3.apply(this, arguments);
- }
- return _handleAvatar;
- }()
- }, {
- key: "calculatePriority",
- value: function calculatePriority(e, t) {
- var n;
- return e === this._room.userId ? EAvatarRelationRank.Self : (n = this._room.options.firends) != null && n.includes(e) ? EAvatarRelationRank.Friend : EAvatarRelationRank.Stranger;
- }
- }, {
- key: "updateAvatarPositionAndRotation",
- value: function updateAvatarPositionAndRotation(e) {
- var t, r;
- if ((t = e == null ? void 0 : e.playerState) != null && t.player) {
- var _e$playerState$player = e.playerState.player,
- n = _e$playerState$player.position,
- o = _e$playerState$player.angle;
- var a = this.avatars.get(e.userId);
- if (!a) return;
- if (n = positionPrecisionProtect(n), o = rotationPrecisionProtect(o), a.isSelf && !this._room.networkController.rtcp.workers.inPanoMode && (a.setPosition(n), a.setRotation(o)), e.event && (((r = e.event) == null ? void 0 : r.points.length) || 0) > 1 && !a.isSelf && a.statusSyncQueue.append({
- type: QueueType.Move,
- action: function action() {
- return a.statusSync(e);
- }
- }), e.renderInfo && a.isSelf) {
- var _e$renderInfo = e.renderInfo,
- s = _e$renderInfo.isMoving,
- l = _e$renderInfo.isRotating;
- this._updateAvatarMovingStatus({
- id: e.userId,
- isMoving: !!s,
- isRotating: !!l
- });
- }
- }
- }
- }, {
- key: "addAvatar",
- value: function () {
- var _addAvatar = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee5(e) {
- var t, r, n, o, a, s, _e$avatarComponents, l, u, _e$group, c, _e$avatarScale, h, f, d, _, g, v, y, b, T, C;
- return regenerator.wrap(function _callee5$(_context5) {
- while (1) {
- switch (_context5.prev = _context5.next) {
- case 0:
- t = e.userId, r = e.isHost, n = e.avatarPosition, o = e.avatarId, a = e.avatarRotation, s = e.nickname, _e$avatarComponents = e.avatarComponents, l = _e$avatarComponents === void 0 ? [] : _e$avatarComponents, u = e.priority, _e$group = e.group, c = _e$group === void 0 ? AvatarGroup.Npc : _e$group, _e$avatarScale = e.avatarScale, h = _e$avatarScale === void 0 ? DEFAULT_AVATAR_SCALE : _e$avatarScale, f = e.extraInfo, d = e.prioritySync, _ = t === this._room.userId;
- g = this.avatars.get(t);
- if (!g) {
- _context5.next = 4;
- break;
- }
- return _context5.abrupt("return", Promise.resolve(g));
- case 4:
- if (!(g = new xe.subAvatar({
- userId: t,
- isHost: r,
- isSelf: _,
- room: this._room,
- avatarComponents: l,
- avatarId: o,
- nickname: s,
- group: c
- }), this.avatars.set(t, g), !g.withModel)) {
- _context5.next = 6;
- break;
- }
- return _context5.abrupt("return", (g.isLoading = !1, g.avatarLoadedHook(), this._room.emit("avatarChanged", {
- avatars: this._room.avatars
- }), g));
- case 6:
- _context5.next = 8;
- return this._room.modelManager.getAvatarModelList();
- case 8:
- v = _context5.sent.find(function (b) {
- return b.id === o;
- });
- y = Date.now();
- if (v) {
- _context5.next = 12;
- break;
- }
- return _context5.abrupt("return", (this._room.emit("avatarChanged", {
- avatars: this._room.avatars
- }), this.avatars.delete(t), Promise.reject("no such avatar model with id: ".concat(o))));
- case 12:
- _context5.prev = 12;
- _context5.next = 15;
- return avatarComponentsModify(v, l);
- case 15:
- b = _context5.sent;
- b = b.filter(function (A) {
- return A.type != "pendant";
- });
- _context5.next = 19;
- return avatarComponentsParser(v, b);
- case 19:
- T = _context5.sent;
- _context5.next = 22;
- return this.xAvatarManager.loadAvatar({
- id: t,
- avatarType: o,
- priority: u,
- avatarManager: this.xAvatarManager,
- assets: T,
- status: {
- avatarPosition: n,
- avatarRotation: a,
- avatarScale: h
- }
- })._timeout(8e3, new TimeoutError$1("loadAvatar timeout(8s)"));
- case 22:
- C = _context5.sent;
- return _context5.abrupt("return", (C.setPickBoxScale(t === this._room.userId ? 0 : 1), g.xAvatar = C, g.setScale(h), g.extraInfo = f, g.priority = u, g.isLoading = !1, g.prioritySync = !!d, g._playAnimation("Idle", !0, !0), g.avatarLoadedHook(), this._room.emit("avatarChanged", {
- avatars: this._room.avatars
- }), s && g._setNickname(s), t === this._room.userId && (logger.infoAndReportMeasurement({
- metric: "avatarLoadDuration",
- startTime: y,
- group: "costs"
- }), logger.infoAndReportMeasurement({
- metric: "avatarLoadAt",
- startTime: this._room._startTime,
- group: "costs"
- })), g));
- case 26:
- _context5.prev = 26;
- _context5.t0 = _context5["catch"](12);
- return _context5.abrupt("return", (g.isLoading = !1, this._room.emit("avatarChanged", {
- avatars: this._room.avatars
- }), logger.error(_context5.t0), Promise.reject(_context5.t0)));
- case 29:
- case "end":
- return _context5.stop();
- }
- }
- }, _callee5, this, [[12, 26]]);
- }));
- function addAvatar(_x4) {
- return _addAvatar.apply(this, arguments);
- }
- return addAvatar;
- }()
- }, {
- key: "removeAvatar",
- value: function removeAvatar(e) {
- var t = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : !1;
- var r = this.avatars.get(e);
- if (!!r) {
- if (r.removeWhenDisconnected || t) {
- r.xAvatar && this.xAvatarManager.deleteAvatar(r.xAvatar), this.avatars.delete(e), this._room.emit("avatarChanged", {
- avatars: this._room.avatars
- });
- return;
- }
- r.setConnectionStatus(!0);
- }
- }
- }, {
- key: "clearOtherUsers",
- value: function clearOtherUsers() {
- var _this5 = this;
- this.avatars.forEach(function (e) {
- !e.isSelf && e.group === AvatarGroup.User && _this5.removeAvatar(e.userId);
- });
- }
- }, {
- key: "_updateAvatarMovingStatus",
- value: function () {
- var _updateAvatarMovingStatus2 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee6(e) {
- var t, r, n, o, a, _a;
- return regenerator.wrap(function _callee6$(_context6) {
- while (1) {
- switch (_context6.prev = _context6.next) {
- case 0:
- t = e.id, r = e.isMoving, n = e.isRotating, o = this.avatars.get(t);
- if (!!o) {
- if (o.isRotating !== n) {
- o.isRotating = n;
- a = "Idle";
- n && (a = "Walking", o.motionType === MotionType.Run && (a = "Running")), o._playAnimation(a, !0, !0), logger.infoAndReportMeasurement({
- startTime: Date.now(),
- value: 0,
- metric: n ? "userAvatarStartRotating" : "userAvatarStopRotating",
- extra: {
- motionType: o.motionType,
- moveToExtra: this._room.moveToExtra
- }
- });
- }
- if (o.isMoving !== r) {
- o.isMoving = r;
- _a = "Idle";
- r && (_a = "Walking", o.motionType === MotionType.Run && (_a = "Running")), r ? (o.avatarStartMovingHook(), o.emit("startMoving", {
- target: o,
- extra: this._room.moveToExtra
- })) : (o.avatarStopMovingHook(), o.emit("stopMoving", {
- target: o,
- extra: this._room.moveToExtra
- })), o._playAnimation(_a, !0, !0), logger.infoAndReportMeasurement({
- startTime: Date.now(),
- value: 0,
- metric: r ? "userAvatarStartMoving" : "userAvatarStopMoving",
- extra: {
- motionType: o.motionType,
- moveToExtra: this._room.moveToExtra
- }
- });
- }
- }
- case 2:
- case "end":
- return _context6.stop();
- }
- }
- }, _callee6, this);
- }));
- function _updateAvatarMovingStatus(_x5) {
- return _updateAvatarMovingStatus2.apply(this, arguments);
- }
- return _updateAvatarMovingStatus;
- }()
- }, {
- key: "_usersStatistics",
- value: function _usersStatistics() {
- var _this6 = this;
- this.on("userAvatarLoaded", function () {
- window.setInterval(function () {
- var e = _this6._room.avatars.filter(function (r) {
- return r.group === AvatarGroup.User;
- }).length || 0,
- t = _this6._room.avatars.filter(function (r) {
- return r.group === AvatarGroup.User && r.isRender;
- }).length || 0;
- _this6._room.stats.assign({
- userNum: e,
- syncUserNum: _this6.syncAvatarsLength,
- renderedUserNum: t
- });
- }, 3e3);
- });
- }
- }]);
- return XverseAvatarManager;
- }(EventEmitter);
- var PathManager = /*#__PURE__*/function () {
- function PathManager() {
- _classCallCheck(this, PathManager);
- this.currentArea = '';
- this.currentPathName = '';
- this.currentAttitude = '';
- this.speed = 0;
- }
- _createClass(PathManager, [{
- key: "getSpeed",
- value: function getSpeed(e) {
- var t = {
- guangchang: {
- [MotionType.Walk]: 17,
- [MotionType.Run]: 51
- },
- tower: {
- [MotionType.Walk]: 12.5,
- [MotionType.Run]: 25
- },
- zhiboting: {
- [MotionType.Walk]: 12.5,
- [MotionType.Run]: 25
- },
- youxiting: {
- [MotionType.Walk]: 12.5,
- [MotionType.Run]: 25
- },
- diqing: {
- [MotionType.Walk]: 12.5,
- [MotionType.Run]: 25
- }
- },
- r = t[this.currentArea] || t.guangchang;
- return this.speed = r[e] * 30, this.speed;
- }
- }]);
- return PathManager;
- }();
- var CameraStates = {
- Normal: 0,
- ItemView: 1,
- CGView: 2,
- PathView: 3
- };
- var Person$1 = {
- Third: 0,
- First: 1
- };
- function _createSuper$c(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$c(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
- function _isNativeReflectConstruct$c() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
- var Camera = /*#__PURE__*/function (_EventEmitter) {
- _inherits(Camera, _EventEmitter);
- var _super = _createSuper$c(Camera);
- function Camera(e) {
- var _this;
- _classCallCheck(this, Camera);
- _this = _super.call(this);
- _this.initialFov = 0;
- _this._state = CameraStates.Normal;
- _this._person = Person$1.Third;
- _this._cameraFollowing = !0;
- _this._room = e;
- return _this;
- }
- _createClass(Camera, [{
- key: "checkPointOnLeftOrRight",
- value: function checkPointOnLeftOrRight(e) {
- var t = ue4Position2Xverse(e);
- if (!t || this.checkPointInView(e)) return;
- var o = this._room.scene.activeCamera;
- if (!o) return;
- var a = [o.target.x, o.target.y, o.target.z],
- s = [o.position.x, o.position.y, o.position.z],
- l = t.x,
- u = t.y,
- c = t.z,
- h = calNormVector(s, a),
- f = calNormVector(s, [l, u, c]);
- return vectorCrossMulti(h, f) < 0 ? Direction.Right : Direction.Left;
- }
- }, {
- key: "checkPointInView",
- value: function checkPointInView(e, t, r) {
- var n = ue4Position2Xverse({
- x: e,
- y: t,
- z: r
- });
- if (!n) return !1;
- for (var o = 0; o < 6; o++) {
- if (this._room.scene.frustumPlanes[o].dotCoordinate(n) < 0) return !1;
- }
- return !0;
- }
- }, {
- key: "person",
- get: function get() {
- return this._person;
- }
- }, {
- key: "state",
- get: function get() {
- return this._state;
- }
- }, {
- key: "pose",
- get: function get() {
- return this._room.currentClickingState.camera;
- }
- }, {
- key: "cameraFollowing",
- get: function get() {
- return this._cameraFollowing;
- },
- set: function set(e) {
- logger.info("cameraFollowing setter", e), this.setCameraFollowing({
- isFollowHost: e
- });
- }
- }, {
- key: "setCameraFollowing",
- value: function setCameraFollowing(_ref) {
- _ref.isFollowHost;
- }
- }, {
- key: "handleRenderInfo",
- value: function handleRenderInfo(e) {
- var t = e.renderInfo.cameraStateType,
- r = this._room.sceneManager;
- if (t !== this._state && (this._state = t, logger.debug("camera._state changed to", CameraStates[t]), t === CameraStates.CGView ? (r.cameraComponent.switchToCgCamera(), r.staticmeshComponent.getCgMesh().show()) : (r.cameraComponent.switchToMainCamera(), r.staticmeshComponent.getCgMesh().hide()), this.emit("stateChanged", {
- state: t
- })), this._room.isHost) return;
- var n = e.playerState.isFollowHost;
- !!n !== this._cameraFollowing && (this._cameraFollowing = !!n, this.emit("cameraFollowingChanged", {
- cameraFollowing: !!n
- }));
- }
- }, {
- key: "setCameraState",
- value: function setCameraState(_ref2) {
- var e = _ref2.state;
- if (this._state === e) {
- logger.warn("You are already in ".concat(CameraStates[e], " camera state"));
- return;
- }
- e === CameraStates.Normal || this._state === CameraStates.ItemView && logger.warn("CloseUp camera state can only be triggerd by room internally");
- }
- }, {
- key: "turnToFace",
- value: function turnToFace(_ref3) {
- var _ref3$extra = _ref3.extra,
- e = _ref3$extra === void 0 ? "" : _ref3$extra,
- _ref3$offset = _ref3.offset,
- t = _ref3$offset === void 0 ? 0 : _ref3$offset;
- var r = {
- action_type: Actions.TurnToFace,
- turn_to_face_action: {
- offset: t
- }
- };
- return this.emit("viewChanged", {
- extra: e
- }), this._room.actionsHandler.sendData({
- data: r
- });
- }
- }, {
- key: "isInDefaultView",
- value: function isInDefaultView() {
- if (!this._room.isHost) {
- logger.warn("It is recommended to call the function on the host side");
- return;
- }
- if (!this._room._currentClickingState) return logger.error("CurrentState should not be empty"), !1;
- var _this$_room$_currentC = this._room._currentClickingState,
- e = _this$_room$_currentC.camera,
- t = _this$_room$_currentC.player;
- return Math.abs(t.angle.yaw - 180 - e.angle.yaw) % 360 <= 4;
- }
- }, {
- key: "screenShot",
- value: function () {
- var _screenShot = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee(_ref4) {
- var e, _ref4$autoSave, t, r, n, o;
- return regenerator.wrap(function _callee$(_context) {
- while (1) {
- switch (_context.prev = _context.next) {
- case 0:
- e = _ref4.name, _ref4$autoSave = _ref4.autoSave, t = _ref4$autoSave === void 0 ? !1 : _ref4$autoSave;
- r = this._room.scene.getEngine(), n = this._room.scene.activeCamera;
- _context.prev = 2;
- this._room.sceneManager.setImageQuality(EImageQuality.high);
- _context.next = 6;
- return CreateScreenshotAsync(r, n, {
- precision: 1
- });
- case 6:
- o = _context.sent;
- return _context.abrupt("return", (this._room.sceneManager.setImageQuality(EImageQuality.low), t === !0 && downloadFileByBase64(o, e), Promise.resolve(o)));
- case 10:
- _context.prev = 10;
- _context.t0 = _context["catch"](2);
- return _context.abrupt("return", (this._room.sceneManager.setImageQuality(EImageQuality.low), Promise.reject(_context.t0)));
- case 13:
- case "end":
- return _context.stop();
- }
- }
- }, _callee, this, [[2, 10]]);
- }));
- function screenShot(_x) {
- return _screenShot.apply(this, arguments);
- }
- return screenShot;
- }()
- }, {
- key: "changeToFirstPerson",
- value: function changeToFirstPerson(e, t, r) {
- var _this2 = this;
- var n = e.camera,
- o = e.player,
- a = e.attitude,
- s = e.areaName,
- l = e.pathName;
- return this._room.actionsHandler.requestPanorama({
- camera: n,
- player: o,
- attitude: a,
- areaName: s,
- pathName: l
- }, t, r).then(function () {
- _this2._room.networkController.rtcp.workers.changePanoMode(!0);
- var _ref5 = o || {},
- u = _ref5.position,
- c = _ref5.angle;
- _this2._room.sceneManager.cameraComponent.changeToFirstPersonView({
- position: u,
- rotation: c
- });
- });
- }
- }, {
- key: "setPerson",
- value: function setPerson(e) {
- var t = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
- camera: this._room._currentClickingState.camera,
- player: this._room._currentClickingState.player
- };
- var r = Date.now();
- return this._setPerson(e, t).then(function (n) {
- return logger.infoAndReportMeasurement({
- tag: Person$1[e],
- startTime: r,
- metric: "setPerson"
- }), n;
- }).catch(function (n) {
- return logger.infoAndReportMeasurement({
- tag: Person$1[e],
- startTime: r,
- metric: "setPerson",
- error: n
- }), Promise.reject(n);
- });
- }
- }, {
- key: "_setPerson",
- value: function _setPerson(e) {
- var _this3 = this;
- var t = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
- camera: this._room._currentClickingState.camera,
- player: this._room._currentClickingState.player
- };
- return e !== Person$1.First && e !== Person$1.Third ? Promise.reject("invalid person " + e) : !t.camera || !t.player ? Promise.reject(new ParamError("wrong camera or player")) : e === Person$1.First ? this._room.panorama.access({
- camera: t.camera,
- player: t.player,
- tag: "setPerson"
- }).then(function () {
- var o, a;
- _this3._person = e, (o = _this3._room._userAvatar) == null || o.hide();
- var _ref6 = ((a = _this3._room.currentClickingState) == null ? void 0 : a.camera) || {},
- r = _ref6.position,
- n = _ref6.angle;
- !r || !n || _this3._room.sceneManager.cameraComponent.changeToFirstPersonView({
- position: r,
- rotation: n
- });
- }) : this._room.panorama.exit({
- camera: t.camera,
- player: t.player
- }).then(function () {
- var r, n;
- _this3._person = e, (r = _this3._room._userAvatar) != null && r.xAvatar && ((n = _this3._room._userAvatar) == null || n.xAvatar.show());
- });
- }
- }, {
- key: "setCameraPose",
- value: function setCameraPose(e) {
- this._room.sceneManager.cameraComponent.setCameraPose({
- position: e.position,
- rotation: e.angle
- });
- }
- }, {
- key: "setMainCameraRotationLimit",
- value: function setMainCameraRotationLimit(e) {
- var t = e.limitAxis,
- r = e.limitRotation;
- this._room.sceneManager.cameraComponent.setMainCameraRotationLimit(t, r);
- }
- }]);
- return Camera;
- }(EventEmitter);
- function _createSuper$b(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$b(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
- function _isNativeReflectConstruct$b() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
- var numberFormat = new Intl.NumberFormat(window.navigator.language, {
- maximumFractionDigits: 0
- });
- var Stats = /*#__PURE__*/function (_EventEmitter) {
- _inherits(Stats, _EventEmitter);
- var _super = _createSuper$b(Stats);
- function Stats(e) {
- var _this;
- _classCallCheck(this, Stats);
- _this = _super.call(this);
- _this._netInterval = null;
- _this._disabled = !1;
- _this._show = !1;
- _this._aggregatedStats = {};
- _this._displayElement = null;
- _this._extraStats = {};
- _this._networkSamples = [];
- _this.externalStats = null;
- _this.constructedTime = null;
- _this.room = e, _this.constructedTime = Date.now(), _this._interval = window.setInterval(function () {
- var t, r, n;
- _this._disabled || _this.onStats((n = (r = (t = e.networkController) == null ? void 0 : t.rtcp) == null ? void 0 : r.workers) == null ? void 0 : n.uploadDataToServer());
- }, 1e3), _this._netInterval = window.setInterval(function () {
- _this.getIsWeakNet();
- }, NET_INTERVAL * 1e3);
- return _this;
- }
- _createClass(Stats, [{
- key: "isShow",
- get: function get() {
- return this._show;
- }
- }, {
- key: "assign",
- value: function assign(e) {
- Object.assign(this._extraStats, e), ((e == null ? void 0 : e.hb) || (e == null ? void 0 : e.rtt)) && this.startStatsNetSamples();
- }
- }, {
- key: "appendExternalStats",
- value: function appendExternalStats(e) {
- var _this2 = this;
- var t = {};
- if (!e || typeof e != "object") {
- console.warn("appendExternalStats should be plain object");
- return;
- }
- Object.keys(e).forEach(function (r) {
- Object.prototype.hasOwnProperty.call(_this2._aggregatedStats, r) ? console.warn("".concat(r, " is duplicate with internal stats")) : t[r] = e[r];
- }), !(Object.keys(t).length > 10) && (this.externalStats = t);
- }
- }, {
- key: "getRtt",
- value: function getRtt() {
- var e = this._extraStats.rtt;
- return typeof e != "number" ? 0 : e > 999 ? 999 : e;
- }
- }, {
- key: "enable",
- value: function enable() {
- this._disabled = !1;
- }
- }, {
- key: "disable",
- value: function disable() {
- this._disabled = !0;
- }
- }, {
- key: "disableNet",
- value: function disableNet() {
- this._netInterval && window.clearInterval(this._netInterval);
- }
- }, {
- key: "show",
- value: function show() {
- this._show = !0, this._render();
- }
- }, {
- key: "hide",
- value: function hide() {
- this._show = !1, this._displayElement && document.body.removeChild(this._displayElement), this._displayElement = null;
- }
- }, {
- key: "getIsWeakNet",
- value: function getIsWeakNet() {
- var _this3 = this;
- var e = !1;
- var t = this._networkSamples.length - 1;
- if (t < 0) return;
- var r = this._networkSamples[t].time,
- n = this._networkSamples[0].time,
- o = r - n,
- a = 1e3 * (DURATION - 2);
- if (o < a) return;
- var s = this._networkSamples.map(function (g) {
- return _this3.isNetDelay(g, "rtt");
- }),
- l = this._networkSamples.map(function (g) {
- return _this3.isNetDelay(g, "hb");
- }),
- u = s.reduce(function (g, m) {
- return g + m;
- }, 0),
- c = l.reduce(function (g, m) {
- return g + m;
- }, 0),
- h = Math.floor(u / this._networkSamples.length) * 100,
- f = Math.floor(c / this._networkSamples.length) * 100,
- d = 70;
- (h >= d || f >= d) && (e = !0);
- var _ = this.room.viewMode === "observer" || this.room.viewMode === "serverless";
- e && !_ && (logger.infoAndReportMeasurement({
- metric: "weakNetwork",
- startTime: Date.now(),
- extra: {
- msg: this._networkSamples.slice(20),
- netDelayRTTValues: u,
- netDelayHBValues: c
- }
- }), this.emit("weakNetwork"));
- }
- }, {
- key: "startStatsNetSamples",
- value: function startStatsNetSamples() {
- var _this$_extraStats = this._extraStats,
- e = _this$_extraStats.rtt,
- t = _this$_extraStats.hb;
- if (e || t) {
- var r = {
- rtt: e,
- hb: t,
- time: new Date().getTime()
- };
- this._networkSamples.push(r);
- var n = this._networkSamples.length - 1;
- if (n < 0) return;
- var o = this._networkSamples[n].time,
- a = 1e3 * DURATION;
- this._networkSamples = this._networkSamples.filter(function (s) {
- return s.time > o - a;
- });
- }
- }
- }, {
- key: "isNetDelay",
- value: function isNetDelay(e, t) {
- return t === "rtt" ? e.rtt > RTT_MAX_VALUE ? 1 : 0 : t === "hb" && e.hb > HB_MAX_VALUE ? 1 : 0;
- }
- }, {
- key: "getPreciesTimer",
- value: function getPreciesTimer(e, t) {
- var r = t * 1e3,
- n = new Date().getTime();
- var o = 0;
- o++;
- var a = new Date().getTime() - (n + o * 1e3),
- s = r - a,
- l = setTimeout(function () {
- clearTimeout(l), e();
- }, s);
- }
- }, {
- key: "_render",
- value: function _render() {
- var c, h, f, d, _, g, m, v, y, b, T, C, A, S, P, R, M, x, I, w;
- if (!this._aggregatedStats) return;
- this._displayElement || (this._displayElement = document.createElement("div"), this._displayElement.style.position = "absolute", this._displayElement.style.top = "10px", this._displayElement.style.left = "200px", this._displayElement.style.width = "200px", this._displayElement.style.backgroundColor = "rgba(0,0,0,.5)", this._displayElement.style.color = "white", this._displayElement.style.textAlign = "left", this._displayElement.style.fontSize = "8px", this._displayElement.style.lineHeight = "10px", document.body.appendChild(this._displayElement));
- var e = [],
- t = Date.now() - this.constructedTime,
- r = Math.floor(t / 1e3 % 60),
- n = Math.floor(t / (1e3 * 60) % 60),
- o = Math.floor(t / (1e3 * 60 * 60) % 24),
- a = o < 10 ? "0" + o.toString() : o.toString(),
- s = n < 10 ? "0" + n : n,
- l = r < 10 ? "0" + r : r;
- e.push({
- key: new Date(Math.floor(this._aggregatedStats.timestamp || 0)).toLocaleString("en-GB"),
- value: a + ":" + s + ":" + l
- }), e.push({
- key: "rtt: " + this._extraStats.rtt + " hb: " + this._extraStats.hb,
- value: "FPS: " + this._extraStats.fps + " avatar: " + ((c = this.room._userAvatar) == null ? void 0 : c.state)
- }), e.push({
- key: "SDK: " + Xverse$1.SUB_PACKAGE_VERSION,
- value: "ENGINE:" + VERSION$1 + " uid:" + this._extraStats.userId
- }), e.push({
- key: "\u540C\u6B65/\u6709\u6548/\u663E\u793A\u73A9\u5BB6",
- value: "".concat(this._extraStats.syncUserNum || 0, "/").concat(this._extraStats.userNum || 0, "/").concat(this._extraStats.renderedUserNum || 0)
- }), e.push({
- key: "media/meta bitrate(kbps)",
- value: numberFormat.format(this._aggregatedStats.mediaBitrate || 0) + "/" + numberFormat.format(this._aggregatedStats.metaBitrate || 0)
- }), e.push({
- key: ":----------------Decoding---------------",
- value: ""
- }), e.push({
- key: "-max/avg decodeTime(ms)",
- value: numberFormat.format(this._aggregatedStats.decodeTimeMaxFrame || 0) + "/" + numberFormat.format(this._aggregatedStats.decodeTimePerFrame || 0)
- }), e.push({
- key: "-frmAwait/Lost/Drop",
- value: numberFormat.format(this._aggregatedStats.framesAwait || 0) + "/" + numberFormat.format(this._aggregatedStats.packetsLost || 0) + "/" + numberFormat.format(this._aggregatedStats.packetsDrop || 0) + "/" + numberFormat.format(this._aggregatedStats.updateDropFrame) || 0
- }), e.push({
- key: ":----------------FrameLoop-------------",
- value: ""
- }), e.push({
- key: "interval(max/avg/>40)",
- value: (((h = this._extraStats.maxFrameTime) == null ? void 0 : h.toFixed(1)) || 0) + "/" + (((f = this._extraStats.avgFrameTime) == null ? void 0 : f.toFixed(0)) || 0) + "/" + this._extraStats.engineSloppyCnt
- }), e.push({
- key: "systemStuck",
- value: this._extraStats.systemStuckCnt
- }), e.push({
- key: "--update",
- value: (this._aggregatedStats.maxGraphicTime.toFixed(1) || 0) + "/" + (((d = this._aggregatedStats.averageGraphicTime) == null ? void 0 : d.toFixed(0)) || 0)
- }), e.push({
- key: "--timeout",
- value: (((_ = this._extraStats.maxTimeoutTime) == null ? void 0 : _.toFixed(1)) || 0) + "/" + ((g = this._extraStats.avgTimeoutTime) == null ? void 0 : g.toFixed(0)) || 0
- }), e.push({
- key: "--render",
- value: (((m = this._extraStats.maxRenderFrameTime) == null ? void 0 : m.toFixed(1)) || 0) + "/" + (((v = this._extraStats.renderFrameTime) == null ? void 0 : v.toFixed(0)) || 0)
- }), e.push({
- key: "---anim/regBR/clip(avg ms)",
- value: (this._extraStats.animationTime.toFixed(2) || 0) + " / " + (this._extraStats.registerBeforeRenderTime.toFixed(2) || 0) + " / " + (this._extraStats.meshSelectTime.toFixed(2) || 0)
- }), e.push({
- key: "---anim/regBR/clip(max ms)",
- value: (this._extraStats.maxAnimationTime.toFixed(2) || 0) + " / " + (this._extraStats.maxRegisterBeforeRenderTime.toFixed(2) || 0) + " / " + (this._extraStats.maxMeshSelectTime.toFixed(2) || 0)
- }), e.push({
- key: "---rTR/drC/regAF(avg ms)",
- value: (this._extraStats.renderTargetRenderTime.toFixed(2) || 0) + " / " + (this._extraStats.drawcallTime.toFixed(2) || 0) + " / " + (this._extraStats.registerAfterRenderTime.toFixed(2) || 0)
- }), e.push({
- key: "---rTR/drC/regAF(max ms)",
- value: (this._extraStats.maxRenderTargetRenderTime.toFixed(2) || 0) + " / " + (this._extraStats.maxDrawcallTime.toFixed(2) || 0) + " / " + (this._extraStats.maxRegisterAfterRenderTime.toFixed(2) || 0)
- }), e.push({
- key: "--tri/drC/pati/bones/anim(Num)",
- value: (this._extraStats.triangle || 0) + " / " + (this._extraStats.drawcall.toFixed(0) || 0) + " / " + (this._extraStats.activeParticles.toFixed(0) || 0) + " / " + (this._extraStats.activeBones.toFixed(0) || 0) + " / " + (this._extraStats.activeAnimation.toFixed(0) || 0)
- }), e.push({
- key: "--rootN/mesh/geo/tex/mat(Num)",
- value: (this._extraStats.totalRootNodes.toFixed(0) || 0) + " / " + (this._extraStats.totalMeshes.toFixed(0) || 0) + " / " + (this._extraStats.totalGeometries.toFixed(0) || 0) + " / " + (this._extraStats.totalTextures.toFixed(0) || 0) + " / " + (this._extraStats.totalMaterials.toFixed(0) || 0)
- }), e.push({
- key: "--registerBF/AF(Num)",
- value: (this._extraStats.registerBeforeCount.toFixed(0) || 0) + " / " + (this._extraStats.registerAfterCount.toFixed(0) || 0)
- }), e.push({
- key: ":----------------Rotation-------------------",
- value: ""
- }), e.push({
- key: "Total(ms/miss)",
- value: (((y = this._aggregatedStats.avgOverallTime) == null ? void 0 : y.toFixed(2)) || 0) + "/" + (this._aggregatedStats.responseMissPs + this._aggregatedStats.processMissPs + this._aggregatedStats.displayMissPs)
- }), e.push({
- key: "--rotateRsp",
- value: (((b = this._aggregatedStats.avgResponseTime) == null ? void 0 : b.toFixed(1)) || 0) + "/" + this._aggregatedStats.responseMissPs
- }), e.push({
- key: "--rotateProc",
- value: (((T = this._aggregatedStats.avgProcessTime) == null ? void 0 : T.toFixed(1)) || 0) + "/" + this._aggregatedStats.processMissPs
- }), e.push({
- key: "--rotateShow",
- value: (((C = this._aggregatedStats.avgDisplayTime) == null ? void 0 : C.toFixed(1)) || 0) + "/" + this._aggregatedStats.displayMissPs
- }), ((A = this.room._userAvatar) == null ? void 0 : A.state) == "moving", e.push({
- key: ":----------------Move----------------------",
- value: ""
- }), e.push({
- key: "-startDelay",
- value: (this._aggregatedStats.moveEvent == "MoveTo" ? this._aggregatedStats.moveResponseDelay || 0 : this._aggregatedStats.flyResponseDelay || 0) + "/" + (this._aggregatedStats.moveEvent == "MoveTo" ? this._aggregatedStats.moveProcessDelay || 0 : this._aggregatedStats.flyProcessDelay || 0) + "/" + (this._aggregatedStats.moveEvent == "MoveTo" ? this._aggregatedStats.moveDisplayDelay || 0 : this._aggregatedStats.flyDisplayDelay || 0)
- }), (((S = this.room._userAvatar) == null ? void 0 : S.state) == "moving" || this._aggregatedStats.moveEvent == "GetOnAirship" || this._aggregatedStats.moveEvent == "GetOnVehicle") && e.push({
- key: "-srvInterFrm(max/avg)",
- value: (this._aggregatedStats.maxServerDiff || 0) + "/" + (this._aggregatedStats.avgServerDiff.toFixed(1) || 0)
- }), e.push({
- key: "-interFrameDelay",
- value: "(max/avg/jank)"
- }), e.push({
- key: "--toDisplay",
- value: (this._aggregatedStats.moveEvent == "MoveTo" ? this._aggregatedStats.maxDisplayMoveDiff || 0 : this._aggregatedStats.maxDisplayFlyDiff || 0) + "/" + (this._aggregatedStats.moveEvent == "MoveTo" ? this._aggregatedStats.avgDisplayMoveDiff.toFixed(1) || 0 : this._aggregatedStats.avgDisplayFlyDiff.toFixed(1) || 0) + "/" + (this._aggregatedStats.moveEvent == "MoveTo" ? ((P = this._aggregatedStats.moveDisplayJank) == null ? void 0 : P.toFixed(3)) || 0 : ((R = this._aggregatedStats.flyDisplayJank) == null ? void 0 : R.toFixed(3)) || 0)
- }), e.push({
- key: "--received",
- value: (this._aggregatedStats.moveEvent == "MoveTo" ? this._aggregatedStats.maxResponseMoveDiff || 0 : this._aggregatedStats.maxResponseFlyDiff || 0) + "/" + (this._aggregatedStats.moveEvent == "MoveTo" ? this._aggregatedStats.avgResponseMoveDiff.toFixed(1) || 0 : this._aggregatedStats.avgResponseFlyDiff.toFixed(1) || 0) + "/" + (this._aggregatedStats.moveEvent == "MoveTo" ? ((M = this._aggregatedStats.moveResponseJank) == null ? void 0 : M.toFixed(3)) || 0 : ((x = this._aggregatedStats.flyResponseJank) == null ? void 0 : x.toFixed(3)) || 0)
- }), e.push({
- key: "--decoded",
- value: (this._aggregatedStats.moveEvent == "MoveTo" ? this._aggregatedStats.maxProcessMoveDiff || 0 : this._aggregatedStats.maxProcessFlyDiff || 0) + "/" + (this._aggregatedStats.moveEvent == "MoveTo" ? this._aggregatedStats.avgProcessMoveDiff.toFixed(1) || 0 : this._aggregatedStats.avgProcessFlyDiff.toFixed(1) || 0) + "/" + (this._aggregatedStats.moveEvent == "MoveTo" ? ((I = this._aggregatedStats.moveProcessJank) == null ? void 0 : I.toFixed(3)) || 0 : ((w = this._aggregatedStats.flyProcessJank) == null ? void 0 : w.toFixed(3)) || 0)
- }), e.push({
- key: ":----------------DevInfo-----------------",
- value: ""
- }), e.push({
- key: "sd",
- value: (this._aggregatedStats.sdMoveResponseLongTime.toFixed(1) || 0) + "/" + (this._aggregatedStats.sdMoveProcessLongTime.toFixed(1) || 0) + "/" + (this._aggregatedStats.sdMoveDisplayLongTime.toFixed(1) || 0)
- }), e.push({
- key: "----hardwareInfo",
- value: this._extraStats.hardwareInfo
- });
- var u = "";
- for (var _i = 0, _e = e; _i < _e.length; _i++) {
- var O = _e[_i];
- u += "<div><span>".concat(O.key, "</span>: <span>").concat(O.value, "</span> </div>");
- }
- this._displayElement.innerHTML = u;
- }
- }, {
- key: "onStats",
- value: function onStats(e) {
- var _this4 = this;
- var n;
- if (!e) return;
- var t = {},
- r = this;
- r._aggregatedStats || (r._aggregatedStats = {}), t.timestamp = e.timestamp, t.mediaBytesReceived = e.mediaBytesReceived, t.metaBytesReceived = e.metaBytesReceived, t.packetsLost = e.packetsLost, t.frameHeight = e.frameHeight, t.frameWidth = e.frameWidth, t.framesReceivedUI = e.framesReceived, t.framesReceived = e.framesReceivedWorker, t.framesDecoded = e.framesDecoded, t.framesEmited = e.framesEmited, t.decodeTimePerFrame = e.decodeTimePerFrame, t.decodeTimeMaxFrame = e.decodeTimeMaxFrame, t.packetsDrop = e.packetsDrop, t.framesAwait = e.framesAwait, t.updateDropFrame = e.updateDropFrame, t.firstMediaArraval = e.firstMediaArraval, t.firstYUVDecoded = e.firstYUVDecoded, t.firstRender = e.firstRender, t.returnFrames = e.returnFrames, t.sendOutBuffer = e.sendOutBuffer, t.averageGraphicTime = e.averageGraphicTime, t.maxGraphicTime = e.maxGraphicTime, t.jankTimes = e.jankTimes, t.bigJankTimes = e.bigJankTimes, t.decodeJankTimes = e.decodeJankTimes, t.bigDecodeJankTimes = e.bigDecodeJankTimes, t.serverFrameFast = e.serverFrameFast, t.serverFrameSlow = e.serverFrameSlow, t.clientFrameFast = e.clientFrameFast, t.clientFrameSlow = e.clientFrameSlow, t.rtcMessageReceived = e.rtcMessageReceived, t.rtcBytesReceived = e.rtcBytesReceived, t.receiveIframes = e.receiveIframes, t.decodeIframes = e.decodeIframes, t.avgResponseTime = e.avgResponseTime, t.avgProcessTime = e.avgProcessTime, t.avgDisplayTime = e.avgDisplayTime, t.avgOverallTime = e.avgOverallTime, t.overallTimeCount = e.overallTimeCount, t.responseMiss = e.responseMiss, t.processMiss = e.processMiss, t.displayMiss = e.displayMiss, t.avgResponseMoveDiff = e.avgResponseMoveDiff, t.avgProcessMoveDiff = e.avgProcessMoveDiff, t.avgDisplayMoveDiff = e.avgDisplayMoveDiff, t.maxResponseMoveDiff = e.maxResponseMoveDiff, t.maxProcessMoveDiff = e.maxProcessMoveDiff, t.maxDisplayMoveDiff = e.maxDisplayMoveDiff, t.moveResponseDelay = e.moveResponseDelay, t.moveProcessDelay = e.moveProcessDelay, t.moveDisplayDelay = e.moveDisplayDelay, t.moveResponseJank = e.moveResponseJank, t.moveProcessJank = e.moveProcessJank, t.moveDisplayJank = e.moveDisplayJank, t.avgMetaParseTime = e.avgMetaParseTime, t.maxMetaParseTime = e.maxMetaParseTime, t.moveResponseCounts = e.moveResponseCounts, t.moveProcessCounts = e.moveProcessCounts, t.moveDisplayCounts = e.moveDisplayCounts, t.MoveDisplayCountGood = e.MoveDisplayCountGood, t.MoveDisplayCountWell = e.MoveDisplayCountWell, t.MoveDisplayCountFair = e.MoveDisplayCountFair, t.MoveDisplayCountBad = e.MoveDisplayCountBad, t.MoveDisplayCountRest = e.MoveDisplayCountRest, t.avgServerDiff = e.avgServerDiff, t.maxServerDiff = e.maxServerDiff, t.avgResponseFlyDiff = e.avgResponseFlyDiff, t.avgProcessFlyDiff = e.avgProcessFlyDiff, t.avgDisplayFlyDiff = e.avgDisplayFlyDiff, t.maxResponseFlyDiff = e.maxResponseFlyDiff, t.maxProcessFlyDiff = e.maxProcessFlyDiff, t.maxDisplayFlyDiff = e.maxDisplayFlyDiff, t.flyResponseCounts = e.flyResponseCounts, t.flyProcessCounts = e.flyProcessCounts, t.flyDisplayCounts = e.flyDisplayCounts, t.flyResponseJank = e.flyResponseJank, t.flyProcessJank = e.flyProcessJank, t.flyDisplayJank = e.flyDisplayJank, t.flyResponseDelay = e.flyResponseDelay, t.flyProcessDelay = e.flyProcessDelay, t.flyDisplayDelay = e.flyDisplayDelay, t.moveEvent = e.moveEvent, t.sdMoveResponseLongTime = e.sdMoveResponseLongTime, t.sdMoveProcessLongTime = e.sdMoveProcessLongTime, t.sdMoveDisplayLongTime = e.sdMoveDisplayLongTime, r._aggregatedStats && r._aggregatedStats.timestamp && (t.mediaBitrate = 8 * (t.mediaBytesReceived - r._aggregatedStats.mediaBytesReceived) / 1e3, t.mediaBitrate = Math.round(t.mediaBitrate || 0), t.metaBitrate = 8 * (t.metaBytesReceived - r._aggregatedStats.metaBytesReceived) / 1e3, t.metaBitrate = Math.round(t.metaBitrate || 0), t.rtcMessagePs = t.rtcMessageReceived - r._aggregatedStats.rtcMessageReceived, t.rtcBitrate = 8 * (t.rtcBytesReceived - r._aggregatedStats.rtcBytesReceived) / 1e3, t.rtcBitrate = Math.round(t.rtcBitrate || 0), t.framesEmitedPs = t.framesEmited - r._aggregatedStats.framesEmited, t.framesEmitedPs = Math.round(t.framesEmitedPs || 0), t.framesReceivedPs = t.framesReceived - r._aggregatedStats.framesReceived, t.framesReceivedPs = Math.round(t.framesReceivedPs || 0), t.framesDecodedPs = t.framesDecoded - r._aggregatedStats.framesDecoded, t.framesDecodedPs = Math.round(t.framesDecodedPs || 0), t.returnFramesPs = t.returnFrames - r._aggregatedStats.returnFrames, t.returnFramesPs = Math.round(t.returnFramesPs || 0), t.responseMissPs = t.responseMiss - r._aggregatedStats.responseMiss, t.processMissPs = t.processMiss - r._aggregatedStats.processMiss, t.displayMissPs = t.displayMiss - r._aggregatedStats.displayMiss, t.returnFrames = e.returnFrames), this._show && this._render(), t.registerBeforeRenderTime = this._extraStats.registerBeforeRenderTime, t.registerAfterRenderTime = this._extraStats.registerAfterRenderTime, t.renderTargetRenderTime = this._extraStats.renderTargetRenderTime, t.renderFrameTime = this._extraStats.renderFrameTime, t.maxRenderFrameTime = this._extraStats.maxRenderFrameTime, t.interFrameTime = this._extraStats.interFrameTime, t.animationTime = this._extraStats.animationTime, t.meshSelectTime = this._extraStats.meshSelectTime, t.drawcall = this._extraStats.drawcall, t.drawcallTime = this._extraStats.drawcallTime, t.triangle = this._extraStats.triangle, t.registerAfterCount = this._extraStats.registerAfterCount, t.registerBeforeCount = this._extraStats.registerBeforeCount, t.fps = this._extraStats.fps, t.rtt = this._extraStats.rtt, t.hb = this._extraStats.hb, t.avgFrameTime = this._extraStats.avgFrameTime, t.avgTimeoutTime = this._extraStats.avgTimeoutTime, t.engineSloppyCnt = this._extraStats.engineSloppyCnt, t.systemStuckCnt = this._extraStats.systemStuckCnt, t.avatarState = (n = this.room._userAvatar) == null ? void 0 : n.state, t.maxFrameTime = this._extraStats.maxFrameTime, t.maxTimeoutTime = this._extraStats.maxTimeoutTime, t.activeParticles = this._extraStats.activeParticles, t.activeBones = this._extraStats.activeBones, t.activeAnimation = this._extraStats.activeAnimation, t.totalRootNodes = this._extraStats.totalRootNodes, t.totalGeometries = this._extraStats.totalGeometries, t.totalMeshes = this._extraStats.totalMeshes, t.totalTextures = this._extraStats.totalTextures, t.totalMaterials = this._extraStats.totalMaterials, t.hardwareInfo = this._extraStats.hardwareInfo, t.maxInterFrameTime = this._extraStats.maxInterFrameTime, t.maxDrawcallTime = this._extraStats.maxDrawcallTime, t.maxMeshSelectTime = this._extraStats.maxMeshSelectTime, t.maxAnimationTime = this._extraStats.maxAnimationTime, t.maxRegisterBeforeRenderTime = this._extraStats.maxRegisterBeforeRenderTime, t.maxRegisterAfterRenderTime = this._extraStats.maxRegisterAfterRenderTime, t.maxRenderTargetRenderTime = this._extraStats.maxRenderTargetRenderTime, this.externalStats && Object.keys(this.externalStats || {}).forEach(function (o) {
- t[o] = _this4.externalStats[o];
- }), r._aggregatedStats = t, this.emit("stats", {
- stats: t
- });
- }
- }]);
- return Stats;
- }(EventEmitter);
- var Actions$1 = {
- Clicking: 1,
- PlayCG: 6,
- Back: 7,
- ChangeRoom: 8,
- ChangeSkin: 13,
- Joystick: 15,
- Transfer: 18,
- GetOnVehicle: 22,
- GetOffVehicle: 23,
- StopMoving: 34,
- UnaryActionLine: 1e3,
- Init: 1001,
- Exit: 1002,
- SetIFrameInfo: 1003,
- GetNeighborPoints: 1004,
- ReserveSeat: 1005,
- GetReserveStatus: 1006,
- ChangeNickname: 1007,
- ChangeBitRateInfo: 1008,
- Echo: 1009,
- SetPlayerState: 1010,
- TurnTo: 1011,
- TurnToFace: 1012,
- RotateTo: 1013,
- Rotation: 1014,
- CameraTurnTo: 1015,
- ConfirmEvent: 1016,
- Broadcast: 1017,
- NotifyActionLine: 2e4,
- AudienceChangeToVisitor: 1020,
- VisitorChangeToAudience: 1021,
- RemoveVisitor: 1022,
- GetUserWithAvatar: 1023
- };
- var ActionsHandler = /*#__PURE__*/function () {
- function ActionsHandler(e) {
- _classCallCheck(this, ActionsHandler);
- this.currentActiveAction = null;
- this.room = e;
- }
- _createClass(ActionsHandler, [{
- key: "avatarComponentsSync",
- value: function () {
- var _avatarComponentsSync = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee(e) {
- var t;
- return regenerator.wrap(function _callee$(_context) {
- while (1) {
- switch (_context.prev = _context.next) {
- case 0:
- t = {
- action_type: Actions$1.SetPlayerState,
- set_player_state_action: {
- player_state: {
- avatar_components: JSON.stringify(e)
- }
- }
- };
- this.sendData({
- data: t
- });
- case 2:
- case "end":
- return _context.stop();
- }
- }
- }, _callee, this);
- }));
- function avatarComponentsSync(_x) {
- return _avatarComponentsSync.apply(this, arguments);
- }
- return avatarComponentsSync;
- }()
- }, {
- key: "sendData",
- value: function () {
- var _sendData = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee2(e) {
- var _this = this;
- var t, _e$sampleRate, r, _e$timeout, n, o, a, s;
- return regenerator.wrap(function _callee2$(_context2) {
- while (1) {
- switch (_context2.prev = _context2.next) {
- case 0:
- _context2.next = 2;
- return this.beforeSend(e);
- case 2:
- t = uuid$1();
- if (!(this.room.networkController.sendRtcData(le(oe({}, e.data), {
- trace_id: t,
- user_id: this.room.options.userId
- })), e.track === !1)) {
- _context2.next = 5;
- break;
- }
- return _context2.abrupt("return", Promise.resolve(null));
- case 5:
- _e$sampleRate = e.sampleRate, r = _e$sampleRate === void 0 ? 1 : _e$sampleRate, _e$timeout = e.timeout, n = _e$timeout === void 0 ? 2e3 : _e$timeout, o = e.tag, a = e.data, s = e.special;
- return _context2.abrupt("return", eventsManager.track({
- timeout: n,
- traceId: t,
- event: a.action_type,
- tag: o,
- extra: a
- }, {
- special: s,
- sampleRate: r,
- noReport: this.room.viewMode === "serverless" || this.room.options.viewMode === "serverless"
- }).finally(function () {
- QueueActions.includes(e.data.action_type) && (_this.currentActiveAction = void 0);
- }));
- case 7:
- case "end":
- return _context2.stop();
- }
- }
- }, _callee2, this);
- }));
- function sendData(_x2) {
- return _sendData.apply(this, arguments);
- }
- return sendData;
- }()
- }, {
- key: "beforeSend",
- value: function () {
- var _beforeSend = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee3(e) {
- var o, t, r;
- return regenerator.wrap(function _callee3$(_context3) {
- while (1) {
- switch (_context3.prev = _context3.next) {
- case 0:
- t = (o = this.room._userAvatar) == null ? void 0 : o.isMoving, r = e.data.action_type;
- if (!QueueActions.includes(r)) {
- _context3.next = 5;
- break;
- }
- if (!this.currentActiveAction) {
- _context3.next = 4;
- break;
- }
- return _context3.abrupt("return", (log$p.error("".concat(Actions$1[this.currentActiveAction], " still pending, reject ").concat(Actions$1[r])), Promise.reject(new FrequencyLimitError("".concat(Actions$1[r], " action request frequency limit")))));
- case 4:
- this.currentActiveAction = r;
- case 5:
- if (!(t && QueueActions.includes(e.data.action_type))) {
- _context3.next = 14;
- break;
- }
- _context3.prev = 6;
- _context3.next = 9;
- return this.stopMoving();
- case 9:
- _context3.next = 14;
- break;
- case 11:
- _context3.prev = 11;
- _context3.t0 = _context3["catch"](6);
- this.currentActiveAction = void 0, log$p.error("before action stopMoving failed", _context3.t0);
- case 14:
- case "end":
- return _context3.stop();
- }
- }
- }, _callee3, this, [[6, 11]]);
- }));
- function beforeSend(_x3) {
- return _beforeSend.apply(this, arguments);
- }
- return beforeSend;
- }()
- }, {
- key: "moveTo",
- value: function () {
- var _moveTo = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee4(e) {
- var t, _e$extra, r, n, o;
- return regenerator.wrap(function _callee4$(_context4) {
- while (1) {
- switch (_context4.prev = _context4.next) {
- case 0:
- t = e.point, _e$extra = e.extra, r = _e$extra === void 0 ? "" : _e$extra, n = e.motionType, o = {
- action_type: Actions$1.Clicking,
- clicking_action: {
- clicking_point: t,
- clicking_type: ClickType.IgnoreView,
- extra: encodeURIComponent(r),
- attitude: n
- },
- clicking_state: this.room._currentClickingState
- };
- return _context4.abrupt("return", this.sendData({
- data: o
- }));
- case 2:
- case "end":
- return _context4.stop();
- }
- }
- }, _callee4, this);
- }));
- function moveTo(_x4) {
- return _moveTo.apply(this, arguments);
- }
- return moveTo;
- }()
- }, {
- key: "transfer",
- value: function transfer(e) {
- var _this2 = this;
- var t = e.renderType,
- r = e.player,
- n = e.camera,
- o = e.areaName,
- a = e.attitude,
- s = e.pathName,
- l = e.person,
- u = e.noMedia,
- c = e.timeout,
- h = e.tag,
- f = e.special,
- d = {
- data: {
- action_type: Actions$1.Transfer,
- transfer_action: {
- render_type: t,
- player: r,
- camera: n,
- areaName: o,
- attitude: a,
- pathName: s,
- person: {
- type: l
- },
- noMedia: u,
- tiles: [0, 1, 2, 4]
- }
- },
- special: f,
- timeout: c || 4e3,
- tag: h
- };
- return this.sendData(d).then(function (_) {
- return typeof l != "undefined" && _this2.room.updateCurrentNetworkOptions({
- person: l,
- rotationRenderType: t
- }), _;
- });
- }
- }, {
- key: "changeRotationRenderType",
- value: function changeRotationRenderType(e) {
- var t = e.renderType,
- r = e.player,
- n = e.camera,
- o = e.areaName,
- a = e.attitude,
- s = e.pathName;
- return this.transfer({
- renderType: t,
- player: r,
- camera: n,
- areaName: o,
- attitude: a,
- pathName: s,
- tag: "changeToRotationVideo"
- });
- }
- }, {
- key: "requestPanorama",
- value: function requestPanorama(e, t, r) {
- var n = e.camera,
- o = e.player,
- a = e.areaName,
- s = e.attitude,
- l = e.pathName,
- u = e.tag;
- return this.transfer({
- renderType: RenderType.ClientRotationPano,
- player: o,
- camera: n,
- person: Person.First,
- areaName: a,
- attitude: s,
- pathName: l,
- noMedia: t,
- timeout: r,
- tag: u || "requestPanorama",
- special: !t
- });
- }
- }, {
- key: "setMotionType",
- value: function setMotionType(e) {
- return this.transfer({
- attitude: e,
- tag: "setMotionType"
- });
- }
- }, {
- key: "setNickName",
- value: function setNickName(e) {
- var t = {
- action_type: Actions$1.ChangeNickname,
- change_nickname_action: {
- nickname: e
- }
- };
- return this.sendData({
- data: t
- });
- }
- }, {
- key: "getReserveSeat",
- value: function getReserveSeat(_ref) {
- var e = _ref.routeId,
- t = _ref.name;
- var r = {
- action_type: Actions$1.ReserveSeat,
- reserve_seat_action: {
- route_id: e,
- name: t
- }
- };
- return this.sendData({
- data: r
- });
- }
- }, {
- key: "getReserveStatus",
- value: function getReserveStatus(_ref2) {
- var e = _ref2.routeId,
- t = _ref2.name,
- r = _ref2.need_detail;
- var n = {
- action_type: Actions$1.GetReserveStatus,
- get_reserve_status_action: {
- route_id: e,
- name: t,
- need_detail: r
- }
- };
- return this.sendData({
- data: n,
- timeout: 2e3
- }).then(function (o) {
- return o.reserveDetail;
- });
- }
- }, {
- key: "stopMoving",
- value: function stopMoving() {
- var e = {
- action_type: Actions$1.StopMoving,
- stop_move_action: {}
- };
- return this.sendData({
- data: e
- });
- }
- }, {
- key: "getOnVehicle",
- value: function getOnVehicle(_ref3) {
- var e = _ref3.routeId,
- t = _ref3.name,
- r = _ref3.camera;
- var n = {
- action_type: Actions$1.GetOnVehicle,
- get_on_vehicle_action: {
- route_id: e,
- name: t,
- camera: r
- }
- };
- return this.sendData({
- data: n
- });
- }
- }, {
- key: "getOffVehicle",
- value: function getOffVehicle(_ref4) {
- var e = _ref4.renderType,
- t = _ref4.player,
- r = _ref4.camera;
- var n = {
- action_type: Actions$1.GetOffVehicle,
- get_off_vehicle_action: {
- render_type: e,
- player: t,
- camera: r
- }
- };
- return this.sendData({
- data: n
- });
- }
- }, {
- key: "confirmEvent",
- value: function confirmEvent(e) {
- var t = {
- action_type: Actions$1.ConfirmEvent,
- confirm_event_action: {
- id: e
- }
- };
- return this.sendData({
- data: t,
- track: !1
- });
- }
- }, {
- key: "echo",
- value: function echo(e) {
- var t = {
- action_type: Actions$1.Echo,
- echo_msg: {
- echoMsg: e
- }
- };
- return this.sendData({
- data: t,
- track: !1
- });
- }
- }, {
- key: "changeSkin",
- value: function () {
- var _changeSkin = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee6(e) {
- var _this3 = this;
- var t, r, n, _e$landingType, o, a, s, l, u, c, h, f, d, _, _e$roomTypeId, g, m, y, v;
- return regenerator.wrap(function _callee6$(_context6) {
- while (1) {
- switch (_context6.prev = _context6.next) {
- case 0:
- t = e.special === void 0 ? e.renderType === RenderType.ClientRotationPano : e.special, r = e.skinId, n = e.mode, _e$landingType = e.landingType, o = _e$landingType === void 0 ? LandingType.Stay : _e$landingType, a = e.landingPoint, s = e.landingCamera, l = e.renderType, u = e.areaName, c = e.attitude, h = e.pathName, f = e.person, d = e.noMedia, _ = e.timeout, _e$roomTypeId = e.roomTypeId, g = _e$roomTypeId === void 0 ? "" : _e$roomTypeId, m = this.room.skinList.filter(function (y) {
- return y.id === r;
- })[0];
- if (m) {
- _context6.next = 4;
- break;
- }
- y = "skin ".concat(r, " is invalid");
- return _context6.abrupt("return", (log$p.error(y), Promise.reject(new ParamError(y))));
- case 4:
- v = {
- action_type: Actions$1.ChangeSkin,
- change_skin_action: {
- skinID: r,
- mode: n === ChangeMode.Preview ? ChangeMode.Preview : ChangeMode.Confirm,
- skin_data_version: r + m.versionId,
- landing_type: o,
- landing_point: a,
- landing_camera: s,
- render_wrapper: {
- render_type: l
- },
- areaName: u,
- attitude: c,
- noMedia: d,
- person: f,
- pathName: h,
- roomTypeId: g
- }
- };
- return _context6.abrupt("return", this.sendData({
- data: v,
- timeout: _ || 6e3,
- special: t
- }).then( /*#__PURE__*/function () {
- var _ref5 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee5(y) {
- var b, _ref6, T;
- return regenerator.wrap(function _callee5$(_context5) {
- while (1) {
- switch (_context5.prev = _context5.next) {
- case 0:
- if (!(l === RenderType.ClientRotationPano && y)) {
- _context5.next = 8;
- break;
- }
- _context5.next = 3;
- return _this3.room.modelManager.findRoute(r, h);
- case 3:
- b = _context5.sent;
- _ref6 = getRandomItem(b.birthPointList) || {};
- T = _ref6.camera;
- _context5.next = 8;
- return _this3.room.panorama.handleReceivePanorama(y, T);
- case 8:
- return _context5.abrupt("return", _this3.handleChangeSkin(e));
- case 9:
- case "end":
- return _context5.stop();
- }
- }
- }, _callee5);
- }));
- return function (_x6) {
- return _ref5.apply(this, arguments);
- };
- }()).catch(function (y) {
- return d ? _this3.handleChangeSkin(e) : Promise.reject(y);
- }));
- case 6:
- case "end":
- return _context6.stop();
- }
- }
- }, _callee6, this);
- }));
- function changeSkin(_x5) {
- return _changeSkin.apply(this, arguments);
- }
- return changeSkin;
- }()
- }, {
- key: "handleChangeSkin",
- value: function handleChangeSkin(e) {
- var _this4 = this;
- var t = e.skinId,
- r = e.mode,
- n = e.renderType,
- o = e.areaName,
- a = e.attitude,
- s = e.pathName;
- return this.room.sceneManager.staticmeshComponent.getCgMesh().show(), this.room.sceneManager.cameraComponent.switchToCgCamera(), this.room.engineProxy._updateSkinAssets(t).then(function () {
- _this4.room.sceneManager.staticmeshComponent.getCgMesh().hide(), _this4.room.sceneManager.cameraComponent.switchToMainCamera(), _this4.room.pathManager.currentArea = o, log$p.info("changeSkin _updateSkinAssets susccss"), _this4.room.updateCurrentNetworkOptions({
- pathName: s,
- attitude: a,
- areaName: o
- }), _this4.room.skinChangedHook(), _this4.room.emit("skinChanged", {
- skin: {
- id: t
- },
- mode: r
- }), n === RenderType.ClientRotationPano && _this4.room.sceneManager.cameraComponent.allowMainCameraController();
- });
- }
- }, {
- key: "rotate",
- value: function rotate(_ref7) {
- var e = _ref7.pitch,
- t = _ref7.yaw;
- var n;
- if (this.room.disableRotate || this.room.isPano || ((n = this.room._userAvatar) == null ? void 0 : n._isChangingComponentsMode)) return;
- var r = {
- action_type: Actions$1.Rotation,
- rotation_action: {
- vertical_move: e,
- horizontal_move: -t
- }
- };
- this.sendData({
- data: r,
- sampleRate: .02
- });
- }
- }, {
- key: "turnTo",
- value: function turnTo(e) {
- var _ref8 = e || {},
- t = _ref8.point,
- _ref8$timeout = _ref8.timeout,
- r = _ref8$timeout === void 0 ? 2e3 : _ref8$timeout,
- _ref8$offset = _ref8.offset,
- n = _ref8$offset === void 0 ? 8 : _ref8$offset,
- o = {
- action_type: Actions$1.TurnTo,
- turn_to_action: {
- turn_to_point: t,
- offset: n
- }
- };
- return this.sendData({
- data: o,
- timeout: r
- });
- }
- }, {
- key: "rotateTo",
- value: function rotateTo(e) {
- var _ref9 = e || {},
- t = _ref9.point,
- _ref9$offset = _ref9.offset,
- r = _ref9$offset === void 0 ? 0 : _ref9$offset,
- _ref9$speed = _ref9.speed,
- n = _ref9$speed === void 0 ? 3 : _ref9$speed,
- o = {
- action_type: Actions$1.RotateTo,
- rotate_to_action: {
- rotate_to_point: t,
- offset: r,
- speed: n
- }
- };
- return this.sendData({
- data: o
- });
- }
- }, {
- key: "broadcast",
- value: function broadcast(e) {
- var t = e.data,
- _e$msgType = e.msgType,
- r = _e$msgType === void 0 ? MessageHandleType.MHT_FollowListMulticast : _e$msgType,
- n = e.targetUserIds;
- if (r === MessageHandleType.MHT_CustomTargetSync && !Array.isArray(n)) return Promise.reject(new ParamError("param targetUserIds is required when msgType is ".concat(MessageHandleType[r])));
- var o = {
- action_type: Actions$1.Broadcast,
- broadcast_action: {
- data: JSON.stringify(t),
- user_id: this.room.options.userId,
- msgType: r
- }
- };
- return Array.isArray(n) && r === MessageHandleType.MHT_CustomTargetSync && (o.broadcast_action.target_user_ids = n), this.room.actionsHandler.sendData({
- data: o,
- tag: t.broadcastType
- });
- }
- }, {
- key: "getNeighborPoints",
- value: function getNeighborPoints(e) {
- var t = e.point,
- _e$containSelf = e.containSelf,
- r = _e$containSelf === void 0 ? !1 : _e$containSelf,
- _e$searchRange = e.searchRange,
- n = _e$searchRange === void 0 ? 500 : _e$searchRange,
- o = {
- action_type: Actions$1.GetNeighborPoints,
- get_neighbor_points_action: {
- point: t,
- level: 1,
- containSelf: r,
- searchRange: n
- }
- };
- return this.sendData({
- data: o
- }).then(function (a) {
- return a.nps;
- });
- }
- }, {
- key: "playCG",
- value: function playCG(e) {
- var t = {
- action_type: Actions$1.PlayCG,
- play_cg_action: {
- cg_name: e
- }
- };
- return this.sendData({
- data: t
- });
- }
- }, {
- key: "audienceToVisitor",
- value: function audienceToVisitor(e) {
- var t = e.avatarId,
- r = e.avatarComponents,
- n = e.player,
- o = e.camera,
- a = {
- action_type: Actions$1.AudienceChangeToVisitor,
- audienceChangeToVisitorAction: {
- avatarID: t,
- avatarComponents: r,
- player: n,
- camera: o
- }
- };
- return log$p.debug("send data: audience to visitor"), this.sendData({
- data: a
- });
- }
- }, {
- key: "visitorToAudience",
- value: function visitorToAudience(e) {
- var t = e.renderType,
- r = e.player,
- n = e.camera,
- o = e.areaName,
- a = e.attitude,
- s = e.pathName,
- l = e.person,
- u = e.noMedia,
- c = {
- action_type: Actions$1.VisitorChangeToAudience,
- visitorChangeToAudienceAction: {
- transferAction: {
- render_type: t,
- player: r,
- camera: n,
- areaName: o,
- attitude: a,
- pathName: s,
- person: {
- type: l
- },
- noMedia: u,
- tiles: [0, 1, 2, 4]
- }
- }
- };
- return log$p.debug("send data: visitor to audience"), this.sendData({
- data: c
- });
- }
- }, {
- key: "removeVisitor",
- value: function removeVisitor(e) {
- var t = e.removeType,
- r = e.userIDList,
- _e$extraInfo = e.extraInfo,
- n = _e$extraInfo === void 0 ? "" : _e$extraInfo,
- o = {
- action_type: Actions$1.RemoveVisitor,
- removeVisitorAction: {
- removeVisitorEvent: t,
- userIDList: r,
- extraInfo: encodeURIComponent(n)
- }
- };
- return log$p.debug("send data: remove visitor"), this.sendData({
- data: o
- });
- }
- }, {
- key: "getUserWithAvatar",
- value: function getUserWithAvatar(e, t) {
- var r = {
- action_type: Actions$1.GetUserWithAvatar,
- getUserWithAvatarAction: {
- userType: e,
- roomID: t
- }
- };
- return log$p.debug("send data: get user with avatar"), this.sendData({
- data: r
- }).then(function (n) {
- return n.userWithAvatarList;
- });
- }
- }, {
- key: "joystick",
- value: function joystick(e) {
- var t = e.degree,
- _e$level = e.level,
- r = _e$level === void 0 ? 1 : _e$level,
- n = uuid$1();
- var o = -t + 90 + 360;
- o >= 360 && (o -= 360);
- var a = {
- action_type: Actions$1.Joystick,
- dir_action: {
- move_angle: o,
- speed_level: r
- },
- trace_id: n,
- user_id: this.room.options.userId,
- packet_id: n
- };
- return this.sendData({
- data: a,
- track: !1
- });
- }
- }]);
- return ActionsHandler;
- }();
- var Signal = /*#__PURE__*/function () {
- function Signal(e) {
- _classCallCheck(this, Signal);
- this.signalHandleActived = !0;
- this.isUpdatedYUV = !0;
- this._room = e;
- }
- _createClass(Signal, [{
- key: "handleSignal",
- value: function handleSignal(e) {
- var _this = this;
- var a, s, l;
- if (!this.signalHandleActived) return;
- var t = e.signal,
- r = e.alreadyUpdateYUV;
- if (this.handleActionResponses(t), this._room.handleSignalHook(t), !r) {
- var u = (a = t.newUserStates) == null ? void 0 : a.find(function (c) {
- return c.userId === _this._room.userId;
- });
- if ((u == null ? void 0 : u.renderInfo) && ((s = this._room._userAvatar) == null ? void 0 : s.isMoving)) {
- logger.debug("stream stoped, make avatar to stop");
- var _u$renderInfo = u.renderInfo,
- c = _u$renderInfo.isMoving,
- h = _u$renderInfo.isRotating;
- this._room.avatarManager._updateAvatarMovingStatus({
- id: u.userId,
- isMoving: !!c,
- isRotating: !!h
- });
- }
- return;
- }
- this.isUpdatedYUV = r;
- var n = t;
- if (!t) {
- logger.warn("metadata signal is empty");
- return;
- }
- if (n.code === Codes.RepeatLogin) {
- this._room.handleRepetLogin();
- return;
- }
- n.code !== void 0 && n.code !== Codes.Success && n.code !== Codes.ActionMaybeDelay && n.code !== Codes.DoActionBlocked && n.code !== Codes.GetOnVehicle && (logger.error("signal errcode: ", n), this._room.emit("error", n));
- var o = (l = n.newUserStates) == null ? void 0 : l.find(function (u) {
- return u.userId === _this._room.userId;
- });
- if (n.broadcastAction) try {
- var _u = JSON.parse(n.broadcastAction.data);
- Broadcast.handlers.forEach(function (c) {
- return c(_u);
- });
- } catch (u) {
- logger.error(u);
- }
- if (n.newUserStates && n.newUserStates.length > 0 && this._room.avatarManager.handleAvatar(n), o != null && o.playerState) {
- this._room._currentClickingState = o.playerState;
- var _o$playerState = o.playerState,
- _u2 = _o$playerState.pathName,
- _c = _o$playerState.attitude,
- _h = _o$playerState.areaName,
- f = _o$playerState.skinId;
- if (_u2 && (this._room.pathManager.currentPathName = _u2, this._room.updateCurrentState({
- pathName: _u2
- })), f && this.udpateSkinInfo(f), _h && this._room.updateCurrentState({
- areaName: _h
- }), _c) {
- var d = this._room.skin.routeList.find(function (g) {
- return g.areaName === _this._room.currentState.areaName;
- }),
- _ = ((d == null ? void 0 : d.step) || 7.5) * 30;
- this._room.updateCurrentState({
- speed: _,
- attitude: _c
- }), this._room.pathManager.currentAttitude = _c, this._room._userAvatar && (this._room._userAvatar.motionType = _c);
- }
- this._room.sceneManager.getCurrentShaderMode() !== ECurrentShaderMode.pano && !this._room.isPano && o.playerState.camera && this._room.camera.setCameraPose(o.playerState.camera);
- }
- if (o != null && o.renderInfo && this._room.camera.handleRenderInfo(o), n.actionType !== void 0) {
- var _u3 = n.actionType,
- _c2 = n.code,
- _h2 = n.echoMsg,
- _f = n.traceId;
- _u3 === Actions.Echo && _c2 === Codes.Success && this._room.networkController.rtcp.heartbeat.pong(_h2, _f), _c2 !== Codes.Success ? eventsManager.remove(_f, _c2) : [Actions.GetReserveStatus, Actions.Broadcast, Actions.ChangeNickname, Actions.ConfirmEvent, Actions.ReserveSeat, Actions.Rotation, Actions.TurnTo, Actions.RotateTo, Actions.SetPlayerState, Actions.GetNeighborPoints, Actions.TurnToFace, Actions.AudienceChangeToVisitor, Actions.RemoveVisitor, Actions.GetUserWithAvatar].includes(_u3) && eventsManager.remove(_f, _c2, n);
- }
- }
- }, {
- key: "handleActionResponses",
- value: function handleActionResponses(e) {
- var _this2 = this;
- !(e != null && e.actionResponses) || e.actionResponses.length === 0 || e.actionResponses.forEach(function (t) {
- if (t.actionType == null) return;
- var r = t.pointType,
- n = t.extra,
- o = t.actionType,
- a = t.traceId,
- s = t.code,
- l = t.msg;
- o === Actions.GetNeighborPoints ? eventsManager.remove(a, s, t.nps) : o === Actions.GetUserWithAvatar ? eventsManager.remove(a, s, t.userWithAvatarList) : eventsManager.remove(a, s, l), r === PointType.Path && o === Actions.Clicking && (_this2._room.moveToExtra = decodeURIComponent(n));
- });
- }
- }, {
- key: "udpateSkinInfo",
- value: function () {
- var _udpateSkinInfo = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee(e) {
- var t;
- return regenerator.wrap(function _callee$(_context) {
- while (1) {
- switch (_context.prev = _context.next) {
- case 0:
- this._room.updateCurrentState({
- skinId: e
- });
- _context.next = 3;
- return this._room.skinList.find(function (r) {
- return r.id === e;
- });
- case 3:
- t = _context.sent;
- t && this._room.updateCurrentState({
- skin: t
- });
- case 5:
- case "end":
- return _context.stop();
- }
- }
- }, _callee, this);
- }));
- function udpateSkinInfo(_x) {
- return _udpateSkinInfo.apply(this, arguments);
- }
- return udpateSkinInfo;
- }()
- }]);
- return Signal;
- }();
- function _createSuper$a(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$a(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
- function _isNativeReflectConstruct$a() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
- var ParamError$1 = /*#__PURE__*/function (_XverseError) {
- _inherits(ParamError, _XverseError);
- var _super = _createSuper$a(ParamError);
- function ParamError(e) {
- _classCallCheck(this, ParamError);
- return _super.call(this, 1001, e || "\u53C2\u6570\u9519\u8BEF");
- }
- return _createClass(ParamError);
- }(XverseError);
- var MotionType$1 = {
- Walk: 'walk',
- Run: 'run',
- Fly: 'fly'
- };
- var Heartbeat = /*#__PURE__*/function () {
- function Heartbeat(e) {
- _classCallCheck(this, Heartbeat);
- this._interval = null;
- this.handler = e;
- }
- _createClass(Heartbeat, [{
- key: "ping",
- value: function ping() {
- var e = Date.now().toString();
- this.handler.ping(e);
- }
- }, {
- key: "start",
- value: function start() {
- this.stop(), logger.debug("Setting ping interval to ".concat(PING_INTERVAL_MS, "ms")), this._interval = window.setInterval(this.ping, PING_INTERVAL_MS);
- }
- }, {
- key: "stop",
- value: function stop() {
- logger.debug("stop heartbeat"), this._interval && window.clearInterval(this._interval);
- }
- }, {
- key: "pong",
- value: function pong(e, t) {
- !e || typeof e == "string" && this.handler.pong(Date.now() - Number(e), t);
- }
- }]);
- return Heartbeat;
- }();
- var Timeout$1 = /*#__PURE__*/function () {
- function Timeout(e, t) {
- var r = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : !0;
- _classCallCheck(this, Timeout);
- this._timeout = null;
- this._fn = e, this._delay = t, r && this.start();
- }
- _createClass(Timeout, [{
- key: "delay",
- get: function get() {
- return this._delay;
- }
- }, {
- key: "isSet",
- get: function get() {
- return !!this._timeout;
- }
- }, {
- key: "setDelay",
- value: function setDelay(e) {
- this._delay = e;
- }
- }, {
- key: "start",
- value: function start() {
- var _this = this;
- this.isSet || (this._timeout = window.setTimeout(function () {
- var e = _this._fn;
- _this.clear(), e();
- }, this._delay));
- }
- }, {
- key: "clear",
- value: function clear() {
- window.clearTimeout(this._timeout), this._timeout = void 0;
- }
- }, {
- key: "reset",
- value: function reset() {
- this.clear(), this.start();
- }
- }]);
- return Timeout;
- }();
- function _createSuper$9(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$9(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
- function _isNativeReflectConstruct$9() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
- var InitNetworkTimeoutError = /*#__PURE__*/function (_XverseError) {
- _inherits(InitNetworkTimeoutError, _XverseError);
- var _super = _createSuper$9(InitNetworkTimeoutError);
- function InitNetworkTimeoutError(e) {
- _classCallCheck(this, InitNetworkTimeoutError);
- return _super.call(this, 1007, e || "\u7F51\u7EDC\u521D\u59CB\u5316\u8D85\u65F6");
- }
- return _createClass(InitNetworkTimeoutError);
- }(XverseError);
- function _createSuper$8(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$8(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
- function _isNativeReflectConstruct$8() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
- var Socket = /*#__PURE__*/function (_EventEmitter) {
- _inherits(Socket, _EventEmitter);
- var _super = _createSuper$8(Socket);
- function Socket(e) {
- var _this;
- _classCallCheck(this, Socket);
- _this = _super.call(this);
- _this._ws = null;
- _this._openTimer = null;
- _this.connected = !1;
- _this._hasTimeout = !1;
- _this.heartbeat = null;
- _this.network = e, _this.heartbeat = new Heartbeat({
- ping: function ping(t) {
- var r;
- if (!_this.connected) {
- _this.heartbeat.stop(), (r = e.room.stats) == null || r.assign({
- rtt: 0
- });
- return;
- }
- _this.send({
- id: "heartbeat",
- data: t
- });
- },
- pong(t) {
- var r;
- (r = e.room.stats) == null || r.assign({
- rtt: t
- });
- }
- });
- return _this;
- }
- _createClass(Socket, [{
- key: "latency",
- value: function latency(e, t) {
- this.send({
- id: "checkLatency",
- data: JSON.stringify(e),
- packet_id: t
- });
- }
- }, {
- key: "send",
- value: function send(e) {
- if (this.wsNoReady()) return;
- var t = JSON.stringify(e);
- e.id !== "heartbeat" && logger.info("send ws frame", t), this._ws.send(t);
- }
- }, {
- key: "startGame",
- value: function startGame() {
- var _this$network$room$cu = this.network.room.currentNetworkOptions,
- e = _this$network$room$cu.roomId,
- t = _this$network$room$cu.userId,
- r = _this$network$room$cu.avatarId,
- n = _this$network$room$cu.skinId,
- o = _this$network$room$cu.role,
- a = _this$network$room$cu.avatarComponents,
- s = _this$network$room$cu.versionId,
- l = _this$network$room$cu.rotationRenderType,
- u = _this$network$room$cu.isAllSync,
- c = _this$network$room$cu.nickname,
- h = _this$network$room$cu.avatarScale,
- f = _this$network$room$cu.appId,
- d = _this$network$room$cu.camera,
- _ = _this$network$room$cu.player,
- g = _this$network$room$cu.firends,
- m = _this$network$room$cu.syncByEvent,
- v = _this$network$room$cu.areaName,
- y = _this$network$room$cu.attitude,
- b = _this$network$room$cu.pathName,
- T = _this$network$room$cu.person,
- _this$network$room$cu2 = _this$network$room$cu.roomTypeId,
- C = _this$network$room$cu2 === void 0 ? "" : _this$network$room$cu2,
- A = _this$network$room$cu.syncToOthers,
- S = _this$network$room$cu.hasAvatar,
- P = _this$network$room$cu.prioritySync,
- _this$network$room$cu3 = _this$network$room$cu.extra,
- R = _this$network$room$cu3 === void 0 ? {} : _this$network$room$cu3,
- M = _this$network$room$cu.removeWhenDisconnected;
- R.removeWhenDisconnected = M;
- var x = {
- id: "start",
- room_id: e,
- user_id: t,
- trace_id: uuid$1(),
- data: JSON.stringify({
- avatar_components: JSON.stringify(a),
- avatar_id: r,
- skin_id: n,
- is_host: o ? o == "host" : !0,
- skin_data_version: n !== void 0 && s !== void 0 ? n + s : void 0,
- rotation_render_type: l,
- is_all_sync: u,
- nick_name: encodeURIComponent(c || ""),
- app_id: f,
- camera: d,
- player: _,
- person: T,
- firends: JSON.stringify(g),
- sync_by_event: m,
- area_name: v,
- path_name: b,
- attitude: y,
- room_type_id: C,
- syncToOthers: A,
- hasAvatar: S,
- avatarSize: h,
- prioritySync: P,
- extra: JSON.stringify(R)
- })
- };
- this.send(x), logger.warn("startGame", le(oe({}, x), {
- data: JSON.parse(x.data)
- }));
- }
- }, {
- key: "connection",
- get: function get() {
- return this._ws;
- }
- }, {
- key: "start",
- value: function start() {
- var _this2 = this;
- this._hasTimeout = !1;
- var e = this.getAddress();
- logger.info("connecting to ".concat(e));
- var t = Date.now();
- this._ws = new WebSocket(e), this._openTimer = new Timeout$1(function () {
- var r = "Failed to open websocket in ".concat(DEFAULT_OPEN_TIMEOUT_MS, " ms");
- _this2._hasTimeout = !0, _this2.emit("socketClosed", new InitNetworkTimeoutError(r));
- }, DEFAULT_OPEN_TIMEOUT_MS), this._ws.onopen = function () {
- var r;
- (r = _this2._openTimer) == null || r.clear(), _this2.connected = !0, _this2.heartbeat.start(), _this2.network.room.currentNetworkOptions.reconnect || (logger.infoAndReportMeasurement({
- metric: "wsOpenedAt",
- group: "joinRoom",
- startTime: _this2.network.room._startTime
- }), logger.infoAndReportMeasurement({
- metric: "wsOpenedCost",
- group: "joinRoom",
- startTime: t
- }));
- }, this.handleWSEvent();
- }
- }, {
- key: "getAddress",
- value: function getAddress() {
- var _this$network$room$cu4 = this.network.room.currentNetworkOptions,
- e = _this$network$room$cu4.wsServerUrl,
- t = _this$network$room$cu4.reconnect,
- r = _this$network$room$cu4.sessionId,
- n = _this$network$room$cu4.token,
- o = _this$network$room$cu4.roomId,
- a = _this$network$room$cu4.userId,
- s = _this$network$room$cu4.pageSession,
- l = this.network.room.skinId;
- var u = e;
- t && (u = u + "?reconnect=true&lastSessionID=".concat(r));
- var c = "userId=".concat(a, "&roomId=").concat(o, "&pageSession=").concat(s) + (this.network.room.isHost ? "&skinId=".concat(l) : "") + (n ? "&token=".concat(n) : "");
- return u = u.indexOf("?") > -1 ? u + "&" + c : u + "?" + c, u;
- }
- }, {
- key: "handleWSEvent",
- value: function handleWSEvent() {
- var _this3 = this;
- var e = this._ws;
- e.addEventListener("error", function (t) {
- _this3.connected = !1, logger.error("webscoket error", t), _this3.emit("socketClosed", new InternalError("connect to address error: " + _this3.network.room.currentNetworkOptions.wsServerUrl));
- }), e.addEventListener("close", function (t) {
- _this3.connected = !1, _this3._onClose(t);
- }), e.addEventListener("message", function (t) {
- if (!t || _this3._hasTimeout || !_this3.connected) return;
- var r = null;
- try {
- r = JSON.parse(t.data);
- } catch (o) {
- logger.error(o);
- return;
- }
- if (!r) return;
- var n = r.id;
- if (!!n) switch (n !== "heartbeat" && logger.info("receive ws frame: ".concat(t.data)), n) {
- case "fail":
- break;
- case "init":
- try {
- var o = r.data.slice(-37, -1);
- reporter$1.updateBody({
- serverSession: o
- });
- } catch (o) {
- console.error(o);
- }
- _this3.network.rtcp.start();
- break;
- case "heartbeat":
- _this3.heartbeat.pong(r.data);
- break;
- case "offer":
- _this3.network.rtcp.setRemoteDescription(r.data, _this3.network.stream.el);
- break;
- case "ice_candidate":
- _this3.network.rtcp.addCandidate(r.data);
- break;
- case "start":
- _this3.emit("gameRoomAvailable", r);
- break;
- case "error":
- try {
- var _JSON$parse = JSON.parse(r.data),
- _o = _JSON$parse.Code,
- a = _JSON$parse.Msg;
- if (_o) {
- if (_o == 3003) return _this3.emit("socketClosed", new TokenExpiredError());
- if (authenticationErrorCodes.indexOf(_o) > -1) return _this3.emit("socketClosed", new AuthenticationError("\u9274\u6743\u9519\u8BEF:" + a));
- {
- var s = getErrorByCode(_o);
- _this3.emit("socketClosed", new s(a));
- }
- }
- } catch (o) {
- logger.error(o), _this3.emit("socketClosed", new InternalError(r.data));
- }
- break;
- case "checkLatency":
- {
- var _o2 = r.packet_id,
- _a = r.data.split(",");
- _this3.onLatencyCheck({
- packetId: _o2,
- addresses: _a
- });
- break;
- }
- default:
- logger.warn("unkown ws message type", n, r);
- }
- });
- }
- }, {
- key: "onLatencyCheck",
- value: function onLatencyCheck(e) {
- var _this4 = this;
- var t = _toConsumableArray(new Set(e.addresses || []));
- Promise.all(t.map(function (r) {
- return {
- [r]: 9999
- };
- })).then(function (r) {
- var n = Object.assign.apply(Object, [{}].concat(_toConsumableArray(r)));
- _this4.latency(n, e.packetId);
- });
- }
- }, {
- key: "wsNoReady",
- value: function wsNoReady() {
- return this._ws.readyState == WebSocket.CLOSED || this._ws.readyState == WebSocket.CLOSING || this._ws.readyState == WebSocket.CONNECTING;
- }
- }, {
- key: "prepareReconnect",
- value: function prepareReconnect() {
- this._close({
- code: WS_CLOSE_RECONNECT,
- reason: "reconnect"
- });
- }
- }, {
- key: "_onClose",
- value: function _onClose(_ref) {
- var e = _ref.code,
- t = _ref.reason;
- this._openTimer && this._openTimer.clear(), logger.warn("ws closed: ".concat(e, " ") + t), [WS_CLOSE_RECONNECT, WS_CLOSE_NORMAL].includes(e) || this.emit("socketClosed", new InternalError("Websocket error"));
- }
- }, {
- key: "_close",
- value: function _close(_ref2) {
- var e = _ref2.code,
- t = _ref2.reason;
- var r;
- (r = this._ws) == null || r.close(e, t);
- }
- }, {
- key: "quit",
- value: function quit() {
- this._close({
- code: WS_CLOSE_NORMAL,
- reason: "quit"
- });
- }
- }]);
- return Socket;
- }(EventEmitter);
- function add(i, e) {
- return e == -1 && (e = 0), i + e;
- }
- function max(i, e) {
- return Math.max(i, e);
- }
- function count_sd(i, e) {
- function t(r, n) {
- var o = 0;
- return n == -1 ? o = 0 : o = (n - e) * (n - e), r + o;
- }
- return Math.sqrt(i.reduce(t, 0) / i.reduce(count_valid, 0)) || 0;
- }
- function count_valid(i, e) {
- var t = 0;
- return e != -1 && (t = 1), i + t;
- }
- function count_less(i, e) {
- function t(r, n) {
- var o = 0;
- return n != -1 && n < e && (o = 1), r + o;
- }
- return i.reduce(t, 0);
- }
- var CircularArray = /*#__PURE__*/function () {
- function CircularArray(e, t, r) {
- _classCallCheck(this, CircularArray);
- this.sum = 0, this.incomingSum = 0, this.count = 0, this.incomingCount = 0, this.max = 0, this.incomingMax = 0, this.goodLess = 0, this.wellLess = 0, this.fairLess = 0, this.badLess = 0, this.countLess = !1, this.lessThreshes = [], this.incomingData = [], this.circularData = Array(e).fill(-1), this.circularPtr = 0, this.circularLength = e, t && (this.countLess = !0, this.lessThreshes = r);
- }
- _createClass(CircularArray, [{
- key: "add",
- value: function add(e) {
- this.circularData[this.circularPtr] != -1 ? (this.sum -= this.circularData[this.circularPtr], Math.abs(this.circularData[this.circularPtr] - this.max) < .01 && (this.circularData[this.circularPtr] = -1, this.max = this.getMax(!1))) : this.count += 1, this.sum += e, this.incomingSum += e, this.incomingCount += 1, this.max < e && (this.max = e), this.incomingMax < e && (this.incomingMax = e), this.circularData[this.circularPtr] = e, this.circularPtr = (this.circularPtr + 1) % this.circularLength, this.incomingData.push(e), this.incomingData.length > this.circularLength && (this.clearIncoming(), this.incomingCount = 0, this.incomingSum = 0);
- }
- }, {
- key: "computeAvg",
- value: function computeAvg(e) {
- return e.reduce(add, 0) / e.reduce(count_valid, 0) || 0;
- }
- }, {
- key: "computeMax",
- value: function computeMax(e) {
- return e.reduce(max, 0) || 0;
- }
- }, {
- key: "computeThreshPercent",
- value: function computeThreshPercent(e) {
- if (this.countLess) {
- var t = count_less(e, this.lessThreshes[0]) || 0,
- r = count_less(e, this.lessThreshes[1]) || 0,
- n = count_less(e, this.lessThreshes[2]) || 0,
- o = count_less(e, this.lessThreshes[3]) || 0,
- a = e.reduce(count_valid, 0);
- return [t, r, n, o, a];
- } else return [0, 0, 0, 0, 0];
- }
- }, {
- key: "getAvg",
- value: function getAvg() {
- var e = this.sum / this.count || 0,
- t = this.computeAvg(this.circularData) || 0;
- return Math.abs(e - t) > .01 && console.error("avg value mismatch: ", e, t), this.computeAvg(this.circularData) || 0;
- }
- }, {
- key: "getMax",
- value: function getMax() {
- var e = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : !0;
- var t = this.computeMax(this.circularData) || 0;
- return e && Math.abs(t - this.max) > .01 && console.error("max value mismatch: ", this.max, t), this.computeMax(this.circularData) || 0;
- }
- }, {
- key: "getStandardDeviation",
- value: function getStandardDeviation() {
- return count_sd(this.circularData, this.getAvg());
- }
- }, {
- key: "getThreshPercent",
- value: function getThreshPercent() {
- return this.computeThreshPercent(this.circularData);
- }
- }, {
- key: "getIncomingMax",
- value: function getIncomingMax() {
- return this.computeMax(this.incomingData) || 0;
- }
- }, {
- key: "getIncomingAvg",
- value: function getIncomingAvg() {
- return this.computeAvg(this.incomingData) || 0;
- }
- }, {
- key: "getIncomingStandardDeviation",
- value: function getIncomingStandardDeviation() {
- return count_sd(this.incomingData, this.getIncomingAvg());
- }
- }, {
- key: "getIncomingThreshPercent",
- value: function getIncomingThreshPercent() {
- return this.computeThreshPercent(this.incomingData);
- }
- }, {
- key: "clearFastComputeItem",
- value: function clearFastComputeItem() {
- this.sum = 0, this.incomingSum = 0, this.count = 0, this.incomingCount = 0, this.max = 0, this.incomingMax = 0, this.goodLess = 0, this.wellLess = 0, this.fairLess = 0, this.badLess = 0;
- }
- }, {
- key: "clearIncoming",
- value: function clearIncoming() {
- for (; this.incomingData.length > 0;) {
- this.incomingData.pop();
- }
- }
- }, {
- key: "clear",
- value: function clear() {
- this.circularData.fill(-1), this.circularPtr = 0, this.clearFastComputeItem(), this.clearIncoming();
- }
- }]);
- return CircularArray;
- }();
- function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
- function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
- function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
- var defaultLogger = {
- info: console.log,
- debug: console.log,
- error: console.error,
- infoAndReportMeasurement: function infoAndReportMeasurement() {}
- };
- var USER_ID = "987412365",
- PAGE_SESSION = "aaabbbccc",
- SERVER_SESSION = "cccbbbaaa",
- COS_PREFIX = "error-bitstreams-auto-uploaded-from-application/",
- FRAME_COMPOSE_LENGTH = 5;
- var Workers = /*#__PURE__*/function () {
- function Workers(e, t) {
- var _this = this;
- _classCallCheck(this, Workers);
- this.rtcp = e, this.cacheSize = 0, this.cacheBuffer = new Uint8Array(262144), this.cacheFrameCnt = 0, this.startReceiveTime = 0, this.cacheFrameComposes = new Array(0), this.cacheSizes = new Array(5).fill(0), this.cacheFrameCnts = new Array(5).fill(-1), this.cacheStartReceiveTimes = new Array(5).fill(0), this.cacheBuffers = [new Uint8Array(262144), new Uint8Array(262144), new Uint8Array(262144), new Uint8Array(262144), new Uint8Array(262144)], this.panoCacheSize = 0, this.panoCacheBuffer = new Uint8Array(2097152), this.cachePanoTileID = 0, this.receivedMedia = 0, this.receivedMedia_worker = 0, this.receivedYUV = 0, this.receivedEmit = 0, this.returnFrames = 0, this.lastReturnFrames = 0, this.lastReceivedEmit = 0, this.mediaBytesReceived = 0, this.metaBytesReceived = 0, this.noWasmBytesReceived = 0, this.rtcBytesReceived = 0, this.rtcMessageReceived = 0, this.packetsDrop = 0, this.framesAwait = 0, this.sendOutBuffer = 0, this.decodeTimePerFrame = 0, this.decodeTimeMaxFrame = 0, this.lastRenderTs = 0, this.JankTimes = 0, this.bigJankTimes = 0, this.DecodeJankTimes = 0, this.bigDecodeJankTimes = 0, this.saveframe = !1, this.SaveMediaStream = !1, this.packetsLost = 0, this.showAllReceivedMetadata = !1, this.firstMediaArraval = 0, this.firstMediaReceived = !1, this.firstYUVDecoded = 0, this.firstRender = 0, this.firstYUVReceived = !1, this.reconnectSignal = !1, this.serverFrameSlow = 0, this.serverFrameFast = 0, this.clientFrameSlow = 0, this.clientFrameFast = 0, this.lastServerTS = 0, this.lastClientTS = 0, this.lastSeq = 0, this.lastIsPureMeta = !1, this.lastHBPacketTs = 0, this.HBPacketInterval = 0, this.lastHBPacketSrvSentTs = 0, this.HBPacketIntervalSrvSent = 0, this.cachedLength = 2, this.cachedStreams = new Array(this.cachedLength), this.cachedMetas = new Array(this.cachedLength), this.cachedPtss = new Array(this.cachedLength), this.cachedRender = Array(this.cachedLength).fill(!1), this.cachedResolution = new Array(this.cachedLength), this.getPtr = 0, this.setPtr = 0, this.receiveIframes = 0, this.decodeIframes = 0, this.prevSenderTs = -1, this.serverSendTimeArray = new CircularArray(120, !1, []), this.inPanoMode = !1, this.PanoStatus = {
- x: 0,
- y: 0,
- z: 0,
- tiles: []
- }, this.DynamicPanoTest = !1, this.PanoMask = new ArrayBuffer(8), this.PanoView = new DataView(this.PanoMask), this.userId_test = "", this.PendingMasks = [], this.traceIdMap = new Map(), this.responseTimeArray = [], this.processTimeArray = [], this.displayTimeArray = [], this.overallTimeArray = [], this.responseMiss = 0, this.processMiss = 0, this.displayMiss = 0, this.updateYUVCircular = new CircularArray(120, !1, []), this.updateDropFrame = 0, this.metaParseAraay = [], this.responseMoveMiss = 0, this.processMoveMiss = 0, this.displayMoveMiss = 0, this.MovingTraceId = "", this.PendingMovingTraceId = "", this.inMovingMode = !1, this.StartMovingTs = 0, this.PendingStartMovingTs = 0, this.moveEvent = "", this.MoveToFrameCnt = 0, this.lastIsMoving = 0, this.MoveResponseDelay = 0, this.MoveProcessDelay = 0, this.MoveDisplayDelay = 0, this.lastMoveResponseTime = 0, this.lastMoveProcessTime = 0, this.lastMoveDisplayTime = 0, this.moveResponseCircular = new CircularArray(120, !0, [STUCK_STAGE_GOOD, STUCK_STAGE_WELL, STUCK_STAGE_FAIR, STUCK_STAGE_BAD]), this.moveProcessCircular = new CircularArray(120, !0, [STUCK_STAGE_GOOD, STUCK_STAGE_WELL, STUCK_STAGE_FAIR, STUCK_STAGE_BAD]), this.moveDisplayCircular = new CircularArray(120, !0, [STUCK_STAGE_GOOD, STUCK_STAGE_WELL, STUCK_STAGE_FAIR, STUCK_STAGE_BAD]), this.moveStartPts = -1, this.frameServerCircular = new CircularArray(120, !1, []), this.srvMetaIntervalCircular = new CircularArray(120, !1, []), this.srvMediaIntervalCircular = new CircularArray(120, !1, []), this.srvHBMetaIntervalCircular = new CircularArray(120, !1, []), this.srvHBMetaIntervalSrvSentCircular = new CircularArray(120, !1, []), this.frameClientCircular = new CircularArray(120, !1, []), this.firstUpdateYUV = !0, this.functionMap = new Map(), this.WASM_VERSION = "WASM-1.1", this.frameHistory = [], this.getVersion = function () {
- return DECODER_VERSION;
- }, this.downloadBlob = function (r, n, o) {
- var a = new Blob([r], {
- type: o
- }),
- s = window.URL.createObjectURL(a);
- _this.downloadURL(s, n), setTimeout(function () {
- return window.URL.revokeObjectURL(s);
- }, 1e3);
- }, this.downloadURL = function (r, n) {
- var o = document.createElement("a");
- o.href = r, o.download = n, document.body.appendChild(o), o.style.display = "none", o.click(), o.remove();
- }, this.Stringify = function (r) {
- var n = "";
- for (var a = 0; a < r.length / 8192; a++) {
- n += String.fromCharCode.apply(null, r.slice(a * 8192, (a + 1) * 8192));
- }
- return n;
- }, this._rtcp = e;
- }
- _createClass(Workers, [{
- key: "registerLogger",
- value: function registerLogger(e) {//defaultLogger = e
- }
- }, {
- key: "registerFunction",
- value: function registerFunction(e, t) {
- this.functionMap.set(e, t);
- }
- }, {
- key: "hasFrmCntInCache",
- value: function hasFrmCntInCache(e) {
- var t = -1;
- for (var r = 0; r < this.cacheFrameComposes.length; r++) {
- this.cacheFrameComposes[r].frameCnt == e && (t = r);
- }
- return t;
- }
- }, {
- key: "requestPanoramaTest",
- value: function requestPanoramaTest(e, t, r, n, o) {
- var a = o,
- s = {
- action_type: 16,
- change_rotation_render_type_action: {
- render_type: 5,
- player: {
- position: {
- x: 0,
- y: 0,
- z: 0
- },
- angle: {
- yaw: 0,
- pitch: 0,
- roll: 0
- }
- },
- camera: {
- position: {
- x: e,
- y: t,
- z: r
- },
- angle: {
- yaw: 0,
- pitch: 0,
- roll: 0
- }
- },
- client_pano_titles_bitmap: n
- },
- trace_id: a,
- user_id: this.userId_test,
- packet_id: a
- };
- defaultLogger.debug("send data: ", s), this._rtcp.sendData(s);
- }
- }, {
- key: "onRotateInPanoMode",
- value: function onRotateInPanoMode(e) {
- var t = e.traceId,
- r = {};
- r.width = 1280, r.height = 720, r.horz_fov = 92, r.angle = {
- yaw: 100,
- pitch: 30
- };
- var n = new ArrayBuffer(8),
- o = new DataView(n);
- getTilesInView(r, n);
- var a = n.slice(0);
- this.PendingMasks.unshift({
- buffer: a,
- angle: r.angle
- }), MaskSetToOne(18, this.PanoView), operateForDataView(o, this.PanoView, o, function (s, l) {
- return s ^ s & l;
- }), this.requestPanoramaTest(0, 0, 0, [o.getUint8(0), o.getUint8(1), o.getUint8(2), o.getUint8(3), o.getUint8(4), o.getUint8(5), o.getUint8(6), o.getUint8(7)], t);
- }
- }, {
- key: "processMetaWithTraceId",
- value: function processMetaWithTraceId(e) {
- var _iterator = _createForOfIteratorHelper(e.traceIds),
- _step;
- try {
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
- var t = _step.value;
- if (this.traceIdMap.has(t)) {
- var r = this.traceIdMap.get(t);
- r != null && (r.receiveTime = Date.now(), r.status = 1);
- }
- if (t == this.PendingMovingTraceId) {
- this.inMovingMode = !0, this.MovingTraceId = this.PendingMovingTraceId, this.StartMovingTs = this.PendingStartMovingTs, this.PendingMovingTraceId = "", this.PendingStartMovingTs = 0, defaultLogger.info("MoveTo TraceId match", this.StartMovingTs, Date.now());
- var _r = Date.now();
- this.lastMoveResponseTime = _r, this.lastMoveProcessTime = _r, this.lastMoveDisplayTime = _r, this.frameServerCircular.clear(), this.frameClientCircular.clear();
- }
- }
- } catch (err) {
- _iterator.e(err);
- } finally {
- _iterator.f();
- }
- }
- }, {
- key: "onTraceId",
- value: function onTraceId(e) {
- var _this2 = this;
- var r = e.traceId,
- n = e.timestamp,
- o = e.event;
- if (o === "Rotation") {
- var a = {
- traceId: r,
- pts: 0,
- startTime: n,
- receiveTime: 0,
- readyTime: 0,
- displayTime: 0,
- status: 0
- };
- this.traceIdMap.set(r, a);
- var s = setTimeout(function () {
- if (s && clearTimeout(s), _this2.traceIdMap.has(r)) {
- var l = _this2.traceIdMap.get(r);
- switch (l == null ? void 0 : l.status) {
- case 0:
- {
- _this2.responseMiss += 1;
- break;
- }
- case 1:
- {
- _this2.processMiss += 1;
- var u = l.receiveTime - l.startTime;
- _this2.responseTimeArray.push(u);
- break;
- }
- case 2:
- {
- _this2.displayMiss += 1;
- var _u = l.receiveTime - l.startTime,
- c = l.readyTime - l.receiveTime;
- _this2.responseTimeArray.push(_u), _this2.processTimeArray.push(c);
- break;
- }
- case 3:
- defaultLogger.debug("status is 3");
- }
- }
- }, 1e3);
- } else o === "MoveTo" ? (defaultLogger.info("receive moveto traceId ", r, " at timestamp", n), this.PendingMovingTraceId = r, this.PendingStartMovingTs = n, this.moveEvent = o, this.frameServerCircular.clear()) : o === "GetOnAirship" || o === "GetOnVehicle" ? (defaultLogger.info("receive airship traceId ", r, " at timestamp ", n), this.PendingMovingTraceId = r, this.PendingStartMovingTs = n, this.moveEvent = o, this.frameServerCircular.clear()) : (o === "GetOffAirship" || o === "GetOffVehicle") && this.clearMoveArray();
- }
- }, {
- key: "executeFunction",
- value: function executeFunction(e, t) {
- if (this.functionMap.has(e)) {
- var r = this.functionMap.get(e);
- r != null && r(t);
- }
- }
- }, {
- key: "UpdateStats",
- value: function UpdateStats(e) {
- var _this3 = this;
- var t;
- (t = this._rtcp.connection) == null || t.getStats(null).then(function (r) {
- r.forEach(function (n) {
- n.type == "data-channel" && (_this3.rtcMessageReceived = n.messagesReceived - n.messagesSent, _this3.rtcBytesReceived = n.bytesReceived);
- });
- }), this.receivedMedia_worker = e.data.framesReceived, this.receivedYUV = e.data.framesDecoded, this.receivedEmit = e.data.framesRendered, this.mediaBytesReceived = e.data.mediaBytesReceived, this.metaBytesReceived = e.data.metaBytesReceived, this.packetsLost = e.data.packetsLost, this.packetsDrop = e.data.packetsDrop, this.framesAwait = e.data.framesAwait, this.decodeTimePerFrame = e.data.decodeTimePerFrame, this.decodeTimeMaxFrame = e.data.decodeTimeMaxFrame, this.returnFrames = e.data.framesReturned, this.sendOutBuffer = e.data.sendOutBuffer, this.DecodeJankTimes = e.data.JankTimes, this.bigDecodeJankTimes = e.data.bigJankTimes, this.receiveIframes = e.data.receivedIframe, this.decodeIframes = e.data.decodedIframe;
- }
- }, {
- key: "ReceiveDecodeMessage",
- value: function ReceiveDecodeMessage(e) {
- var n;
- if (!this.firstYUVReceived) {
- this.firstYUVDecoded = e.data.yuv_ts;
- var o = this.firstYUVDecoded - this.rtcp.network.room._startTime;
- defaultLogger.infoAndReportMeasurement({
- metric: "firstYUVDecodedAt",
- value: o,
- group: "joinRoom"
- }), this.firstRender = Date.now();
- var a = this.firstYUVDecoded - this.rtcp.network.room._startTime;
- defaultLogger.infoAndReportMeasurement({
- metric: "firstRenderAt",
- value: a,
- group: "joinRoom"
- }), this.firstYUVReceived = !0, this.lastRenderTs = Date.now();
- }
- !this.cachedRender[this.setPtr] && this.cachedMetas[this.setPtr] != null && (this.cachedStreams[this.setPtr] != null && this.cachedStreams[this.setPtr].byteLength != 0 && (e.data.data == null ? (this.executeFunction("stream", {
- stream: this.cachedStreams[this.setPtr],
- width: this.cachedResolution[this.setPtr].width,
- height: this.cachedResolution[this.setPtr].height,
- pts: this.cachedPtss[this.setPtr]
- }), this.executeFunction("signal", {
- signal: this.cachedMetas[this.setPtr],
- pts: this.cachedPtss[this.setPtr],
- alreadyUpdateYUV: !0
- })) : this.updateDropFrame += 1, this.decoderWorker.postMessage({
- t: 2,
- frameCnt: this.cachedPtss[this.setPtr],
- buffer: this.cachedStreams[this.setPtr]
- }, [this.cachedStreams[this.setPtr].buffer])), this.getPtr = (this.getPtr + 1) % this.cachedLength);
- var t = e.data.metadata;
- if ((n = t == null ? void 0 : t.traceIds) != null && n.length) {
- var _iterator2 = _createForOfIteratorHelper(t.traceIds),
- _step2;
- try {
- for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
- var _o = _step2.value;
- if (this.traceIdMap.has(_o)) {
- var _a = this.traceIdMap.get(_o);
- _a != null && (_a.readyTime = Date.now(), _a.status = 2);
- }
- }
- } catch (err) {
- _iterator2.e(err);
- } finally {
- _iterator2.f();
- }
- }
- if (e.data.pts == this.moveStartPts && (this.MoveProcessDelay = Date.now() - this.StartMovingTs), this.userId_test = this.rtcp.network.room.userId, this.inMovingMode) {
- var _o2 = Date.now(),
- _a2 = _o2 - this.lastMoveProcessTime;
- this.moveProcessCircular.add(_a2), this.lastMoveProcessTime = _o2;
- }
- var r = this.setPtr;
- this.cachedStreams[r] = e.data.data, this.cachedMetas[r] = e.data.metadata, this.cachedPtss[r] = e.data.pts, this.cachedRender[r] = !1, this.cachedResolution[r] = {
- width: e.data.width,
- height: e.data.height
- }, this.setPtr = (this.setPtr + 1) % this.cachedLength;
- }
- }, {
- key: "SendCacheFrameInfo",
- value: function SendCacheFrameInfo(e) {
- var _this4 = this;
- var h, f, d, _, g, m, v;
- var t = e.data.cachedKey,
- r = e.data.metadata,
- n = t,
- o = r,
- a = (d = (f = (h = o.newUserStates) == null ? void 0 : h.find(function (y) {
- return y.userId === _this4.rtcp.network.room.userId;
- })) == null ? void 0 : f.playerState) == null ? void 0 : d.roomTypeId,
- s = this.rtcp.network.room.skinId,
- l = (v = (m = (g = (_ = o.newUserStates) == null ? void 0 : _.find(function (y) {
- return y.userId === _this4._rtcp.network.room.userId;
- })) == null ? void 0 : g.playerState) == null ? void 0 : m.player) == null ? void 0 : v.position,
- u = {
- MsgType: 1,
- FrameCacheMsg: {
- FrameIndex: n,
- RoomTypeId: a,
- SkinID: s,
- Position: l
- }
- };
- var c = "";
- try {
- c = JSON.stringify(u);
- } catch (y) {
- defaultLogger.error(y);
- return;
- }
- }
- }, {
- key: "ReceivePanoramaDecodeMessage",
- value: function ReceivePanoramaDecodeMessage(e) {
- defaultLogger.info("Receive Panorama Image in Workers.ts"), MaskSetToOne(e.data.tileId, this.PanoView);
- var t = 0,
- r;
- var n = this.PendingMasks.length;
- for (t = 0; t < n; t++) {
- var o = this.PendingMasks[t].buffer,
- a = new DataView(o),
- s = new ArrayBuffer(8),
- l = new DataView(s);
- if (operateForDataView(this.PanoView, a, l, function (u, c) {
- return c ^ u & c;
- }), IsAll0(l)) {
- r = this.PendingMasks[t].angle;
- break;
- }
- }
- for (var _o3 = t; _o3 < n; _o3++) {
- this.PendingMasks.pop();
- }
- this.executeFunction("panorama", {
- data: e.data.data,
- tileId: e.data.tileId,
- pos: {
- x: e.data.x,
- y: e.data.y,
- z: e.data.z
- },
- uuid: e.data.uuid,
- finished: !0,
- matchAngle: r
- });
- }
- }, {
- key: "enable_decoder_queue_logging",
- value: function enable_decoder_queue_logging() {
- this.decoderWorker.postMessage({
- t: 100,
- status: !0
- });
- }
- }, {
- key: "disable_decoder_queue_logging",
- value: function disable_decoder_queue_logging() {
- this.decoderWorker.postMessage({
- t: 100,
- status: !1
- });
- }
- }, {
- key: "init",
- value: function () {
- var _init = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee() {
- var _this5 = this;
- var e,
- r,
- n,
- t,
- _args = arguments;
- return regenerator.wrap(function _callee$(_context) {
- while (1) {
- switch (_context.prev = _context.next) {
- case 0:
- e = _args.length > 0 && _args[0] !== undefined ? _args[0] : {
- width: 1280,
- height: 720
- };
- for (r = 0; r < FRAME_COMPOSE_LENGTH; r++) {
- n = {
- buffer: new Uint8Array(2621440),
- size: 0,
- startReceiveTime: 0,
- serverTime: 0,
- frameCnt: -1
- };
- this.cacheFrameComposes.push(n);
- }
- t = new Blob([decoder], {
- type: "application/javascript"
- });
- return _context.abrupt("return", (this.decoderWorker = new Worker(URL.createObjectURL(t)), this.decoderWorker.postMessage({
- t: 9,
- url: WASM_URLS[WASM_Version],
- jitterLength: DECODER_PASSIVE_JITTER
- }), this.decoderWorker.postMessage({
- t: 1,
- config: e
- }), new Promise(function (r) {
- _this5.decoderWorker.onmessage = function (n) {
- switch (n.data.t) {
- case 0:
- _this5.ReceiveDecodeMessage(n);
- break;
- case 1:
- _this5.UpdateStats(n);
- break;
- case 2:
- r();
- break;
- case 3:
- _this5.SendCacheFrameInfo(n);
- break;
- case 4:
- {
- var o = new Date().toISOString(),
- a = USER_ID + "-" + PAGE_SESSION + "-" + SERVER_SESSION + "-" + o + ".264";
- uploadStream(COS_PREFIX + a, n.data.fileObj);
- break;
- }
- case 5:
- _this5.executeFunction("signal", {
- signal: n.data.metadata,
- pts: -1,
- alreadyUpdateYUV: !1
- });
- break;
- case 6:
- defaultLogger.infoAndReportMeasurement(n.data), defaultLogger.debug("WASM Ready Cost");
- break;
- case 7:
- _this5.ReceivePanoramaDecodeMessage(n);
- break;
- case 8:
- {
- var _o4 = {
- MstType: 0
- };
- var _a3 = "";
- try {
- _a3 = JSON.stringify(_o4);
- } catch (l) {
- defaultLogger.error(l);
- return;
- }
- var s = "wasm:" + _a3;
- _this5._rtcp.sendStringData(s);
- break;
- }
- case 9:
- {
- defaultLogger.info(n.data.printMsg);
- break;
- }
- case 10:
- {
- defaultLogger.error(n.data.printMsg), _this5.executeFunction("error", {
- code: n.data.code,
- message: n.data.printMsg
- });
- break;
- }
- default:
- defaultLogger.error("Receive unknown message event from decoder"), defaultLogger.debug(n.data);
- break;
- }
- };
- })));
- case 4:
- case "end":
- return _context.stop();
- }
- }
- }, _callee, this);
- }));
- function init() {
- return _init.apply(this, arguments);
- }
- return init;
- }()
- }, {
- key: "UpdateYUV",
- value: function UpdateYUV() {
- var t, r;
- var e = this.getPtr;
- if (this.cachedMetas[e] != null && !this.cachedRender[e]) {
- var n = Date.now();
- if (this.firstUpdateYUV) {
- var h = ((t = this.cachedStreams[e]) == null ? void 0 : t.byteLength) || 0;
- defaultLogger.infoAndReportMeasurement({
- metric: "firstUpdateStreamLength",
- value: h,
- group: "joinRoom"
- }), this.firstUpdateYUV = !1;
- }
- this.cachedStreams[e] != null && this.executeFunction("stream", {
- stream: this.cachedStreams[e],
- width: this.cachedResolution[e].width,
- height: this.cachedResolution[e].height,
- pts: this.cachedPtss[e]
- });
- var o = Date.now();
- this.cachedStreams[e] != null && this.decoderWorker.postMessage({
- t: 2,
- frameCnt: this.cachedPtss[e],
- buffer: this.cachedStreams[e]
- }, [this.cachedStreams[e].buffer]);
- var a = Date.now(),
- s = o - n,
- l = a - o;
- (s > 33 || l > 10) && defaultLogger.debug("[wwwarning] updateYUV takes ", s, " ms, postMessage takes ", l, " ms for index ", this.cachedPtss[e]), o - this.lastRenderTs > 84 && this.JankTimes++, o - this.lastRenderTs > 125 && this.bigJankTimes++, this.lastRenderTs = o;
- var u = o - n;
- this.updateYUVCircular.add(u);
- var c = this.cachedMetas[e];
- if ((r = c == null ? void 0 : c.traceIds) != null && r.length) {
- var _iterator3 = _createForOfIteratorHelper(c.traceIds),
- _step3;
- try {
- for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
- var _h = _step3.value;
- if (this.traceIdMap.has(_h)) {
- var f = this.traceIdMap.get(_h);
- if (f != null) {
- f.displayTime = Date.now(), f.status = 3;
- var d = f.receiveTime - f.startTime,
- _ = f.readyTime - f.receiveTime,
- g = f.displayTime - f.readyTime,
- m = f.displayTime - f.startTime;
- this.responseTimeArray.push(d), this.processTimeArray.push(_), this.displayTimeArray.push(g), this.overallTimeArray.push(m), this.traceIdMap.delete(_h);
- }
- }
- }
- } catch (err) {
- _iterator3.e(err);
- } finally {
- _iterator3.f();
- }
- }
- if (this.cachedPtss[e] == this.moveStartPts && (this.MoveDisplayDelay = Date.now() - this.StartMovingTs), this.inMovingMode) {
- var _h2 = Date.now(),
- _f = _h2 - this.lastMoveDisplayTime;
- this.moveDisplayCircular.add(_f), this.lastMoveDisplayTime = _h2;
- }
- this.executeFunction("signal", {
- signal: this.cachedMetas[e],
- pts: this.cachedPtss[e],
- alreadyUpdateYUV: !0
- }), this.cachedRender[e] = !0, this.getPtr = (this.getPtr + 1) % this.cachedLength;
- }
- }
- }, {
- key: "unmarshalPano",
- value: function unmarshalPano(e) {
- var t = new DataView(e);
- if (t.getUint32(0) != 1723558763) return !1;
- console.log("Receive Pano Message"), t.getUint16(4);
- var n = t.getUint16(6),
- o = t.getUint32(8),
- a = t.getUint32(12) - (1 << 30) * 2,
- s = t.getUint32(16) - (1 << 30) * 2,
- l = t.getUint32(20) - (1 << 30) * 2,
- u = t.getUint32(24),
- c = new Uint8Array(e).subarray(28, 64),
- h = String.fromCharCode.apply(null, c),
- f = t.getUint32(64),
- d = e.byteLength - n;
- if (d == u) {
- var g = {
- data: new Uint8Array(e).subarray(n),
- mediaLen: u,
- tileId: o,
- uuid: h,
- x: a,
- y: s,
- z: l
- };
- this.decoderWorker.postMessage({
- t: 8,
- data: g
- });
- } else {
- var _ = new Uint8Array(e, n, d);
- if (this.cachePanoTileID == o) {
- if (this.panoCacheBuffer.set(_, f), this.panoCacheSize += d, this.panoCacheSize === u) {
- var m = {
- data: new Uint8Array(this.panoCacheBuffer).slice(0, u),
- mediaLen: u,
- tileId: o,
- uuid: h,
- x: a,
- y: s,
- z: l
- };
- this.decoderWorker.postMessage({
- t: 8,
- data: m
- }), this.panoCacheSize = 0;
- }
- } else this.panoCacheBuffer.set(_, f), this.panoCacheSize = d, this.cachePanoTileID = o;
- }
- return !0;
- }
- }, {
- key: "clearMoveArray",
- value: function clearMoveArray() {
- this.MovingTraceId = "", this.inMovingMode = !1, this.StartMovingTs = 0, this.MoveToFrameCnt = 0, this.MoveResponseDelay = 0, this.MoveProcessDelay = 0, this.MoveDisplayDelay = 0, this.moveStartPts = -1, this.moveResponseCircular.clear(), this.moveProcessCircular.clear(), this.moveDisplayCircular.clear(), this.moveEvent = "";
- }
- }, {
- key: "getIsMoving",
- value: function getIsMoving(e) {
- var t;
- if (typeof e.newUserStates != "undefined") for (var r = 0; r < e.newUserStates.length; r++) {
- var n = e.newUserStates[r];
- if (n.userId == this.rtcp.network.room.userId) {
- t = n.renderInfo.isMoving;
- break;
- }
- }
- return t;
- }
- }, {
- key: "isHeartBeatPacket",
- value: function isHeartBeatPacket(e, t) {
- return new DataView(e).getUint32(0) == 2009889916;
- }
- }, {
- key: "resetSendTimeDiff",
- value: function resetSendTimeDiff() {
- this.prevSenderTs = 0, this.serverSendTimeArray.clear();
- }
- }, {
- key: "calcSendTimeDiff",
- value: function calcSendTimeDiff(e) {
- if (this.prevSenderTs == -1) {
- this.prevSenderTs = e;
- return;
- }
- var t = e - this.prevSenderTs;
- this.serverSendTimeArray.add(t), this.prevSenderTs = e;
- }
- }, {
- key: "unmarshalStream",
- value: function unmarshalStream(e) {
- var _this6 = this;
- var T, C, A, S, P, R, M, x, I, w;
- var t = new DataView(e);
- if (t.getUint32(0) != 1437227610) return !1;
- t.getUint16(4);
- var n = t.getUint16(6),
- o = t.getUint16(8),
- a = o,
- s = t.getUint16(10);
- var l = !1;
- s == 1 && (l = !0);
- var u = t.getUint32(12),
- c = t.getUint32(16),
- h = t.getUint32(20),
- f = t.getUint16(24),
- d = t.getUint16(26),
- _ = t.getUint32(28),
- g = t.getUint32(n - 4),
- m = u + c,
- v = e.byteLength - n,
- y = new Uint8Array(e, n, v);
- this.calcSendTimeDiff(h);
- var b;
- if (this.inPanoMode && (c > 0 || f)) return defaultLogger.error("Stream Protocal Violation: receive illegal stream in Pano mode"), !0;
- if (v === m) {
- this.receivedMedia++;
- var O = new Uint8Array(e).subarray(n);
- h - this.lastServerTS > 60 ? this.serverFrameSlow++ : h - this.lastServerTS < 16 && this.serverFrameFast++;
- var D = Date.now();
- D - this.lastClientTS > 60 ? this.clientFrameSlow++ : D - this.lastClientTS < 16 && this.clientFrameFast++;
- var F = c === 0,
- V = h - this.lastServerTS;
- this.lastServerTS != 0 && ((o + 65536 - this.lastSeq) % 65536 === 1 && this.lastIsPureMeta == F && (F ? this.srvMetaIntervalCircular.add(V) : this.srvMediaIntervalCircular.add(V)), this.frameServerCircular.add(V), this.frameClientCircular.add(D - this.lastClientTS)), this.lastSeq = o, this.lastIsPureMeta = F, this.lastServerTS = h, this.lastClientTS = D;
- var N = O.subarray(0, u),
- L = Date.now(),
- k = JSON.parse(this.Stringify(N)),
- U = Date.now();
- this.showAllReceivedMetadata && console.log(h, D, k), this.metaParseAraay.push(U - L), (T = k.traceIds) != null && T.length && this.processMetaWithTraceId(k), c != 0 && this.moveStartPts == -1 && this.inMovingMode && (this.moveStartPts = o), this.moveStartPts == o && (this.MoveResponseDelay = Date.now() - this.StartMovingTs, console.log("move response delay: ", o, this.moveStartPts, this.MoveResponseDelay));
- var z = this.getIsMoving(k);
- if (this.inMovingMode && z == 0 && this.lastIsMoving == 1 && this.clearMoveArray(), typeof z != "undefined" && (this.lastIsMoving = z), this.inMovingMode) {
- var G = Date.now(),
- W = G - this.lastMoveResponseTime;
- this.moveResponseCircular.add(W), this.lastMoveResponseTime = G;
- }
- (f || d) && (b = (P = (S = (A = (C = k.newUserStates) == null ? void 0 : C.find(function (G) {
- return G.userId === _this6._rtcp.network.room.userId;
- })) == null ? void 0 : A.playerState) == null ? void 0 : S.player) == null ? void 0 : P.position);
- var H = {
- t: 0,
- data: O,
- mediaLen: c,
- metaLen: u,
- metadata: k,
- frameCnt: a,
- server_ts: h,
- isIDR: l,
- cacheRequest: d,
- cached: f,
- cachedKey: _,
- position: b
- };
- if (this.inPanoMode) return this.executeFunction("signal", {
- signal: k,
- pts: -1,
- alreadyUpdateYUV: !0
- }), !0;
- if (this.decoderWorker.postMessage(H, [O.buffer]), !this.firstMediaReceived) {
- this.firstMediaArraval = Date.now();
- var _G = this.firstMediaArraval - this.rtcp.network.room._startTime;
- defaultLogger.infoAndReportMeasurement({
- metric: "firstMediaArravalAt",
- value: _G,
- group: "joinRoom"
- }), this.firstMediaReceived = !0;
- }
- } else {
- var _O = this.hasFrmCntInCache(a);
- if (_O != -1) {
- if (this.cacheFrameComposes[_O].buffer.set(y, g), this.cacheFrameComposes[_O].size += v, this.cacheFrameComposes[_O].size === m) {
- var _D = new Uint8Array(this.cacheFrameComposes[_O].buffer).slice(0, m);
- this.cacheFrameComposes[_O].frameCnt = -1, this.cacheFrameComposes[_O].size = 0, this.cacheFrameComposes[_O].startReceiveTime = 0, this.cacheFrameComposes[_O].serverTime = 0, this.receivedMedia++, h - this.lastServerTS > 60 ? this.serverFrameSlow++ : h - this.lastServerTS < 16 && this.serverFrameFast++;
- var _F = Date.now();
- _F - this.lastClientTS > 60 ? this.clientFrameSlow++ : _F - this.lastClientTS < 16 && this.clientFrameFast++, this.lastServerTS != 0 && (this.frameServerCircular.add(h - this.lastServerTS), this.frameClientCircular.add(_F - this.lastClientTS)), this.lastServerTS = h, this.lastClientTS = _F;
- var _V = _D.subarray(0, u),
- _N = Date.now(),
- _L = JSON.parse(this.Stringify(_V)),
- _k = Date.now();
- this.showAllReceivedMetadata && console.log(h, _F, _L), this.metaParseAraay.push(_k - _N), (R = _L.traceIds) != null && R.length && this.processMetaWithTraceId(_L), c != 0 && this.moveStartPts == -1 && this.inMovingMode && (this.moveStartPts = o), this.moveStartPts == o && (this.MoveResponseDelay = Date.now() - this.StartMovingTs);
- var _U = this.getIsMoving(_L);
- if (this.inMovingMode && _U == 0 && this.lastIsMoving == 1 && this.clearMoveArray(), typeof _U != "undefined" && (this.lastIsMoving = _U), this.inMovingMode) {
- var _H = Date.now(),
- _G2 = _H - this.lastMoveResponseTime;
- this.moveResponseCircular.add(_G2), this.lastMoveResponseTime = _H;
- }
- (f || d) && (b = (w = (I = (x = (M = _L.newUserStates) == null ? void 0 : M.find(function (H) {
- return H.userId === _this6._rtcp.network.room.userId;
- })) == null ? void 0 : x.playerState) == null ? void 0 : I.player) == null ? void 0 : w.position);
- var _z = {
- t: 0,
- data: _D,
- mediaLen: c,
- metaLen: u,
- metadata: _L,
- frameCnt: a,
- server_ts: h,
- isIDR: l,
- cacheRequest: d,
- cached: f,
- cachedKey: _,
- position: b
- };
- if (this.inPanoMode) return this.executeFunction("signal", {
- signal: _L,
- pts: -1,
- alreadyUpdateYUV: !0
- }), !0;
- if (this.decoderWorker.postMessage(_z, [_D.buffer]), !this.firstMediaReceived) {
- this.firstMediaArraval = Date.now();
- var _H2 = this.firstMediaArraval - this.rtcp.network.room._startTime;
- defaultLogger.infoAndReportMeasurement({
- metric: "firstMediaArravalAt",
- value: _H2,
- group: "joinRoom"
- }), this.firstMediaReceived = !0;
- }
- } else this.cacheFrameComposes[_O].size > m && defaultLogger.debug("I frame exceed, cache size is ", this.cacheSize, ", total size is ", m);
- } else if (_O == -1) {
- var _D2 = this.hasFrmCntInCache(-1);
- if (_D2 == -1) {
- var _F2 = Date.now() + 1e18,
- _V2 = -1;
- for (var _N2 = 0; _N2 < this.cacheFrameComposes.length; _N2++) {
- this.cacheFrameComposes[_N2].serverTime < _F2 && (_F2 = this.cacheFrameComposes[_N2].serverTime, _V2 = _N2);
- }
- _D2 = _V2;
- }
- this.cacheFrameComposes[_D2].buffer.set(y, g), this.cacheFrameComposes[_D2].size = v, this.cacheFrameComposes[_D2].frameCnt = a, this.cacheFrameComposes[_D2].startReceiveTime = Date.now(), this.cacheFrameComposes[_D2].serverTime = h;
- }
- }
- return !0;
- }
- }, {
- key: "reset",
- value: function reset() {
- defaultLogger.debug("Worker reset is called"), this.cacheFrameCnt = 0, this.receivedMedia = 0, this.reconnectSignal = !0, this.decoderWorker.postMessage({
- t: 4
- });
- }
- }, {
- key: "dataHandleOff",
- value: function dataHandleOff(e) {
- defaultLogger.debug("hhh");
- }
- }, {
- key: "dataHandle",
- value: function dataHandle(e) {
- this.saveframe && (this.decoderWorker.postMessage({
- t: 6
- }), this.saveframe = !1), this.SaveMediaStream && (this.decoderWorker.postMessage({
- t: 7
- }), this.SaveMediaStream = !1);
- var t = new Uint8Array(e);
- if (t.length >= 4 && this.isHeartBeatPacket(t.buffer, t.length) == !0) return;
- if (t.length > 36 && this.unmarshalStream(t.buffer) == !0) {
- this.reconnectSignal && (this.executeFunction("reconnectedFrame", {}), this.reconnectSignal = !1);
- return;
- }
- if (t.length > 20 && this.unmarshalPano(t.buffer) == !0) return;
- this.noWasmBytesReceived += e.byteLength;
- var r = JSON.parse(this.Stringify(t));
- this.executeFunction("signal", {
- signal: r,
- pts: -1,
- alreadyUpdateYUV: !0
- });
- }
- }, {
- key: "changePanoMode",
- value: function changePanoMode(e) {
- this.inPanoMode = e;
- }
- }, {
- key: "uploadDataToServer",
- value: function uploadDataToServer() {
- this.DynamicPanoTest == !0 && (this.onRotateInPanoMode({
- traceId: "b2e1a296-6438-4371-8a31-687beb724ebe"
- }), this.DynamicPanoTest = !1);
- function e(ie, ee) {
- return ee == -1 && (ee = 0), ie + ee;
- }
- function t(ie, ee) {
- return Math.max(ie, ee);
- }
- var r = this.responseTimeArray.reduce(e, 0) / this.responseTimeArray.length || 0,
- n = this.processTimeArray.reduce(e, 0) / this.processTimeArray.length || 0,
- o = this.displayTimeArray.reduce(e, 0) / this.displayTimeArray.length || 0,
- a = this.overallTimeArray.reduce(e, 0) / this.overallTimeArray.length || 0,
- s = this.overallTimeArray.length;
- this.responseTimeArray = [], this.processTimeArray = [], this.displayTimeArray = [], this.overallTimeArray = [];
- var l = this.moveResponseCircular.getThreshPercent(),
- u = l[0],
- c = l[1],
- h = l[2],
- f = l[3],
- d = l[4],
- _ = d - f,
- g = 1 - c / d || 0,
- m = [u, c - u, h - c, f - h, _],
- v = this.moveProcessCircular.getThreshPercent(),
- y = v[0],
- b = v[1],
- T = v[2],
- C = v[3],
- A = v[4],
- S = A - C,
- P = 1 - b / A || 0,
- R = [y, b - y, T - b, C - T, S],
- M = this.moveDisplayCircular.getThreshPercent(),
- x = M[0],
- I = M[1],
- w = M[2],
- O = M[3],
- D = M[4],
- F = D - O,
- V = 1 - I / D || 0,
- N = [x, I - x, w - I, O - w, F],
- L = x,
- k = I - x,
- U = w - I,
- z = O - w,
- H = F,
- G = this.moveResponseCircular.getAvg(),
- W = this.moveProcessCircular.getAvg(),
- j = this.moveDisplayCircular.getAvg(),
- B = this.moveResponseCircular.getMax(),
- X = this.moveProcessCircular.getMax(),
- $ = this.moveDisplayCircular.getMax(),
- Y = this.moveResponseCircular.getStandardDeviation(),
- K = this.moveProcessCircular.getStandardDeviation(),
- Z = this.moveDisplayCircular.getStandardDeviation();
- this.moveResponseCircular.getIncomingAvg(), this.moveProcessCircular.getIncomingAvg(), this.moveDisplayCircular.getIncomingAvg(), this.moveResponseCircular.getIncomingMax(), this.moveProcessCircular.getIncomingMax(), this.moveDisplayCircular.getIncomingMax(), this.moveResponseCircular.clearIncoming(), this.moveProcessCircular.clearIncoming(), this.moveDisplayCircular.clearIncoming();
- var q = this.frameServerCircular.getAvg(),
- J = this.frameServerCircular.getMax();
- this.frameClientCircular.getAvg(), this.frameClientCircular.getMax();
- var Q = this.metaParseAraay.reduce(e, 0) / this.metaParseAraay.length || 0,
- te = this.metaParseAraay.reduce(t, 0);
- this.metaParseAraay = [];
- var re = {
- mediaBytesReceived: this.mediaBytesReceived,
- metaBytesReceived: this.metaBytesReceived,
- packetsLost: this.packetsLost,
- timestamp: Date.now(),
- frameHeight: 1280,
- frameWidth: 720,
- framesReceived: this.receivedMedia,
- framesReceivedWorker: this.receivedMedia_worker,
- framesDecoded: this.receivedYUV,
- framesEmited: this.receivedEmit,
- decodeTimePerFrame: this.decodeTimePerFrame,
- decodeTimeMaxFrame: this.decodeTimeMaxFrame,
- packetsDrop: this.packetsDrop,
- framesAwait: this.framesAwait,
- firstMediaArraval: this.firstMediaArraval,
- firstYUVDecoded: this.firstYUVDecoded,
- firstRender: this.firstRender,
- returnFrames: this.returnFrames,
- sendOutBuffer: this.sendOutBuffer,
- maxGraphicTime: this.updateYUVCircular.getMax(),
- averageGraphicTime: this.updateYUVCircular.getAvg(),
- jankTimes: this.JankTimes,
- bigJankTimes: this.bigJankTimes,
- decodeJankTimes: this.DecodeJankTimes,
- bigDecodeJankTimes: this.bigDecodeJankTimes,
- serverFrameSlow: this.serverFrameSlow,
- serverFrameFast: this.serverFrameFast,
- clientFrameSlow: this.clientFrameSlow,
- clientFrameFast: this.clientFrameFast,
- rtcMessageReceived: this.rtcMessageReceived,
- rtcBytesReceived: this.rtcBytesReceived - this.noWasmBytesReceived,
- receiveIframes: this.receiveIframes,
- decodeIframes: this.decodeIframes,
- avgResponseTime: r,
- avgProcessTime: n,
- avgDisplayTime: o,
- avgOverallTime: a,
- overallTimeCount: s,
- responseMiss: this.responseMiss,
- processMiss: this.processMiss,
- displayMiss: this.displayMiss,
- updateDropFrame: this.updateDropFrame,
- moveEvent: this.moveEvent,
- avgResponseMoveDiff: this.moveEvent == "MoveTo" ? G : 0,
- avgProcessMoveDiff: this.moveEvent == "MoveTo" ? W : 0,
- avgDisplayMoveDiff: this.moveEvent == "MoveTo" ? j : 0,
- maxResponseMoveDiff: this.moveEvent == "MoveTo" ? B : 0,
- maxProcessMoveDiff: this.moveEvent == "MoveTo" ? X : 0,
- maxDisplayMoveDiff: this.moveEvent == "MoveTo" ? $ : 0,
- moveResponseJank: this.moveEvent == "MoveTo" ? g : 0,
- moveProcessJank: this.moveEvent == "MoveTo" ? P : 0,
- moveDisplayJank: this.moveEvent == "MoveTo" ? V : 0,
- moveResponseCounts: this.moveEvent == "MoveTo" ? m.toString() : "0,0,0,0,0",
- moveProcessCounts: this.moveEvent == "MoveTo" ? R.toString() : "0,0,0,0,0",
- moveDisplayCounts: this.moveEvent == "MoveTo" ? N.toString() : "0,0,0,0,0",
- MoveDisplayCountGood: this.moveEvent == "MoveTo" ? L.toString() : "0",
- MoveDisplayCountWell: this.moveEvent == "MoveTo" ? k.toString() : "0",
- MoveDisplayCountFair: this.moveEvent == "MoveTo" ? U.toString() : "0",
- MoveDisplayCountBad: this.moveEvent == "MoveTo" ? z.toString() : "0",
- MoveDisplayCountRest: this.moveEvent == "MoveTo" ? H.toString() : "0",
- moveResponseDelay: this.moveEvent == "MoveTo" ? this.MoveResponseDelay : 0,
- moveProcessDelay: this.moveEvent == "MoveTo" ? this.MoveProcessDelay : 0,
- moveDisplayDelay: this.moveEvent == "MoveTo" ? this.MoveDisplayDelay : 0,
- sdMoveResponseLongTime: Y,
- sdMoveProcessLongTime: K,
- sdMoveDisplayLongTime: Z,
- avgResponseFlyDiff: this.moveEvent == "GetOnVehicle" || this.moveEvent == "GetOnAirship" ? G : 0,
- avgProcessFlyDiff: this.moveEvent == "GetOnVehicle" || this.moveEvent == "GetOnAirship" ? W : 0,
- avgDisplayFlyDiff: this.moveEvent == "GetOnVehicle" || this.moveEvent == "GetOnAirship" ? j : 0,
- maxResponseFlyDiff: this.moveEvent == "GetOnVehicle" || this.moveEvent == "GetOnAirship" ? B : 0,
- maxProcessFlyDiff: this.moveEvent == "GetOnVehicle" || this.moveEvent == "GetOnAirship" ? X : 0,
- maxDisplayFlyDiff: this.moveEvent == "GetOnVehicle" || this.moveEvent == "GetOnAirship" ? $ : 0,
- flyResponseJank: this.moveEvent == "GetOnVehicle" || this.moveEvent == "GetOnAirship" ? g : 0,
- flyProcessJank: this.moveEvent == "GetOnVehicle" || this.moveEvent == "GetOnAirship" ? P : 0,
- flyDisplayJank: this.moveEvent == "GetOnVehicle" || this.moveEvent == "GetOnAirship" ? V : 0,
- flyResponseCounts: this.moveEvent == "GetOnVehicle" || this.moveEvent == "GetOnAirship" ? m.toString() : "0,0,0,0,0",
- flyProcessCounts: this.moveEvent == "GetOnVehicle" || this.moveEvent == "GetOnAirship" ? R.toString() : "0,0,0,0,0",
- flyDisplayCounts: this.moveEvent == "GetOnVehicle" || this.moveEvent == "GetOnAirship" ? N.toString() : "0,0,0,0,0",
- flyResponseDelay: this.moveEvent == "GetOnVehicle" || this.moveEvent == "GetOnAirship" ? this.MoveResponseDelay : 0,
- flyProcessDelay: this.moveEvent == "GetOnVehicle" || this.moveEvent == "GetOnAirship" ? this.MoveProcessDelay : 0,
- flyDisplayDelay: this.moveEvent == "GetOnVehicle" || this.moveEvent == "GetOnAirship" ? this.MoveDisplayDelay : 0,
- avgMetaParseTime: Q,
- maxMetaParseTime: te,
- avgServerDiff: q,
- maxServerDiff: J,
- streamType: WASM_Version
- };
- return this.lastReturnFrames = this.returnFrames, this.lastReceivedEmit = this.receivedEmit, re;
- }
- }]);
- return Workers;
- }();
- function _createSuper$7(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$7(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
- function _isNativeReflectConstruct$7() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
- var Rtcp = /*#__PURE__*/function (_EventEmitter) {
- _inherits(Rtcp, _EventEmitter);
- var _super = _createSuper$7(Rtcp);
- function Rtcp(e) {
- var _this;
- _classCallCheck(this, Rtcp);
- _this = _super.call(this);
- _this.connection = null;
- _this.inputChannel = null;
- _this.mediaStream = null;
- _this.socket = null;
- _this.connected = !1;
- _this.candidates = [];
- _this.isAnswered = !1;
- _this.isFlushing = !1;
- _this.inputReady = !1;
- _this.workers = null;
- _this.actived = !0;
- _this.heartbeat = null;
- _this.network = e; //this.workers = new Workers(this,new Logger("decode")),
- //this.workers.registerLogger(new Logger("decode")),
- _this.workers = new Workers(_assertThisInitialized(_this), logger);
- _this.workers.registerLogger(logger);
- _this.workers.registerFunction("data", function (t) {
- _this.emit("data", t);
- }), _this.heartbeat = new Heartbeat({
- ping: function ping(t) {
- e.room.actionsHandler.echo(t);
- },
- pong(t, r) {
- var n;
- r && t > 500 && logger.warn("high hb value ".concat(t, ", traceId:") + r), (n = e.room.stats) == null || n.assign({
- hb: t
- });
- }
- });
- return _this;
- }
- _createClass(Rtcp, [{
- key: "onIcecandidate",
- value: function onIcecandidate(e) {
- if (e.candidate != null) {
- var t = JSON.stringify(e.candidate);
- logger.debug("Got ice candidate: ".concat(t)), this.network.socket.send({
- id: "ice_candidate",
- data: btoa(t)
- });
- }
- }
- }, {
- key: "onIcecandidateerror",
- value: function onIcecandidateerror(e) {
- logger.error("onicecandidateerror", e.errorCode, e.errorText, e);
- }
- }, {
- key: "onIceStateChange",
- value: function onIceStateChange(e) {
- switch (e.target.iceGatheringState) {
- case "gathering":
- logger.info("ice gathering");
- break;
- case "complete":
- logger.info("Ice gathering completed");
- }
- }
- }, {
- key: "onIceConnectionStateChange",
- value: function onIceConnectionStateChange() {
- if (!!this.connection) switch (logger.info("iceConnectionState: ".concat(this.connection.iceConnectionState)), this.connection.iceConnectionState) {
- case "connected":
- {
- this.connected = !0;
- break;
- }
- case "disconnected":
- {
- this.connected = !1, this.emit("rtcDisconnected");
- break;
- }
- case "failed":
- {
- this.emit("rtcDisconnected"), this.connected = !1;
- break;
- }
- }
- }
- }, {
- key: "setRemoteDescription",
- value: function () {
- var _setRemoteDescription = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee(e, t) {
- var a, s, l, r, n, o, u;
- return regenerator.wrap(function _callee$(_context) {
- while (1) {
- switch (_context.prev = _context.next) {
- case 0:
- if (this.connection) {
- _context.next = 2;
- break;
- }
- return _context.abrupt("return");
- case 2:
- r = JSON.parse(atob(e)), n = new RTCSessionDescription(r);
- _context.next = 5;
- return this.connection.setRemoteDescription(n);
- case 5:
- _context.next = 7;
- return this.connection.createAnswer();
- case 7:
- o = _context.sent;
- if (o.sdp = (a = o.sdp) == null ? void 0 : a.replace(/(a=fmtp:111 .*)/g, "$1;stereo=1;sprop-stereo=1"), ((l = (s = o.sdp) == null ? void 0 : s.match(/a=mid:1/g)) == null ? void 0 : l.length) == 2) {
- u = o.sdp.lastIndexOf("a=mid:1");
- o.sdp = o.sdp.slice(0, u) + "a=mid:2" + o.sdp.slice(u + 7);
- }
- _context.prev = 9;
- _context.next = 12;
- return this.connection.setLocalDescription(o);
- case 12:
- _context.next = 17;
- break;
- case 14:
- _context.prev = 14;
- _context.t0 = _context["catch"](9);
- logger.error("error", _context.t0);
- case 17:
- this.isAnswered = !0, this.network.rtcp.flushCandidate(), this.network.socket.send({
- id: "answer",
- data: btoa(JSON.stringify(o))
- }), t.srcObject = this.mediaStream;
- case 18:
- case "end":
- return _context.stop();
- }
- }
- }, _callee, this, [[9, 14]]);
- }));
- function setRemoteDescription(_x, _x2) {
- return _setRemoteDescription.apply(this, arguments);
- }
- return setRemoteDescription;
- }()
- }, {
- key: "flushCandidate",
- value: function flushCandidate() {
- var _this2 = this;
- this.isFlushing || !this.isAnswered || (this.isFlushing = !0, this.candidates.forEach(function (e) {
- var t = atob(e),
- r = JSON.parse(t);
- if (/172\./.test(r.candidate)) return;
- var n = new RTCIceCandidate(r);
- _this2.connection && _this2.connection.addIceCandidate(n).then(function () {}, function (o) {
- logger.info("add candidate failed", o);
- });
- }), this.isFlushing = !1);
- }
- }, {
- key: "input",
- value: function input(e) {
- var t;
- !this.actived || !this.inputChannel || this.inputChannel.readyState === "open" && ((t = this.inputChannel) == null || t.send(e));
- }
- }, {
- key: "start",
- value: function start() {
- var _this3 = this;
- this.connection = new RTCPeerConnection();
- var e = Date.now();
- this.connection.ondatachannel = function (t) {
- logger.info("ondatachannel: ".concat(t.channel.label)), _this3.inputChannel = t.channel, _this3.inputChannel.onopen = function () {
- var r;
- logger.info("The input channel has opened, id:", (r = _this3.inputChannel) == null ? void 0 : r.id), _this3.inputReady = !0, _this3.emit("rtcConnected"), _this3.network.room.currentNetworkOptions.reconnect || (logger.infoAndReportMeasurement({
- metric: "datachannelOpenedAt",
- startTime: _this3.network.room._startTime,
- group: "joinRoom"
- }), logger.infoAndReportMeasurement({
- metric: "datachannelOpenedCost",
- startTime: e,
- group: "joinRoom"
- }));
- }, _this3.inputChannel.onclose = function () {
- var r;
- return logger.info("The input channel has closed, id:", (r = _this3.inputChannel) == null ? void 0 : r.id);
- }, _this3.inputChannel.onmessage = function (r) {
- _this3.workers.dataHandle(r.data);
- };
- }, this.connection.oniceconnectionstatechange = this.onIceConnectionStateChange, this.connection.onicegatheringstatechange = this.onIceStateChange, this.connection.onicecandidate = this.onIcecandidate, this.connection.onicecandidateerror = this.onIcecandidateerror, this.network.socket.send({
- id: "init_webrtc",
- data: JSON.stringify({
- is_mobile: !0
- })
- });
- }
- }, {
- key: "addCandidate",
- value: function addCandidate(e) {
- e === "" ? this.network.rtcp.flushCandidate() : this.candidates.push(e);
- }
- }, {
- key: "disconnect",
- value: function disconnect() {
- var e, t, r;
- this.heartbeat.stop(), logger.info("ready to close datachannel, id", (e = this.inputChannel) == null ? void 0 : e.id), (t = this.inputChannel) == null || t.close(), (r = this.connection) == null || r.close(), this.connection = null, this.inputChannel = null;
- }
- }, {
- key: "sendStringData",
- value: function sendStringData(e) {
- this.input(e);
- }
- }, {
- key: "sendData",
- value: function sendData(e) {
- var t = "";
- try {
- t = JSON.stringify(e);
- } catch (r) {
- logger.error(r);
- return;
- }
- this.input(t);
- }
- }]);
- return Rtcp;
- }(EventEmitter);
- var NetworkMonitor = /*#__PURE__*/function () {
- function NetworkMonitor(e) {
- _classCallCheck(this, NetworkMonitor);
- this._listener = e;
- }
- _createClass(NetworkMonitor, [{
- key: "isOnline",
- get: function get() {
- var e = window.navigator;
- return typeof e.onLine == "boolean" ? e.onLine : !0;
- }
- }, {
- key: "start",
- value: function start() {
- window.addEventListener("online", this._listener), window.addEventListener("offline", this._listener);
- }
- }, {
- key: "stop",
- value: function stop() {
- window.removeEventListener("online", this._listener), window.removeEventListener("offline", this._listener);
- }
- }]);
- return NetworkMonitor;
- }();
- var Stream = /*#__PURE__*/function () {
- function Stream(e) {
- _classCallCheck(this, Stream);
- this.el = null;
- this._streamPlayTimer = null;
- if (!e) {
- this.el = this.createVideoElement();
- return;
- }
- this.el = e;
- }
- _createClass(Stream, [{
- key: "play",
- value: function play() {
- var _this = this;
- return new Promise(function (e, t) {
- _this._streamPlayTimer = new Timeout(function () {
- t(new InternalError("Stream play timeout"));
- }, 5e3), _this.el && _this.el.play().then(function () {
- var r;
- e(), logger.info("Media can autoplay"), (r = _this._streamPlayTimer) == null || r.clear();
- }).catch(function (r) {
- var n;
- logger.error("Media Failed to autoplay"), logger.error(r), t(new InternalError("Media Failed to autoplay")), (n = _this._streamPlayTimer) == null || n.clear();
- });
- });
- }
- }, {
- key: "createVideoElement",
- value: function createVideoElement() {
- var e = document.createElement("video");
- return e.muted = !0, e.autoplay = !1, e.playsInline = !0, e.setAttribute("autostart", "false"), e.setAttribute("controls", "controls"), e.setAttribute("muted", "true"), e.setAttribute("preload", "auto"), e.setAttribute("hidden", "hidden"), document.body.appendChild(e), e;
- }
- }]);
- return Stream;
- }();
- function _createSuper$6(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$6(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
- function _isNativeReflectConstruct$6() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
- var InternalError$1 = /*#__PURE__*/function (_XverseError) {
- _inherits(InternalError, _XverseError);
- var _super = _createSuper$6(InternalError);
- function InternalError(e) {
- _classCallCheck(this, InternalError);
- return _super.call(this, 1002, e || "\u5185\u90E8\u9519\u8BEF");
- }
- return _createClass(InternalError);
- }(XverseError);
- function _createSuper$5(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$5(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
- function _isNativeReflectConstruct$5() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
- var workerSourceCode = "onmessage = function (event) {\n const data = event.data\n if (!data) return\n \n if (data.type === 'start') {\n const startTime = Date.now()\n const request = new XMLHttpRequest()\n request.open('GET', data.url)\n try {\n request.send()\n } catch (error) {\n console.error(error)\n }\n request.addEventListener('readystatechange', () => {\n if (request.readyState == 4) {\n if (request.status == 200) {\n postMessage(Date.now() - startTime)\n }\n }\n })\n }\n }\n ";
- var NetworkController = /*#__PURE__*/function (_EventEmitter) {
- _inherits(NetworkController, _EventEmitter);
- var _super = _createSuper$5(NetworkController);
- function NetworkController(e) {
- var _this;
- _classCallCheck(this, NetworkController);
- _this = _super.call(this);
- _this.socket = null;
- _this.rtcp = null;
- _this.stream = null;
- _this._state = 'connecting';
- _this._networkMonitor = null;
- _this.blockedActions = [];
- _this.reconnectCount = 0;
- _this.room = e, _this.socket = new Socket(_assertThisInitialized(_this));
- _this.rtcp = new Rtcp(_assertThisInitialized(_this));
- _this.stream = new Stream();
- _this._networkMonitor = new NetworkMonitor(function () {
- logger.info("network changed, online:", _this._networkMonitor.isOnline), _this._state === "disconnected" && _this._networkMonitor.isOnline && (logger.info("network back to online, try to reconnect"), _this.reconnect());
- });
- _this.checkNetworkQuality(_this.room.currentNetworkOptions.wsServerUrl);
- _this._networkMonitor.start();
- new VisibilityChangeHandler().subscribe(function (r) {
- var n, o;
- r ? ((o = _this.room.stats) == null || o.disable(), logger.infoAndReportMeasurement({
- metric: "pageHide",
- startTime: Date.now()
- })) : ((n = _this.room.stats) == null || n.enable(), logger.infoAndReportMeasurement({
- metric: "pageShow",
- startTime: Date.now(),
- extra: {
- state: _this._state
- }
- }), _this._state === "disconnected" && _this.reconnect());
- });
- return _this;
- }
- _createClass(NetworkController, [{
- key: "startGame",
- value: function startGame() {
- var _this2 = this;
- return new Promise(function (e, t) {
- if (!_this2.rtcp.connected) return t(new InternalError$1("Game cannot load. Please refresh"));
- if (!_this2.rtcp.inputReady) return t(new InternalError$1("Game is not ready yet. Please wait"));
- _this2.socket.on("gameRoomAvailable", function (r) {
- _this2.setState("connected"), e(r), _this2.rtcp.heartbeat.start();
- }), _this2.socket.on("socketClosed", function (r) {
- t(r);
- }), _this2.socket.startGame();
- });
- }
- }, {
- key: "addBlockedActions",
- value: function addBlockedActions(e) {
- var _this$blockedActions;
- (_this$blockedActions = this.blockedActions).push.apply(_this$blockedActions, _toConsumableArray(e));
- }
- }, {
- key: "removeBlockedActions",
- value: function removeBlockedActions(e) {
- if (!e) {
- this.blockedActions = [];
- return;
- }
- var t = this.blockedActions.indexOf(e);
- this.blockedActions.splice(t, 1);
- }
- }, {
- key: "setState",
- value: function setState(e) {
- this._state !== e && (logger.info("Set network state to ", e), this._state = e);
- }
- }, {
- key: "connectAndStart",
- value: function () {
- var _connectAndStart = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee(e) {
- return regenerator.wrap(function _callee$(_context) {
- while (1) {
- switch (_context.prev = _context.next) {
- case 0:
- return _context.abrupt("return", this.connect(e).then(this.startGame));
- case 1:
- case "end":
- return _context.stop();
- }
- }
- }, _callee, this);
- }));
- function connectAndStart(_x) {
- return _connectAndStart.apply(this, arguments);
- }
- return connectAndStart;
- }()
- }, {
- key: "connect",
- value: function () {
- var _connect = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee2() {
- var _this3 = this;
- var e,
- _args2 = arguments;
- return regenerator.wrap(function _callee2$(_context2) {
- while (1) {
- switch (_context2.prev = _context2.next) {
- case 0:
- e = _args2.length > 0 && _args2[0] !== undefined ? _args2[0] : !1;
- this.room.updateCurrentNetworkOptions({
- reconnect: e
- });
- return _context2.abrupt("return", new Promise(function (t, r) {
- _this3.rtcp.on("rtcConnected", function () {
- _this3.setState("connected"), t();
- }), _this3.rtcp.on("rtcDisconnected", function () {
- logger.info("rtc disconnected"), _this3._state === "connecting" ? (_this3.setState("disconnected"), r(new InternalError$1("rtc connect failed"))) : (_this3.setState("disconnected"), logger.info("rtc disconnected, start to reconnect"), _this3.reconnect());
- }), _this3.socket.on("socketQuit", function () {
- logger.info("socket quit success"), _this3.setState("closed");
- }), _this3.socket.on("socketClosed", function (n) {
- _this3._state === "connecting" && (_this3.setState("disconnected"), r(n)), r(n);
- }), _this3.socket.start();
- }));
- case 3:
- case "end":
- return _context2.stop();
- }
- }
- }, _callee2, this);
- }));
- function connect() {
- return _connect.apply(this, arguments);
- }
- return connect;
- }()
- }, {
- key: "reconnect",
- value: function reconnect() {
- var _this4 = this;
- if (this.room.viewMode === "observer") return;
- var e = Date.now();
- if (this.reconnectCount++, this.reconnectCount > MAX_RECONNECT_COUNT) {
- logger.error("reconnect failed, reached max reconnect count", MAX_RECONNECT_COUNT), this.reconnectCount = 0, this.emit("stateChanged", {
- state: "disconnected"
- });
- return;
- }
- return logger.info("start reconnect, count:", this.reconnectCount), this._reconnect().then(function () {
- logger.infoAndReportMeasurement({
- startTime: e,
- metric: "reconnect"
- });
- }).catch(function (t) {
- if (logger.infoAndReportMeasurement({
- startTime: e,
- metric: "reconnect",
- error: t
- }), t.code === Codes.RepeatLogin) {
- _this4.room.handleRepetLogin();
- return;
- }
- var r = 1e3;
- logger.info("reconnect failed, wait " + r + " ms for next reconnect"), setTimeout(function () {
- _this4.reconnect();
- }, r);
- });
- }
- }, {
- key: "_reconnect",
- value: function _reconnect() {
- var _this5 = this;
- return this._state === "closed" ? (logger.warn("connection closed already"), Promise.reject()) : this._state === "connecting" ? (logger.warn("connection is already in connecting state"), Promise.reject()) : this._state !== "disconnected" ? Promise.reject() : (this.prepareReconnect(), this._state = "connecting", this.emit("stateChanged", {
- state: "reconnecting",
- count: this.reconnectCount
- }), this.socket.off("gameRoomAvailable"), this.socket.off("socketClosed"), this.rtcp.off("rtcDisconnected"), this.rtcp.off("rtcConnected"), this.connectAndStart(!0).then(function (_ref) {
- var e = _ref.session_id;
- _this5.room.updateCurrentNetworkOptions({
- sessionId: e
- }), reporter.updateBody({
- serverSession: e
- }), logger.info("reconnect success"), _this5.setState("connected"), _this5.reconnectCount = 0, _this5.emit("stateChanged", {
- state: "reconnected"
- });
- }));
- }
- }, {
- key: "prepareReconnect",
- value: function prepareReconnect() {
- this.rtcp.disconnect(), this.socket.prepareReconnect(), this.prepareReconnectOptions();
- }
- }, {
- key: "prepareReconnectOptions",
- value: function prepareReconnectOptions() {
- var _ref2 = this.room.currentClickingState || {},
- e = _ref2.camera,
- t = _ref2.player;
- e && t && this.room.updateCurrentNetworkOptions({
- camera: e,
- player: t
- });
- }
- }, {
- key: "sendRtcData",
- value: function sendRtcData(e) {
- if (this.blockedActions.includes(e.action_type)) {
- logger.info("action: ".concat(Actions[e.action_type], " was blocked"));
- return;
- }
- this.rtcp.sendData(e);
- }
- }, {
- key: "sendSocketData",
- value: function sendSocketData(e) {
- logger.debug("ws send ->", e), this.socket.send(e);
- }
- }, {
- key: "quit",
- value: function quit() {
- var e = uuid$1(),
- t = {
- action_type: Actions.Exit,
- trace_id: e,
- exit_action: {},
- user_id: this.room.options.userId,
- packet_id: e
- };
- this.setState("closed"), this.socket.quit(), this.sendRtcData(t);
- }
- }, {
- key: "checkNetworkQuality",
- value: function checkNetworkQuality(i) {
- var worker = null;
- if (!i) return;
- var e = Date.now();
- if (this.pingOthers("https://www.baidu.com", function (t, r) {
- logger.infoAndReportMeasurement({
- metric: "baiduRtt",
- group: "http",
- value: r,
- startTime: e
- });
- }), !worker) {
- var t = new Blob([workerSourceCode], {
- type: "application/javascript"
- });
- worker = new Worker(URL.createObjectURL(t)), worker.onmessage = function (r) {
- logger.infoAndReportMeasurement({
- metric: "workerRtt",
- group: "http",
- startTime: e,
- value: r.data
- });
- };
- }
- }
- }, {
- key: "pingOthers",
- value: function pingOthers(i, e) {
- var t = !1;
- var r = new Image();
- r.onload = o, r.onerror = a;
- var n = Date.now();
- function o(l) {
- t = !0, s();
- }
- function a(l) {}
- function s() {
- var l = Date.now() - n;
- if (typeof e == "function") return t ? e(null, l) : (console.error("error loading resource"), e("error", l));
- }
- r.src = i + "/favicon.ico?" + +new Date();
- }
- }]);
- return NetworkController;
- }(EventEmitter);
- function _createSuper$4(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$4(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
- function _isNativeReflectConstruct$4() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
- var InitConfigTimeoutError = /*#__PURE__*/function (_XverseError) {
- _inherits(InitConfigTimeoutError, _XverseError);
- var _super = _createSuper$4(InitConfigTimeoutError);
- function InitConfigTimeoutError(e) {
- _classCallCheck(this, InitConfigTimeoutError);
- return _super.call(this, 1009, e || "\u914D\u7F6E\u521D\u59CB\u5316\u8D85\u65F6");
- }
- return _createClass(InitConfigTimeoutError);
- }(XverseError);
- function _createSuper$3(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$3(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
- function _isNativeReflectConstruct$3() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
- var InitDecoderTimeoutError = /*#__PURE__*/function (_XverseError) {
- _inherits(InitDecoderTimeoutError, _XverseError);
- var _super = _createSuper$3(InitDecoderTimeoutError);
- function InitDecoderTimeoutError(e) {
- _classCallCheck(this, InitDecoderTimeoutError);
- return _super.call(this, 1008, e || "Decoder \u521D\u59CB\u5316\u8D85\u65F6");
- }
- return _createClass(InitDecoderTimeoutError);
- }(XverseError);
- function _createSuper$2(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$2(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
- function _isNativeReflectConstruct$2() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
- var Xverse_Room = /*#__PURE__*/function (_EventEmitter) {
- _inherits(Xverse_Room, _EventEmitter);
- var _super = _createSuper$2(Xverse_Room);
- function Xverse_Room(e) {
- var _this;
- _classCallCheck(this, Xverse_Room);
- _this = _super.call(this);
- _this.disableAutoTurn = !1;
- _this._currentNetworkOptions = null;
- _this.lastSkinId = null;
- _this.debug = null;
- _this.isFirstDataUsed = !1;
- _this.userId = null;
- _this.pathManager = new PathManager();
- _this.networkController = null;
- _this._startTime = Date.now();
- _this.canvas = null;
- _this.eventsController = null;
- _this.panorama = null;
- _this.engineProxy = null;
- _this._id = null;
- _this.skinList = [];
- _this.isHost = !1;
- _this.avatarManager = new XverseAvatarManager(_assertThisInitialized(_this));
- _this.effectManager = new XverseAvatarManager(_assertThisInitialized(_this));
- _this.sceneManager = null;
- _this.scene = null;
- _this.breathPointManager = null;
- _this._currentState = null;
- _this.joined = !1;
- _this.disableRotate = !1;
- _this.isPano = !1;
- _this.movingByClick = !0;
- _this.camera = new Camera(_assertThisInitialized(_this));
- _this.stats = new Stats(_assertThisInitialized(_this));
- _this.isUpdatedRawYUVData = !1;
- _this.actionsHandler = new ActionsHandler(_assertThisInitialized(_this));
- _this._currentClickingState = null;
- _this.signal = new Signal(_assertThisInitialized(_this));
- _this.firstFrameTimestamp = null;
- _this.moveToExtra = '';
- _this.options = e;
- _this.options.wsServerUrl || (_this.options.wsServerUrl = SERVER_URLS.DEV);
- _this.modelManager = ModelManager.getInstance(e.appId, e.releaseId), _this.updateReporter();
- var n = e;
- n.canvas;
- var r = Oe(n, ["canvas"]);
- logger.infoAndReportMeasurement({
- metric: "startJoinRoomAt",
- startTime: Date.now(),
- group: "joinRoom",
- extra: r,
- value: 0
- });
- return _this;
- }
- _createClass(Xverse_Room, [{
- key: "receiveRtcData",
- value: function () {
- var _receiveRtcData = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee() {
- var _this2 = this;
- var e, t, r, n;
- return regenerator.wrap(function _callee$(_context) {
- while (1) {
- switch (_context.prev = _context.next) {
- case 0:
- logger.info("Invoke receiveRtcData");
- e = !1, t = !1, r = !1, n = !1;
- return _context.abrupt("return", this.viewMode === "serverless" ? (logger.warn("set view mode to serverless"), this.setViewMode("observer").then(function () {
- return _this2;
- }, function () {
- return _this2;
- })) : new Promise(function (o) {
- var a = _this2.networkController.rtcp.workers;
- a.registerFunction("signal", function (s) {
- _this2.signal.handleSignal(s);
- }), a.registerFunction("stream", function (s) {
- var l;
- if (_this2.emit("streamTimestamp", {
- timestamp: Date.now()
- }), t || (t = !0, logger.info("Invoke stream event")), s.stream) {
- r || (r = !0, logger.info("Invoke updateRawYUVData")), _this2.isUpdatedRawYUVData = !1;
- var u = (l = _this2._currentState.skin) == null ? void 0 : l.fov;
- _this2.sceneManager.materialComponent.updateRawYUVData(s.stream, s.width, s.height, u), _this2.isUpdatedRawYUVData = !0;
- }
- e || (logger.info("Invoke isAfterRenderRegistered"), e = !0, _this2.scene.registerAfterRender(function () {
- _this2.engineProxy.frameRenderNumber >= 2 && (n || (n = !0, logger.info("Invoke registerAfterRender")), _this2.isFirstDataUsed || (logger.info("Invoke isStreamAvailable"), _this2.isFirstDataUsed = !0, _this2.firstFrameTimestamp = Date.now(), o(_this2), _this2.afterJoinRoom()));
- }));
- }), _this2.panorama.bindListener(function () {
- o(_this2), _this2.afterJoinRoom();
- }), a.registerFunction("reconnectedFrame", function () {}), logger.info("Invoke decoderWorker.postMessage"), a.decoderWorker.postMessage({
- t: 5
- });
- }));
- case 3:
- case "end":
- return _context.stop();
- }
- }
- }, _callee, this);
- }));
- function receiveRtcData() {
- return _receiveRtcData.apply(this, arguments);
- }
- return receiveRtcData;
- }()
- }, {
- key: "currentNetworkOptions",
- get: function get() {
- return this._currentNetworkOptions;
- }
- }, {
- key: "viewMode",
- get: function get() {
- var e;
- return ((e = this._currentState) == null ? void 0 : e.viewMode) || "full";
- }
- }, {
- key: "id",
- get: function get() {
- return this._id;
- }
- }, {
- key: "skinId",
- get: function get() {
- return this._currentState.skinId;
- }
- }, {
- key: "skin",
- get: function get() {
- return this._currentState.skin;
- }
- }, {
- key: "sessionId",
- get: function get() {
- return this.currentNetworkOptions.sessionId;
- }
- }, {
- key: "pictureQualityLevel",
- get: function get() {
- return this.currentState.pictureQualityLevel;
- }
- }, {
- key: "avatars",
- get: function get() {
- return Array.from(this.avatarManager.avatars.values());
- }
- }, {
- key: "currentState",
- get: function get() {
- var e;
- return le(oe({}, this._currentState), {
- state: (e = this.networkController) == null ? void 0 : e._state
- });
- }
- }, {
- key: "_userAvatar",
- get: function get() {
- var _this3 = this;
- return this.avatars.find(function (e) {
- return e.userId === _this3.userId;
- });
- }
- }, {
- key: "tvs",
- get: function get() {
- return this.engineProxy._tvs;
- }
- }, {
- key: "tv",
- get: function get() {
- return this.tvs[0];
- }
- }, {
- key: "currentClickingState",
- get: function get() {
- return this._currentClickingState;
- }
- }, {
- key: "afterJoinRoomHook",
- value: function afterJoinRoomHook() {}
- }, {
- key: "beforeJoinRoomResolveHook",
- value: function beforeJoinRoomResolveHook() {}
- }, {
- key: "afterReconnectedHook",
- value: function afterReconnectedHook() {}
- }, {
- key: "handleSignalHook",
- value: function handleSignalHook(e) {}
- }, {
- key: "skinChangedHook",
- value: function skinChangedHook() {}
- }, {
- key: "beforeStartGameHook",
- value: function () {
- var _beforeStartGameHook = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee2(e) {
- return regenerator.wrap(function _callee2$(_context2) {
- while (1) {
- switch (_context2.prev = _context2.next) {
- case 0:
- case "end":
- return _context2.stop();
- }
- }
- }, _callee2);
- }));
- function beforeStartGameHook(_x) {
- return _beforeStartGameHook.apply(this, arguments);
- }
- return beforeStartGameHook;
- }()
- }, {
- key: "loadAssetsHook",
- value: function loadAssetsHook() {}
- }, {
- key: "afterUserAvatarLoadedHook",
- value: function afterUserAvatarLoadedHook() {}
- }, {
- key: "audienceViewModeHook",
- value: function audienceViewModeHook() {}
- }, {
- key: "setViewModeToObserver",
- value: function setViewModeToObserver() {}
- }, {
- key: "handleVehicleHook",
- value: function handleVehicleHook(e) {}
- }, {
- key: "updateReporter",
- value: function updateReporter() {
- var _this$options = this.options,
- e = _this$options.avatarId,
- t = _this$options.skinId,
- r = _this$options.userId,
- n = _this$options.roomId,
- o = _this$options.role,
- a = _this$options.appId,
- s = _this$options.wsServerUrl;
- reporter$1.updateHeader({
- userId: r
- }), reporter$1.updateBody({
- roomId: n,
- role: o,
- skinId: t,
- avatarId: e,
- appId: a,
- wsServerUrl: s
- });
- }
- }, {
- key: "initRoom",
- value: function () {
- var _initRoom2 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee3() {
- var _this$options$timeout, e;
- return regenerator.wrap(function _callee3$(_context3) {
- while (1) {
- switch (_context3.prev = _context3.next) {
- case 0:
- _this$options$timeout = this.options.timeout, e = _this$options$timeout === void 0 ? DEFAULT_JOINROOM_TIMEOUT : _this$options$timeout;
- if (!util.isSupported()) {
- _context3.next = 5;
- break;
- }
- return _context3.abrupt("return", this._initRoom()._timeout(e, new TimeoutError("initRoom timeout")));
- case 5:
- return _context3.abrupt("return", Promise.reject(new UnsupportedError()));
- case 6:
- case "end":
- return _context3.stop();
- }
- }
- }, _callee3, this);
- }));
- function initRoom() {
- return _initRoom2.apply(this, arguments);
- }
- return initRoom;
- }()
- }, {
- key: "_initRoom",
- value: function () {
- var _initRoom3 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee4() {
- var e, _this$options2, t, r, n, o, a, s, l, u, c, _this$options2$isAllS, h, f, d, _, g, m, v, _this$options2$firend, y, _this$options2$syncBy, b, T, _this$options2$attitu, C, A, _this$options2$viewMo, S, P, R, M, _this$options2$hasAva, x, _this$options2$syncTo, I, _this$options2$priori, w, _this$options2$remove, O, D, F, V, N;
- return regenerator.wrap(function _callee4$(_context4) {
- while (1) {
- switch (_context4.prev = _context4.next) {
- case 0:
- e = this.validateOptions(this.options);
- if (!e) {
- _context4.next = 3;
- break;
- }
- return _context4.abrupt("return", (logger.error("initRoom param error", e), Promise.reject(e)));
- case 3:
- _this$options2 = this.options, t = _this$options2.canvas, r = _this$options2.avatarId, n = _this$options2.skinId, o = _this$options2.userId, a = _this$options2.wsServerUrl, s = _this$options2.role, l = _this$options2.token, u = _this$options2.pageSession, c = _this$options2.rotationRenderType, _this$options2$isAllS = _this$options2.isAllSync, h = _this$options2$isAllS === void 0 ? !1 : _this$options2$isAllS, f = _this$options2.appId, d = _this$options2.camera, _ = _this$options2.player, g = _this$options2.avatarComponents, m = _this$options2.nickname, v = _this$options2.avatarScale, _this$options2$firend = _this$options2.firends, y = _this$options2$firend === void 0 ? [] : _this$options2$firend, _this$options2$syncBy = _this$options2.syncByEvent, b = _this$options2$syncBy === void 0 ? !1 : _this$options2$syncBy, T = _this$options2.areaName, _this$options2$attitu = _this$options2.attitude, C = _this$options2$attitu === void 0 ? MotionType$1.Walk : _this$options2$attitu, A = _this$options2.pathName, _this$options2$viewMo = _this$options2.viewMode, S = _this$options2$viewMo === void 0 ? "full" : _this$options2$viewMo, P = _this$options2.person, R = _this$options2.roomId, M = _this$options2.roomTypeId, _this$options2$hasAva = _this$options2.hasAvatar, x = _this$options2$hasAva === void 0 ? !1 : _this$options2$hasAva, _this$options2$syncTo = _this$options2.syncToOthers, I = _this$options2$syncTo === void 0 ? !1 : _this$options2$syncTo, _this$options2$priori = _this$options2.prioritySync, w = _this$options2$priori === void 0 ? !1 : _this$options2$priori, _this$options2$remove = _this$options2.removeWhenDisconnected, O = _this$options2$remove === void 0 ? !0 : _this$options2$remove, D = _this$options2.extra;
- this.setCurrentNetworkOptions({
- avatarId: r,
- skinId: n,
- roomId: R,
- userId: o,
- wsServerUrl: a,
- role: s,
- token: l,
- pageSession: u,
- rotationRenderType: c,
- isAllSync: h,
- appId: f,
- camera: d,
- player: _,
- avatarComponents: g,
- nickname: m,
- avatarScale: v,
- firends: y,
- syncByEvent: b,
- areaName: T,
- attitude: C,
- pathName: A,
- person: P,
- roomTypeId: M,
- hasAvatar: x,
- syncToOthers: I,
- prioritySync: w,
- extra: D,
- removeWhenDisconnected: O
- });
- this.userId = o;
- this.canvas = t;
- T && (this.pathManager.currentArea = T);
- this.networkController = new NetworkController(this);
- this.setCurrentState({
- areaName: T,
- pathName: A,
- attitude: C,
- speed: 0,
- viewMode: S,
- state: this.networkController._state,
- skinId: n
- });
- _context4.prev = 10;
- _context4.next = 13;
- return Promise.all([this.initNetwork(), this.initConfig(), this.initWasm()]);
- case 13:
- logger.info("network config wasm all ready, start to create game");
- _context4.next = 16;
- return this.requestCreateRoom({
- skinId: n
- });
- case 16:
- F = _context4.sent;
- V = F.routeList.find(function (L) {
- return L.areaName === T;
- });
- N = ((V == null ? void 0 : V.step) || 7.5) * 30;
- this.updateCurrentState({
- skin: F,
- skinId: F.id,
- versionId: F.versionId,
- speed: N
- });
- _context4.next = 22;
- return this.initEngine(F);
- case 22:
- _context4.next = 27;
- break;
- case 24:
- _context4.prev = 24;
- _context4.t0 = _context4["catch"](10);
- return _context4.abrupt("return", Promise.reject(_context4.t0));
- case 27:
- return _context4.abrupt("return", (this.beforeJoinRoomResolve(), this.receiveRtcData()));
- case 28:
- case "end":
- return _context4.stop();
- }
- }
- }, _callee4, this, [[10, 24]]);
- }));
- function _initRoom() {
- return _initRoom3.apply(this, arguments);
- }
- return _initRoom;
- }()
- }, {
- key: "beforeJoinRoomResolve",
- value: function beforeJoinRoomResolve() {
- this.setupStats(), this.eventsController = new EventsController(this), this.eventsController.bindEvents(), this.panorama = new Panorama(this), this.beforeJoinRoomResolveHook();
- }
- }, {
- key: "afterJoinRoom",
- value: function afterJoinRoom() {
- this.joined = !0, this.viewMode === "observer" && this.setViewModeToObserver(), logger.infoAndReportMeasurement({
- tag: this.viewMode,
- value: this.firstFrameTimestamp - this._startTime,
- startTime: Date.now(),
- metric: "joinRoom"
- }), this.camera.initialFov = this.sceneManager.cameraComponent.getCameraFov(), this.stats.on("stats", function (_ref) {
- var e = _ref.stats;
- reporter$1.report("stats", oe({}, e));
- }), this.debug = new Debug(this), this.afterJoinRoomHook();
- }
- }, {
- key: "afterReconnected",
- value: function afterReconnected() {
- this.avatarManager.clearOtherUsers(), this.afterReconnectedHook();
- }
- }, {
- key: "leave",
- value: function leave() {
- var e, t;
- return logger.info("Invoke room.leave"), (e = this.eventsController) == null || e.clearEvents(), (t = this.networkController) == null || t.quit(), this;
- }
- }, {
- key: "validateOptions",
- value: function validateOptions(e) {
- var _ref2 = e || {},
- t = _ref2.canvas,
- r = _ref2.avatarId,
- n = _ref2.skinId,
- o = _ref2.userId,
- a = _ref2.role;
- _ref2.roomId;
- var l = _ref2.token,
- u = _ref2.appId;
- _ref2.avatarComponents;
- var h = [];
- t instanceof HTMLCanvasElement || h.push(new ParamError$1("`canvas` must be instanceof of HTMLCanvasElement"));
- (!o || typeof o != "string") && h.push(new ParamError$1("`userId` must be string"));
- (!l || typeof l != "string") && h.push(new ParamError$1("`token` must be string"));
- (!u || typeof u != "string") && h.push(new ParamError$1("`appId` must be string"));
- a == "audience" || (!r || !n) && h.push(new ParamError$1("`avatarId` and `skinId` is required when create room"));
- return h[0];
- }
- }, {
- key: "initNetwork",
- value: function () {
- var _initNetwork = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee5() {
- var e;
- return regenerator.wrap(function _callee5$(_context5) {
- while (1) {
- switch (_context5.prev = _context5.next) {
- case 0:
- if (!(this.viewMode === "serverless")) {
- _context5.next = 2;
- break;
- }
- return _context5.abrupt("return", Promise.resolve());
- case 2:
- e = Date.now();
- _context5.prev = 3;
- _context5.next = 6;
- return this.networkController.connect()._timeout(8e3, new InitNetworkTimeoutError());
- case 6:
- logger.infoAndReportMeasurement({
- metric: "networkInitAt",
- startTime: this._startTime,
- group: "joinRoom"
- });
- logger.infoAndReportMeasurement({
- metric: "networkInitCost",
- startTime: e,
- group: "joinRoom"
- });
- _context5.next = 13;
- break;
- case 10:
- _context5.prev = 10;
- _context5.t0 = _context5["catch"](3);
- throw logger.infoAndReportMeasurement({
- metric: "networkInitAt",
- startTime: e,
- group: "joinRoom",
- error: _context5.t0
- }), _context5.t0;
- case 13:
- case "end":
- return _context5.stop();
- }
- }
- }, _callee5, this, [[3, 10]]);
- }));
- function initNetwork() {
- return _initNetwork.apply(this, arguments);
- }
- return initNetwork;
- }()
- }, {
- key: "initConfig",
- value: function () {
- var _initConfig = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee6() {
- var e;
- return regenerator.wrap(function _callee6$(_context6) {
- while (1) {
- switch (_context6.prev = _context6.next) {
- case 0:
- e = Date.now();
- _context6.prev = 1;
- _context6.next = 4;
- return this.modelManager.getApplicationConfig()._timeout(8e3, new InitConfigTimeoutError());
- case 4:
- logger.infoAndReportMeasurement({
- metric: "configInitAt",
- startTime: this._startTime,
- group: "joinRoom"
- });
- logger.infoAndReportMeasurement({
- metric: "configInitCost",
- startTime: e,
- group: "joinRoom"
- });
- _context6.next = 11;
- break;
- case 8:
- _context6.prev = 8;
- _context6.t0 = _context6["catch"](1);
- throw logger.infoAndReportMeasurement({
- metric: "configInitAt",
- startTime: e,
- group: "joinRoom",
- error: _context6.t0
- }), _context6.t0;
- case 11:
- case "end":
- return _context6.stop();
- }
- }
- }, _callee6, this, [[1, 8]]);
- }));
- function initConfig() {
- return _initConfig.apply(this, arguments);
- }
- return initConfig;
- }()
- }, {
- key: "initEngine",
- value: function () {
- var _initEngine = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee7(e) {
- var t, n;
- return regenerator.wrap(function _callee7$(_context7) {
- while (1) {
- switch (_context7.prev = _context7.next) {
- case 0:
- t = Date.now();
- _context7.prev = 1;
- this.engineProxy = new EngineProxy(this);
- _context7.next = 5;
- return this.engineProxy.initEngine(e);
- case 5:
- logger.infoAndReportMeasurement({
- metric: "webglInitAt",
- startTime: this._startTime,
- group: "joinRoom"
- });
- logger.infoAndReportMeasurement({
- metric: "webglInitCost",
- startTime: t,
- group: "joinRoom"
- });
- return _context7.abrupt("return");
- case 10:
- _context7.prev = 10;
- _context7.t0 = _context7["catch"](1);
- n = _context7.t0;
- return _context7.abrupt("return", (_context7.t0.code !== Codes.InitEngineTimeout && (n = new InitEngineError()), logger.error(_context7.t0), logger.infoAndReportMeasurement({
- metric: "webglInitAt",
- startTime: t,
- group: "joinRoom",
- error: n
- }), Promise.reject(n)));
- case 14:
- case "end":
- return _context7.stop();
- }
- }
- }, _callee7, this, [[1, 10]]);
- }));
- function initEngine(_x2) {
- return _initEngine.apply(this, arguments);
- }
- return initEngine;
- }()
- }, {
- key: "initWasm",
- value: function () {
- var _initWasm = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee8() {
- var _this4 = this;
- var e;
- return regenerator.wrap(function _callee8$(_context8) {
- while (1) {
- switch (_context8.prev = _context8.next) {
- case 0:
- if (!(this.viewMode === "serverless")) {
- _context8.next = 2;
- break;
- }
- return _context8.abrupt("return", Promise.resolve());
- case 2:
- e = Date.now();
- _context8.prev = 3;
- _context8.next = 6;
- return this.networkController.rtcp.workers.init(this.options.resolution)._timeout(8e3, new InitDecoderTimeoutError());
- case 6:
- this.networkController.rtcp.workers.registerFunction("error", function (t) {
- logger.error("decode error", t);
- var r = t.code,
- n = t.message;
- _this4.emit("error", {
- code: r,
- msg: n
- });
- });
- logger.infoAndReportMeasurement({
- metric: "wasmInitAt",
- group: "joinRoom",
- startTime: this._startTime
- });
- logger.infoAndReportMeasurement({
- metric: "wasmInitCost",
- group: "joinRoom",
- startTime: e
- });
- eventsManager.on("traceId", function (t) {
- _this4.networkController.rtcp.workers.onTraceId(t);
- });
- _context8.next = 15;
- break;
- case 12:
- _context8.prev = 12;
- _context8.t0 = _context8["catch"](3);
- throw logger.infoAndReportMeasurement({
- metric: "wasmInitAt",
- group: "joinRoom",
- startTime: e,
- error: _context8.t0
- }), _context8.t0;
- case 15:
- case "end":
- return _context8.stop();
- }
- }
- }, _callee8, this, [[3, 12]]);
- }));
- function initWasm() {
- return _initWasm.apply(this, arguments);
- }
- return initWasm;
- }()
- }, {
- key: "requestCreateRoom",
- value: function () {
- var _requestCreateRoom = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee9(_ref3) {
- var e, t, r, _ref4, n, o, _yield$this$networkCo, _r, _n, _o, a, s;
- return regenerator.wrap(function _callee9$(_context9) {
- while (1) {
- switch (_context9.prev = _context9.next) {
- case 0:
- e = _ref3.skinId;
- if (!e) {
- _context9.next = 11;
- break;
- }
- _context9.next = 4;
- return this.getSkin(e);
- case 4:
- t = _context9.sent;
- _context9.next = 7;
- return this.modelManager.findRoute(e, this.options.pathName);
- case 7:
- r = _context9.sent;
- this.updateCurrentNetworkOptions({
- areaName: r.areaName,
- attitude: r.attitude,
- versionId: t.versionId
- });
- _ref4 = getRandomItem(r.birthPointList) || this.options, n = _ref4.camera, o = _ref4.player;
- this.options.camera || this.updateCurrentNetworkOptions({
- camera: n
- }), this.options.player || this.updateCurrentNetworkOptions({
- player: o
- });
- case 11:
- if (!(this.viewMode === "serverless")) {
- _context9.next = 13;
- break;
- }
- return _context9.abrupt("return", t);
- case 13:
- _context9.prev = 13;
- _context9.next = 16;
- return this.beforeStartGameHook(this.options);
- case 16:
- _context9.next = 18;
- return this.networkController.startGame();
- case 18:
- _yield$this$networkCo = _context9.sent;
- _r = _yield$this$networkCo.room_id;
- _n = _yield$this$networkCo.data;
- _o = _yield$this$networkCo.session_id;
- this._id = _r;
- a = JSON.parse(_n);
- this.isHost = a.IsHost, e = a.SkinID || e;
- _context9.next = 27;
- return this.getSkin(e);
- case 27:
- s = _context9.sent;
- return _context9.abrupt("return", (this.updateCurrentNetworkOptions({
- roomId: _r,
- sessionId: _o
- }), reporter$1.updateBody({
- roomId: _r,
- skinId: e,
- serverSession: _o
- }), s));
- case 31:
- _context9.prev = 31;
- _context9.t0 = _context9["catch"](13);
- throw logger.error("Request create room error", _context9.t0), _context9.t0;
- case 34:
- case "end":
- return _context9.stop();
- }
- }
- }, _callee9, this, [[13, 31]]);
- }));
- function requestCreateRoom(_x3) {
- return _requestCreateRoom.apply(this, arguments);
- }
- return requestCreateRoom;
- }()
- }, {
- key: "pause",
- value: function pause() {
- return this.engineProxy.pause();
- }
- }, {
- key: "resume",
- value: function resume() {
- return this.engineProxy.resume();
- }
- }, {
- key: "reconnect",
- value: function reconnect() {
- this.networkController.reconnect();
- }
- }, {
- key: "setViewMode",
- value: function () {
- var _setViewMode = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee10(e) {
- return regenerator.wrap(function _callee10$(_context10) {
- while (1) {
- switch (_context10.prev = _context10.next) {
- case 0:
- case "end":
- return _context10.stop();
- }
- }
- }, _callee10);
- }));
- function setViewMode(_x4) {
- return _setViewMode.apply(this, arguments);
- }
- return setViewMode;
- }()
- }, {
- key: "handleRepetLogin",
- value: function handleRepetLogin() {
- logger.warn("receive " + Codes.RepeatLogin + " for repeat login"), this.emit("repeatLogin"), reporter$1.disable(), this.networkController.quit();
- }
- }, {
- key: "setPictureQualityLevel",
- value: function setPictureQualityLevel(e) {
- var t = {
- high: EImageQuality.high,
- low: EImageQuality.low,
- average: EImageQuality.mid
- };
- return this.updateCurrentState({
- pictureQualityLevel: e
- }), this.sceneManager.setImageQuality(t[e]);
- }
- }, {
- key: "getSkin",
- value: function () {
- var _getSkin = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee11(e) {
- var t, n;
- return regenerator.wrap(function _callee11$(_context11) {
- while (1) {
- switch (_context11.prev = _context11.next) {
- case 0:
- t = null;
- _context11.next = 3;
- return this.modelManager.getSkinsList();
- case 3:
- t = (this.skinList = _context11.sent).find(function (n) {
- return n.id === e || n.id === e;
- });
- if (!t) {
- _context11.next = 6;
- break;
- }
- return _context11.abrupt("return", t);
- case 6:
- n = "skin is invalid: skinId: ".concat(e);
- return _context11.abrupt("return", Promise.reject(new ParamError$1(n)));
- case 8:
- case "end":
- return _context11.stop();
- }
- }
- }, _callee11, this);
- }));
- function getSkin(_x5) {
- return _getSkin.apply(this, arguments);
- }
- return getSkin;
- }()
- }, {
- key: "setupStats",
- value: function setupStats() {
- this.stats.assign({
- roomId: this.id,
- userId: this.userId
- }), setInterval(this.engineProxy.updateStats, 1e3);
- }
- }, {
- key: "proxyEvents",
- value: function proxyEvents(e, t) {
- this.emit(e, t);
- }
- }, {
- key: "setCurrentNetworkOptions",
- value: function setCurrentNetworkOptions(e) {
- this._currentNetworkOptions = e;
- }
- }, {
- key: "updateCurrentNetworkOptions",
- value: function updateCurrentNetworkOptions(e) {
- Object.assign(this._currentNetworkOptions, e), Object.assign(this.options, e);
- }
- }, {
- key: "setCurrentState",
- value: function setCurrentState(e) {
- this._currentState = e;
- }
- }, {
- key: "updateCurrentState",
- value: function updateCurrentState(e) {
- e.skinId && (this.lastSkinId = this.currentState.skinId, this.updateCurrentNetworkOptions({
- skinId: e.skinId
- })), e.versionId && this.updateCurrentNetworkOptions({
- versionId: e.versionId
- }), Object.assign(this._currentState, e);
- }
- }]);
- return Xverse_Room;
- }(EventEmitter);
- function _createSuper$1(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
- function _isNativeReflectConstruct$1() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
- var XverseRoom = /*#__PURE__*/function (_Xverse_Room) {
- _inherits(XverseRoom, _Xverse_Room);
- var _super = _createSuper$1(XverseRoom);
- function XverseRoom(e) {
- var _this;
- _classCallCheck(this, XverseRoom);
- _this = _super.call(this, e);
- _this.joyStick = new JoyStick(_assertThisInitialized(_this));
- return _this;
- }
- _createClass(XverseRoom, [{
- key: "afterJoinRoomHook",
- value: function afterJoinRoomHook() {
- this.joyStick.init({});
- }
- }]);
- return XverseRoom;
- }(Xverse_Room);
- var BaseTable = /*#__PURE__*/function () {
- function BaseTable(e, t) {
- _classCallCheck(this, BaseTable);
- this.db = null;
- this.isCreatingTable = !1;
- this.hasCleared = !1;
- this.dbName = e, this.dbVersion = t;
- }
- _createClass(BaseTable, [{
- key: "clearDataBase",
- value: function () {
- var _clearDataBase = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee(e) {
- var _this = this;
- return regenerator.wrap(function _callee$(_context) {
- while (1) {
- switch (_context.prev = _context.next) {
- case 0:
- return _context.abrupt("return", this.hasCleared || (e && (this.hasCleared = !0), !window.indexedDB.databases) ? Promise.resolve() : new Promise(function (t, r) {
- var n = window.indexedDB.deleteDatabase(_this.dbName);
- n.onsuccess = function () {
- t();
- }, n.onerror = r;
- }));
- case 1:
- case "end":
- return _context.stop();
- }
- }
- }, _callee, this);
- }));
- function clearDataBase(_x) {
- return _clearDataBase.apply(this, arguments);
- }
- return clearDataBase;
- }()
- }, {
- key: "tableName",
- value: function tableName() {
- throw new Error("Derived class have to override 'tableName', and set a proper table name!");
- }
- }, {
- key: "keyPath",
- value: function keyPath() {
- throw new Error("Derived class have to override 'keyPath', and set a proper index name!");
- }
- }, {
- key: "index",
- value: function index() {
- throw new Error("Derived class have to override 'index', and set a proper index name!");
- }
- }, {
- key: "checkAndOpenDatabase",
- value: function () {
- var _checkAndOpenDatabase = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee2() {
- var _this2 = this;
- return regenerator.wrap(function _callee2$(_context2) {
- while (1) {
- switch (_context2.prev = _context2.next) {
- case 0:
- return _context2.abrupt("return", this.db ? Promise.resolve(this.db) : new Promise(function (e, t) {
- var n = setTimeout(function () {
- logger.info("wait db to open for", 200), _this2.db ? e(_this2.db) : e(_this2.checkAndOpenDatabase()), clearTimeout(n);
- }, 200);
- _this2.openDatabase(_this2.dbName, _this2.dbVersion || 1, function () {
- _this2.db && !_this2.isCreatingTable && e(_this2.db), logger.info("successCallback called, this.db: ".concat(!!_this2.db, ", this.isCreatingStore: ").concat(_this2.isCreatingTable)), clearTimeout(n);
- }, function () {
- t(new Error("Failed to open database!")), clearTimeout(n);
- }, function () {
- _this2.db && e(_this2.db), clearTimeout(n), logger.info("successCallback called, this.db: ".concat(!!_this2.db, ", this.isCreatingStore: ").concat(_this2.isCreatingTable));
- });
- }));
- case 1:
- case "end":
- return _context2.stop();
- }
- }
- }, _callee2, this);
- }));
- function checkAndOpenDatabase() {
- return _checkAndOpenDatabase.apply(this, arguments);
- }
- return checkAndOpenDatabase;
- }()
- }, {
- key: "openDatabase",
- value: function openDatabase(e, t, r, n, o) {
- var _this3 = this;
- if (this.isCreatingTable) return;
- this.isCreatingTable = !0, logger.info(e, t);
- var a = window.indexedDB.open(e, t),
- s = this.tableName();
- a.onsuccess = function (l) {
- _this3.db = a.result, logger.info("IndexedDb ".concat(e, " is opened.")), _this3.db.objectStoreNames.contains(s) && (_this3.isCreatingTable = !1), r && r(l);
- }, a.onerror = function (l) {
- var u;
- logger.error("Failed to open database", (u = l == null ? void 0 : l.srcElement) == null ? void 0 : u.error), _this3.isCreatingTable = !1, n && n(l), _this3.clearDataBase(!0);
- }, a.onupgradeneeded = function (l) {
- var u = l.target.result,
- c = _this3.index();
- logger.info("Creating table ".concat(s, "."));
- var h = u.objectStoreNames.contains(s);
- if (h) h = u.transaction([s], "readwrite").objectStore(s);else {
- var f = _this3.keyPath();
- h = u.createObjectStore(s, {
- keyPath: f
- });
- }
- c.map(function (f) {
- h.createIndex(f, f, {
- unique: !1
- });
- }), _this3.isCreatingTable = !1, logger.info("Table ".concat(s, " opened")), o && o(l);
- };
- }
- }, {
- key: "add",
- value: function () {
- var _add = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee3(e) {
- var t, o;
- return regenerator.wrap(function _callee3$(_context3) {
- while (1) {
- switch (_context3.prev = _context3.next) {
- case 0:
- t = this.tableName();
- _context3.next = 3;
- return this.checkAndOpenDatabase();
- case 3:
- o = _context3.sent.transaction([t], "readwrite").objectStore(t).add(e);
- return _context3.abrupt("return", new Promise(function (a, s) {
- o.onsuccess = function (l) {
- a(l);
- }, o.onerror = function (l) {
- var u;
- logger.error((u = l.srcElement) == null ? void 0 : u.error), s(l);
- };
- }));
- case 5:
- case "end":
- return _context3.stop();
- }
- }
- }, _callee3, this);
- }));
- function add(_x2) {
- return _add.apply(this, arguments);
- }
- return add;
- }()
- }, {
- key: "put",
- value: function () {
- var _put = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee4(e) {
- var t, o;
- return regenerator.wrap(function _callee4$(_context4) {
- while (1) {
- switch (_context4.prev = _context4.next) {
- case 0:
- t = this.tableName();
- _context4.next = 3;
- return this.checkAndOpenDatabase();
- case 3:
- o = _context4.sent.transaction([t], "readwrite").objectStore(t).put(e);
- return _context4.abrupt("return", new Promise(function (a, s) {
- o.onsuccess = function (l) {
- a(l);
- }, o.onerror = function (l) {
- var u;
- logger.error("db put error", (u = l.srcElement) == null ? void 0 : u.error), s(l);
- };
- }));
- case 5:
- case "end":
- return _context4.stop();
- }
- }
- }, _callee4, this);
- }));
- function put(_x3) {
- return _put.apply(this, arguments);
- }
- return put;
- }()
- }, {
- key: "delete",
- value: function _delete(e, t, r) {
- var n = this.tableName();
- this.checkAndOpenDatabase().then(function (o) {
- var s = o.transaction([n], "readwrite").objectStore(n).delete(e);
- s.onsuccess = t, s.onerror = r;
- });
- }
- }, {
- key: "update",
- value: function update() {
- this.checkAndOpenDatabase().then(function (e) {});
- }
- }, {
- key: "getAllKeys",
- value: function () {
- var _getAllKeys = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee5() {
- var e, t;
- return regenerator.wrap(function _callee5$(_context5) {
- while (1) {
- switch (_context5.prev = _context5.next) {
- case 0:
- e = this.tableName();
- _context5.next = 3;
- return this.checkAndOpenDatabase();
- case 3:
- t = _context5.sent;
- return _context5.abrupt("return", new Promise(function (r, n) {
- var a = t.transaction([e], "readonly").objectStore(e).getAllKeys();
- a.onsuccess = function (s) {
- r(s.target.result);
- }, a.onerror = function (s) {
- logger.error("db getAllKeys error", s), n(s);
- };
- }));
- case 5:
- case "end":
- return _context5.stop();
- }
- }
- }, _callee5, this);
- }));
- function getAllKeys() {
- return _getAllKeys.apply(this, arguments);
- }
- return getAllKeys;
- }()
- }, {
- key: "query",
- value: function () {
- var _query = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee6(e, t) {
- var r, n;
- return regenerator.wrap(function _callee6$(_context6) {
- while (1) {
- switch (_context6.prev = _context6.next) {
- case 0:
- r = this.tableName();
- _context6.next = 3;
- return this.checkAndOpenDatabase();
- case 3:
- n = _context6.sent;
- return _context6.abrupt("return", new Promise(function (o, a) {
- var u = n.transaction([r], "readonly").objectStore(r).index(e).get(t);
- u.onsuccess = function (c) {
- var f;
- var h = (f = c == null ? void 0 : c.target) == null ? void 0 : f.result;
- o && o(h);
- }, u.onerror = function (c) {
- logger.error("db query error", c), a(c);
- };
- }));
- case 5:
- case "end":
- return _context6.stop();
- }
- }
- }, _callee6, this);
- }));
- function query(_x4, _x5) {
- return _query.apply(this, arguments);
- }
- return query;
- }()
- }, {
- key: "sleep",
- value: function () {
- var _sleep = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee7(e) {
- return regenerator.wrap(function _callee7$(_context7) {
- while (1) {
- switch (_context7.prev = _context7.next) {
- case 0:
- return _context7.abrupt("return", new Promise(function (t) {
- setTimeout(function () {
- t("");
- }, e);
- }));
- case 1:
- case "end":
- return _context7.stop();
- }
- }
- }, _callee7);
- }));
- function sleep(_x6) {
- return _sleep.apply(this, arguments);
- }
- return sleep;
- }()
- }]);
- return BaseTable;
- }();
- function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
- function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
- var ModelTable = /*#__PURE__*/function (_BaseTable) {
- _inherits(ModelTable, _BaseTable);
- var _super = _createSuper(ModelTable);
- function ModelTable() {
- _classCallCheck(this, ModelTable);
- return _super.call(this, "XverseDatabase", 1);
- }
- _createClass(ModelTable, [{
- key: "tableName",
- value: function tableName() {
- return "models";
- }
- }, {
- key: "index",
- value: function index() {
- return ["url"];
- }
- }, {
- key: "keyPath",
- value: function keyPath() {
- return "url";
- }
- }]);
- return ModelTable;
- }(BaseTable);
- var modelTable = new ModelTable();
- var Preload = /*#__PURE__*/function () {
- function Preload(e) {
- _classCallCheck(this, Preload);
- this.config = null;
- this.allKeys = [];
- this.oldResourcesDeleted = !1;
- this.requests = {
- simple: {
- stopped: !0,
- requests: {}
- },
- observer: {
- stopped: !0,
- requests: {}
- },
- full: {
- stopped: !0,
- requests: {}
- }
- };
- this.modelManager = e, this.init(e.appId);
- }
- _createClass(Preload, [{
- key: "init",
- value: function init(e) {
- reporter$1.updateBody({
- appId: e
- });
- }
- }, {
- key: "getConfig",
- value: function () {
- var _getConfig = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee(e) {
- var _yield$this$modelMana, t;
- return regenerator.wrap(function _callee$(_context) {
- while (1) {
- switch (_context.prev = _context.next) {
- case 0:
- if (!this.config) {
- _context.next = 2;
- break;
- }
- return _context.abrupt("return", this.config);
- case 2:
- _context.next = 4;
- return this.modelManager.requestConfig();
- case 4:
- _yield$this$modelMana = _context.sent;
- t = _yield$this$modelMana.preload;
- return _context.abrupt("return", t ? (this.config = t, Promise.resolve(t)) : Promise.reject("no preload config"));
- case 7:
- case "end":
- return _context.stop();
- }
- }
- }, _callee, this);
- }));
- function getConfig(_x) {
- return _getConfig.apply(this, arguments);
- }
- return getConfig;
- }()
- }, {
- key: "getAllKeys",
- value: function () {
- var _getAllKeys = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee2() {
- var e, t;
- return regenerator.wrap(function _callee2$(_context2) {
- while (1) {
- switch (_context2.prev = _context2.next) {
- case 0:
- if (!this.allKeys.length) {
- _context2.next = 2;
- break;
- }
- return _context2.abrupt("return", this.allKeys);
- case 2:
- _context2.prev = 2;
- _context2.next = 5;
- return modelTable.getAllKeys();
- case 5:
- e = _context2.sent;
- this.allKeys = e;
- return _context2.abrupt("return", e);
- case 10:
- _context2.prev = 10;
- _context2.t0 = _context2["catch"](2);
- t = "preload getAllKeys error";
- return _context2.abrupt("return", (logger.error(t), Promise.reject(t)));
- case 14:
- case "end":
- return _context2.stop();
- }
- }
- }, _callee2, this, [[2, 10]]);
- }));
- function getAllKeys() {
- return _getAllKeys.apply(this, arguments);
- }
- return getAllKeys;
- }()
- }, {
- key: "stop",
- value: function stop(e) {
- e === "serverless" && (e = "observer"), this.requests[e].stopped = !0;
- var t = this.requests[e].requests;
- Object.keys(t).forEach(function (r) {
- http1.canceler.removePending(r), delete t[r];
- });
- }
- }, {
- key: "clearPreload",
- value: function clearPreload(e) {
- this.requests[e].stopped = !1, this.allKeys = [];
- }
- }, {
- key: "start",
- value: function () {
- var _start = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee3(e, t, r) {
- var n, o, a, s, l, u, h, f, _s;
- return regenerator.wrap(function _callee3$(_context3) {
- while (1) {
- switch (_context3.prev = _context3.next) {
- case 0:
- n = Date.now(), o = 0;
- _context3.prev = 1;
- if (!(e === "serverless" && (e = "observer"), !this.requests[e])) {
- _context3.next = 4;
- break;
- }
- return _context3.abrupt("return", Promise.reject(new ParamError("invalid stage name: " + e)));
- case 4:
- this.clearPreload(e);
- _context3.next = 7;
- return this.getConfig(e);
- case 7:
- a = _context3.sent;
- _context3.next = 10;
- return this.getAllKeys();
- case 10:
- s = _context3.sent;
- _context3.prev = 11;
- _context3.next = 14;
- return this.deleteOldResources(a.assetUrls.map(function (d) {
- return d.url;
- }), s);
- case 14:
- _context3.next = 19;
- break;
- case 16:
- _context3.prev = 16;
- _context3.t0 = _context3["catch"](11);
- logger.error(_context3.t0);
- case 19:
- l = a.baseUrls, u = a.assetUrls;
- _context3.t1 = e;
- _context3.next = _context3.t1 === "simple" ? 23 : _context3.t1 === "observer" ? 25 : _context3.t1 === "full" ? 27 : 29;
- break;
- case 23:
- h = l;
- return _context3.abrupt("break", 30);
- case 25:
- h = u;
- return _context3.abrupt("break", 30);
- case 27:
- h = u;
- return _context3.abrupt("break", 30);
- case 29:
- h = u;
- case 30:
- f = h.filter(function (d) {
- return !s.includes(d.url);
- });
- r && isFunction(r) && (f = f.filter(r));
- o = f.length;
- logger.debug("keysNeedToPreload", f);
- f.length || t && t(h.length, h.length);
- n = Date.now();
- _context3.next = 38;
- return this._preload(e, f, t);
- case 38:
- logger.infoAndReportMeasurement({
- tag: e,
- startTime: n,
- metric: "assetsPreload",
- extra: {
- total: o
- }
- });
- return _context3.abrupt("return");
- case 42:
- _context3.prev = 42;
- _context3.t2 = _context3["catch"](1);
- _s = _context3.t2;
- return _context3.abrupt("return", ((this.requests[e].stopped || axios.isCancel(_context3.t2)) && (_s = new PreloadCanceledError()), logger.infoAndReportMeasurement({
- tag: e,
- startTime: n,
- metric: "assetsPreload",
- extra: {
- total: o
- },
- error: _s,
- reportOptions: {
- immediate: !0
- }
- }), Promise.reject(_s)));
- case 46:
- case "end":
- return _context3.stop();
- }
- }
- }, _callee3, this, [[1, 42], [11, 16]]);
- }));
- function start(_x2, _x3, _x4) {
- return _start.apply(this, arguments);
- }
- return start;
- }()
- }, {
- key: "deleteOldResources",
- value: function deleteOldResources(e, t) {
- if (!this.oldResourcesDeleted) this.oldResourcesDeleted = !0;else return Promise.resolve();
- var r = t.filter(function (n) {
- return !e.includes(n);
- });
- return logger.debug("keysNeedToDelete", r), logger.warn("keysNeedToDelete", r.length), Promise.all(r.map(function (n) {
- return modelTable.delete(n);
- }));
- }
- }, {
- key: "_preload",
- value: function () {
- var _preload2 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee6(e, t, r) {
- var _this = this;
- var n, o, a;
- return regenerator.wrap(function _callee6$(_context6) {
- while (1) {
- switch (_context6.prev = _context6.next) {
- case 0:
- n = t.length;
- if (n) {
- _context6.next = 3;
- break;
- }
- return _context6.abrupt("return", Promise.resolve());
- case 3:
- o = 0;
- a = window.setInterval(function () {
- r && r(o, n), o >= n && window.clearInterval(a);
- }, 1e3);
- return _context6.abrupt("return", util.mapLimit(t, 10, /*#__PURE__*/function () {
- var _ref = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee5(s) {
- var l, u;
- return regenerator.wrap(function _callee5$(_context5) {
- while (1) {
- switch (_context5.prev = _context5.next) {
- case 0:
- l = s.size, u = s.url;
- return _context5.abrupt("return", _this.requests[e].stopped ? Promise.reject(new PreloadCanceledError()) : http1.get({
- url: u,
- timeout: Preload.getTimeoutBySize(l),
- responseType: "blob",
- retry: 2,
- beforeRequest: function beforeRequest() {
- _this.requests[e].requests[u] = !0;
- }
- }).then( /*#__PURE__*/function () {
- var _ref2 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee4(c) {
- var h, f;
- return regenerator.wrap(function _callee4$(_context4) {
- while (1) {
- switch (_context4.prev = _context4.next) {
- case 0:
- h = c.data;
- if (h instanceof Blob) {
- _context4.next = 3;
- break;
- }
- return _context4.abrupt("return", (logger.error("request blob failed, type:", typeof h, u), Promise.reject("request blob failed " + u)));
- case 3:
- _context4.next = 5;
- return blobToDataURI(h);
- case 5:
- f = _context4.sent;
- _context4.prev = 6;
- _context4.next = 9;
- return modelTable.put({
- url: u,
- model: f
- });
- case 9:
- return _context4.abrupt("return");
- case 12:
- _context4.prev = 12;
- _context4.t0 = _context4["catch"](6);
- return _context4.abrupt("return", (logger.error("unable to add data to indexedDB", _context4.t0), Promise.reject(new InternalError("preload db error"))));
- case 15:
- case "end":
- return _context4.stop();
- }
- }
- }, _callee4, null, [[6, 12]]);
- }));
- return function (_x9) {
- return _ref2.apply(this, arguments);
- };
- }()).then(function () {
- o++, delete _this.requests[e].requests[u];
- }, function (c) {
- return delete _this.requests[e].requests[u], window.clearInterval(a), Promise.reject(c);
- }));
- case 2:
- case "end":
- return _context5.stop();
- }
- }
- }, _callee5);
- }));
- return function (_x8) {
- return _ref.apply(this, arguments);
- };
- }()));
- case 6:
- case "end":
- return _context6.stop();
- }
- }
- }, _callee6);
- }));
- function _preload(_x5, _x6, _x7) {
- return _preload2.apply(this, arguments);
- }
- return _preload;
- }()
- }], [{
- key: "getTimeoutBySize",
- value: function getTimeoutBySize(e) {
- return e ? e < 500 * 1e3 ? 30 * 1e3 : e < 1e3 * 1e3 ? 60 * 1e3 : 100 * 1e3 : 100 * 1e3;
- }
- }]);
- return Preload;
- }();
- var RenderType$1 = {
- PathVideo: 0,
- RotationVideo: 1,
- RotationImage: 2,
- PanoramaImage: 3,
- CGVideo: 4,
- ClientRotationPano: 5,
- CloudRotationPano: 6
- };
- var Xverse = /*#__PURE__*/function () {
- function Xverse(e) {
- _classCallCheck(this, Xverse);
- e || (e = {});
- var _e = e,
- t = _e.onLog,
- r = _e.env,
- n = _e.appId,
- o = _e.releaseId,
- a = _e.subPackageVersion;
- this.NO_CACHE = !1, this.env = r || "PROD", this.SUB_PACKAGE_VERSION = a, this.debug && logger.setLevel(LoggerLevels.Debug);
- var s = this.pageSession = util.uuid();
- reporter$1.updateHeader({
- pageSession: s
- });
- reporter$1.updateReportUrl(REPORT_URL[this.env]);
- a && reporter$1.updateBody({
- sdkVersion: a
- });
- logger.infoAndReportMeasurement({
- metric: "sdkInit",
- startTime: Date.now(),
- extra: {
- version: a,
- enviroment: r,
- pageSession: s
- }
- });
- logger.debug("debug mode:", this.debug);
- reporter$1.on("report", function (l) {
- t && t(l);
- });
- if (n) {
- this.appId = n, this.releaseId = o;
- var l = ModelManager.getInstance(n, o);
- this.preload = new Preload(l);
- }
- }
- _createClass(Xverse, [{
- key: "isSupported",
- get: function get() {
- return isSupported();
- }
- }, {
- key: "disableLogUpload",
- value: function disableLogUpload() {
- reporter$1.disable(), logger.debug("logger upload has been disabled");
- }
- }, {
- key: "getSkinList",
- value: function () {
- var _getSkinList = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee() {
- return regenerator.wrap(function _callee$(_context) {
- while (1) {
- switch (_context.prev = _context.next) {
- case 0:
- return _context.abrupt("return", []);
- case 1:
- case "end":
- return _context.stop();
- }
- }
- }, _callee);
- }));
- function getSkinList() {
- return _getSkinList.apply(this, arguments);
- }
- return getSkinList;
- }()
- }, {
- key: "getAvatarList",
- value: function () {
- var _getAvatarList = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee2() {
- return regenerator.wrap(function _callee2$(_context2) {
- while (1) {
- switch (_context2.prev = _context2.next) {
- case 0:
- return _context2.abrupt("return", []);
- case 1:
- case "end":
- return _context2.stop();
- }
- }
- }, _callee2);
- }));
- function getAvatarList() {
- return _getAvatarList.apply(this, arguments);
- }
- return getAvatarList;
- }()
- }, {
- key: "getGiftList",
- value: function () {
- var _getGiftList = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee3() {
- return regenerator.wrap(function _callee3$(_context3) {
- while (1) {
- switch (_context3.prev = _context3.next) {
- case 0:
- return _context3.abrupt("return", [{
- id: "hack "
- }]);
- case 1:
- case "end":
- return _context3.stop();
- }
- }
- }, _callee3);
- }));
- function getGiftList() {
- return _getGiftList.apply(this, arguments);
- }
- return getGiftList;
- }()
- }, {
- key: "joinRoom",
- value: function () {
- var _joinRoom = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee4(e) {
- var t, r, n, o;
- return regenerator.wrap(function _callee4$(_context4) {
- while (1) {
- switch (_context4.prev = _context4.next) {
- case 0:
- t = e.pathName || "thirdwalk", r = e.rotationRenderType || RenderType$1.RotationVideo, n = e.person || Person$1.Third, o = new XverseRoom(le(oe({}, e), {
- appId: e.appId || this.appId,
- releaseId: e.releaseId || this.releaseId,
- pageSession: this.pageSession,
- isAllSync: !0,
- rotationRenderType: r,
- syncByEvent: !0,
- pathName: t,
- person: n,
- role: e.role || "audience"
- }));
- return _context4.abrupt("return", o.initRoom().then(function () {
- return o;
- }));
- case 2:
- case "end":
- return _context4.stop();
- }
- }
- }, _callee4, this);
- }));
- function joinRoom(_x) {
- return _joinRoom.apply(this, arguments);
- }
- return joinRoom;
- }()
- }]);
- return Xverse;
- }();
- var xverse = new Xverse({
- env: "DEV",
- appId: "10016",
- releaseId: '2203120033_29769e'
- });
- var l = /*#__PURE__*/function () {
- var _ref = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee() {
- var R;
- return regenerator.wrap(function _callee$(_context) {
- while (1) {
- switch (_context.prev = _context.next) {
- case 0:
- _context.prev = 0;
- _context.next = 3;
- return (R = xverse.preload) == null ? void 0 : R.start('full', function (M, x) {
- });
- case 3:
- _context.next = 12;
- break;
- case 5:
- _context.prev = 5;
- _context.t0 = _context["catch"](0);
- if (!(console.error(_context.t0), _context.t0.code === Codes.PreloadCanceled)) {
- _context.next = 10;
- break;
- }
- toast("\u9884\u52A0\u8F7D\u88AB\u53D6\u6D88");
- return _context.abrupt("return");
- case 10:
- toast("\u8FDB\u5165\u5931\u8D25, \u8BF7\u91CD\u8BD5");
- return _context.abrupt("return");
- case 12:
- _context.prev = 12;
- _context.next = 15;
- return xverse.joinRoom({
- canvas: document.getElementById('canvas'),
- skinId: 10092,
- avatarId: 'KGe_Boy',
- roomId: 'e629ef3e-022d-4e64-8654-703bb96410eb',
- userId: '1f7acca1db9d5',
- wsServerUrl: 'wss://uat-eks.xverse.cn/ws',
- appId: "10016",
- token: " ",
- nickname: '1f7acca1db9d5',
- firends: ["user1"],
- viewMode: "full",
- resolution: {
- width: 1728,
- height: 720
- },
- pathName: 'thirdwalk',
- objectFit: null,
- hasAvatar: !0,
- syncToOthers: !0
- });
- case 15:
- room = _context.sent;
- debugger;
- u();
- c();
- window.room = room;
- e(!1);
- _context.next = 28;
- break;
- case 23:
- _context.prev = 23;
- _context.t1 = _context["catch"](12);
- console.error(_context.t1);
- alert(_context.t1);
- return _context.abrupt("return");
- case 28:
- case "end":
- return _context.stop();
- }
- }
- }, _callee, null, [[0, 5], [12, 23]]);
- }));
- return function l() {
- return _ref.apply(this, arguments);
- };
- }();
- var u = function u() {
- room.on("_coreClick", function (_ref2) {
- var f = _ref2.point;
- room._userAvatar.moveTo({
- point: f
- });
- });
- };
- var c = function c() {
- room.on("repeatLogin", function () {
- toast("\u8BE5\u7528\u6237\u5DF2\u7ECF\u5728\u5176\u4ED6\u5730\u70B9\u767B\u5F55", {
- duration: 1e4
- });
- }), room.on("reconnecting", function (_ref3) {
- var f = _ref3.count;
- toast("\u5C1D\u8BD5\u7B2C".concat(f, "\u6B21\u91CD\u8FDE"));
- }), room.on("reconnected", function () {
- toast("\u91CD\u8FDE\u6210\u529F");
- }), room.on("disconnected", function () {
- var f = toast("\u8FDE\u63A5\u5931\u8D25\uFF0C\u624B\u52A8\u70B9\u51FB\u91CD\u8BD5", {
- duration: 1e5,
- onClick() {
- f.hideToast(), room.reconnect();
- }
- });
- });
- };
- l();
- }));
- //# sourceMappingURL=index.js.map
|