123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538 |
- class XverseRoom extends XverseRoom$1 {
- constructor() {
- super(...arguments);
- E(this, "joyStick", new JoyStick(this))
- }
- afterJoinRoomHook() {
- this.joyStick.init({})
- }
- }
- const log$3 = new Logger("xverse-room");
- class XverseRoom$1 extends EventEmitter {
- constructor(e) {
- super();
- E(this, "disableAutoTurn", !1);
- E(this, "options");
- E(this, "_currentNetworkOptions");
- E(this, "lastSkinId");
- E(this, "debug");
- E(this, "isFirstDataUsed", !1);
- E(this, "userId", null);
- E(this, "pathManager", new PathManager);
- E(this, "networkController");
- E(this, "_startTime", Date.now());
- E(this, "canvas");
- E(this, "modelManager");
- E(this, "eventsController");
- E(this, "panorama");
- E(this, "engineProxy");
- E(this, "_id");
- E(this, "skinList", []);
- E(this, "isHost", !1);
- E(this, "avatarManager", new XverseAvatarManager(this));
- E(this, "effectManager", new XverseEffectManager(this));
- E(this, "sceneManager");
- E(this, "scene");
- E(this, "breathPointManager");
- E(this, "_currentState");
- E(this, "joined", !1);
- E(this, "disableRotate", !1);
- E(this, "isPano", !1);
- E(this, "movingByClick", !0);
- E(this, "camera", new Camera(this));
- E(this, "stats", new Stats(this));
- E(this, "isUpdatedRawYUVData", !1);
- E(this, "actionsHandler", new ActionsHandler(this));
- E(this, "_currentClickingState", null);
- E(this, "signal", new Signal(this));
- E(this, "firstFrameTimestamp");
- E(this, "receiveRtcData", async()=>{
- log$3.info("Invoke receiveRtcData");
- let e = !1
- , t = !1
- , r = !1
- , n = !1;
- return this.viewMode === "serverless" ? (log$3.warn("set view mode to serverless"),
- this.setViewMode("observer").then(()=>this, ()=>this)) : new Promise(o=>{
- const a = this.networkController.rtcp.workers;
- a.registerFunction("signal", s=>{
- this.signal.handleSignal(s)
- }
- ),
- a.registerFunction("stream", s=>{
- var l;
- if (this.emit("streamTimestamp", {
- timestamp: Date.now()
- }),
- t || (t = !0,
- log$3.info("Invoke stream event")),
- s.stream) {
- r || (r = !0,
- log$3.info("Invoke updateRawYUVData")),
- this.isUpdatedRawYUVData = !1;
- const u = (l = this._currentState.skin) == null ? void 0 : l.fov;
- this.sceneManager.materialComponent.updateRawYUVData(s.stream, s.width, s.height, u),
- this.isUpdatedRawYUVData = !0
- }
- e || (log$3.info("Invoke isAfterRenderRegistered"),
- e = !0,
- this.scene.registerAfterRender(()=>{
- this.engineProxy.frameRenderNumber >= 2 && (n || (n = !0,
- log$3.info("Invoke registerAfterRender")),
- this.isFirstDataUsed || (log$3.info("Invoke isStreamAvailable"),
- this.isFirstDataUsed = !0,
- this.firstFrameTimestamp = Date.now(),
- o(this),
- this.afterJoinRoom()))
- }
- ))
- }
- ),
- this.panorama.bindListener(()=>{
- o(this),
- this.afterJoinRoom()
- }
- ),
- a.registerFunction("reconnectedFrame", ()=>{}
- ),
- log$3.info("Invoke decoderWorker.postMessage"),
- a.decoderWorker.postMessage({
- t: 5
- })
- }
- )
- }
- );
- E(this, "moveToExtra", "");
- this.options = e,
- this.options.wsServerUrl || (this.options.wsServerUrl = SERVER_URLS.DEV),
- this.modelManager = ModelManager.getInstance(e.appId, e.releaseId),
- this.updateReporter();
- const n = e
- , {canvas: t} = n
- , r = Oe(n, ["canvas"]);
- log$3.infoAndReportMeasurement({
- metric: "startJoinRoomAt",
- startTime: Date.now(),
- group: "joinRoom",
- extra: r,
- value: 0
- })
- }
- get currentNetworkOptions() {
- return this._currentNetworkOptions
- }
- get viewMode() {
- var e;
- return ((e = this._currentState) == null ? void 0 : e.viewMode) || "full"
- }
- get id() {
- return this._id
- }
- get skinId() {
- return this._currentState.skinId
- }
- get skin() {
- return this._currentState.skin
- }
- get sessionId() {
- return this.currentNetworkOptions.sessionId
- }
- get pictureQualityLevel() {
- return this.currentState.pictureQualityLevel
- }
- get avatars() {
- return Array.from(this.avatarManager.avatars.values())
- }
- get currentState() {
- var e;
- return le(oe({}, this._currentState), {
- state: (e = this.networkController) == null ? void 0 : e._state
- })
- }
- get _userAvatar() {
- return this.avatars.find(e=>e.userId === this.userId)
- }
- get tvs() {
- return this.engineProxy._tvs
- }
- get tv() {
- return this.tvs[0]
- }
- get currentClickingState() {
- return this._currentClickingState
- }
- afterJoinRoomHook() {}
- beforeJoinRoomResolveHook() {}
- afterReconnectedHook() {}
- handleSignalHook(e) {}
- skinChangedHook() {}
- async beforeStartGameHook(e) {}
- loadAssetsHook() {}
- afterUserAvatarLoadedHook() {}
- audienceViewModeHook() {}
- setViewModeToObserver() {}
- handleVehicleHook(e) {}
- updateReporter() {
- const {avatarId: e, skinId: t, userId: r, roomId: n, role: o, appId: a, wsServerUrl: s} = this.options;
- reporter.updateHeader({
- userId: r
- }),
- reporter.updateBody({
- roomId: n,
- role: o,
- skinId: t,
- avatarId: e,
- appId: a,
- wsServerUrl: s
- })
- }
- async initRoom() {
- const {timeout: e=DEFAULT_JOINROOM_TIMEOUT} = this.options;
- return isSupported() ? this._initRoom()._timeout(e, new TimeoutError("initRoom timeout")) : Promise.reject(new UnsupportedError)
- }
- async _initRoom() {
- const e = this.validateOptions(this.options);
- if (e)
- return log$3.error("initRoom param error", e),
- Promise.reject(e);
- const {canvas: t, avatarId: r, skinId: n, userId: o, wsServerUrl: a, role: s, token: l, pageSession: u, rotationRenderType: c, isAllSync: h=!1, appId: f, camera: d, player: _, avatarComponents: g, nickname: m, avatarScale: v, firends: y=[], syncByEvent: b=!1, areaName: T, attitude: C=MotionType.Walk, pathName: A, viewMode: S="full", person: P, roomId: R, roomTypeId: M, hasAvatar: x=!1, syncToOthers: I=!1, prioritySync: w=!1, removeWhenDisconnected: O=!0, extra: D} = this.options;
- 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
- });
- try {
- await Promise.all([this.initNetwork(), this.initConfig(), this.initWasm()]),
- log$3.info("network config wasm all ready, start to create game");
- const F = await this.requestCreateRoom({
- skinId: n
- })
- , V = F.routeList.find(L=>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
- }),
- await this.initEngine(F)
- } catch (F) {
- return Promise.reject(F)
- }
- return this.beforeJoinRoomResolve(),
- this.receiveRtcData()
- }
- beforeJoinRoomResolve() {
- this.setupStats(),
- this.eventsController = new EventsController(this),
- this.eventsController.bindEvents(),
- this.panorama = new Panorama(this),
- this.beforeJoinRoomResolveHook()
- }
- afterJoinRoom() {
- this.joined = !0,
- this.viewMode === "observer" && this.setViewModeToObserver(),
- log$3.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", ({stats: e})=>{
- reporter.report("stats", oe({}, e))
- }
- ),
- this.debug = new Debug(this),
- this.afterJoinRoomHook()
- }
- afterReconnected() {
- this.avatarManager.clearOtherUsers(),
- this.afterReconnectedHook()
- }
- leave() {
- var e, t;
- return log$3.info("Invoke room.leave"),
- (e = this.eventsController) == null || e.clearEvents(),
- (t = this.networkController) == null || t.quit(),
- this
- }
- validateOptions(e) {
- const {canvas: t, avatarId: r, skinId: n, userId: o, role: a, roomId: s, token: l, appId: u, avatarComponents: c} = e || {}
- , h = [];
- return t instanceof HTMLCanvasElement || h.push(new ParamError("`canvas` must be instanceof of HTMLCanvasElement")),
- (!o || typeof o != "string") && h.push(new ParamError("`userId` must be string")),
- (!l || typeof l != "string") && h.push(new ParamError("`token` must be string")),
- (!u || typeof u != "string") && h.push(new ParamError("`appId` must be string")),
- a == "audience" || (!r || !n) && h.push(new ParamError("`avatarId` and `skinId` is required when create room")),
- h[0]
- }
- async initNetwork() {
- if (this.viewMode === "serverless")
- return Promise.resolve();
- const e = Date.now();
- try {
- await this.networkController.connect()._timeout(8e3, new InitNetworkTimeoutError),
- log$3.infoAndReportMeasurement({
- metric: "networkInitAt",
- startTime: this._startTime,
- group: "joinRoom"
- }),
- log$3.infoAndReportMeasurement({
- metric: "networkInitCost",
- startTime: e,
- group: "joinRoom"
- })
- } catch (t) {
- throw log$3.infoAndReportMeasurement({
- metric: "networkInitAt",
- startTime: e,
- group: "joinRoom",
- error: t
- }),
- t
- }
- }
- async initConfig() {
- const e = Date.now();
- try {
- await this.modelManager.getApplicationConfig()._timeout(8e3, new InitConfigTimeoutError),
- log$3.infoAndReportMeasurement({
- metric: "configInitAt",
- startTime: this._startTime,
- group: "joinRoom"
- }),
- log$3.infoAndReportMeasurement({
- metric: "configInitCost",
- startTime: e,
- group: "joinRoom"
- })
- } catch (t) {
- throw log$3.infoAndReportMeasurement({
- metric: "configInitAt",
- startTime: e,
- group: "joinRoom",
- error: t
- }),
- t
- }
- }
- async initEngine(e) {
- const t = Date.now();
- try {
- this.engineProxy = new EngineProxy(this),
- await this.engineProxy.initEngine(e),
- log$3.infoAndReportMeasurement({
- metric: "webglInitAt",
- startTime: this._startTime,
- group: "joinRoom"
- }),
- log$3.infoAndReportMeasurement({
- metric: "webglInitCost",
- startTime: t,
- group: "joinRoom"
- });
- return
- } catch (r) {
- let n = r;
- return r.code !== Codes$1.InitEngineTimeout && (n = new InitEngineError),
- log$3.error(r),
- log$3.infoAndReportMeasurement({
- metric: "webglInitAt",
- startTime: t,
- group: "joinRoom",
- error: n
- }),
- Promise.reject(n)
- }
- }
- async initWasm() {
- if (this.viewMode === "serverless")
- return Promise.resolve();
- const e = Date.now();
- try {
- await this.networkController.rtcp.workers.init(this.options.resolution)._timeout(8e3, new InitDecoderTimeoutError),
- this.networkController.rtcp.workers.registerFunction("error", t=>{
- log$3.error("decode error", t);
- const {code: r, message: n} = t;
- this.emit("error", {
- code: r,
- msg: n
- })
- }
- ),
- log$3.infoAndReportMeasurement({
- metric: "wasmInitAt",
- group: "joinRoom",
- startTime: this._startTime
- }),
- log$3.infoAndReportMeasurement({
- metric: "wasmInitCost",
- group: "joinRoom",
- startTime: e
- }),
- eventsManager.on("traceId", t=>{
- this.networkController.rtcp.workers.onTraceId(t)
- }
- )
- } catch (t) {
- throw log$3.infoAndReportMeasurement({
- metric: "wasmInitAt",
- group: "joinRoom",
- startTime: e,
- error: t
- }),
- t
- }
- }
- async requestCreateRoom({skinId: e}) {
- let t;
- if (e) {
- t = await this.getSkin(e);
- const r = await this.modelManager.findRoute(e, this.options.pathName);
- this.updateCurrentNetworkOptions({
- areaName: r.areaName,
- attitude: r.attitude,
- versionId: t.versionId
- });
- const {camera: n, player: o} = getRandomItem(r.birthPointList) || this.options;
- this.options.camera || this.updateCurrentNetworkOptions({
- camera: n
- }),
- this.options.player || this.updateCurrentNetworkOptions({
- player: o
- })
- }
- if (this.viewMode === "serverless")
- return t;
- try {
- await this.beforeStartGameHook(this.options);
- const {room_id: r, data: n, session_id: o} = await this.networkController.startGame();
- this._id = r;
- const a = JSON.parse(n);
- this.isHost = a.IsHost,
- e = a.SkinID || e;
- const s = await this.getSkin(e);
- return this.updateCurrentNetworkOptions({
- roomId: r,
- sessionId: o
- }),
- reporter.updateBody({
- roomId: r,
- skinId: e,
- serverSession: o
- }),
- s
- } catch (r) {
- throw log$3.error("Request create room error", r),
- r
- }
- }
- pause() {
- return this.engineProxy.pause()
- }
- resume() {
- return this.engineProxy.resume()
- }
- reconnect() {
- this.networkController.reconnect()
- }
- async setViewMode(e) {}
- handleRepetLogin() {
- log$3.warn("receive " + Codes$1.RepeatLogin + " for repeat login"),
- this.emit("repeatLogin"),
- reporter.disable(),
- this.networkController.quit()
- }
- setPictureQualityLevel(e) {
- const t = {
- high: EImageQuality.high,
- low: EImageQuality.low,
- average: EImageQuality.mid
- };
- return this.updateCurrentState({
- pictureQualityLevel: e
- }),
- this.sceneManager.setImageQuality(t[e])
- }
- async getSkin(e) {
- let t = null;
- if (t = (this.skinList = await this.modelManager.getSkinsList()).find(n=>n.id === e || n.id === e),
- t)
- return t;
- {
- const n = `skin is invalid: skinId: ${e}`;
- return Promise.reject(new ParamError(n))
- }
- }
- setupStats() {
- this.stats.assign({
- roomId: this.id,
- userId: this.userId
- }),
- setInterval(this.engineProxy.updateStats, 1e3)
- }
- proxyEvents(e, t) {
- this.emit(e, t)
- }
- setCurrentNetworkOptions(e) {
- this._currentNetworkOptions = e
- }
- updateCurrentNetworkOptions(e) {
- Object.assign(this._currentNetworkOptions, e),
- Object.assign(this.options, e)
- }
- setCurrentState(e) {
- this._currentState = e
- }
- 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)
- }
- }
|