Repository navigation
Expand file tree
/
Copy pathmain.js
More file actions
3344 lines (3129 loc) · 133 KB
/
Copy pathmain.js
File metadata and controls
3344 lines (3129 loc) · 133 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
// Table Cube — WebXR AR demo for Magic Leap 2 (works on other WebXR AR devices too).
//
// How it works:
// 1. Every few frames we grab the headset's RGB camera image (WebXR raw camera access)
// and shrink it to 160x120.
// 2. Bright + low-colour pixels are "white". Small gaps are closed and holes (things
// lying on the table) are filled, then we keep the biggest rectangle-like blob.
// 3. Every pixel of that blob is projected onto the table plane, so we measure the
// table in metres. We fit a rounded rectangle to it: centre, direction, size and
// corner radius. This also removes the perspective error of using the image centre.
// Table height comes from: hit-test along the camera ray → detected planes → a guess.
// 4. The outline and the content follow the table and lock.
//
// If the camera feed is not available it falls back to "gaze mode":
// look at the table and press the trigger to place the content.
// Default table setup is corner calibration: aim at the 4 corners and press the trigger.
//
// What goes on the table (start-page menu "build", ?build=manual|cards|demo):
// - manual: a palette of assets lies along the table edge nearest to you. Trigger on a
// palette tile picks an asset, trigger on the table places it (as often as you like).
// Trigger on "Done" → connect: trigger on an asset, then on a second one = connect
// them. Trigger on "Done" again → finished view with animated flows (manual.js, palette.js).
// - cards: colour squares calibrate the card colours, then trigger on a card adds the
// asset that assets/components.json maps its colour to (cards.js, assets.js).
// Trigger on two assets connects them, as in manual mode.
// - demo: the fixed diorama from assets/scenes/demo.json (diorama.js).
// Link types follow from what the assets produce and consume (system.js); flows are
// animated (links.js). Bumper = undo / step back, hold the bumper = calibrate again.
//
// Everything that happens is logged: on the page (bottom right), inside the headset
// (bottom right of your view), in localStorage, and — when served by devserver.mjs —
// live to the laptop, which is the only log that survives the browser crashing.
import * as THREE from 'three';
import {
dilate, erode, planeProjector, buildColourTable, detectCards, mergeScans, filterNew, rgbToHex, describeColour,
worldToPixel, samplePatch, nearestColour, balanceColour, alignProjection, sampleSlots, pixelShiftToNdc,
} from './cards.js';
import { EnergySystem, colourForType } from './system.js';
import {
loadComponents, preloadModels, makeAssetObject, disposeAssetObject, faceTowards, pickAsset, displayColour,
} from './assets.js';
import { LinkView } from './links.js';
import { insideTable, backAction } from './manual.js';
import { createPalette } from './palette.js';
window.__tableCubeLoaded = true;
// ---------------------------------------------------------------------------
// Settings
// ---------------------------------------------------------------------------
const params = new URLSearchParams(location.search);
const CONFIG = {
analysisWidth: 160, // camera image is downscaled to this for detection
analysisHeight: 120,
analyseEveryNFrames: 6, // roughly 10 detections per second at 60 fps
minWhiteLuma: 110, // nothing darker than this (0–255) counts as white
maxAutoThreshold: 215, // the automatic threshold never goes above this
whiteLuma: params.has('white') ? parseFloat(params.get('white')) : null, // fixed threshold
maxSaturation: 45, // white = low colour: max(r,g,b) - min(r,g,b)
minAreaFraction: 0.02, // blob must cover at least 2% of the camera image
minImageFill: 0.45, // loose shape check in the image (perspective distorts it)
minMetricFill: 0.65, // shape check in metres; a rounded rectangle is ~0.9–1.0
minTableWidth: 0.35, // metres, plausibility check
maxTableLength: 4.0, // metres, plausibility check
maxDistance: 6.0, // ignore table pixels further away than this (metres)
cornerRadius: params.has('corner') ? parseFloat(params.get('corner')) : null, // null = estimate
smoothing: 0.25, // 0..1, higher follows new detections faster
lockTolerance: 0.02, // metres; detections this close count as stable
lockFrames: 8, // stable detections in a row before locking
tableHeight: parseFloat(params.get('table') ?? '0.75'), // fallback, metres above floor
minTableHeight: 0.3, // ignore surfaces lower than this (the floor)
hitTestIntervalMs: 400, // how often to refresh the camera-ray hit-test
cameraTimeoutMs: 6000, // switch to gaze mode if no camera image by then
heartbeatMs: 5000, // "still running" log line, useful to see when a crash happened
touchDistance: 0.04, // corner calibration: controller tip this close to the table = touching
scanWidth: 320, // camera image size for card scans (cards are small)
scanHeight: 240,
scanFrames: 6, // camera frames per scan…
scanFrameGapMs: 100, // …this far apart
scanMinFrames: 4, // a card must show up in this many of them
// The camera image is a little older than the head pose it comes with: while the head
// turns, cards land in the wrong place. Frames taken while turning faster are skipped.
scanMaxTurnDegPerS: 20,
slotInnerRadius: 0.025, // colour squares: sample only the middle (radius, m) of each card
slotSearch: 0.1, // …and look up to this far (m) for the camera image shift
slotFrames: 3, // camera frames per colour calibration
patchRadius: 0.015, // card colour = median of the camera pixels within this (m) of the aimed point
whiteRadius: 0.2, // table white for white balance: from this far (m) around it
scanTimeoutMs: 4000, // give up when the camera doesn't deliver
bumperHoldMs: 1500, // hold the bumper this long to calibrate again
flipCameraY: params.get('flipy') === '1',
debug: params.get('debug') === '1',
};
// ---------------------------------------------------------------------------
// Logger: page panel, headset panel and localStorage (survives crashes)
// ---------------------------------------------------------------------------
const LOG_KEY = 'tablecube-log-v1';
const logLines = [];
// When the page is served by devserver.mjs, every log line is also sent to the laptop.
// That is the only log that survives the whole browser crashing.
const remote = { enabled: false, probing: true, queue: [], seq: 0 };
let previousLog = [];
const logListEl = document.getElementById('log-list');
const logState = { dirty: true };
function timeStamp() {
const d = new Date();
return d.toTimeString().slice(0, 8) + '.' + String(d.getMilliseconds()).padStart(3, '0');
}
function renderLogLine(line, old = false) {
if (!logListEl) return;
const li = document.createElement('li');
li.className = line.level + (old ? ' old' : '');
li.textContent = `${line.t} ${line.text}`;
logListEl.appendChild(li);
while (logListEl.children.length > 500) logListEl.firstElementChild.remove();
logListEl.scrollTop = logListEl.scrollHeight;
}
function persistLog() {
try {
localStorage.setItem(LOG_KEY, JSON.stringify(logLines.slice(-250)));
} catch {
// storage unavailable (private mode etc.) – the on-screen log still works
}
}
function log(level, msg, data) {
let text = String(msg);
if (data !== undefined) {
try {
text += ' ' + (typeof data === 'string' ? data : JSON.stringify(data));
} catch {
text += ' [unprintable data]';
}
}
const line = { t: timeStamp(), level, text };
logLines.push(line);
if (logLines.length > 400) logLines.shift();
const out = level === 'error' ? console.error : level === 'warn' ? console.warn : console.log;
out('[TableCube]', text);
renderLogLine(line);
persistLog();
remoteLog(line);
logState.dirty = true;
}
function remoteSend(lines) {
if (!lines.length) return;
try {
// sendBeacon is queued by the browser even if the page dies right after.
const body = JSON.stringify(lines);
if (navigator.sendBeacon && navigator.sendBeacon('/log', new Blob([body], { type: 'text/plain' }))) return;
fetch('/log', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(lines),
keepalive: true,
}).catch(() => {});
} catch {
// ignore: logging must never break the app
}
}
function remoteLog(line) {
const l = { ...line, n: ++remote.seq };
if (remote.enabled) remoteSend([l]);
else if (remote.probing) remote.queue.push(l);
}
const info = (m, d) => log('info', m, d);
const warn = (m, d) => log('warn', m, d);
const error = (m, d) => log('error', m, d);
// Bump on every change: the log and the page show it, so we can tell whether the headset
// runs the newest code (leaving and re-entering AR does NOT reload it, reloading the page does).
const APP_VERSION = 'manual v2';
info('Table Cube version ' + APP_VERSION);
// index.html checks this: without it, the page is running an older (cached) main.js.
window.__tableCubeVersion = APP_VERSION;
{
const el = document.getElementById('app-version');
if (el) el.textContent = 'Version ' + APP_VERSION;
}
const onceKeys = new Set();
function once(key, level, msg, data) {
if (onceKeys.has(key)) return;
onceKeys.add(key);
log(level, msg, data);
}
function errText(err) {
if (!err) return 'unknown error';
const where = err.stack ? String(err.stack).split('\n').find((l) => l.includes('.js')) : '';
return `${err.name || 'Error'}: ${err.message || err}${where ? ' @ ' + where.trim() : ''}`;
}
(function restorePreviousLog() {
try {
previousLog = JSON.parse(localStorage.getItem(LOG_KEY) || '[]');
} catch {
previousLog = [];
}
if (previousLog.length) {
renderLogLine({ t: '--------', level: 'info', text: 'Previous page load (kept in case the browser crashed):' }, true);
for (const l of previousLog) renderLogLine(l, true);
renderLogLine({ t: '--------', level: 'info', text: 'New page load' }, true);
}
})();
document.getElementById('log-copy')?.addEventListener('click', async () => {
const text = [...previousLog.map((l) => `(prev) ${l.t} [${l.level}] ${l.text}`),
...logLines.map((l) => `${l.t} [${l.level}] ${l.text}`)].join('\n');
try {
await navigator.clipboard.writeText(text);
info('Log copied to clipboard');
} catch {
const ta = document.createElement('textarea');
ta.value = text;
document.body.appendChild(ta);
ta.select();
try { document.execCommand('copy'); info('Log copied to clipboard'); } catch { warn('Copy failed'); }
ta.remove();
}
});
document.getElementById('log-clear')?.addEventListener('click', () => {
logLines.length = 0;
previousLog = [];
if (logListEl) logListEl.innerHTML = '';
persistLog();
logState.dirty = true;
});
document.getElementById('log-toggle')?.addEventListener('click', (e) => {
const panel = document.getElementById('log-panel');
const collapsed = panel.classList.toggle('collapsed');
e.target.textContent = collapsed ? 'Show' : 'Hide';
});
(async function probeLogServer() {
try {
const r = await fetch('/log/ping', { cache: 'no-store' });
remote.enabled = r.ok && (await r.text()).trim() === 'tablecube-log-server';
} catch {
remote.enabled = false;
}
remote.probing = false;
if (remote.enabled) {
remoteSend(remote.queue);
info('Laptop log server found: every log line is also sent there');
} else {
info('No laptop log server (only available when served by devserver.mjs)');
}
remote.queue = [];
})();
window.addEventListener('error', (e) => {
error('Uncaught error', e.error ? errText(e.error) : `${e.message} @ ${e.filename}:${e.lineno}`);
});
window.addEventListener('unhandledrejection', (e) => error('Unhandled promise rejection', errText(e.reason)));
document.addEventListener('visibilitychange', () => info('Page visibility', document.visibilityState));
window.addEventListener('pagehide', () => info('Page is being hidden or unloaded'));
// ---------------------------------------------------------------------------
// Page UI
// ---------------------------------------------------------------------------
const startBtn = document.getElementById('start');
const safeBtn = document.getElementById('start-safe');
const rawBtn = document.getElementById('start-raw');
const statusEl = document.getElementById('status');
const featuresEl = document.getElementById('features');
const FEATURE_KEY = 'tablecube-features-v1';
const pickerInputs = [...document.querySelectorAll('#feature-picker input[data-feature]')];
try {
const saved = JSON.parse(localStorage.getItem(FEATURE_KEY) || 'null');
if (Array.isArray(saved)) for (const inp of pickerInputs) inp.checked = saved.includes(inp.dataset.feature);
} catch { /* ignore */ }
function chosenFeatures() {
return pickerInputs.filter((i) => i.checked).map((i) => i.dataset.feature);
}
for (const inp of pickerInputs) {
inp.addEventListener('change', () => {
try { localStorage.setItem(FEATURE_KEY, JSON.stringify(chosenFeatures())); } catch { /* ignore */ }
});
}
// Table setup: 'corners' (point at the 4 corners) or 'detect' (camera). ?setup= overrides.
const SETUP_KEY = 'tablecube-setup-v1';
const setupInputs = [...document.querySelectorAll('#setup-picker input[name="setup"]')];
try {
const saved = params.get('setup') || localStorage.getItem(SETUP_KEY);
for (const inp of setupInputs) if (saved) inp.checked = inp.value === saved;
} catch { /* ignore */ }
function chosenSetup() {
return setupInputs.find((i) => i.checked)?.value || 'corners';
}
for (const inp of setupInputs) {
inp.addEventListener('change', () => {
try { localStorage.setItem(SETUP_KEY, chosenSetup()); } catch { /* ignore */ }
updateBuildPicker();
});
}
// What goes on the table after the corner setup: 'manual' (palette), 'cards' (colour
// cards) or 'demo' (the diorama). ?build= overrides. Camera table detection never reaches
// the build step, so it always shows the demo.
const BUILD_KEY = 'tablecube-build-v1';
const BUILD_MODES = ['manual', 'cards', 'demo'];
const buildPicker = document.getElementById('build-picker');
const buildInputs = [...document.querySelectorAll('#build-picker input[name="build"]')];
try {
const saved = [params.get('build'), localStorage.getItem(BUILD_KEY)].find((v) => BUILD_MODES.includes(v));
if (saved) for (const inp of buildInputs) inp.checked = inp.value === saved;
} catch { /* ignore */ }
function chosenBuild() {
if (chosenSetup() === 'detect') return 'demo';
const v = buildInputs.find((i) => i.checked)?.value;
return BUILD_MODES.includes(v) ? v : 'manual';
}
function updateBuildPicker() {
const detect = chosenSetup() === 'detect';
if (buildPicker) buildPicker.disabled = detect;
const note = document.getElementById('build-note');
if (note) note.hidden = !detect;
}
for (const inp of buildInputs) {
inp.addEventListener('change', () => {
try { localStorage.setItem(BUILD_KEY, chosenBuild()); } catch { /* ignore */ }
});
}
updateBuildPicker();
function setPageStatus(text) {
statusEl.textContent = text;
}
function showFeatures(list) {
featuresEl.innerHTML = '';
for (const [name, ok] of list) {
const li = document.createElement('li');
li.className = ok ? 'ok' : 'no';
li.textContent = name;
featuresEl.appendChild(li);
}
}
async function checkSupport() {
info('Page loaded', {
url: location.href,
secure: window.isSecureContext,
ua: navigator.userAgent,
});
if (!window.isSecureContext) {
startBtn.textContent = 'Needs HTTPS or localhost';
setPageStatus('WebXR only runs on https:// or http://localhost. Use GitHub Pages or adb reverse.');
error('Not a secure context: WebXR is blocked. Use https:// or http://localhost');
return;
}
if (!('xr' in navigator)) {
startBtn.textContent = 'WebXR not available';
setPageStatus('This browser has no WebXR. Open the page in the Magic Leap 2 browser.');
error('navigator.xr is missing');
return;
}
let ar = false, vr = false;
try { ar = await navigator.xr.isSessionSupported('immersive-ar'); } catch (err) { warn('isSessionSupported(ar) threw', errText(err)); }
try { vr = await navigator.xr.isSessionSupported('immersive-vr'); } catch { /* ignore */ }
info('WebXR support', {
'immersive-ar': ar,
'immersive-vr': vr,
XRWebGLBinding: typeof XRWebGLBinding !== 'undefined',
getCameraImage: typeof XRWebGLBinding !== 'undefined' && 'getCameraImage' in XRWebGLBinding.prototype,
XRRay: typeof XRRay !== 'undefined',
});
if (!ar) {
startBtn.textContent = 'AR not supported here';
setPageStatus('This device or browser cannot start an immersive AR session.');
return;
}
startBtn.disabled = false;
safeBtn.disabled = false;
rawBtn.disabled = false;
startBtn.textContent = 'Start AR';
setPageStatus('Ready. Stand so the table is in front of you.');
}
// ---------------------------------------------------------------------------
// three.js scene
// ---------------------------------------------------------------------------
// We create the WebGL2 context ourselves with xrCompatible: true (like the raw test).
// Otherwise three.js calls gl.makeXRCompatible() inside setSession, which on Android
// Chromium can lose/recreate the GL context in the middle of starting the session.
// ?xrcompat=0 goes back to three.js's own context for comparison.
const glCanvas = document.createElement('canvas');
const glAttributes = {
alpha: true,
antialias: params.get('aa') !== '0',
depth: true,
stencil: false,
premultipliedAlpha: true,
preserveDrawingBuffer: false,
powerPreference: 'default',
xrCompatible: params.get('xrcompat') !== '0',
};
const glContext = glCanvas.getContext('webgl2', glAttributes);
const renderer = new THREE.WebGLRenderer({ canvas: glCanvas, context: glContext, ...glAttributes });
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.xr.enabled = true;
document.body.appendChild(renderer.domElement);
const gl = renderer.getContext();
info('WebGL context', {
xrCompatible: gl.getContextAttributes()?.xrCompatible ?? 'not reported',
antialias: gl.getContextAttributes()?.antialias,
renderer: (() => {
const ext = gl.getExtension('WEBGL_debug_renderer_info');
return ext ? gl.getParameter(ext.UNMASKED_RENDERER_WEBGL) : gl.getParameter(gl.RENDERER);
})(),
});
renderer.domElement.addEventListener('webglcontextlost', (e) => {
e.preventDefault();
error('WebGL context lost (GPU reset or out of memory)');
});
renderer.domElement.addEventListener('webglcontextrestored', () => info('WebGL context restored'));
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 0.01, 50);
scene.add(camera); // so we can attach head-locked panels to it
scene.add(new THREE.HemisphereLight(0xffffff, 0x8899aa, 2.0));
const sun = new THREE.DirectionalLight(0xffffff, 1.5);
sun.position.set(0.5, 1, 0.3);
scene.add(sun);
// Everything on the table hangs off this group: origin = table centre on its surface,
// local +X = the table's long side.
// Note: Magic Leap 2 is an additive display, so dark colours look transparent.
const tableAnchor = new THREE.Group();
tableAnchor.visible = false;
scene.add(tableAnchor);
// ---------------------------------------------------------------------------
// Diorama: the scene on the table, loaded from assets/scenes/<name>.json with the models
// from assets/library.json (see diorama.js). Built in real metres; this group is scaled
// down to fit the table, so all models keep true proportions.
// Diorama axes: +X = the table's long side, +Z = across the table, +Y = up.
// ?scene=demo which scene file (assets/scenes/demo.json)
// ?asset=office-pv show just one library asset (handy with ?preview=1)
// ?scale=50 fixed 1:50 instead of "as big as fits"
// ?flows=0 hide the energy flows
// ?labels=0 hide the floating asset names (see asset-labels.js)
// ?labelsize=1.5 make the asset names bigger (default 1, 1.8 in ?preview=1)
// ---------------------------------------------------------------------------
const DIORAMA = {
fill: 0.85, // use at most 85% of the table
maxScale: 1 / 20, // never bigger than 1:20, even on a huge table
fixedScale: params.has('scale') ? 1 / parseFloat(params.get('scale')) : null,
scene: params.get('scene') || 'demo',
labels: params.get('labels') !== '0',
// On a laptop screen the panels need to be bigger than in the headset to be readable.
labelSize: params.has('labelsize') ? parseFloat(params.get('labelsize')) : params.get('preview') === '1' ? 1.8 : 1,
};
const diorama = new THREE.Group();
tableAnchor.add(diorama);
const dioramaState = { ground: { length: 15, width: 11 }, update: null, table: { length: 1.2, width: 0.8 } };
let assetLabels = null; // floating asset names, once asset-labels.js has loaded
(async function loadDiorama() {
const asset = params.get('asset');
try {
info('Loading diorama…', asset ? { asset } : { scene: DIORAMA.scene });
// Dynamic import: if the loader or a CDN file fails, the rest of the app keeps working.
const { buildDiorama } = await import('./diorama.js');
const d = await buildDiorama({
sceneSource: asset
? { ground: 'auto', items: [{ id: asset, asset }] }
: `assets/scenes/${encodeURIComponent(DIORAMA.scene)}.json`,
libraryUrl: asset ? 'assets/library.json' : undefined,
log: { info, warn },
});
d.flowsGroup.visible = params.get('flows') !== '0';
if (DIORAMA.labels) await addAssetLabels(d);
diorama.add(d.group);
dioramaState.ground = d.ground;
dioramaState.update = d.update;
dioramaScale = 0; // force a log line with the real scale
fitDiorama(dioramaState.table.length, dioramaState.table.width);
} catch (err) {
error('Diorama failed to load, showing a placeholder', errText(err));
const box = new THREE.Mesh(new THREE.BoxGeometry(0.1, 0.1, 0.1), new THREE.MeshStandardMaterial({ color: 0x33ccff }));
box.position.y = 0.05;
diorama.add(box);
dioramaState.ground = { length: 0.1 / DIORAMA.maxScale, width: 0.1 / DIORAMA.maxScale };
}
})();
// Scale the diorama to the table: true proportions, as big as fits.
let dioramaScale = 0;
function fitDiorama(tableLength, tableWidth) {
dioramaState.table = { length: tableLength, width: tableWidth };
const { length, width } = dioramaState.ground;
let s = DIORAMA.fixedScale ?? Math.min(
(DIORAMA.fill * tableLength) / length,
(DIORAMA.fill * tableWidth) / width,
DIORAMA.maxScale,
);
if (!(s > 0)) s = 1 / 100;
diorama.scale.setScalar(s);
if (Math.abs(s - dioramaScale) > 0.05 * s) {
info('Diorama scaled', {
scale: '1:' + Math.round(1 / s),
footprint: `${(length * s * 100).toFixed(0)} x ${(width * s * 100).toFixed(0)} cm`,
});
}
dioramaScale = s;
}
// Called every frame with the time since the last frame (seconds): animates the flows.
let lastDioramaTime = 0;
function animateDiorama(time) {
const dt = lastDioramaTime ? Math.min(0.1, (time - lastDioramaTime) / 1000) : 0;
lastDioramaTime = time;
if (dioramaState.update && tableAnchor.visible && diorama.visible) dioramaState.update(dt);
if (assetLabels) {
// The names belong to the diorama: hidden with it (manual and cards mode).
assetLabels.group.visible = diorama.visible;
if (tableAnchor.visible && diorama.visible) assetLabels.update(diorama, dt);
}
}
// Floating name panels above the assets (asset-labels.js). Loaded separately: if it fails,
// the diorama still shows, just without names.
async function addAssetLabels(d) {
try {
const { createAssetLabels } = await import('./asset-labels.js');
const labels = createAssetLabels({
items: d.items, flows: d.flows, root: d.group, size: DIORAMA.labelSize, log: { info, warn },
});
tableAnchor.add(labels.group);
assetLabels = labels;
info('Asset labels ready', { count: labels.labels.length });
} catch (err) {
warn('Asset labels failed, showing the diorama without them', errText(err));
}
}
// Energy-system components (assets/components.json) and their models, loaded at page
// load so problems show up in the log before entering AR.
// loaded = true once the models are in too (or loading failed): the manual palette waits for it.
const components = { config: null, templates: new Map(), colourTable: [], error: null, loaded: false };
components.ready = (async () => {
try {
const config = await loadComponents();
components.config = config;
components.colourTable = buildColourTable(config);
info('components.json loaded', {
cards: config.cards,
assets: Object.keys(config.assets),
colours: components.colourTable.colours.map((c) => c.name),
});
const unmapped = Object.entries(config.cards).filter(([, t]) => t === null).map(([c]) => c);
if (unmapped.length) info('Card colours without an asset (shown as placeholder cubes)', unmapped);
components.templates = await preloadModels(config, { info, warn });
} catch (err) {
components.error = errText(err);
error('Could not load the components', components.error);
} finally {
components.loaded = true;
}
})();
// Rounded-rectangle outline of the detected table.
const outline = new THREE.LineLoop(
new THREE.BufferGeometry(),
new THREE.LineBasicMaterial({ color: 0x7cffb2 })
);
tableAnchor.add(outline);
let outlineDims = { length: 0, width: 0, radius: 0 };
function roundedRectPoints(length, width, radius) {
const r = Math.max(0, Math.min(radius, length / 2, width / 2));
const hx = length / 2 - r;
const hz = width / 2 - r;
const pts = [];
const corners = [[hx, hz, 0], [-hx, hz, Math.PI / 2], [-hx, -hz, Math.PI], [hx, -hz, 1.5 * Math.PI]];
for (const [cx, cz, a0] of corners) {
for (let i = 0; i <= 8; i++) {
const a = a0 + (i / 8) * (Math.PI / 2);
pts.push(new THREE.Vector3(cx + r * Math.cos(a), 0.004, cz + r * Math.sin(a)));
}
}
return pts;
}
function updateOutline(length, width, radius) {
const d = outlineDims;
if (Math.abs(d.length - length) < 0.005 && Math.abs(d.width - width) < 0.005 && Math.abs(d.radius - radius) < 0.005) return;
outline.geometry.dispose();
outline.geometry = new THREE.BufferGeometry().setFromPoints(roundedRectPoints(length, width, radius));
outlineDims = { length, width, radius };
fitDiorama(length, width);
}
// Reticle for gaze (fallback) mode.
const reticle = new THREE.Mesh(
new THREE.RingGeometry(0.04, 0.055, 32).rotateX(-Math.PI / 2),
new THREE.MeshBasicMaterial({ color: 0xffd60a })
);
reticle.matrixAutoUpdate = false;
reticle.visible = false;
scene.add(reticle);
// ---------------------------------------------------------------------------
// Head-locked panels (the web page is not visible inside the headset)
// Positions are in metres, 1 m in front of your eyes.
// ---------------------------------------------------------------------------
function makeCanvasPanel(cw, ch, mw, mh, x, y, order) {
const canvas = document.createElement('canvas');
canvas.width = cw;
canvas.height = ch;
const ctx = canvas.getContext('2d');
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const mesh = new THREE.Mesh(
new THREE.PlaneGeometry(mw, mh),
new THREE.MeshBasicMaterial({ map: texture, transparent: true, depthTest: false, depthWrite: false })
);
mesh.renderOrder = order;
mesh.position.set(x, y, -1.0);
camera.add(mesh);
return { canvas, ctx, texture, mesh };
}
// Status line, centre bottom.
const statusPanel = makeCanvasPanel(1024, 200, 0.46, 0.09, -0.02, -0.15, 999);
let lastStatus = '';
function setHud(line1, line2 = '') {
const text = line1 + '\n' + line2;
if (text === lastStatus) return;
lastStatus = text;
const { ctx, canvas, texture } = statusPanel;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillStyle = 'rgba(255,255,255,0.95)';
ctx.font = '600 46px system-ui, sans-serif';
ctx.fillText(line1, canvas.width / 2, 62, canvas.width - 32); // long text is squeezed to fit
ctx.fillStyle = 'rgba(170,230,255,0.95)';
ctx.font = '400 32px system-ui, sans-serif';
ctx.fillText(line2, canvas.width / 2, 142, canvas.width - 32);
texture.needsUpdate = true;
}
// Log, bottom right of the view.
const logPanel = makeCanvasPanel(1024, 512, 0.38, 0.19, 0.2, -0.33, 1000);
let lastLogDraw = 0;
function drawHeadsetLog(time) {
if (!logState.dirty || time - lastLogDraw < 250) return; // max 4 redraws per second
logState.dirty = false;
lastLogDraw = time;
const { ctx, canvas, texture } = logPanel;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.strokeStyle = 'rgba(255,255,255,0.35)';
ctx.lineWidth = 3;
ctx.strokeRect(2, 2, canvas.width - 4, canvas.height - 4);
ctx.font = '600 28px ui-monospace, Menlo, Consolas, monospace';
ctx.textAlign = 'left';
ctx.textBaseline = 'top';
const lines = logLines.slice(-12);
lines.forEach((l, i) => {
ctx.fillStyle = l.level === 'error' ? '#ff8080' : l.level === 'warn' ? '#ffd860' : '#e6f4ff';
let s = `${l.t.slice(3, 8)} ${l.text}`;
if (s.length > 58) s = s.slice(0, 57) + '…';
ctx.fillText(s, 16, 14 + i * 40);
});
texture.needsUpdate = true;
}
// Debug view of the detector, upper left of the view.
// dimmed camera image, yellow = white pixels, cyan = chosen table blob, magenta = centre
function makeDebugPanel(w, h) {
const data = new Uint8Array(w * h * 4);
const texture = new THREE.DataTexture(data, w, h, THREE.RGBAFormat);
texture.colorSpace = THREE.SRGBColorSpace;
texture.magFilter = THREE.NearestFilter;
const mesh = new THREE.Mesh(
new THREE.PlaneGeometry(0.28, 0.21),
new THREE.MeshBasicMaterial({ map: texture, depthTest: false, depthWrite: false })
);
mesh.renderOrder = 998;
mesh.position.set(-0.22, 0.05, -1.0);
mesh.visible = CONFIG.debug;
camera.add(mesh);
return {
get visible() { return mesh.visible; },
set visible(v) { mesh.visible = v; },
// Card scan: dimmed camera image with
// - cyan line: where the calibrated table is according to the camera model. It must
// lie on the real table edges in the picture; if not, the camera image and the
// head pose don't line up and cards get placed in the wrong spot.
// - accepted cards in their card colour, rejected blobs in a darker shade.
// colours: [r, g, b] per colour label (label 1 = colours[0]).
updateCards(pixels, det, colours) {
const { labelMap, blobMap, inside } = det;
const n = w * h;
for (let i = 0, j = 0; i < n; i++, j += 4) {
const c = labelMap[i] ? colours[labelMap[i] - 1] : null;
const x = i % w;
const edge = inside[i] && (x === 0 || x === w - 1 || i < w || i >= n - w ||
!inside[i - 1] || !inside[i + 1] || !inside[i - w] || !inside[i + w]);
if (edge) {
data[j] = 0; data[j + 1] = 230; data[j + 2] = 255;
} else if (c && blobMap[i]) {
const k = blobMap[i] === 1 ? 1 : 0.4;
data[j] = c[0] * k; data[j + 1] = c[1] * k; data[j + 2] = c[2] * k;
} else {
const k = inside[i] ? 0.6 : 0.3;
data[j] = pixels[j] * k; data[j + 1] = pixels[j + 1] * k; data[j + 2] = pixels[j + 2] * k;
}
data[j + 3] = 255;
}
texture.needsUpdate = true;
},
// Colour calibration: camera image, magenta cross = where the user pointed (camera
// model), cyan cross = the card found there. Their distance = camera misalignment.
updateSample(pixels, at, sample) {
for (let j = 0; j < w * h * 4; j += 4) {
data[j] = pixels[j] * 0.7; data[j + 1] = pixels[j + 1] * 0.7; data[j + 2] = pixels[j + 2] * 0.7; data[j + 3] = 255;
}
const cross = (cx, cy, r, g, b) => {
const x0 = Math.round(cx), y0 = Math.round(cy);
for (let d = -6; d <= 6; d++) {
for (const [x, y] of [[x0 + d, y0], [x0, y0 + d]]) {
if (x < 0 || y < 0 || x >= w || y >= h) continue;
const j = (y * w + x) * 4;
data[j] = r; data[j + 1] = g; data[j + 2] = b;
}
}
};
cross(at.px, at.py, 255, 0, 200);
if (sample) cross(sample.px, sample.py, 0, 230, 255);
texture.needsUpdate = true;
},
// Colour squares: magenta = where each square should be (camera model), cyan = where
// its card was found (after the measured shift).
updateSlots(pixels, slots, r) {
this.updateSample(pixels, slots[0], null);
const cross = (cx, cy, c) => {
const x0 = Math.round(cx), y0 = Math.round(cy);
for (let d = -5; d <= 5; d++) {
for (const [x, y] of [[x0 + d, y0], [x0, y0 + d]]) {
if (x < 0 || y < 0 || x >= w || y >= h) continue;
const j = (y * w + x) * 4;
data[j] = c[0]; data[j + 1] = c[1]; data[j + 2] = c[2];
}
}
};
for (const s of slots) {
cross(s.px, s.py, [255, 0, 200]);
if (r) cross(s.px + r.shift.x, s.py + r.shift.y, [0, 230, 255]);
}
texture.needsUpdate = true;
},
toggle() {
mesh.visible = !mesh.visible;
info('Debug view ' + (mesh.visible ? 'on' : 'off'));
},
update(pixels, mask, labels, label, cx, cy) {
const n = w * h;
for (let i = 0, j = 0; i < n; i++, j += 4) {
if (label && labels[i] === label) {
data[j] = 0; data[j + 1] = 230; data[j + 2] = 255;
} else if (mask[i]) {
data[j] = 255; data[j + 1] = 214; data[j + 2] = 10;
} else {
data[j] = pixels[j] * 0.6; data[j + 1] = pixels[j + 1] * 0.6; data[j + 2] = pixels[j + 2] * 0.6;
}
data[j + 3] = 255;
}
if (label) {
const x0 = Math.round(cx), y0 = Math.round(cy);
for (let d = -4; d <= 4; d++) {
for (const [x, y] of [[x0 + d, y0], [x0, y0 + d]]) {
if (x < 0 || y < 0 || x >= w || y >= h) continue;
const j = (y * w + x) * 4;
data[j] = 255; data[j + 1] = 0; data[j + 2] = 200;
}
}
}
texture.needsUpdate = true;
},
};
}
const debugPanel = makeDebugPanel(CONFIG.analysisWidth, CONFIG.analysisHeight);
// Same place in view; only one of the two is shown (table detection vs card scans).
const cardDebugPanel = makeDebugPanel(CONFIG.scanWidth, CONFIG.scanHeight);
cardDebugPanel.visible = false;
// ---------------------------------------------------------------------------
// Camera image → small RGBA buffer (raw WebGL; three.js state is restored after)
// ---------------------------------------------------------------------------
class CameraReader {
constructor(glContext, width, height) {
this.gl = glContext;
this.width = width;
this.height = height;
this.pixels = new Uint8Array(width * height * 4);
const g = this.gl;
const vs = `#version 300 es
in vec2 aPos;
out vec2 vUv;
void main() { vUv = aPos * 0.5 + 0.5; gl_Position = vec4(aPos, 0.0, 1.0); }`;
// 4 taps per output pixel to reduce aliasing when shrinking the big camera image.
const fs = `#version 300 es
precision mediump float;
in vec2 vUv;
uniform sampler2D uTex;
uniform bool uFlipY;
uniform vec2 uStep;
out vec4 outColor;
void main() {
vec2 uv = uFlipY ? vec2(vUv.x, 1.0 - vUv.y) : vUv;
vec4 c = texture(uTex, uv + vec2(-uStep.x, -uStep.y))
+ texture(uTex, uv + vec2( uStep.x, -uStep.y))
+ texture(uTex, uv + vec2(-uStep.x, uStep.y))
+ texture(uTex, uv + vec2( uStep.x, uStep.y));
outColor = vec4(c.rgb * 0.25, 1.0);
}`;
this.program = this.#link(vs, fs);
this.uTex = g.getUniformLocation(this.program, 'uTex');
this.uFlipY = g.getUniformLocation(this.program, 'uFlipY');
this.uStep = g.getUniformLocation(this.program, 'uStep');
const aPos = g.getAttribLocation(this.program, 'aPos');
this.vao = g.createVertexArray();
g.bindVertexArray(this.vao);
const buffer = g.createBuffer();
g.bindBuffer(g.ARRAY_BUFFER, buffer);
g.bufferData(g.ARRAY_BUFFER, new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]), g.STATIC_DRAW);
g.enableVertexAttribArray(aPos);
g.vertexAttribPointer(aPos, 2, g.FLOAT, false, 0, 0);
g.bindVertexArray(null);
this.target = g.createTexture();
g.bindTexture(g.TEXTURE_2D, this.target);
g.texImage2D(g.TEXTURE_2D, 0, g.RGBA8, width, height, 0, g.RGBA, g.UNSIGNED_BYTE, null);
g.texParameteri(g.TEXTURE_2D, g.TEXTURE_MIN_FILTER, g.LINEAR);
g.texParameteri(g.TEXTURE_2D, g.TEXTURE_MAG_FILTER, g.LINEAR);
g.bindTexture(g.TEXTURE_2D, null);
this.fbo = g.createFramebuffer();
g.bindFramebuffer(g.FRAMEBUFFER, this.fbo);
g.framebufferTexture2D(g.FRAMEBUFFER, g.COLOR_ATTACHMENT0, g.TEXTURE_2D, this.target, 0);
const status = g.checkFramebufferStatus(g.FRAMEBUFFER);
g.bindFramebuffer(g.FRAMEBUFFER, null);
if (status !== g.FRAMEBUFFER_COMPLETE) throw new Error('Camera framebuffer incomplete: 0x' + status.toString(16));
}
#link(vsSource, fsSource) {
const g = this.gl;
const compile = (type, src) => {
const s = g.createShader(type);
g.shaderSource(s, src);
g.compileShader(s);
if (!g.getShaderParameter(s, g.COMPILE_STATUS)) throw new Error('Shader: ' + g.getShaderInfoLog(s));
return s;
};
const p = g.createProgram();
g.attachShader(p, compile(g.VERTEX_SHADER, vsSource));
g.attachShader(p, compile(g.FRAGMENT_SHADER, fsSource));
g.linkProgram(p);
if (!g.getProgramParameter(p, g.LINK_STATUS)) throw new Error('Program: ' + g.getProgramInfoLog(p));
return p;
}
// cameraTexture: from XRWebGLBinding.getCameraImage(). Only valid during this XR frame.
read(cameraTexture) {
const g = this.gl;
g.bindFramebuffer(g.FRAMEBUFFER, this.fbo);
g.viewport(0, 0, this.width, this.height);
g.disable(g.DEPTH_TEST);
g.disable(g.BLEND);
g.disable(g.CULL_FACE);
g.disable(g.SCISSOR_TEST);
g.colorMask(true, true, true, true);
g.useProgram(this.program);
g.activeTexture(g.TEXTURE0);
g.bindTexture(g.TEXTURE_2D, cameraTexture);
g.uniform1i(this.uTex, 0);
g.uniform1i(this.uFlipY, CONFIG.flipCameraY ? 1 : 0);
g.uniform2f(this.uStep, 0.25 / this.width, 0.25 / this.height);
g.bindVertexArray(this.vao);
g.drawArrays(g.TRIANGLE_STRIP, 0, 4);
g.readPixels(0, 0, this.width, this.height, g.RGBA, g.UNSIGNED_BYTE, this.pixels);
g.bindVertexArray(null);
g.bindTexture(g.TEXTURE_2D, null);
g.bindFramebuffer(g.FRAMEBUFFER, null);
return this.pixels; // row 0 = bottom of the image
}
}
// ---------------------------------------------------------------------------
// Detection (pure functions, no three.js)
// ---------------------------------------------------------------------------
const W = CONFIG.analysisWidth;
const H = CONFIG.analysisHeight;
const scratch = {
luma: new Uint8Array(W * H),
raw: new Uint8Array(W * H),
tmp: new Uint8Array(W * H),
mask: new Uint8Array(W * H),
outside: new Uint8Array(W * H),
labels: new Int32Array(W * H),
stack: new Int32Array(W * H),
hist: new Uint32Array(256),
ptX: new Float32Array(W * H),
ptZ: new Float32Array(W * H),
ptW: new Float32Array(W * H),
bins: new Float64Array(512),
};
// Weighted 'lo' and 'hi' quantiles of values[0..n) (histogram, no sorting).
function weightedRange(values, weights, n, lo, hi) {
let min = Infinity, max = -Infinity, total = 0;
for (let i = 0; i < n; i++) {
if (values[i] < min) min = values[i];
if (values[i] > max) max = values[i];
total += weights[i];
}
const bins = scratch.bins;
const nb = bins.length;
bins.fill(0);
const span = max - min || 1e-6;
for (let i = 0; i < n; i++) {
bins[Math.min(nb - 1, Math.floor(((values[i] - min) / span) * nb))] += weights[i];
}
let acc = 0, a = min, b = max, gotA = false;
for (let k = 0; k < nb; k++) {
acc += bins[k];
if (!gotA && acc >= lo * total) { a = min + (k / nb) * span; gotA = true; }
if (acc >= hi * total) { b = min + ((k + 1) / nb) * span; break; }
}
return [a, b];
}
// Holes = background regions that do not touch the image border (a laptop or cup on the table).
function fillHoles(mask, w, h) {
const { outside, stack } = scratch;
outside.fill(0);
let sp = 0;
const push = (i) => { if (!mask[i] && !outside[i]) { outside[i] = 1; stack[sp++] = i; } };
for (let x = 0; x < w; x++) { push(x); push((h - 1) * w + x); }
for (let y = 0; y < h; y++) { push(y * w); push(y * w + w - 1); }
while (sp > 0) {
const i = stack[--sp];
const x = i % w;
const y = (i - x) / w;
if (x > 0) push(i - 1);
if (x < w - 1) push(i + 1);
if (y > 0) push(i - w);
if (y < h - 1) push(i + w);
}
for (let i = 0; i < w * h; i++) if (!mask[i] && !outside[i]) mask[i] = 1;
}
// Otsu split of the histogram between brightness 'from' and 255.
function otsuSplit(hist, from) {
let total = 0, sumAll = 0;
for (let v = from; v < 256; v++) { total += hist[v]; sumAll += v * hist[v]; }
if (total === 0) return null;
let wB = 0, sumB = 0, best = -1, res = null;
for (let v = from; v < 256; v++) {
wB += hist[v];
if (wB === 0) continue;
const wF = total - wB;
if (wF === 0) break;
sumB += v * hist[v];
const mB = sumB / wB;
const mF = (sumAll - sumB) / wF;
const between = wB * wF * (mB - mF) * (mB - mF);
if (between > best) { best = between; res = { thr: v + 1, meanLow: mB, meanHigh: mF, countHigh: wF }; }
}
return res;
}
// Split dark from bright, then keep splitting the bright group while it still contains
// two clearly different brightness levels (light-grey surroundings vs the white table).
function otsuThreshold(hist, total) {
const first = otsuSplit(hist, 0);
if (!first) return 128;