-
Notifications
You must be signed in to change notification settings - Fork 0
/
microverse.js
1016 lines (881 loc) · 38.7 KB
/
microverse.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
// Copyright 2022 by Croquet Corporation, Inc. All Rights Reserved.
// https://croquet.io
import {
Constants, App, ModelRoot, ViewRoot, StartWorldcore,
InputManager, PlayerManager, q_euler} from "./worldcore";
import { THREE, ThreeRenderManager } from "./ThreeRender.js";
import { PhysicsManager } from "./physics.js";
/*import { AgoraChatManager } from "./agoraChat.js"; */
import { DolbyChatManager } from "./dolbyChat.js";
import {
KeyFocusManager, SyncedStateManager,
FontModelManager, FontViewManager } from "./text/text.js";
import { CardActor, MicroverseAppManager } from "./card.js";
import { AvatarActor, } from "./avatar.js";
import { WalkManager } from "./walkManager.js"
import { frameName, sendToShell, addShellListener } from "./frame.js";
import { BehaviorModelManager, BehaviorViewManager, CodeLibrary, checkModule } from "./code.js";
import { TextFieldActor } from "./text/text.js";
import { PortalActor } from "./portal.js";
import { WorldSaver } from "./worldSaver.js";
import { startSettingsMenu } from "./settingsMenu.js";
import JSZip from 'jszip';
import * as fflate from 'fflate';
import {AssetManager} from "./wcAssetManager.js";
const defaultAvatarNames = [
"newwhite", "madhatter", "marchhare", "queenofhearts", "cheshirecat", "alice"
];
const defaultSystemBehaviorDirectory = "behaviors/croquet";
const defaultSystemBehaviorModules = [
"avatarEvents.js", "billboard.js", "elected.js", "menu.js", "pdfview.js", "physics.js", "rapier.js", "scrollableArea.js", "singleUser.js", "stickyNote.js", "halfBodyAvatar.js", "fullBodyAvatar.js", "propertySheet.js", "dragAndDrop.js", "gizmo.js"
];
let AA = true;
let HighDPI = false;
console.log("%cTHREE.REVISION:", "color: #f00", THREE.REVISION);
async function getDisplayOptions() {
// turn off antialiasing for mobile and safari
// Safari has exhibited a number of problems when using antialiasing. It is also extremely slow rendering webgl. This is likely on purpose by Apple.
// Firefox seems to be dissolving in front of our eyes as well. It is also much slower.
// mobile devices are usually slower, so we don't want to run those with antialias either. Modern iPads are very fast but see the previous line.
// allows to enable HighDPI rendering. uses more canvas pixel sizes but css scales it.
let aa;
let highdpi;
let aaOption = new URL(window.location).searchParams.get("AA");
if (aaOption) {
if (aaOption === "true") {
console.log(`antialias is true, urlOption AA is set`);
aa = true;
} else {
console.log(`antialias is false, urlOption AA is unset`);
aa = false;
}
}
let dpiOption = new URL(window.location).searchParams.get("HighDPI");
if (dpiOption) {
if (dpiOption === "true") {
console.log(`HighDPI is true, urlOption HighDPI is set`);
highdpi = true;
} else {
console.log(`HighDPI is false, urlOption HighDPI is unset`);
highdpi = false;
}
}
const isSafari = navigator.userAgent.includes("Safari") && !navigator.userAgent.includes("Chrome");
const isFirefox = navigator.userAgent.includes("Firefox");
const isMobile = !!("ontouchstart" in window);
// the code below looks redundant, but let us keep it so that we remember what to do when
// we change our mind again.
if (highdpi === undefined) {
let showcase = window.showcase;
if (showcase) {
highdpi = showcase.highDPI !== undefined ? showcase.highDPI : true;
}
}
if (aa === undefined) {
if (isMobile) {
aa = false;
} else if (isSafari && isMobile) {
aa = false;
} else if (isFirefox) {
aa = true;
} else {
aa = true;
// when there is no url option, deafults to true
}
}
if (highdpi === undefined) {
highdpi = false;
/*
if (isMobile) {
highdpi = false;
} else if (isSafari && isMobile) {
highdpi = false;
} else if (isFirefox) {
highdpi = true;
} else {
// when there is no url option, deafults to true
}
*/
}
try {
const supported = await navigator.xr.isSessionSupported("immersive-vr");
if (supported) {aa = supported;}
} catch (_) { /* ignore */ }
console.log(`antialias is ${aa}, highDPI is ${highdpi}, mobile: ${isMobile}, browser: ${isFirefox ? "Firefox" : isSafari ? "Safari" : "Other Browser"}`);
return {AA: aa, HighDPI: highdpi};
}
function loadLoaders() {
window.JSZip = JSZip;
window.fflate = fflate;
window.THREE = THREE;
return Promise.resolve(THREE);
}
function basenames() {
let url = window.location.origin + window.location.pathname;
let match = /([^/]+)\.html$/.exec(url);
let basename = new URL(window.location).searchParams.get("world");
if (!basename) {
basename = (!match || match[1] === "index") ? "default" : match[1];
}
let baseurl;
if (match) {
baseurl = url.slice(0, match.index);
} else {
let slash = url.lastIndexOf("/");
baseurl = url.slice(0, slash + 1);
}
return {baseurl, basename};
}
function loadInitialBehaviors(paths, directory) {
let library = Constants.Library || new CodeLibrary();
Constants.Library = library;
if (!paths || !directory) {return;}
let {baseurl, _pathname} = basenames();
if (!directory) {
throw new Error("directory argument has to be specified. It is a name for a sub directory name under the ./behaviors directory.");
}
let isSystem = directory === Constants.SystemBehaviorDirectory;
let root = window.microverseDir ? window.microverseDir : baseurl;
let promises = paths.map((path) => {
if (!isSystem) {
let code = `import('${root}${directory}/${path}')`;
return eval(code).then((module) => {
let rest = directory.slice("behaviors".length);
if (rest[0] === "/") {rest = rest.slice(1);}
return [`${rest === "" ? "" : (rest + "/")}${path}`, module];
})
} else {
let modulePath = `${directory.split("/")[1]}/${path}`;
let code = `import('${root}behaviors/${modulePath}')`;
return eval(code).then((module) => {
return [modulePath, module];
})
}
});
return Promise.all(promises).then((array) => {
array.forEach((pair) => {
let [path, module] = pair;
let dot = path.lastIndexOf(".");
let fileName = path.slice(0, dot);
checkModule(module); // may throw an error
library.add(module.default, fileName, isSystem);
});
return true;
});
}
class MyPlayerManager extends PlayerManager {
init(name) {
super.init(name);
this.avatarCount = 0;
this.presentationMode = null; // or the viewId of the leader
this.followers = new Set();
this.subscribe("playerManager", "create", this.playerCreated);
this.subscribe("playerManager", "details", this.playerDetails);
this.subscribe("playerManager", "destroy", this.playerDestroyed);
this.subscribe("playerManager", "enter", this.playerEnteredWorld);
this.subscribe("playerManager", "leave", this.playerLeftWorld);
}
get presenter() { return this.players.get(this.presentationMode); }
createPlayer(playerOptions) {
// invoked by PlayerManager.onJoin.
// when we have a better user management,
// options will be compatible with a card spec
// until then, we check the AvatarNames variable, and if it is a short name
// (as it is) it'd fall back to use the short string as a stem of the model file name.
// if it is an object, we use it as the card spec.
// when an avatar is created to hold the through-portal camera in a secondary
// world, it is initialised according to the next entry in the rota of default
// names/shapes (but remains invisible). if the user comes through into this
// world, at that point the avatar is updated to the name and shape that the
// user had in the previous world (see AvatarPawn.frameTypeChanged).
// this method does not need to call super.createPlayer, which has null
// behaviour. once the player is created and returned, onJoin will publish
// "playerManager:create", which we handle here with playerCreated.
let index = this.avatarCount % Constants.AvatarNames.length;
this.avatarCount++;
let avatarSpec = Constants.AvatarNames[index];
// console.log(frameName(), "MyPlayerManager", this.avatarCount);
let options = {...playerOptions, ...{noSave: true, type: "3d", singleSided: true}};
if (typeof avatarSpec === "string") {
options = {...options, ...{
name: avatarSpec,
dataScale: [0.3, 0.3, 0.3],
dataRotation: q_euler(0, Math.PI, 0),
dataTranslation: [0, -0.4, 0],
dataLocation: `./assets/avatars/${avatarSpec}.zip`,
avatarType: "wonderland",
type: "initial", // this is "initial" here to not show the avatar that may be changed
}};
} else {
options = {...options , avatarType: "custom", avatarIndex: index, ...avatarSpec};
}
return AvatarActor.create(options);
}
playerDetails({ playerId, details }) {
// any object can publish a "playerManager:details" event specifying
// a player id and some new property values for that player. for example,
// this is how the AgoraChatManager informs everyone when its local view
// has joined or left the chat.
const player = this.players.get(playerId);
if (!player) return;
player.setAndPublish(details); // will publish a "playerManager:detailsUpdated" event
}
destroyPlayer(player) {
// although the player itself is about to be removed and doesn't care,
// setting its inWorld to false will trigger event subscribers that do -
// for example, this manager's own playerLeftWorld
if (player.inWorld) player.setAndPublish({ inWorld: false });
super.destroyPlayer(player);
}
playerInWorldChanged(player) {
// invoked directly from AvatarActor.inWorldSet when someone has toggled
// the inWorld property of an AvatarActor. this can happen either directly
// in the model domain (such as from destroyPlayer above) or from the
// AvatarPawn, with a say("_set", <props>).
// this method then publishes a player enter or leave event, based on the
// value of inWorld. one subscriber to those events is this MyPlayerManager
// itself: the playerEnteredWorld and playerLeftWorld methods below do
// appropriate housekeeping for the change of state. any view that needs to
// note arrival and departure of avatars in the world is also free to subscribe.
// being in or out of world is a distinct layer from the
// view-join and view-exit events that signal connection and
// disconnection in a Croquet session. the latter are subscribed to in
// the Worldcore PlayerManager - this manager's superclass - and handled
// by invoking createPlayer and destroyPlayer on the manager. the event
// "playerManager:create" is published after createPlayer has completed;
// "playerManager:destroy" is published as part of destroyPlayer, before
// invocation of player.destroy() - mainly handled in Actor - that does
// the cleanup.
// in summary:
// to respond to players having been created or about to be destroyed,
// subscribe to
// playerManager:create
// playerManager:destroy
// to respond to players having entered or left this world, subscribe to
// playerManager:enter
// playerManager:leave
// NB: if a tab goes dormant and is then revived, the model state that will
// be constructed on that revival depends on the state of the session...
// (a) if there are other users in the session:
// the model will process the destruction of the tab's previous avatar
// and creation of a new one, which means that the avatar pawn's
// constructor will find that the actor does not yet have the inWorld
// property. the pawn will publish the dormantAvatarSpec it recorded on
// going dormant (see avatar.js), which will transfer all saved properties
// (position, nickname, 3d model pointer etc) to the new actor.
// (b) if there are no other users in the session:
// the model will process the re-creation of the old avatar as if
// it has never been seen before (or load it from snapshot, if one was
// taken after the avatar's creation). the avatar pawn's constructor
// in the primary frame will find that the actor *does* already have the
// inWorld flag. it will use dormantAvatarSpec to impose the avatar's
// saved properties, as above.
//
// the avatar pawn constructor is the place where we get to ensure that
// avatar properties that must *not* be preserved across dormancy - for now,
// this means inChat - are explicitly reset.
if (player.inWorld) {
this.publish("playerManager", "enter", player);
} else {
this.publish("playerManager", "leave", player);
}
}
playersInWorld() {
return [...this.players.values()].filter((player) => player.inWorld);
}
startPresentation(playerId, presenterToken = null) {
// sent by AvatarActor.comeToMe or this.continuePresenting (triggered by a
// presenter arriving from another world). in either case it may turn out
// that some other presenter has beaten them to it. if so, the arriving
// presenter and their followers will be left to their own devices.
if (this.presentationMode && this.presentationMode !== playerId) return;
this.presentationMode = playerId;
// examining the current inWorld players, decide who will join this
// presentation. if a token was provided, only those players carrying the same
// token are signed up (which will include the presenter, and any follower that
// showed up here before the presenter). only the presenter needs to keep
// that token, to catch potential late followers.
// if no token, grab everyone (and delete any token they might have, while we're
// about it).
for (const player of this.playersInWorld()) {
if (presenterToken && player.presenterToken !== presenterToken) continue;
if (!presenterToken || player.playerId !== playerId) delete player.presenterToken;
this.followers.add(player.playerId);
}
this.publish("playerManager", "presentationStarted");
this.publish("playerManager", "playerCountChanged");
}
addFollower(playerId) {
this.followers.add(playerId);
}
stopPresentation() {
this.presentationMode = null;
this.publish("playerManager", "presentationStopped");
this.publish("playerManager", "playerCountChanged");
this.followers.clear();
}
leavePresentation(playerId) {
if (this.presentationMode === playerId) {return;}
this.followers.delete(playerId);
this.publish("playerManager", "playerCountChanged");
}
continuePresenting(presenter, presenterToken) {
// a presenter came into this world through a portal carrying a token. if there
// is not already a presentation in progress we make them the presenter, and make
// all followers carrying the same token follow them. note that followers may
// enter before or after the presenter.
if (!this.presentationMode) {
console.log(frameName(), "continuePresenting", presenter.id, presenterToken);
presenter.presenterToken = presenterToken; // we keep this for as long as we're presenting
this.startPresentation(presenter.playerId, presenterToken);
} else {
console.log(frameName(), "continuePresenting rejected due to presentation in progress");
}
}
continueFollowing(follower, presenterToken) {
// a follower came into this world through a portal carrying a token, hoping
// to follow the presenter with the same token. the follower may be entering
// before or after the presenter. if the expected presenter isn't presenting,
// the follower will just wait; even if someone else is presenting now, it's
// conceivable - albeit unlikely - that the current presentation will end in
// time for the expected presenter to take over.
if (this.presentationMode && this.presenter.presenterToken === presenterToken) {
console.log(frameName(), "continueFollowing", this.presenter.id, presenterToken);
this.followers.add(follower.playerId);
follower.presentationStarted();
this.publish("playerManager", "playerCountChanged");
} else {
follower.presenterToken = presenterToken;
console.log(frameName(), "continueFollowing: expected presenter not presenting", presenterToken);
}
}
playerEnteredWorld(_player) {
// console.log(frameName(), "playerEnteredWorld", player);
this.publish("playerManager", "playerCountChanged");
}
playerLeftWorld(player) {
// console.log(frameName(), "playerLeftWorld", player);
if (player.playerId === this.presentationMode) {
this.stopPresentation();
}
delete player.presenterToken;
this.followers.delete(player.playerId);
if (player._inChat) player.setAndPublish({ inChat: false });
this.publish("playerManager", "playerCountChanged");
}
playerCreated(_player) {
// console.log(frameName(), "playerCreated", player);
this.publish("playerManager", "playerCountChanged");
}
playerDestroyed(_player) {
// console.log(frameName(), "playerDestroyed", player);
this.publish("playerManager", "playerCountChanged");
}
}
MyPlayerManager.register("MyPlayerManager");
class MyModelRoot extends ModelRoot {
static modelServices() {
return [
MyPlayerManager,
MicroverseAppManager,
BehaviorModelManager,
FontModelManager,
PhysicsManager,
];
}
init(options, persistentData) {
super.init(options);
let appManager = this.service("MicroverseAppManager");
appManager.add(TextFieldActor);
appManager.add(PortalActor);
this.ensurePersistenceProps();
this.subscribe(this.sessionId, "triggerPersist", "triggerPersist");
this.subscribe(this.sessionId, "setPersistentDataFlag", "setPersistentDataFlag");
this.subscribe(this.sessionId, "addBroadcaster", "addBroadcaster");
this.subscribe(this.id, "loadStart", "loadStart");
this.subscribe(this.id, "loadOne", "loadOne");
this.subscribe(this.id, "loadDone", "loadDone");
this.subscribe(this.id, "removeAll", "removeAll");
if (persistentData) {
console.log("loading persistent data");
this.loadPersistentData(persistentData);
return;
}
this.loadBehaviorModules(Constants.Library.modules, "1");
if (Constants.ShowCaseSpec) {
this.publish(this.sessionId, "disableCodeLoadFlag");
}
this.load(Constants.DefaultCards, "1");
}
ensurePersistenceProps() {
if (!this.persistPeriod) {
let period = 1 * 60 * 1000;
this.persistPeriod = period;
}
if (this.lastPersistTime === undefined) {
this.lastPersistTime = 0;
}
if (this.persistRequested === undefined) {
this.persistRequested = false;
}
}
loadPersistentData({ _name, version, data }) {
try {
delete this.loadingPersistentDataErrored;
this.loadingPersistentData = true;
let saver = new WorldSaver(CardActor);
let json = saver.parse(JSON.stringify(data));
//maybe we need to delete all DefaultUserBehaviors at this point.
let lib = Constants.Library;
let systemModules = new Map();
for (let [k, v] of lib.modules) {
if (v.systemModule) {
systemModules.set(k, v);
}
}
this.loadBehaviorModules(systemModules, version);
this.loadBehaviorModules(json.behaviorModules, version);
if (json.cards) {
this.load(json.cards, version);
}
} catch (error) {
console.error("error in loading persistent data", error);
this.loadingPersistentDataErrored = true;
} finally {
delete this.loadingPersistentData;
}
}
savePersistentData() {
if (this.loadingPersistentData) {return;}
if (this.loadingPersistentDataErrored) {return;}
this.lastPersistTime = this.now();
let func = () => this.saveData();
this.persistSession(func);
}
saveData() {
let name = this.sessionName || "Unknown";
let saver = new WorldSaver(CardActor);
let json = saver.save(this);
let string = saver.stringify(json);
return {name, version: "1", data: JSON.parse(string)};
}
loadBehaviorModules(moduleDefs, version) {
// the persistent data should never contain a system behavior
if (version === "1") {
let behaviorManager = this.service("BehaviorModelManager");
return behaviorManager.loadLibraries([...moduleDefs.values()]);
}
return null;
}
load(cards, version) {
if (version === "1") {
return CardActor.load(cards, this, version);
}
}
setPersistentDataFlag(flag) {
this.persistentDataDisabled = !flag;
console.log("persistentData: " + (this.persistentDataDisabled ? "disabled" : "enabled"));
}
triggerPersist() {
let now = this.now();
let diff = now - this.lastPersistTime;
let period = this.persistPeriod;
if (diff < period) {
if (!this.persistRequested) {
this.persistRequested = true;
this.future(period - diff).triggerPersist();
}
//console.log("persist not ready");
return;
}
this.lastPersistTime = now;
this.persistRequested = false;
if (!this.persistentDataDisabled) {
this.savePersistentData();
}
}
addBroadcaster(viewId) {
let manager = this.service("PlayerManager");
let player = manager.player(viewId);
if (player) player.broadcaster = true;
if (!this.broadcastMode) {
this.broadcastMode = true;
this.publish(this.sessionId, "broadcastModeEnabled");
}
}
loadStart(key) {
this.loadKey = key;
this.loadBuffer = [];
}
loadOne(data) {
let {key, buf} = data;
if (key !== this.loadKey) {return;}
this.loadBuffer.push(buf);
}
loadDone(data) {
let {key, asScene, pose} = data;
if (key !== this.loadKey) {return;}
let array = this.loadBuffer;
this.loadBuffer = [];
this.loadKey = null;
if (!array) {
console.log("inconsistent message");
return;
}
let len = array.reduce((acc, cur) => acc + cur.length, 0);
let all = new Uint8Array(len);
let ind = 0;
for (let i = 0; i < array.length; i++) {
all.set(array[i], ind);
ind += array[i].length;
}
let result = new TextDecoder("utf-8").decode(all);
let savedData = JSON.parse(result);
if (savedData.version === "1") {
let string = JSON.stringify(savedData.data);
savedData.data = string;
this.loadFromFile(savedData, asScene, pose);
}
}
removeAll() {
/*
let actors = this.service("ActorManager").actors;
let avatarBehaviors = new Set();
for (let [_k, actor] of actors) {
if (actor.playerId) {
if (actor.behaviorModules) {
avatarBehaviors.add(...actor.behaviorModules);
}
continue;
}
actor.destroy();
}
let manager = this.service("BehaviorModelManager");
let modules = manager.moduleDefs;
let newModuleDefs = [];
for (let [_k, v] of modules) {
if (avatarBehaviors.has(v.externalName)) {
newModuleDefs.push(v);
}
}
manager.cleanUp();
manager.loadLibraries(newModuleDefs);
*/
}
loadFromFile({ _name, version, data }, asScene, pose) {
try {
let saver = new WorldSaver(CardActor);
let json = saver.parse(data);
let nameMap = this.loadBehaviorModules(json.behaviorModules, version);
if (json.cards) {
let result = this.load({array: json.cards, nameMap: asScene ? null : nameMap}, version);
if (pose) {
result.forEach((card) => {
if (!card.parent) {
card._translation = pose.translation;
card._rotation = pose.rotation;
}
});
}
}
} catch (error) {
console.error("error in loading persistent data", error);
}
}
}
MyModelRoot.register("MyModelRoot");
// Broadcast mode is to support larger audiences. It disables sending
// reflector messages for mere spectators. Broadcasters are still able
// to send reflector messages.
// This should be a method of MyViewRoot but we can't access "this"
// until after the super() call in the constructor.
// We need it this early because otherwise messages would be
// sent during construction of some views
function setupBroadcastMode(model) {
const searchParams = new URLSearchParams(window.location.search);
const broadcasting = searchParams.get("broadcastMode") === "true";
if (model.broadcastMode && !broadcasting) {
// HACK need a proper way to enable viewOnly mode
model.__realm.vm.controller.sessionSpec.viewOnly = true;
}
return broadcasting;
}
class MyViewRoot extends ViewRoot {
static viewServices() {
const services = [
InputManager,
{service: ThreeRenderManager, options:{useBVH: true, antialias: AA, useDevicePixelRatio: HighDPI}},
AssetManager,
KeyFocusManager,
FontViewManager,
SyncedStateManager,
BehaviorViewManager,
WalkManager,
];
if (window.settingsMenuConfiguration?.voice ||
Constants.ShowCaseSpec && Constants.ShowCaseSpec.voiceChat) {
services.push(DolbyChatManager);
}
return services;
}
constructor(model) {
const broadcasting = setupBroadcastMode(model);
super(model);
const threeRenderManager = this.service("ThreeRenderManager");
const renderer = threeRenderManager.renderer;
window.scene = threeRenderManager.scene;
this.service("FontViewManager").setModel(model.service("FontModelManager"));
renderer.toneMapping = THREE.ReinhardToneMapping;
renderer.toneMappingExposure = 2.5;
renderer.shadowMap.enabled = true;
renderer.localClippingEnabled = true;
this.setAnimationLoop(this.session);
// When any of *initial* cards has loadSynchronously property,
// two properties synchrnousLoadCards and notLoadedSynchronousCards are created.
// a behavior in synchronousLoad.js checks those properties to decide what to do.
// (The order of things is tricky as a behavior won't be installed to pawns;
// publishing messages from this constructor won't be received by them.
let actorManager = this.model.service("ActorManager");
let cards = [...actorManager.actors].filter((a) => a[1].isCard).map(a => a[1]);
this.synchronousLoadCards = cards.filter((c) => c._cardData.loadSynchronously);
if (this.synchronousLoadCards) {
this.notLoadedSynchronousCards = new Set(this.synchronousLoadCards.map(c => c.id));
}
this.subscribe(this.sessionId, "synchronousCardLoaded", "synchronousCardLoaded");
if (broadcasting) this.publish(this.sessionId, "addBroadcaster", this.viewId);
if (Constants.ShowCaseSpec && !model.persistentDataDisabled) this.publish(this.sessionId, "setPersistentDataFlag", false);
window.viewRoot = this; // used by getViewRoot() function
}
detach() {
console.log("ViewRoot detached");
delete window.viewRoot;
super.detach();
}
setAnimationLoop(session) {
// manual stepping management happens here.
const threeRenderManager = this.service("ThreeRenderManager");
const renderer = threeRenderManager.renderer;
let step = (time, xrFrame) => {
if (xrFrame) {
session.step(time);
}
};
renderer.setAnimationLoop(step);
/*
// we do not need this "backup" ticking (as far as I can tell).
let basicStep = (time) => {
console.log("basicStep", time);
window.requestAnimationFrame(basicStep);
session.step(time);
};
basicStep(Date.now());
*/
}
synchronousCardLoaded(data) {
if (!this.notLoadedSynchronousCards) {return;}
if (this.notLoadedSynchronousCards.size === 0) {return;}
let id = data.id;
this.notLoadedSynchronousCards.delete(id);
if (this.notLoadedSynchronousCards.size === 0) {
this.publish(this.sessionId, "allSynchronousCardsLoaded");
}
}
}
function deleteParameter(url, key) {
const urlObj = new URL(url, location.href);
urlObj.searchParams.delete(key);
return urlObj.toString();
}
let resolveConfiguration = null;
function startWorld(appParameters, world) {
// appParameters are loaded from apiKey.js (see index.js)
// and typically provide apiKey and appId
let sessionParameters = {
// microverse defaults
name: appParameters.name || App.autoSession(),
password: appParameters.password || App.autoPassword(),
model: MyModelRoot,
view: MyViewRoot,
tps: 30,
eventRateLimit: 60,
options: {world},
// developer can override defaults
...appParameters,
};
// identify microverse sessions per flags
if (!Array.isArray(sessionParameters.flags)) sessionParameters.flags = [];
if (!sessionParameters.flags.includes("microverse")) sessionParameters.flags.push("microverse");
// remove portal and broadcast parameters from url for QR code
App.sessionURL = deleteParameter(App.sessionURL, "portal");
App.sessionURL = deleteParameter(App.sessionURL, "broadcastMode");
return loadLoaders()
.then(() => {
return loadInitialBehaviors(Constants.SystemBehaviorModules, Constants.SystemBehaviorDirectory);
}).then(() => {
return loadInitialBehaviors(Constants.UserBehaviorModules, Constants.UserBehaviorDirectory);
}).then(() => {
return StartWorldcore(sessionParameters);
}).then((session) => {
session.view.setAnimationLoop(session);
let {baseurl} = basenames();
let root = window.microverseDir ? window.microverseDir : baseurl;
return fetch(`${root}meta/version.txt`);
}).then((response) => {
if (`${response.status}`.startsWith("2")) {
return response.text();
}
return "(version not found)";
}).then((text) => {
console.log(`
Croquet Microverse
${text}
https://croquet.io`.trim());
});
}
function isRunningLocalNetwork() {
let hostname = window.location.hostname;
if (/^\[.*\]$/.test(hostname)) {
hostname = hostname.slice(1, hostname.length - 1);
}
let local_patterns = [
/^localhost$/,
/^.*\.local$/,
/^.*\.ngrok.io$/,
// 10.0.0.0 - 10.255.255.255
/^(::ffff:)?10(?:\.\d{1,3}){3}$/,
// 127.0.0.0 - 127.255.255.255
/^(::ffff:)?127(?:\.\d{1,3}){3}$/,
// 169.254.1.0 - 169.254.254.255
/^(::f{4}:)?169\.254\.([1-9]|1?\d\d|2[0-4]\d|25[0-4])\.\d{1,3}$/,
// 172.16.0.0 - 172.31.255.255
/^(::ffff:)?(172\.1[6-9]|172\.2\d|172\.3[01])(?:\.\d{1,3}){2}$/,
// 192.168.0.0 - 192.168.255.255
/^(::ffff:)?192\.168(?:\.\d{1,3}){2}$/,
// fc00::/7
/^f[cd][\da-f]{2}(::1$|:[\da-f]{1,4}){1,7}$/,
// fe80::/10
/^fe[89ab][\da-f](::1$|:[\da-f]{1,4}){1,7}$/,
// ::1
/^::1$/,
];
for (let i = 0; i < local_patterns.length; i++) {
if (local_patterns[i].test(hostname)) {return true;}
}
return false;
}
export function startMicroverse() {
let setButtons = (display) => {
["homeBtn", "worldMenuBtn"].forEach((n) => {
let btn = document.querySelector("#" + n);
if (btn) {
btn.style.display = display;
}
});
};
// let showcase = Constants.ShowCaseSpec;
// Constants is not initialized yet, as Croquet session has not been started.
let showcase = window.showcase;
sendToShell("hud", {joystick: false, fullscreen: false});
setButtons("none");
const configPromise = new Promise(resolve => resolveConfiguration = resolve)
.then(localConfig => {
window.settingsMenuConfiguration = { ...localConfig };
return !localConfig.showSettings || localConfig.userHasSet
? false // as if user has run dialog with no changes
: new Promise(resolve => startSettingsMenu(true, showcase && !showcase.useAvatar, resolve));
});
sendToShell("send-configuration");
return configPromise.then(changed => {
if (changed) sendToShell("update-configuration", { localConfig: window.settingsMenuConfiguration });
if (!showcase) {
sendToShell("hud", {joystick: true, fullscreen: true});
setButtons("flex");
}
return getDisplayOptions();
}).then((options) => {
AA = options.AA;
HighDPI = options.HighDPI;
launchMicroverse();
});
}
async function launchMicroverse() {
if (window.microverseInitFunction) {
return window.microverseInitFunction(startWorld, { Constants, App });
}
let {baseurl, basename} = basenames();
if (!basename.endsWith(".vrse")) {
// eval to hide import from webpack
const worldModule = await eval(`import("${baseurl}worlds/${basename}.js")`);
// use bit-identical math for constant initialization
ModelRoot.evaluate(() => worldModule.init(Constants));
if (!Constants.SystemBehaviorModules) {
Constants.SystemBehaviorDirectory = defaultSystemBehaviorDirectory;
if (!Constants.ExcludedSystemBehaviorModules && !Constants.IncludedSystemBehaviorModules) {
Constants.SystemBehaviorModules = defaultSystemBehaviorModules;
} else {
let systemBehaviorModules = [...defaultSystemBehaviorModules];
if (Constants.ExcludedSystemBehaviorModules) {
systemBehaviorModules = systemBehaviorModules.filter((n) => {
return !Constants.ExcludedSystemBehaviorModules.includes(n);
});
}
if (Constants.IncludedSystemBehaviorModules) {
systemBehaviorModules.push(...Constants.IncludedSystemBehaviorModules);
}
Constants.SystemBehaviorModules = systemBehaviorModules;
}
}
} else {
const response = await fetch(basename);
if (!response.ok) throw Error(`world not found: ${basename}`);
const text = await response.text();
const json = new WorldSaver().parse(text);
Constants.AvatarNames = defaultAvatarNames;
Constants.SystemBehaviorDirectory = defaultSystemBehaviorDirectory;
Constants.SystemBehaviorModules = defaultSystemBehaviorModules;
Constants.DefaultCards = json.data.cards;
Constants.Library = new CodeLibrary();
Constants.Library.addModules(json.data.behaviorModules);
}
let apiKeysModule;
let local = isRunningLocalNetwork();
let apiKeysFile = local ? "apiKey-dev.js" : "apiKey.js";
try {
// use eval to hide import from webpack
apiKeysModule = await eval(`import('${baseurl}${apiKeysFile}')`);
const { apiKey, appId } = apiKeysModule.default;
if (typeof apiKey !== "string") throw Error(`${apiKeysFile}: apiKey must be a string`);
if (typeof appId !== "string") throw Error(`${apiKeysFile}: appId must be a string`);
if (!apiKey.match(/^[_a-z0-9]+$/i)) throw Error(`${apiKeysFile}: invalid apiKey: "${apiKey}"`);
if (!appId.match(/^[-_.a-z0-9]+$/i)) throw Error(`${apiKeysFile}: invalid appId: "${appId}"`);
} catch (error) {
if (error.name === "TypeError" && local) {
// apiKey-dev.js not found, use default dev key
console.warn(`${apiKeysFile} not found, using default key for local development. Please create a valid apiKey-dev.js for local development, and apiKey.js for deployment (see croquet.io/keys)`);
apiKeysModule = {
default: {
apiKey: "1kBmNnh69v93i5tOpj7bqqaJxjD3HJEucxd7egi7H",
appId: "io.croquet.microverse.localdevdefault",
}
};
} else {
console.error(error);
throw Error("Please make sure that you have created a valid apiKey-dev.js for local development, and apiKey.js for deployment (see croquet.io/keys)");
}
};