-
-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathwalk.js
More file actions
5593 lines (5190 loc) · 203 KB
/
Copy pathwalk.js
File metadata and controls
5593 lines (5190 loc) · 203 KB
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
// /walk — a third-person walkaround for three.ws
//
// Loads the default avatar, attaches the project's AnimationManager so the
// skinned mesh can crossfade between idle / walking / running clips, and
// wires a joystick (mobile) + WASD (desktop) controller that drives the
// avatar across an XZ ground plane while the camera follows behind. An AR
// toggle hides the rendered ground, makes the canvas transparent, and
// streams the back camera into a fullscreen <video> behind everything so
// the avatar appears to walk on whatever surface the phone is pointed at.
import {
AmbientLight,
BoxGeometry,
Box3,
CanvasTexture,
CircleGeometry,
Timer,
Color,
CylinderGeometry,
DirectionalLight,
DoubleSide,
Group,
HemisphereLight,
Mesh,
MeshBasicMaterial,
MeshStandardMaterial,
OrthographicCamera,
PCFShadowMap,
PerspectiveCamera,
PlaneGeometry,
PMREMGenerator,
Quaternion,
Scene,
ShadowMaterial,
SphereGeometry,
Vector3,
WebGLRenderer,
} from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
import { clone as cloneSkinnedScene } from 'three/addons/utils/SkeletonUtils.js';
import { getMeshoptDecoder } from './viewer/internal.js';
import nipplejs from 'nipplejs';
import { AnimationManager } from './animation-manager.js';
import { AccessoryManager } from './agent-accessories.js';
import { WalkGestures, GESTURE_ORDER } from './walk-gestures.js';
import { WalkVoiceChat } from './walk-voice-chat.js';
import { WalkNet } from './walk-net.js';
import { applyLoadout } from './game/cosmetics-loadout.js';
import { getPlayCosmetics } from './game/play-handoff.js';
import { getPresenceTicket, friendsClient } from './friends.js';
import { FriendsPanel } from './game/friends-panel.js';
import { PhysicsWorld } from './physics/physics-world.js';
import { createTerrain } from './game/terrain.js';
import {
fetchEnvironmentManifest,
resolveEnvName,
getEnvironment,
loadEnvironmentScenery,
loadEnvironmentHDR,
applyLighting,
applySky,
skyFadeColor,
terrainColor as envTerrainColor,
} from './walk-environments.js';
import { log } from './shared/log.js';
import { createWalkTrails3D, createTrailSetting, TRAIL_STYLE_LABELS } from './walk-trails.js';
import { createWalkSession, showWelcomeBackToast } from './walk-session.js';
import { createWalkNpcs } from './walk-npcs.js';
import { createWalkWalletProximity } from './walk-wallet.js';
import { openAvatarInspector, isAvatarInspectorOpen, closeAvatarInspector } from './shared/avatar-inspector.js';
import { applyWorldNameplate } from './shared/living-avatar.js';
import { createWalkCapture } from './walk-capture.js';
import { createMarketplaceGallery } from './marketplace-gallery.js';
import { createAgentDeskManager, fetchLiveAgentDesks } from './walk-agent-desk.js';
// Walk-Browse: on /marketplace-walk the page boots with ?gallery=marketplace and
// the engine becomes a strollable 3D marketplace hall. See marketplace-gallery.js.
const GALLERY_MODE = new URLSearchParams(location.search).get('gallery') === 'marketplace';
const AVATAR_URL_DEFAULT = '/avatars/default.glb';
// The GLB URL the local avatar actually loaded from. Captured by resolveAvatarUrl
// so we can (a) broadcast it to the room — other clients render us as our real
// avatar — and (b) short-circuit remote avatar loads that match ours.
let resolvedAvatarUrl = AVATAR_URL_DEFAULT;
// The resolved avatar record (id, name, description, agent_id) from
// /api/avatars/<id>, captured by resolveAvatarUrl so the voice-chat layer can
// answer in the avatar's persona. Null for the default avatar or a direct URL.
let avatarMeta = null;
// When the page is opened as an avatar-editor draft preview
// (?avatar=<draftId>&preview=true), the unsaved appearance to apply on top of
// the base GLB once it loads. Stashed by resolveAvatarUrl, consumed in loadAvatar.
let pendingDraftAppearance = null;
// True for a draft preview — run solo (no multiplayer broadcast of a throwaway
// presigned URL) and skip the player's own equipped cosmetics so the creator
// sees exactly the look they're editing.
let isDraftPreview = false;
async function resolveAvatarUrl() {
const params = new URLSearchParams(location.search);
// A direct GLB/VRM URL wins — this is what the /communities lobby passes when
// a guest drops in with a pasted model or a Ready Player Me link.
const direct = params.get('avatarUrl');
if (direct) {
resolvedAvatarUrl = direct;
return direct;
}
const id = params.get('avatar');
if (!id) {
resolvedAvatarUrl = AVATAR_URL_DEFAULT;
return AVATAR_URL_DEFAULT;
}
// Editor draft preview: resolve the unsaved look through the draft endpoint —
// the base (unbaked) GLB plus an appearance overlay we apply client-side.
if (params.get('preview') === 'true' || params.get('preview') === '1') {
isDraftPreview = true;
const dres = await fetch(`/api/avatars/draft/${encodeURIComponent(id)}`);
if (!dres.ok) throw new Error(`draft ${id} not found (HTTP ${dres.status})`);
const { draft } = await dres.json();
if (!draft?.base_model_url) throw new Error(`draft ${id} has no model URL`);
pendingDraftAppearance = draft.appearance || null;
resolvedAvatarUrl = draft.base_model_url;
return draft.base_model_url;
}
const res = await fetch(`/api/avatars/${encodeURIComponent(id)}`);
if (!res.ok) throw new Error(`avatar ${id} not found (HTTP ${res.status})`);
const { avatar } = await res.json();
if (!avatar?.url) throw new Error(`avatar ${id} has no GLB URL`);
avatarMeta = avatar;
resolvedAvatarUrl = avatar.url;
return avatar.url;
}
// ── Coin community context ────────────────────────────────────────────────
// /walk doubles as the renderer for coin community worlds. When the lobby
// hands off with ?coin=<mint>&coinName=…&coinSymbol=…&coinImage=…, every player
// who entered the same coin shares one room instance (matchmaking key on the
// server) and the world is themed with the coin's identity (HUD + 3D totem).
const COIN_PARAMS = (() => {
const p = new URLSearchParams(location.search);
const mint = (p.get('coin') || '').trim();
const MINT_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
if (!MINT_RE.test(mint))
return { coin: '', name: '', symbol: '', image: '', agent: (p.get('agent') || '').trim() };
return {
coin: mint,
name: (p.get('coinName') || '').slice(0, 48),
symbol: (p.get('coinSymbol') || '').slice(0, 16),
image: (p.get('coinImage') || '').slice(0, 1024),
agent: (p.get('agent') || '').trim(),
};
})();
const ANIMATIONS_MANIFEST_URL = '/animations/manifest.json';
const CLIP_IDLE = 'idle';
const CLIP_WALK = 'av-walk-feminine';
const CLIP_RUN = 'av-walk-feminine'; // no separate run clip; timeScale handles pace difference
const WALK_SPEED = 1.6; // m/s — target ground speed in walk mode
const RUN_SPEED = 4.0; // m/s — target ground speed in run mode
// Natural ground speed of the Mixamo clips at timeScale=1, in m/s. Measured
// from the clip cadence (root-bone delta per cycle ÷ cycle duration on the
// canonical Avaturn rig). We rescale the mixer's timeScale by
// actualSpeed / NATURAL_* so foot-plants line up with translation — kills
// the "skating" artifact that shows when clip cadence != translation speed.
const NATURAL_WALK_SPEED = 1.5;
const NATURAL_RUN_SPEED = 3.4;
const TURN_LERP = 0.18; // 0..1 — how snappy avatar facing follows movement
const CAM_LERP = 0.12; // 0..1 — how snappy follow-camera trails the avatar
// Procedural body lean — pitch the avatar slightly forward when moving so
// the silhouette communicates weight transfer instead of looking like the
// torso is being slid along on rails. Radians, ramped by speed fraction.
const LEAN_WALK_RAD = 0.05;
const LEAN_RUN_RAD = 0.13;
const LEAN_LERP = 0.12;
const CAM_OFFSET = new Vector3(0, 1.85, 3.6); // behind-and-above, relative to avatar yaw
const CAM_LOOK_OFFSET = new Vector3(0, 1.1, 0);
const GROUND_RADIUS = 12;
// Right-hand "look" stick — radians/sec the camera rotates at full deflection.
// Signs mirror the canvas drag-orbit handler so push-right turns right and
// push-up tilts the view up.
const LOOK_YAW_SPEED = 2.6;
const LOOK_PITCH_SPEED = 1.9;
// ── DOM ───────────────────────────────────────────────────────────────────
const stage = document.getElementById('walk-stage');
const canvas = document.getElementById('walk-canvas');
const video = document.getElementById('walk-camera-feed');
const joystickEl = document.getElementById('walk-joystick');
const lookJoystickEl = document.getElementById('walk-look-joystick');
const arBtn = document.getElementById('walk-ar-toggle');
const arCta = document.getElementById('walk-ar-cta');
const recordBtn = document.getElementById('walk-record-btn');
const recordStatus = document.getElementById('walk-record-status');
const recordStatusLabel = recordStatus?.querySelector('[data-label]');
const statusEl = document.getElementById('walk-status');
const onlinePill = document.getElementById('walk-online');
const onlineCountEl = document.getElementById('walk-online-count');
const loadingOverlay = document.getElementById('walk-loading');
const loadingText = document.getElementById('walk-loading-text');
const nameInput = /** @type {HTMLInputElement|null} */ (document.getElementById('walk-name-input'));
const playersPanelEl = document.getElementById('walk-players-panel');
const playersListEl = document.getElementById('walk-players-list');
const playersCloseBtn = document.getElementById('walk-players-close');
const helpToggleBtn = document.getElementById('walk-help-toggle');
const zenBtn = document.getElementById('walk-zen-btn');
const zenExitBtn = document.getElementById('walk-zen-exit');
const emoteTrayEl = document.getElementById('walk-emote-tray');
const cameraModeBtn = document.getElementById('walk-camera-mode-btn');
const envBtn = document.getElementById('walk-env-btn');
const screenshotBtn = document.getElementById('walk-screenshot-btn');
const minimapBtn = document.getElementById('walk-minimap-btn');
const NAME_STORAGE_KEY = 'walk:player-name';
function setStatus(text, { error = false, sticky = false } = {}) {
if (!statusEl) return;
statusEl.textContent = text;
statusEl.classList.toggle('is-error', error);
statusEl.classList.remove('is-hidden');
if (!sticky) {
clearTimeout(setStatus._t);
setStatus._t = setTimeout(() => statusEl.classList.add('is-hidden'), 2200);
}
}
function setLoadingText(text) {
if (loadingText) loadingText.textContent = text;
}
function dismissLoading() {
if (!loadingOverlay) return;
loadingOverlay.classList.add('is-done');
loadingOverlay.addEventListener('transitionend', () => loadingOverlay.remove(), { once: true });
}
// ── Name persistence ─────────────────────────────────────────────────────
function getStoredName() {
const params = new URLSearchParams(location.search);
return (
params.get('name') ||
(typeof localStorage !== 'undefined' && localStorage.getItem(NAME_STORAGE_KEY)) ||
''
);
}
function storeName(name) {
try {
localStorage.setItem(NAME_STORAGE_KEY, name);
} catch {}
}
if (nameInput) {
const initial = getStoredName();
if (initial) nameInput.value = initial;
const commitName = () => {
const v = nameInput.value.trim().slice(0, 24);
if (v) {
storeName(v);
if (net) net.rename(v);
}
};
nameInput.addEventListener('blur', commitName);
nameInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
nameInput.blur();
}
});
}
// ── Help toggle ──────────────────────────────────────────────────────────
const helpEl = document.getElementById('walk-help');
let helpAutoHideTimer = null;
if (helpToggleBtn) {
helpToggleBtn.addEventListener('click', () => {
toggleHelp();
// Also hide the small hints if showing the full overlay
if (helpEl && helpAutoHideTimer) {
clearTimeout(helpAutoHideTimer);
helpAutoHideTimer = null;
}
});
}
// ── Zen mode (hide all UI) ───────────────────────────────────────────────
// Strips every overlay so the scene is just the 3D background and the
// movement joystick. Preference persists across sessions and can be set
// from a shared link with ?ui=hidden.
const ZEN_STORAGE_KEY = 'walk:zen';
let zenActive = false;
function setZen(on) {
zenActive = on;
document.body.classList.toggle('is-zen', on);
if (on) {
// Defer the reveal class one frame so the restore pill fades in.
requestAnimationFrame(() => document.body.classList.add('zen-revealed'));
// Close any open panels so they don't pop back when chrome returns.
// DOM-based checks keep this safe to call during module init.
if (playersPanelEl && !playersPanelEl.hidden) togglePlayersPanel();
if (friendsPanelOpen) closeFriendsPanel();
if (gestures?.isWheelOpen()) gestures.closeWheel();
} else {
document.body.classList.remove('zen-revealed');
}
if (zenBtn) zenBtn.setAttribute('aria-pressed', String(on));
try {
localStorage.setItem(ZEN_STORAGE_KEY, on ? '1' : '0');
} catch {}
}
function toggleZen() {
setZen(!zenActive);
}
if (zenBtn) zenBtn.addEventListener('click', toggleZen);
if (zenExitBtn) zenExitBtn.addEventListener('click', () => setZen(false));
// ── HUD button handlers for new features ─────────────────────────────────
if (cameraModeBtn) cameraModeBtn.addEventListener('click', () => cycleCameraMode());
if (envBtn) {
envBtn.setAttribute('aria-haspopup', 'listbox');
envBtn.setAttribute('aria-expanded', 'false');
envBtn.addEventListener('click', () => toggleEnvPicker());
}
if (screenshotBtn) screenshotBtn.addEventListener('click', () => walkCapture.screenshot());
if (minimapBtn) minimapBtn.addEventListener('click', () => toggleMinimap());
// ── On-screen touch action cluster (mobile) ──────────────────────────────
// jump / camera flip / gestures for thumbs — keyboardless devices can't reach
// Space, C, or G. The gesture button is wired by WalkGestures.attachTouchButton
// (tap = open the wheel, long-press = aim-and-release) once gestures are ready.
document.getElementById('walk-touch-jump')?.addEventListener('click', () => triggerJump());
document.getElementById('walk-touch-camera')?.addEventListener('click', () => cycleCameraMode());
// ── Friends panel (Task 15) ───────────────────────────────────────────────
const friendsOverlay = document.getElementById('walk-friends-overlay');
const friendsBody = document.getElementById('walk-friends-body');
const friendsCloseBtn = document.getElementById('walk-friends-close');
const friendsHudBtn = document.getElementById('walk-friends-btn');
const friendsBadgeEl = document.getElementById('walk-friends-badge');
let _friendsPanel = null;
let friendsPanelOpen = false;
function openFriendsPanel() {
if (friendsPanelOpen) return;
friendsPanelOpen = true;
if (friendsOverlay) {
friendsOverlay.removeAttribute('hidden');
// Trigger animation on next frame so the CSS transition fires.
requestAnimationFrame(() => friendsOverlay.classList.add('is-open'));
}
if (friendsHudBtn) friendsHudBtn.setAttribute('aria-pressed', 'true');
// Lazy-init the panel instance.
if (!_friendsPanel && friendsBody) {
_friendsPanel = new FriendsPanel(friendsBody, { walkMode: true });
}
_friendsPanel?.mount();
}
function closeFriendsPanel() {
if (!friendsPanelOpen) return;
friendsPanelOpen = false;
if (friendsOverlay) {
friendsOverlay.classList.remove('is-open');
// Hide after transition so aria-hidden doesn't cut off the close anim.
const onEnd = () => {
friendsOverlay.setAttribute('hidden', '');
friendsOverlay.removeEventListener('transitionend', onEnd);
};
friendsOverlay.addEventListener('transitionend', onEnd);
}
if (friendsHudBtn) friendsHudBtn.setAttribute('aria-pressed', 'false');
_friendsPanel?.unmount();
}
function toggleFriendsPanel() {
if (friendsPanelOpen) closeFriendsPanel();
else openFriendsPanel();
}
if (friendsHudBtn) friendsHudBtn.addEventListener('click', toggleFriendsPanel);
if (friendsCloseBtn) friendsCloseBtn.addEventListener('click', closeFriendsPanel);
// Close on backdrop click.
if (friendsOverlay) {
friendsOverlay.addEventListener('pointerdown', (e) => {
if (e.target === friendsOverlay) closeFriendsPanel();
});
}
// Keep HUD unread badge live — start a background load immediately so the
// badge appears before the user opens the panel for the first time.
const _fc = friendsClient();
_fc.subscribe(() => {
const n = _fc.totalUnread;
if (friendsBadgeEl) {
friendsBadgeEl.textContent = n > 9 ? '9+' : String(n);
friendsBadgeEl.hidden = n <= 0;
}
if (friendsHudBtn) friendsHudBtn.classList.toggle('walk-friends-btn--alert', n > 0);
});
_fc.refresh(); // seed unread counts without blocking the page
// ── Players panel ────────────────────────────────────────────────────────
let playersPanelOpen = false;
function togglePlayersPanel() {
playersPanelOpen = !playersPanelOpen;
if (playersPanelEl) playersPanelEl.hidden = !playersPanelOpen;
if (playersPanelOpen) renderPlayerList();
}
if (playersCloseBtn) playersCloseBtn.addEventListener('click', togglePlayersPanel);
function renderPlayerList() {
if (!playersListEl) return;
playersListEl.innerHTML = '';
const localName = nameInput?.value?.trim() || 'you';
const li = document.createElement('li');
li.className = 'is-you';
li.innerHTML = `<span class="player-dot" style="background:var(--accent)"></span>${esc(localName)}<span class="player-motion">${currentMotion}</span>`;
playersListEl.appendChild(li);
for (const [sid, rp] of remotePlayers) {
const row = document.createElement('li');
const colorHex = '#' + (rp._color ?? 0xffffff).toString(16).padStart(6, '0');
row.innerHTML = `<span class="player-dot" style="background:${colorHex}"></span>${esc(rp.label?.textContent || sid.slice(0, 6))}<span class="player-motion">${rp.motion}</span>`;
playersListEl.appendChild(row);
}
}
function esc(s) {
return String(s).replace(
/[<>&"']/g,
(c) => ({ '<': '<', '>': '>', '&': '&', '"': '"', "'": ''' })[c],
);
}
// ── Renderer / scene ──────────────────────────────────────────────────────
// preserveDrawingBuffer is required so the canvas pixels remain readable for
// the "Record" feature — without it, drawImage(renderer.domElement, …) into
// the offscreen compositor canvas returns blank pixels after the next paint.
const renderer = new WebGLRenderer({
canvas,
antialias: true,
alpha: true,
preserveDrawingBuffer: true,
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight, false);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = PCFShadowMap;
const scene = new Scene();
const pmrem = new PMREMGenerator(renderer);
scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
// The neutral room IBL — restored for environments that ship no HDR (the void).
const defaultEnvTexture = scene.environment;
// Lights — ambient + hemi for soft fill, directional for shadow cast.
const ambientLight = new AmbientLight(0xffffff, 0.55);
scene.add(ambientLight);
const hemi = new HemisphereLight(0xbcd6ff, 0x202830, 0.6);
hemi.position.set(0, 5, 0);
scene.add(hemi);
const sun = new DirectionalLight(0xffffff, 1.4);
sun.position.set(4, 8, 6);
sun.castShadow = true;
sun.shadow.mapSize.set(1024, 1024);
sun.shadow.camera.near = 0.5;
sun.shadow.camera.far = 30;
sun.shadow.camera.left = -8;
sun.shadow.camera.right = 8;
sun.shadow.camera.top = 8;
sun.shadow.camera.bottom = -8;
sun.shadow.bias = -0.0005;
scene.add(sun);
// sun.target must be in the scene for position updates to take effect.
scene.add(sun.target);
// Ground — opaque disc in non-AR mode, swapped to a shadow-only catcher in AR.
const groundOpaque = new Mesh(
new CircleGeometry(GROUND_RADIUS, 64),
new MeshStandardMaterial({ color: 0x202833, roughness: 0.95, metalness: 0.0 }),
);
groundOpaque.rotation.x = -Math.PI / 2;
groundOpaque.receiveShadow = true;
scene.add(groundOpaque);
// The flat disc is kept only as the AR shadow backing; the rolling heightfield
// terrain below supersedes it as the visible, walkable ground in non-AR mode.
groundOpaque.visible = false;
// Procedural heightfield terrain — the single source of truth for ground shape.
// Its column-major height buffer feeds both this mesh and the Rapier heightfield
// collider (see initWalkPhysics), so the surface you see is the surface you walk.
// `let`, not `const`: each environment regenerates the heightfield with its own
// amplitude/tint/seed (flat indoors, rolling outdoors). Closures that read
// `terrain.*` pick up the new instance because they close over the binding.
let terrain = createTerrain({ color: 0x202833 });
scene.add(terrain.mesh);
// ── Walk path visualization (Task 36) ─────────────────────────────────────
// A footstep / glow / line trail painted behind the avatar. The style choice is
// persisted with the same namespaced-key convention as zen/camera-mode/haptics.
// The system itself is built once the avatar loads (so its accent is known); the
// setting is created up-front so the help-overlay control can render immediately.
const TRAIL_KEY = 'walk:trail-style';
const trailSetting = createTrailSetting(TRAIL_KEY, 'footprints');
/** @type {ReturnType<typeof createWalkTrails3D>|null} */
let trails = null;
// ── NPC companions (Task 19) ───────────────────────────────────────────────
// A small cast of autonomous companions — a greeter, a wanderer, and a guide —
// that make each environment feel inhabited. Built once the avatar + animation
// clips load (so NPCs share the resolved clip library), spawned/despawned per
// environment with its own dialogue table, and ticked in the render loop. The
// on/off choice is persisted with the same namespaced-key convention as the
// other walk settings, and the toggle lives in the controls overlay.
const NPC_KEY = 'walk:npcs';
let npcsEnabled = (() => {
try {
return localStorage.getItem(NPC_KEY) !== '0';
} catch {
return true;
}
})();
/** @type {ReturnType<typeof createWalkNpcs>|null} */
let walkNpcs = null;
/** @type {ReturnType<typeof createAgentDeskManager>|null} */
let walkAgentDesks = null;
// Avatar accent → trail colour. The walk avatar is a raw GLB, so we read any
// authored meta accent (gltf.userData / scene.userData), else fall back to the
// brand --accent token (handled inside the trail system).
function avatarAccent() {
const m = avatar?.userData?.meta || avatar?.userData || avatarTemplate?.userData || null;
const a = m?.accent;
return typeof a === 'string' || typeof a === 'number' ? a : null;
}
const groundShadowCatcher = new Mesh(
new CircleGeometry(GROUND_RADIUS, 64),
new ShadowMaterial({ opacity: 0.32 }),
);
groundShadowCatcher.rotation.x = -Math.PI / 2;
groundShadowCatcher.receiveShadow = true;
groundShadowCatcher.visible = false;
scene.add(groundShadowCatcher);
// Blob contact shadow — radial gradient decal that moves with the avatar.
// Ensures there is always a convincing foot-contact cue even on low-end
// devices where PCF shadow maps may be coarse or disabled.
const _blobCanvas = document.createElement('canvas');
_blobCanvas.width = 64;
_blobCanvas.height = 64;
const _blobCtx = _blobCanvas.getContext('2d');
const _blobGrad = _blobCtx.createRadialGradient(32, 32, 0, 32, 32, 32);
_blobGrad.addColorStop(0, 'rgba(0,0,0,0.68)');
_blobGrad.addColorStop(0.45, 'rgba(0,0,0,0.28)');
_blobGrad.addColorStop(1, 'rgba(0,0,0,0)');
_blobCtx.fillStyle = _blobGrad;
_blobCtx.fillRect(0, 0, 64, 64);
const blobShadow = new Mesh(
new PlaneGeometry(1.0, 1.0),
new MeshBasicMaterial({
map: new CanvasTexture(_blobCanvas),
transparent: true,
depthWrite: false,
opacity: 0,
}),
);
blobShadow.rotation.x = -Math.PI / 2;
blobShadow.position.y = 0.004;
scene.add(blobShadow);
// Camera + follow-rig — avatar lives at scene origin (translated by a group)
// so the camera offset math stays in local space.
const camera = new PerspectiveCamera(50, window.innerWidth / window.innerHeight, 0.05, 200);
const avatarRig = new Group();
scene.add(avatarRig);
const camTarget = new Vector3();
const camDesired = new Vector3();
const camLookTarget = new Vector3();
const camLookCurrent = new Vector3();
let cameraYaw = 0; // user-controlled orbit yaw around avatar (radians)
let cameraPitch = 0.05; // small downward tilt by default
// In AR mode the camera is frozen in world space instead of following the
// avatar — the joystick then walks the avatar around physically and natural
// perspective makes it grow/shrink as it approaches/recedes. Captured when
// AR is enabled, cleared when AR is disabled.
let arFrozenCamPos = null;
let arFrozenCamLook = null;
const PITCH_MIN = -0.6;
const PITCH_MAX = 0.7;
const CAM_ZOOM_MIN = 0.6;
const CAM_ZOOM_MAX = 3.2;
let camZoom = 1.0;
// ── Camera mode system ───────────────────────────────────────────────────
// Modes: 'follow' (default third-person), 'cinematic' (orbiting), 'firstperson', 'topdown'
const CAMERA_MODES = ['follow', 'cinematic', 'firstperson', 'topdown'];
const CAMERA_MODE_LABELS = {
follow: 'Follow',
cinematic: 'Cinematic',
firstperson: 'First Person',
topdown: 'Top Down',
};
const CAMERA_MODE_FOV = { follow: 50, cinematic: 35, firstperson: 75, topdown: 50 };
const CAMERA_MODE_KEY = 'walk:camera-mode';
let cameraMode = 'follow';
let cameraModeTransition = 0; // 0 = done, >0 = lerping
const CAMERA_MODE_TRANSITION_DUR = 0.5; // seconds
let cameraModeFrom = { pos: new Vector3(), look: new Vector3(), fov: 50 };
let cameraModeTo = { pos: new Vector3(), look: new Vector3(), fov: 50 };
let cinematicAngle = 0;
let cinematicCutTimer = 0;
const CINEMATIC_ORBIT_SPEED = 0.15; // rad/s
const CINEMATIC_CUT_INTERVAL = 5; // seconds between auto-cuts
const CINEMATIC_RADIUS_MULT = 1.8;
const CINEMATIC_HEIGHT_MULT = 0.7;
const FP_EYE_HEIGHT_MULT = 0.9; // fraction of avatar height for eye position
const TOPDOWN_HEIGHT = 18;
const TOPDOWN_LOOK_DOWN = new Vector3(0, -1, 0.001); // slight offset so lookAt works
// Hot-path scratch — computeCameraForMode runs every frame; reuse these instead
// of allocating fresh Vector3s per call. _RIGHT is the world +X (pitch) axis;
// upY (the world +Y / yaw axis, defined below) is reused for the yaw rotation.
const _RIGHT = new Vector3(1, 0, 0);
const _camPos = new Vector3();
const _camLook = new Vector3();
const _camOffset = new Vector3();
const _camFpForward = new Vector3();
const _camResult = { pos: _camPos, look: _camLook };
// Restore saved camera mode
try {
const saved = localStorage.getItem(CAMERA_MODE_KEY);
if (saved && CAMERA_MODES.includes(saved)) cameraMode = saved;
} catch {}
function setCameraMode(mode) {
if (mode === cameraMode) return;
// Snapshot current camera state as "from"
cameraModeFrom.pos.copy(camera.position);
cameraModeFrom.look.copy(camLookCurrent);
cameraModeFrom.fov = camera.fov;
cameraMode = mode;
cameraModeTransition = CAMERA_MODE_TRANSITION_DUR;
cameraModeTo.fov = CAMERA_MODE_FOV[mode] || 50;
// Hide/show avatar for first person
if (avatar) avatar.visible = mode !== 'firstperson';
try {
localStorage.setItem(CAMERA_MODE_KEY, mode);
} catch {}
updateCameraModeIndicator();
walkSession?.save();
}
function cycleCameraMode() {
const idx = CAMERA_MODES.indexOf(cameraMode);
setCameraMode(CAMERA_MODES[(idx + 1) % CAMERA_MODES.length]);
setStatus(`Camera: ${CAMERA_MODE_LABELS[cameraMode]}`);
haptics.buzz(5);
}
// Camera mode indicator UI element
const cameraModeIndicator = (() => {
const el = document.createElement('div');
el.id = 'walk-camera-mode';
el.setAttribute('role', 'status');
el.style.cssText = [
'position:fixed',
'z-index:6',
'left:50%',
'top:calc(env(safe-area-inset-top, 0) + 60px)',
'transform:translateX(-50%)',
'background:rgba(17,17,17,0.72)',
'border:1px solid rgba(255,255,255,0.08)',
'border-radius:999px',
'padding:5px 14px',
'font-size:11px',
'font-weight:500',
'color:rgba(255,255,255,0.7)',
'backdrop-filter:blur(10px)',
'-webkit-backdrop-filter:blur(10px)',
'pointer-events:none',
'opacity:0',
'transition:opacity 0.25s ease',
].join(';');
document.body.appendChild(el);
return el;
})();
let cameraModeIndicatorTimer = 0;
function updateCameraModeIndicator() {
cameraModeIndicator.textContent = CAMERA_MODE_LABELS[cameraMode];
cameraModeIndicator.style.opacity = '1';
clearTimeout(cameraModeIndicatorTimer);
cameraModeIndicatorTimer = setTimeout(() => {
cameraModeIndicator.style.opacity = '0';
}, 2000);
}
// Compute desired camera position/look for each mode
// Returns a shared scratch { pos, look } — the caller must read/copy the values
// in the same frame and must not retain the reference across frames.
function computeCameraForMode(mode, avatarPos, avatarHeight) {
const pos = _camPos;
const look = _camLook;
if (mode === 'follow') {
const offset = _camOffset.copy(CAM_OFFSET).multiplyScalar(camZoom);
offset.applyAxisAngle(_RIGHT, -cameraPitch);
offset.applyAxisAngle(upY, cameraYaw);
pos.copy(avatarPos).add(offset);
look.copy(avatarPos).add(CAM_LOOK_OFFSET);
} else if (mode === 'cinematic') {
const r = (avatarHeight || 1.8) * CINEMATIC_RADIUS_MULT * camZoom;
const h = (avatarHeight || 1.8) * CINEMATIC_HEIGHT_MULT;
pos.set(
avatarPos.x + Math.cos(cinematicAngle) * r,
avatarPos.y + h + 0.8,
avatarPos.z + Math.sin(cinematicAngle) * r,
);
look.copy(avatarPos).add(CAM_LOOK_OFFSET);
} else if (mode === 'firstperson') {
const eyeH = (avatarHeight || 1.8) * FP_EYE_HEIGHT_MULT;
pos.set(avatarPos.x, avatarPos.y + eyeH, avatarPos.z);
// Look in the direction the avatar is facing
const fpForward = _camFpForward.set(Math.sin(avatarYaw), 0, Math.cos(avatarYaw));
look.copy(pos).add(fpForward.multiplyScalar(5));
look.y -= 0.15; // slight downward gaze
} else if (mode === 'topdown') {
pos.set(avatarPos.x, avatarPos.y + TOPDOWN_HEIGHT, avatarPos.z + 0.01);
look.copy(avatarPos);
}
return _camResult;
}
// Place the camera at its starting pose immediately so frame 0 isn't blank.
function applyCameraImmediate() {
const offset = CAM_OFFSET.clone().multiplyScalar(camZoom);
offset.applyAxisAngle(new Vector3(1, 0, 0), -cameraPitch);
offset.applyAxisAngle(new Vector3(0, 1, 0), cameraYaw);
camDesired.copy(avatarRig.position).add(offset);
camera.position.copy(camDesired);
camLookTarget.copy(avatarRig.position).add(CAM_LOOK_OFFSET);
camLookCurrent.copy(camLookTarget);
camera.lookAt(camLookCurrent);
}
// Recompute the follow offset so the full avatar plus headroom fits the
// current viewport. Distance is derived from the camera's vertical FOV, and
// portrait/narrow viewports (phones) get pulled back further so the head
// isn't cropped. Safe to call before an avatar loads — uses the cached height.
// On a resize we update the offset only and let the follow loop lerp to it;
// on first load we snap so frame 0 is already framed.
function frameAvatarCamera({ snap = true } = {}) {
const height = avatarHeight || 1.8;
const aspect = camera.aspect || window.innerWidth / window.innerHeight;
// 1.5× the avatar height as the vertical span gives ~25% headroom top and
// bottom; narrower-than-square viewports get up to ~1.6× for clear headroom.
const portraitBoost = aspect < 1 ? 1 + (1 - aspect) * 0.6 : 1;
const coverage = height * 1.5 * portraitBoost;
const vFovRad = (camera.fov * Math.PI) / 180;
const fitDist = coverage / (2 * Math.tan(vFovRad / 2));
CAM_OFFSET.set(0, height * 0.62, fitDist);
CAM_LOOK_OFFSET.set(0, height * 0.5, 0);
if (snap) applyCameraImmediate();
}
applyCameraImmediate();
// ── Canvas camera control — one-finger drag orbits, two-finger pinch zooms ──
// Multi-touch aware via a live pointer map: the joystick(s) and the camera can
// be driven at the same time because pointers that land inside a stick zone are
// never tracked here. A single tracked pointer orbits; a second promotes the
// gesture to pinch-zoom; lifting back to one resumes orbit seamlessly.
{
const pointers = new Map(); // pointerId → { x, y }
let orbitId = -1;
let pinchDist = 0;
const inRect = (el, x, y) => {
if (!el) return false;
const r = el.getBoundingClientRect();
return x >= r.left && x <= r.right && y >= r.top && y <= r.bottom;
};
const pinchDistance = () => {
const [a, b] = [...pointers.values()];
return Math.hypot(a.x - b.x, a.y - b.y);
};
canvas.addEventListener('pointerdown', (e) => {
// Pointers belonging to a stick zone are owned by nipplejs — capturing
// them here would redirect its move stream and break movement.
if (
inRect(joystickEl, e.clientX, e.clientY) ||
inRect(lookJoystickEl, e.clientX, e.clientY)
)
return;
pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });
try {
canvas.setPointerCapture?.(e.pointerId);
} catch {}
if (pointers.size === 1) {
orbitId = e.pointerId;
} else if (pointers.size === 2) {
orbitId = -1; // suspend orbit while pinching
pinchDist = pinchDistance();
}
});
const onMove = (e) => {
const p = pointers.get(e.pointerId);
if (!p) return;
const dx = e.clientX - p.x;
const dy = e.clientY - p.y;
p.x = e.clientX;
p.y = e.clientY;
if (pointers.size >= 2) {
// Pinch: spreading fingers (distance grows) zooms in (camZoom down).
const dist = pinchDistance();
camZoom = Math.max(
CAM_ZOOM_MIN,
Math.min(CAM_ZOOM_MAX, camZoom - (dist - pinchDist) * 0.005),
);
pinchDist = dist;
} else if (e.pointerId === orbitId) {
cameraYaw -= dx * 0.005;
cameraPitch = Math.max(PITCH_MIN, Math.min(PITCH_MAX, cameraPitch - dy * 0.0035));
}
};
const onUp = (e) => {
if (!pointers.has(e.pointerId)) return;
pointers.delete(e.pointerId);
try {
canvas.releasePointerCapture?.(e.pointerId);
} catch {}
// Dropping from pinch back to a single finger resumes orbit with it.
if (pointers.size === 1) {
orbitId = [...pointers.keys()][0];
} else if (pointers.size === 0) {
orbitId = -1;
}
};
canvas.addEventListener('pointermove', onMove);
canvas.addEventListener('pointerup', onUp);
canvas.addEventListener('pointercancel', onUp);
}
// ── Input state — combined keyboard + joystick → unit move vector ────────
const input = {
keys: { forward: 0, back: 0, left: 0, right: 0, run: false },
joy: { x: 0, y: 0, active: false },
look: { x: 0, y: 0, active: false },
};
// ── Haptics ─────────────────────────────────────────────────────────────
// Tactile feedback on touch actions. Default on, persisted, and silently a
// no-op where the Vibration API is absent (every desktop, iOS Safari) so call
// sites never have to guard. Toggleable from the controls overlay.
const haptics = (() => {
const KEY = 'walk:haptics';
const supported = typeof navigator !== 'undefined' && typeof navigator.vibrate === 'function';
let enabled = true;
try {
enabled = localStorage.getItem(KEY) !== '0';
} catch {}
return {
get supported() {
return supported;
},
get enabled() {
return enabled;
},
set(on) {
enabled = !!on;
try {
localStorage.setItem(KEY, enabled ? '1' : '0');
} catch {}
},
buzz(ms) {
if (!enabled || !supported) return;
try {
navigator.vibrate(ms);
} catch {}
},
};
})();
// ── Jump state ────────────────────────────────────────────────────────────
let jumpVelocity = 0;
let jumpActive = false;
const JUMP_FORCE = 5.8;
const GRAVITY = -14;
const GROUND_Y = 0;
// ── Physics ────────────────────────────────────────────────────────────────
// A real Rapier solver drives roaming when available (non-AR). Until the WASM
// runtime finishes loading — and in AR, where the avatar floats in the room —
// movement falls back to the legacy direct-mutation path below.
let physics = null;
let physicsReady = false;
let character = null;
let verticalVel = 0; // m/s — integrated vertical velocity for the physics path
let characterGrounded = true;
let physicsActivePrev = false; // rising-edge guard to resync after AR/legacy
function triggerJump() {
// Physics path: only launch when actually standing on something.
if (physicsReady && character && !arActive) {
if (characterGrounded) {
verticalVel = JUMP_FORCE;
haptics.buzz(10);
}
return;
}
// Legacy parabola (AR / pre-physics).
if (jumpActive) return;
jumpActive = true;
jumpVelocity = JUMP_FORCE;
haptics.buzz(10);
}
// ── Snap-turn (Q / E) ────────────────────────────────────────────────────
const SNAP_TURN_RAD = Math.PI / 4; // 45°
// ── Scroll-wheel zoom ────────────────────────────────────────────────────
canvas.addEventListener(
'wheel',
(e) => {
e.preventDefault();
camZoom = Math.max(CAM_ZOOM_MIN, Math.min(CAM_ZOOM_MAX, camZoom + e.deltaY * 0.001));
},
{ passive: false },
);
// ── Pointer lock (click canvas → lock; Esc → unlock) ────────────────────
let pointerLocked = false;
canvas.addEventListener('click', () => {
if (!pointerLocked && !IS_TOUCH) {
canvas.requestPointerLock?.();
}
});
document.addEventListener('pointerlockchange', () => {
pointerLocked = document.pointerLockElement === canvas;
});
document.addEventListener('mousemove', (e) => {
if (!pointerLocked) return;
cameraYaw -= e.movementX * 0.002;
cameraPitch = Math.max(PITCH_MIN, Math.min(PITCH_MAX, cameraPitch - e.movementY * 0.002));
});
// ── Help overlay (? key) ─────────────────────────────────────────────────
const helpOverlay = (() => {
const el = document.createElement('div');
el.id = 'walk-help-overlay';
el.setAttribute('aria-hidden', 'true');
// The overlay is pointer-events:none at ALL times, including while shown.
// It's a read-only info panel with no interactive controls, and on tall /
// portrait viewports its card overlaps the bottom joysticks — a capturing
// overlay (even at opacity:0) silently eats every joystick / canvas touch
// and makes the controls feel dead. Dismissal is handled entirely by the
// window-level pointerdown listener below plus H / Esc, so the panel never
// needs to capture and the sticks underneath always stay live.
el.style.cssText = [
'position:fixed',
'inset:0',
'z-index:9999',
'display:flex',
'align-items:center',
'justify-content:center',
'background:rgba(0,0,0,0.72)',
'backdrop-filter:blur(6px)',
'color:#fff',
'font-family:system-ui,sans-serif',
'opacity:0',
'pointer-events:none',
'transition:opacity 0.18s',
].join(';');
el.innerHTML = `
<div style="max-width:420px;width:90%;background:rgba(255,255,255,0.07);border:1px solid rgba(255,255,255,0.12);border-radius:16px;padding:28px 32px">
<h2 style="margin:0 0 20px;font-size:18px;font-weight:600;letter-spacing:-0.3px">Controls</h2>
<table style="width:100%;border-collapse:collapse;font-size:14px;line-height:2">
<tr><td style="color:#aaa;padding-right:16px">W A S D / Arrows</td><td>Move</td></tr>
<tr><td style="color:#aaa;padding-right:16px">Shift</td><td>Run</td></tr>
<tr><td style="color:#aaa;padding-right:16px">Space</td><td>Jump</td></tr>
<tr><td style="color:#aaa;padding-right:16px">Q / E</td><td>Snap turn 45°</td></tr>
<tr><td style="color:#aaa;padding-right:16px">C</td><td>Cycle camera mode</td></tr>
<tr><td style="color:#aaa;padding-right:16px">G</td><td>Gesture palette</td></tr>
<tr><td style="color:#aaa;padding-right:16px">1 – 9</td><td>Quick gesture</td></tr>
<tr><td style="color:#aaa;padding-right:16px">T / Enter</td><td>Chat</td></tr>
<tr><td style="color:#aaa;padding-right:16px">V</td><td>Cycle environment</td></tr>