-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
hub.js
1611 lines (1337 loc) · 53.6 KB
/
hub.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import "./webxr-bypass-hacks";
import configs from "./utils/configs";
import "./utils/theme";
import "@babel/polyfill";
import "./utils/debug-log";
console.log(`App version: ${process.env.BUILD_VERSION || "?"}`);
import "./assets/stylesheets/hub.scss";
import initialBatchImage from "./assets/images/warning_icon.png";
import loadingEnvironment from "./assets/models/LoadingEnvironment.glb";
import "aframe";
import "./utils/logging";
import { patchWebGLRenderingContext } from "./utils/webgl";
patchWebGLRenderingContext();
import "three/examples/js/loaders/GLTFLoader";
import "networked-aframe/src/index";
import "naf-janus-adapter";
import "aframe-rounded";
import "webrtc-adapter";
import "aframe-slice9-component";
import "./utils/threejs-positional-audio-updatematrixworld";
import "./utils/threejs-world-update";
import patchThreeAllocations from "./utils/threejs-allocation-patches";
import { detectOS, detect } from "detect-browser";
import {
getReticulumFetchUrl,
getReticulumMeta,
invalidateReticulumMeta,
migrateChannelToSocket
} from "./utils/phoenix-utils";
import nextTick from "./utils/next-tick";
import { addAnimationComponents } from "./utils/animation";
import { authorizeOrSanitizeMessage } from "./utils/permissions-utils";
import Cookies from "js-cookie";
import "./naf-dialog-adapter";
import "./components/scene-components";
import "./components/scale-in-screen-space";
import "./components/mute-mic";
import "./components/bone-mute-state-indicator";
import "./components/bone-visibility";
import "./components/fader";
import "./components/in-world-hud";
import "./components/emoji";
import "./components/emoji-hud";
import "./components/virtual-gamepad-controls";
import "./components/ik-controller";
import "./components/hand-controls2";
import "./components/hoverable-visuals";
import "./components/hover-visuals";
import "./components/offset-relative-to";
import "./components/player-info";
import "./components/debug";
import "./components/hand-poses";
import "./components/hud-controller";
import "./components/freeze-controller";
import "./components/icon-button";
import "./components/text-button";
import "./components/block-button";
import "./components/mute-button";
import "./components/kick-button";
import "./components/close-vr-notice-button";
import "./components/leave-room-button";
import "./components/visible-if-permitted";
import "./components/visibility-on-content-types";
import "./components/hide-when-pinned-and-forbidden";
import "./components/visibility-while-frozen";
import "./components/stats-plus";
import "./components/networked-avatar";
import "./components/media-views";
import "./components/avatar-volume-controls";
import "./components/pinch-to-move";
import "./components/pitch-yaw-rotator";
import "./components/position-at-border";
import "./components/pinnable";
import "./components/pin-networked-object-button";
import "./components/mirror-media-button";
import "./components/close-mirrored-media-button";
import "./components/drop-object-button";
import "./components/remove-networked-object-button";
import "./components/camera-focus-button";
import "./components/unmute-video-button";
import "./components/destroy-at-extreme-distances";
import "./components/visible-to-owner";
import "./components/camera-tool";
import "./components/emit-state-change";
import "./components/action-to-event";
import "./components/action-to-remove";
import "./components/emit-scene-event-on-remove";
import "./components/follow-in-fov";
import "./components/matrix-auto-update";
import "./components/clone-media-button";
import "./components/open-media-button";
import "./components/refresh-media-button";
import "./components/tweet-media-button";
import "./components/remix-avatar-button";
import "./components/transform-object-button";
import "./components/scale-button";
import "./components/hover-menu";
import "./components/disable-frustum-culling";
import "./components/teleporter";
import "./components/set-active-camera";
import "./components/track-pose";
import "./components/replay";
import "./components/visibility-by-path";
import "./components/tags";
import "./components/hubs-text";
import "./components/billboard";
import "./components/periodic-full-syncs";
import "./components/inspect-button";
import "./components/set-max-resolution";
import "./components/avatar-audio-source";
import { sets as userinputSets } from "./systems/userinput/sets";
import ReactDOM from "react-dom";
import React from "react";
import { Router, Route } from "react-router-dom";
import { createBrowserHistory, createMemoryHistory } from "history";
import { pushHistoryState } from "./utils/history";
import UIRoot from "./react-components/ui-root";
import AuthChannel from "./utils/auth-channel";
import HubChannel from "./utils/hub-channel";
import LinkChannel from "./utils/link-channel";
import { connectToReticulum } from "./utils/phoenix-utils";
import { disableiOSZoom } from "./utils/disable-ios-zoom";
import { proxiedUrlFor } from "./utils/media-url-utils";
import { traverseMeshesAndAddShapes } from "./utils/physics-utils";
import { handleExitTo2DInterstitial, exit2DInterstitialAndEnterVR } from "./utils/vr-interstitial";
import { getAvatarSrc } from "./utils/avatar-utils.js";
import MessageDispatch from "./message-dispatch";
import SceneEntryManager from "./scene-entry-manager";
import Subscriptions from "./subscriptions";
import { createInWorldLogMessage } from "./react-components/chat-message";
import "./systems/nav";
import "./systems/frame-scheduler";
import "./systems/personal-space-bubble";
import "./systems/app-mode";
import "./systems/permissions";
import "./systems/exit-on-blur";
import "./systems/auto-pixel-ratio";
import "./systems/idle-detector";
import "./systems/camera-tools";
import "./systems/userinput/userinput";
import "./systems/userinput/userinput-debug";
import "./systems/ui-hotkeys";
import "./systems/tips";
import "./systems/interactions";
import "./systems/hubs-systems";
import "./systems/capture-system";
import "./systems/listed-media";
import "./systems/linked-media";
import { SOUND_CHAT_MESSAGE } from "./systems/sound-effects-system";
import "./gltf-component-mappings";
import { App } from "./App";
import { platformUnsupported } from "./support";
window.APP = new App();
window.APP.RENDER_ORDER = {
HUD_BACKGROUND: 1,
HUD_ICONS: 2,
CURSOR: 3
};
const store = window.APP.store;
store.update({ preferences: { shouldPromptForRefresh: undefined } }); // Clear flag that prompts for refresh from preference screen
const mediaSearchStore = window.APP.mediaSearchStore;
const OAUTH_FLOW_PERMS_TOKEN_KEY = "ret-oauth-flow-perms-token";
const NOISY_OCCUPANT_COUNT = 12; // Above this # of occupants, we stop posting join/leaves/renames
const qs = new URLSearchParams(location.search);
const isMobile = AFRAME.utils.device.isMobile();
const isMobileVR = AFRAME.utils.device.isMobileVR();
const isEmbed = window.self !== window.top;
if (isEmbed && !qs.get("embed_token")) {
// Should be covered by X-Frame-Options, but just in case.
throw new Error("no embed token");
}
THREE.Object3D.DefaultMatrixAutoUpdate = false;
import "./components/owned-object-limiter";
import "./components/owned-object-cleanup-timeout";
import "./components/set-unowned-body-kinematic";
import "./components/scalable-when-grabbed";
import "./components/networked-counter";
import "./components/event-repeater";
import "./components/set-yxz-order";
import "./components/cursor-controller";
import "./components/nav-mesh-helper";
import "./components/tools/pen";
import "./components/tools/pen-laser";
import "./components/tools/networked-drawing";
import "./components/tools/drawing-manager";
import "./components/body-helper";
import "./components/shape-helper";
import registerNetworkSchemas from "./network-schemas";
import registerTelemetry from "./telemetry";
import { warmSerializeElement } from "./utils/serialize-element";
import { getAvailableVREntryTypes, VR_DEVICE_AVAILABILITY, ONLY_SCREEN_AVAILABLE } from "./utils/vr-caps-detect";
import detectConcurrentLoad from "./utils/concurrent-load-detector";
import qsTruthy from "./utils/qs_truthy";
const PHOENIX_RELIABLE_NAF = "phx-reliable";
NAF.options.firstSyncSource = PHOENIX_RELIABLE_NAF;
NAF.options.syncSource = PHOENIX_RELIABLE_NAF;
const isBotMode = qsTruthy("bot");
const isTelemetryDisabled = qsTruthy("disable_telemetry");
const isDebug = qsTruthy("debug");
if (!isBotMode && !isTelemetryDisabled) {
registerTelemetry("/hub", "Room Landing Page");
}
disableiOSZoom();
detectConcurrentLoad();
function setupLobbyCamera() {
const camera = document.getElementById("scene-preview-node");
const previewCamera = document.getElementById("environment-scene").object3D.getObjectByName("scene-preview-camera");
if (previewCamera) {
camera.object3D.position.copy(previewCamera.position);
camera.object3D.rotation.copy(previewCamera.rotation);
camera.object3D.rotation.reorder("YXZ");
} else {
const cameraPos = camera.object3D.position;
camera.object3D.position.set(cameraPos.x, 2.5, cameraPos.z);
}
camera.object3D.matrixNeedsUpdate = true;
camera.removeAttribute("scene-preview-camera");
camera.setAttribute("scene-preview-camera", "positionOnly: true; duration: 60");
}
let uiProps = {};
// Hub ID and slug are the basename
let routerBaseName = document.location.pathname
.split("/")
.slice(0, 2)
.join("/");
if (document.location.pathname.includes("hub.html")) {
routerBaseName = "/";
}
// when loading the client as a "default room" on the homepage, use MemoryHistory since exposing all the client paths at the root is undesirable
const history = routerBaseName === "/" ? createMemoryHistory() : createBrowserHistory({ basename: routerBaseName });
window.APP.history = history;
const qsVREntryType = qs.get("vr_entry_type");
function mountUI(props = {}) {
const scene = document.querySelector("a-scene");
const disableAutoExitOnIdle =
qsTruthy("allow_idle") || (process.env.NODE_ENV === "development" && !qs.get("idle_timeout"));
const isCursorHoldingPen =
scene &&
(scene.systems.userinput.activeSets.includes(userinputSets.rightCursorHoldingPen) ||
scene.systems.userinput.activeSets.includes(userinputSets.leftCursorHoldingPen));
const hasActiveCamera = scene && !!scene.systems["camera-tools"].getMyCamera();
const forcedVREntryType = qsVREntryType;
ReactDOM.render(
<Router history={history}>
<Route
render={routeProps => (
<UIRoot
{...{
scene,
isBotMode,
disableAutoExitOnIdle,
forcedVREntryType,
store,
mediaSearchStore,
isCursorHoldingPen,
hasActiveCamera,
...props,
...routeProps
}}
/>
)}
/>
</Router>,
document.getElementById("ui-root")
);
}
function remountUI(props) {
uiProps = { ...uiProps, ...props };
mountUI(uiProps);
}
function setupPeerConnectionConfig(adapter, host, turn) {
const forceTurn = qs.get("force_turn");
const forceTcp = qs.get("force_tcp");
const peerConnectionConfig = {};
if (turn && turn.enabled) {
const iceServers = [];
turn.transports.forEach(ts => {
// Try both TURN DTLS and TCP/TLS
if (!forceTcp) {
iceServers.push({ urls: `turns:${host}:${ts.port}`, username: turn.username, credential: turn.credential });
}
iceServers.push({
urls: `turns:${host}:${ts.port}?transport=tcp`,
username: turn.username,
credential: turn.credential
});
});
iceServers.push({ urls: "stun:stun1.l.google.com:19302" });
peerConnectionConfig.iceServers = iceServers;
peerConnectionConfig.iceTransportPolicy = "all";
if (forceTurn || forceTcp) {
peerConnectionConfig.iceTransportPolicy = "relay";
}
} else {
peerConnectionConfig.iceServers = [
{ urls: "stun:stun1.l.google.com:19302" },
{ urls: "stun:stun2.l.google.com:19302" }
];
}
adapter.setPeerConnectionConfig(peerConnectionConfig);
}
async function updateEnvironmentForHub(hub, entryManager) {
let sceneUrl;
let isLegacyBundle; // Deprecated
const sceneErrorHandler = () => {
remountUI({ roomUnavailableReason: "scene_error" });
entryManager.exitScene();
};
const environmentScene = document.querySelector("#environment-scene");
const sceneEl = document.querySelector("a-scene");
if (hub.scene) {
isLegacyBundle = false;
sceneUrl = hub.scene.model_url;
} else if (hub.scene === null) {
// delisted/removed scene
sceneUrl = loadingEnvironment;
} else {
const defaultSpaceTopic = hub.topics[0];
const glbAsset = defaultSpaceTopic.assets.find(a => a.asset_type === "glb");
const bundleAsset = defaultSpaceTopic.assets.find(a => a.asset_type === "gltf_bundle");
sceneUrl = (glbAsset || bundleAsset).src || loadingEnvironment;
const hasExtension = /\.gltf/i.test(sceneUrl) || /\.glb/i.test(sceneUrl);
isLegacyBundle = !(glbAsset || hasExtension);
}
if (isLegacyBundle) {
// Deprecated
const res = await fetch(sceneUrl);
const data = await res.json();
const baseURL = new URL(THREE.LoaderUtils.extractUrlBase(sceneUrl), window.location.href);
sceneUrl = new URL(data.assets[0].src, baseURL).href;
} else {
sceneUrl = proxiedUrlFor(sceneUrl);
}
console.log(`Scene URL: ${sceneUrl}`);
let environmentEl = null;
if (environmentScene.childNodes.length === 0) {
const environmentEl = document.createElement("a-entity");
environmentEl.addEventListener(
"model-loaded",
() => {
environmentEl.removeEventListener("model-error", sceneErrorHandler);
// Show the canvas once the model has loaded
document.querySelector(".a-canvas").classList.remove("a-hidden");
sceneEl.addState("visible");
//TODO: check if the environment was made with spoke to determine if a shape should be added
traverseMeshesAndAddShapes(environmentEl);
},
{ once: true }
);
environmentEl.addEventListener("model-error", sceneErrorHandler, { once: true });
environmentEl.setAttribute("gltf-model-plus", { src: sceneUrl, useCache: false, inflate: true });
environmentScene.appendChild(environmentEl);
} else {
// Change environment
environmentEl = environmentScene.childNodes[0];
// Clear the three.js image cache and load the loading environment before switching to the new one.
THREE.Cache.clear();
const waypointSystem = sceneEl.systems["hubs-systems"].waypointSystem;
waypointSystem.releaseAnyOccupiedWaypoints();
environmentEl.addEventListener(
"model-loaded",
() => {
environmentEl.addEventListener(
"model-loaded",
() => {
environmentEl.removeEventListener("model-error", sceneErrorHandler);
traverseMeshesAndAddShapes(environmentEl);
// We've already entered, so move to new spawn point once new environment is loaded
if (sceneEl.is("entered")) {
waypointSystem.moveToSpawnPoint();
}
const fader = document.getElementById("viewing-camera").components["fader"];
// Add a slight delay before de-in to reduce hitching.
setTimeout(() => fader.fadeIn(), 2000);
},
{ once: true }
);
sceneEl.emit("leaving_loading_environment");
environmentEl.setAttribute("gltf-model-plus", { src: sceneUrl });
},
{ once: true }
);
if (!sceneEl.is("entered")) {
environmentEl.addEventListener("model-error", sceneErrorHandler, { once: true });
}
environmentEl.setAttribute("gltf-model-plus", { src: loadingEnvironment });
}
}
async function updateUIForHub(hub, hubChannel) {
remountUI({ hub, entryDisallowed: !hubChannel.canEnterRoom(hub) });
}
function handleHubChannelJoined(entryManager, hubChannel, messageDispatch, data) {
const scene = document.querySelector("a-scene");
const isRejoin = NAF.connection.isConnected();
if (isRejoin) {
// Slight hack, to ensure correct presence state we need to re-send the entry event
// on re-join. Ideally this would be updated into the channel socket state but this
// would require significant changes to the hub channel events and socket management.
if (scene.is("entered")) {
hubChannel.sendEnteredEvent();
}
// Send complete sync on phoenix re-join.
NAF.connection.entities.completeSync(null, true);
return;
}
// Turn off NAF for embeds as an optimization, so the user's browser isn't getting slammed
// with NAF traffic on load.
if (isEmbed) {
hubChannel.allowNAFTraffic(false);
}
const hub = data.hubs[0];
let embedToken = hub.embed_token;
if (!embedToken) {
const embedTokenEntry = store.state.embedTokens && store.state.embedTokens.find(t => t.hubId === hub.hub_id);
if (embedTokenEntry) {
embedToken = embedTokenEntry.embedToken;
}
}
console.log(`Janus host: ${hub.host}:${hub.port}`);
remountUI({
onSendMessage: messageDispatch.dispatch,
onLoaded: () => store.executeOnLoadActions(scene),
onMediaSearchResultEntrySelected: (entry, selectAction) =>
scene.emit("action_selected_media_result_entry", { entry, selectAction }),
onMediaSearchCancelled: entry => scene.emit("action_media_search_cancelled", entry),
onAvatarSaved: entry => scene.emit("action_avatar_saved", entry),
embedToken: embedToken
});
scene.addEventListener("action_selected_media_result_entry", e => {
const { entry, selectAction } = e.detail;
if ((entry.type !== "scene_listing" && entry.type !== "scene") || selectAction !== "use") return;
if (!hubChannel.can("update_hub")) return;
hubChannel.updateScene(entry.url);
});
// Handle request for user gesture
scene.addEventListener("2d-interstitial-gesture-required", () => {
remountUI({
showInterstitialPrompt: true,
onInterstitialPromptClicked: () => {
remountUI({ showInterstitialPrompt: false, onInterstitialPromptClicked: null });
scene.emit("2d-interstitial-gesture-complete");
}
});
});
const objectsScene = document.querySelector("#objects-scene");
const objectsUrl = getReticulumFetchUrl(`/${hub.hub_id}/objects.gltf`);
const objectsEl = document.createElement("a-entity");
scene.addEventListener("adapter-ready", () => {
// Append objects once adapter is ready since ownership may be taken.
objectsEl.setAttribute("gltf-model-plus", { src: objectsUrl, useCache: false, inflate: true });
if (!isBotMode) {
objectsScene.appendChild(objectsEl);
}
});
// TODO Remove this once transition completed.
// Wait for scene objects to load before connecting, so there is no race condition on network state.
const connectToScene = async () => {
let adapter = "janus";
try {
// Meta endpoint exists only on dialog
await fetch(`https://${hub.host}:${hub.port}/meta`);
adapter = "dialog";
} catch (e) {
// Ignore, set to janus.
}
scene.setAttribute("networked-scene", {
room: hub.hub_id,
serverURL: `wss://${hub.host}:${hub.port}`,
debug: !!isDebug,
adapter
});
while (!scene.components["networked-scene"] || !scene.components["networked-scene"].data) await nextTick();
scene.addEventListener("adapter-ready", ({ detail: adapter }) => {
let newHostPollInterval = null;
// When reconnecting, update the server URL if necessary
adapter.setReconnectionListeners(
() => {
if (newHostPollInterval) return;
newHostPollInterval = setInterval(async () => {
const currentServerURL = NAF.connection.adapter.serverUrl;
const { host, port, turn } = await hubChannel.getHost();
const newServerURL = `wss://${host}:${port}`;
setupPeerConnectionConfig(adapter, host, turn);
if (currentServerURL !== newServerURL) {
console.log("Connecting to new Janus server " + newServerURL);
scene.setAttribute("networked-scene", { serverURL: newServerURL });
adapter.serverUrl = newServerURL;
}
}, 1000);
},
() => {
clearInterval(newHostPollInterval);
newHostPollInterval = null;
},
null
);
const sendViaPhoenix = reliable => (clientId, dataType, data) => {
const payload = { dataType, data };
if (clientId) {
payload.clientId = clientId;
}
const isOpen = hubChannel.channel.socket.connectionState() === "open";
if (isOpen || reliable) {
const hasFirstSync =
payload.dataType === "um" ? payload.data.d.find(r => r.isFirstSync) : payload.data.isFirstSync;
if (hasFirstSync) {
if (isOpen) {
hubChannel.channel.push("naf", payload);
} else {
// Memory is re-used, so make a copy
hubChannel.channel.push("naf", AFRAME.utils.clone(payload));
}
} else {
// Optimization: Strip isFirstSync and send payload as a string to reduce server parsing.
// The server will not parse messages without isFirstSync keys when sent to the nafr event.
//
// The client must assume any payload that does not have a isFirstSync key is not a first sync.
const nafrPayload = AFRAME.utils.clone(payload);
if (nafrPayload.dataType === "um") {
for (let i = 0; i < nafrPayload.data.d.length; i++) {
delete nafrPayload.data.d[i].isFirstSync;
}
} else {
delete nafrPayload.data.isFirstSync;
}
hubChannel.channel.push("nafr", { naf: JSON.stringify(nafrPayload) });
}
}
};
adapter.reliableTransport = sendViaPhoenix(true);
adapter.unreliableTransport = sendViaPhoenix(false);
});
const loadEnvironmentAndConnect = () => {
updateEnvironmentForHub(hub, entryManager);
function onConnectionError() {
console.error("Unknown error occurred while attempting to connect to networked scene.");
remountUI({ roomUnavailableReason: "connect_error" });
entryManager.exitScene();
}
const connectionErrorTimeout = setTimeout(onConnectionError, 90000);
scene.components["networked-scene"]
.connect()
.then(() => {
clearTimeout(connectionErrorTimeout);
scene.emit("didConnectToNetworkedScene");
})
.catch(connectError => {
clearTimeout(connectionErrorTimeout);
// hacky until we get return codes
const isFull = connectError.msg && connectError.msg.match(/\bfull\b/i);
console.error(connectError);
remountUI({ roomUnavailableReason: isFull ? "full" : "connect_error" });
entryManager.exitScene();
return;
});
};
window.APP.hub = hub;
updateUIForHub(hub, hubChannel);
scene.emit("hub_updated", { hub });
if (!isEmbed) {
loadEnvironmentAndConnect();
} else {
remountUI({
onPreloadLoadClicked: () => {
hubChannel.allowNAFTraffic(true);
remountUI({ showPreload: false });
loadEnvironmentAndConnect();
}
});
}
};
connectToScene();
}
async function runBotMode(scene, entryManager) {
const noop = () => {};
const alwaysFalse = () => false;
scene.renderer = {
setAnimationLoop: noop,
render: noop,
shadowMap: {},
vr: { isPresenting: alwaysFalse },
setSize: noop
};
while (!NAF.connection.isConnected()) await nextTick();
entryManager.enterSceneWhenLoaded(new MediaStream(), false);
}
function checkForAccountRequired() {
// If the app requires an account to join a room, redirect to the sign in page.
if (!configs.feature("require_account_for_join")) return;
if (store.state.credentials && store.state.credentials.token) return;
document.location = `/?sign_in&sign_in_destination=hub&sign_in_destination_url=${encodeURIComponent(
document.location.toString()
)}`;
}
document.addEventListener("DOMContentLoaded", async () => {
await store.initProfile();
const canvas = document.querySelector(".a-canvas");
canvas.classList.add("a-hidden");
warmSerializeElement();
if (platformUnsupported()) {
return;
}
const detectedOS = detectOS(navigator.userAgent);
const browser = detect();
// HACK - it seems if we don't initialize the mic track up-front, voices can drop out on iOS
// safari when initializing it later.
if (["iOS", "Mac OS"].includes(detectedOS) && ["safari", "ios"].includes(browser.name)) {
try {
await navigator.mediaDevices.getUserMedia({ audio: true });
} catch (e) {
remountUI({ showSafariMicDialog: true });
return;
}
}
const defaultRoomId = configs.feature("default_room_id");
const hubId =
qs.get("hub_id") ||
(document.location.pathname === "/" && defaultRoomId
? defaultRoomId
: document.location.pathname.substring(1).split("/")[0]);
console.log(`Hub ID: ${hubId}`);
if (!defaultRoomId) {
// Default room won't work if account is required to access
checkForAccountRequired();
}
const subscriptions = new Subscriptions(hubId);
if (navigator.serviceWorker) {
try {
navigator.serviceWorker
.register("/hub.service.js")
.then(() => {
navigator.serviceWorker.ready
.then(registration => subscriptions.setRegistration(registration))
.catch(() => subscriptions.setRegistrationFailed());
})
.catch(() => subscriptions.setRegistrationFailed());
} catch (e) {
subscriptions.setRegistrationFailed();
}
} else {
subscriptions.setRegistrationFailed();
}
const scene = document.querySelector("a-scene");
scene.renderer.debug.checkShaderErrors = false;
// HACK - Trigger initial batch preparation with an invisible object
scene
.querySelector("#batch-prep")
.setAttribute("media-image", { batch: true, src: initialBatchImage, contentType: "image/png" });
const onSceneLoaded = () => {
const physicsSystem = scene.systems["hubs-systems"].physicsSystem;
physicsSystem.setDebug(isDebug || physicsSystem.debug);
patchThreeAllocations();
};
if (scene.hasLoaded) {
onSceneLoaded();
} else {
scene.addEventListener("loaded", onSceneLoaded, { once: true });
}
// If the stored avatar doesn't have a valid src, reset to a legacy avatar.
const avatarSrc = await getAvatarSrc(store.state.profile.avatarId);
if (!avatarSrc) {
await store.resetToRandomDefaultAvatar();
}
const authChannel = new AuthChannel(store);
const hubChannel = new HubChannel(store, hubId);
const entryManager = new SceneEntryManager(hubChannel, authChannel, history);
const performConditionalSignIn = async (predicate, action, messageId, onFailure) => {
if (predicate()) return action();
const signInContinueTextId = scene.is("vr-mode") ? "entry.return-to-vr" : "dialog.close";
await handleExitTo2DInterstitial(true, () => remountUI({ showSignInDialog: false }));
remountUI({
showSignInDialog: true,
signInMessageId: `sign-in.${messageId}`,
signInCompleteMessageId: `sign-in.${messageId}-complete`,
signInContinueTextId,
onContinueAfterSignIn: async () => {
remountUI({ showSignInDialog: false });
let actionError = null;
if (predicate()) {
try {
await action();
} catch (e) {
actionError = e;
}
} else {
actionError = new Error("Predicate failed post sign-in");
}
if (actionError && onFailure) onFailure(actionError);
exit2DInterstitialAndEnterVR();
}
});
};
window.addEventListener("action_create_avatar", () => {
performConditionalSignIn(
() => hubChannel.signedIn,
() => pushHistoryState(history, "overlay", "avatar-editor"),
"create-avatar"
);
});
scene.addEventListener("scene_media_selected", e => {
const sceneInfo = e.detail;
performConditionalSignIn(
() => hubChannel.can("update_hub"),
() => hubChannel.updateScene(sceneInfo),
"change-scene"
);
});
scene.addEventListener("action_media_tweet", async e => {
let isInModal = false;
let isInOAuth = false;
const exitOAuth = () => {
isInOAuth = false;
store.clearOnLoadActions();
remountUI({ showOAuthDialog: false, oauthInfo: null });
};
await handleExitTo2DInterstitial(true, () => {
if (isInModal) history.goBack();
if (isInOAuth) exitOAuth();
});
performConditionalSignIn(
() => hubChannel.signedIn,
async () => {
// Strip el from stored payload because it won't serialize into the store.
const serializableDetail = {};
Object.assign(serializableDetail, e.detail);
delete serializableDetail.el;
if (hubChannel.can("tweet")) {
isInModal = true;
pushHistoryState(history, "modal", "tweet", serializableDetail);
} else {
if (e.detail.el) {
// Pin the object if we have to go through OAuth, since the page will refresh and
// the object will otherwise be removed
e.detail.el.setAttribute("pinnable", "pinned", true);
}
const url = await hubChannel.getTwitterOAuthURL();
isInOAuth = true;
store.enqueueOnLoadAction("emit_scene_event", { event: "action_media_tweet", detail: serializableDetail });
remountUI({
showOAuthDialog: true,
oauthInfo: [{ type: "twitter", url: url }],
onCloseOAuthDialog: () => exitOAuth()
});
}
},
"tweet"
);
});
remountUI({
performConditionalSignIn,
embed: isEmbed,
showPreload: isEmbed
});
entryManager.performConditionalSignIn = performConditionalSignIn;
entryManager.init();
const linkChannel = new LinkChannel(store);
window.APP.scene = scene;
window.APP.hubChannel = hubChannel;
window.dispatchEvent(new CustomEvent("hub_channel_ready"));
const handleEarlyVRMode = () => {
// If VR headset is activated, refreshing page will fire vrdisplayactivate
// which puts A-Frame in VR mode, so exit VR mode whenever it is attempted
// to be entered and we haven't entered the room yet.
if (scene.is("vr-mode") && !scene.is("vr-entered") && !isMobileVR) {
console.log("Pre-emptively exiting VR mode.");
scene.exitVR();
return true;
}
return false;
};
remountUI({ availableVREntryTypes: ONLY_SCREEN_AVAILABLE, checkingForDeviceAvailability: true });
const availableVREntryTypesPromise = getAvailableVREntryTypes();
scene.addEventListener("enter-vr", () => {
if (handleEarlyVRMode()) return true;
if (isMobileVR) {
// Optimization, stop drawing UI if not visible
remountUI({ hide: true });
}
document.body.classList.add("vr-mode");
availableVREntryTypesPromise.then(availableVREntryTypes => {
// Don't stretch canvas on cardboard, since that's drawing the actual VR view :)
if ((!isMobile && !isMobileVR) || availableVREntryTypes.cardboard !== VR_DEVICE_AVAILABILITY.yes) {
document.body.classList.add("vr-mode-stretch");
}
});
});
handleEarlyVRMode();
// HACK A-Frame 0.9.0 seems to fail to wire up vrdisplaypresentchange early enough
// to catch presentation state changes and recognize that an HMD is presenting on startup.
window.addEventListener(
"vrdisplaypresentchange",
() => {
if (scene.is("vr-entered")) return;
if (scene.is("vr-mode")) return;
const device = AFRAME.utils.device.getVRDisplay();
if (device && device.isPresenting) {
if (!scene.is("vr-mode")) {
console.warn("Hit A-Frame bug where VR display is presenting but A-Frame has not entered VR mode.");
scene.enterVR();
}
}
},
{ once: true }
);
scene.addEventListener("exit-vr", () => {
document.body.classList.remove("vr-mode");
document.body.classList.remove("vr-mode-stretch");
remountUI({ hide: false });
// HACK: Oculus browser pauses videos when exiting VR mode, so we need to resume them after a timeout.
if (/OculusBrowser/i.test(window.navigator.userAgent)) {
document.querySelectorAll("[media-video]").forEach(m => {
const videoComponent = m.components["media-video"];
if (videoComponent) {
videoComponent._ignorePauseStateChanges = true;
setTimeout(() => {
const video = videoComponent.video;
if (video && video.paused && !videoComponent.data.videoPaused) {
video.play();
}
videoComponent._ignorePauseStateChanges = false;
}, 1000);
}
});
}
});
registerNetworkSchemas();
remountUI({
authChannel,
hubChannel,
linkChannel,
subscriptions,
enterScene: entryManager.enterScene,
exitScene: reason => {
entryManager.exitScene();
if (reason) {
remountUI({ roomUnavailableReason: reason });
}
},
initialIsSubscribed: subscriptions.isSubscribed(),