File size: 31,816 Bytes
0aefd10
72949a1
0aefd10
 
 
 
 
52a987b
0aefd10
1e45c26
 
b808764
1e45c26
237ff06
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e45c26
0aefd10
b808764
 
 
 
 
1950dae
b808764
 
 
 
 
 
 
1950dae
 
 
 
 
b808764
 
 
 
 
 
 
 
 
52a987b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0aefd10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1950dae
1e45c26
 
0aefd10
 
 
237ff06
 
 
 
0aefd10
b808764
52a987b
 
1950dae
 
b808764
1950dae
52a987b
 
 
 
 
 
 
 
 
 
 
 
1e45c26
 
 
 
 
 
 
 
 
237ff06
1e45c26
 
0aefd10
 
 
1e45c26
 
 
 
0aefd10
 
 
 
 
 
ddf99ea
7d2497a
0aefd10
 
1e45c26
237ff06
0aefd10
1e45c26
 
 
0aefd10
1e45c26
 
 
 
 
 
 
 
 
 
237ff06
 
1e45c26
0aefd10
237ff06
 
1e45c26
 
b808764
 
 
 
1e45c26
 
 
 
 
0aefd10
 
 
 
 
 
 
 
 
 
 
ddf99ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72949a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5c939d
96ebbc7
 
72949a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0aefd10
72949a1
 
0aefd10
 
 
 
 
 
 
 
 
 
7d2497a
0aefd10
 
 
9f23d2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0aefd10
f5c939d
 
 
 
 
 
 
96ebbc7
0aefd10
 
 
 
7d2497a
f5c939d
 
 
 
96ebbc7
7d2497a
 
 
 
 
 
 
 
 
 
 
 
 
 
96ebbc7
f5c939d
96ebbc7
 
 
 
 
 
 
 
f5c939d
96ebbc7
 
f5c939d
 
 
 
 
 
 
96ebbc7
f5c939d
96ebbc7
 
 
 
 
 
 
 
 
 
 
 
 
0aefd10
 
2d77bd6
9f23d2d
2d77bd6
0aefd10
 
9f23d2d
0aefd10
 
 
 
2d77bd6
 
0aefd10
7cba63f
72949a1
0aefd10
 
 
 
 
 
 
 
 
2d77bd6
52a987b
9f23d2d
0aefd10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72949a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0aefd10
 
96ebbc7
 
7d2497a
 
0aefd10
 
 
2d77bd6
 
1e45c26
237ff06
ddf99ea
2d77bd6
 
 
 
 
 
 
 
 
 
 
 
 
0aefd10
 
 
72949a1
96ebbc7
f5c939d
0aefd10
 
72949a1
 
0aefd10
 
 
 
 
 
 
 
72949a1
0aefd10
 
 
72949a1
 
 
 
7d2497a
0aefd10
 
7d2497a
72949a1
0aefd10
72949a1
0aefd10
72949a1
 
 
 
 
 
 
 
0aefd10
 
7d2497a
0aefd10
7d2497a
 
 
72949a1
0aefd10
 
 
 
7d2497a
 
0aefd10
72949a1
 
0aefd10
72949a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0aefd10
 
 
 
 
7d2497a
0aefd10
237ff06
0aefd10
72949a1
0aefd10
 
 
 
 
 
9f23d2d
0aefd10
 
96ebbc7
 
0aefd10
 
ddf99ea
 
 
0aefd10
 
 
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
// Interactive 3D preview: loads previews/<asset>.glb and its rig (previews/<asset>.json),
// then lets the viewer orbit, drag parts or their joint dots, and move each joint with a slider.
// One renderer is reused for every asset; app.js moves its element into the detail panel.
import * as THREE from "three";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js";
import { DRACOLoader } from "three/addons/loaders/DRACOLoader.js";
import { RGBELoader } from "three/addons/loaders/RGBELoader.js";

// Neutral grey studio (both themes): dark-to-light grey sky, grey floor with a faint grid
// fading into the horizon, one shadow-casting key light plus soft fill.
const STUDIO = { top: "#2b2d31", horizon: "#74777c", floor: 0x4f5257, grid: 0x3f4247 };

// The sky is a dome around the camera whose gradient follows the real horizon (not the
// screen), and the floor and grid fade out with distance into the same horizon colour, so
// the floor melts into the sky with no edge. Colours are sRGB, drawn as they are.
const SKY = { top: [0x2b, 0x2d, 0x31], mid: [0x4b, 0x4e, 0x53], horizon: [0x7c, 0x7f, 0x84] };
function skyDome() {
  const v = (c) => new THREE.Vector3(c[0] / 255, c[1] / 255, c[2] / 255);
  const mat = new THREE.ShaderMaterial({
    uniforms: { top: { value: v(SKY.top) }, mid: { value: v(SKY.mid) }, horizon: { value: v(SKY.horizon) } },
    vertexShader: `varying vec3 vDir;
      void main() {
        vDir = (modelMatrix * vec4(position, 1.0)).xyz - cameraPosition;
        gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
      }`,
    fragmentShader: `uniform vec3 top, mid, horizon; varying vec3 vDir;
      void main() {
        float h = normalize(vDir).y;
        vec3 c = mix(horizon, mid, smoothstep(0.0, 0.22, h));
        c = mix(c, top, smoothstep(0.22, 0.75, h));
        gl_FragColor = vec4(c, 1.0);
      }`,
    side: THREE.BackSide, depthWrite: false, depthTest: false, toneMapped: false, fog: false,
  });
  const dome = new THREE.Mesh(new THREE.SphereGeometry(1, 48, 24), mat);
  dome.renderOrder = -1;
  dome.frustumCulled = false;
  return dome;
}
// Fade a floor-level material out between fade.x and fade.y metres from fade centre (xz).
function fadeWithDistance(material, fade) {
  material.transparent = true;
  material.onBeforeCompile = (sh) => {
    sh.uniforms.fadeCenter = fade.center;
    sh.uniforms.fadeRange = fade.range;
    sh.vertexShader = sh.vertexShader
      .replace("#include <common>", "#include <common>\nvarying vec3 vFadePos;")
      .replace("#include <project_vertex>", "#include <project_vertex>\nvFadePos = (modelMatrix * vec4(transformed, 1.0)).xyz;");
    sh.fragmentShader = sh.fragmentShader
      .replace("#include <common>", "#include <common>\nvarying vec3 vFadePos;\nuniform vec3 fadeCenter;\nuniform vec2 fadeRange;")
      .replace("#include <dithering_fragment>",
        "#include <dithering_fragment>\ngl_FragColor.a *= 1.0 - smoothstep(fadeRange.x, fadeRange.y, distance(vFadePos.xz, fadeCenter.xz));");
  };
}

// Reflections: an even grey room with soft light panels on every side, so metal and
// glossy parts stay lit from any viewing angle (the stock room light is one-sided).
function studioEnvironment(pmrem) {
  const env = new THREE.Scene();
  env.add(new THREE.Mesh(new THREE.BoxGeometry(10, 10, 10),
    new THREE.MeshBasicMaterial({ color: 0x75787d, side: THREE.BackSide })));
  const panel = (w, h, pos, power) => {
    const m = new THREE.Mesh(new THREE.PlaneGeometry(w, h),
      new THREE.MeshBasicMaterial({ color: new THREE.Color(1, 1, 1).multiplyScalar(power), side: THREE.DoubleSide }));
    m.position.set(...pos);
    m.lookAt(0, 0, 0);
    env.add(m);
  };
  panel(7, 7, [0, 4.8, 0], 1.8);      // overhead softbox
  panel(5, 5, [-4.8, 1.5, 1], 1.5);   // left (key side)
  panel(5, 5, [4.8, 1.5, -1], 1.1);   // right
  panel(6, 4, [0, 1.5, 4.8], 0.95);    // front
  panel(6, 4, [0, 1.5, -4.8], 0.95);   // back
  const ground = new THREE.Mesh(new THREE.PlaneGeometry(10, 10), new THREE.MeshBasicMaterial({ color: 0x55585d }));
  ground.rotation.x = -Math.PI / 2;
  ground.position.y = -4.9;
  env.add(ground);
  const tex = pmrem.fromScene(env, 0.035).texture;
  env.traverse((o) => { if (o.isMesh) { o.geometry.dispose(); o.material.dispose(); } });
  return tex;
}

// Lighting comes from an HDRI (Poly Haven's small_hangar_02, CC0, 1K): it lights the model and
// shows in its reflections, but the background stays the grey studio gradient. Until it loads
// (or if it fails) the studio environment above and the fill lights are used instead.
const HDRI = "env/small_hangar_02_1k.hdr";
const HDRI_LIGHTS = { exposure: 1.05, key: 0.9, hemi: 0, fill: 0, rim: 0, floor: 0x7b8898 };

function spaceUrl(path) {
  const url = new URL(path, import.meta.url);
  const sign = new URLSearchParams(location.search).get("__sign");   // private Space token
  if (sign) url.searchParams.set("__sign", sign);
  return url.href;
}

// See-through parts. The previews carry glass and liquids as 40%-opaque surfaces, which look
// milky and are drawn back to front by their centre: a bottle and the liquid inside it (nearly
// the same centre) swap order as the camera moves, and whenever the bottle draws first its
// depth hides the liquid (same bug as kaedim_app's Simple3DViewer #1107). So:
//  - each transparent mesh that sits inside another one (liquid, dip tube) gets a fixed slot,
//    contents before the shell around them;
//  - on assets, the outer shells become clear glass (transmission: see-through with reflections,
//    tinted by their colour) that doesn't hide what's inside. Scenes keep plain transparency,
//    which is cheaper to draw.
function prepareTransparent(root, { glass = true } = {}) {
  const items = [];
  root.updateMatrixWorld(true);
  root.traverse((o) => {
    if (!o.isMesh) return;
    const mats = Array.isArray(o.material) ? o.material : [o.material];
    if (!mats.some((m) => m && m.transparent)) return;
    const box = new THREE.Box3().setFromObject(o);
    const d = box.getSize(new THREE.Vector3());
    items.push({ o, box, vol: d.x * d.y * d.z, tol: d.length() * 0.02 });
  });
  const inside = (a, b) => a.vol < b.vol
    && a.box.min.x >= b.box.min.x - b.tol && a.box.min.y >= b.box.min.y - b.tol && a.box.min.z >= b.box.min.z - b.tol
    && a.box.max.x <= b.box.max.x + b.tol && a.box.max.y <= b.box.max.y + b.tol && a.box.max.z <= b.box.max.z + b.tol;
  for (const a of items) a.depth = items.filter((b) => b !== a && inside(a, b)).length;
  const deepest = Math.max(0, ...items.map((a) => a.depth));
  for (const a of items) {
    a.o.renderOrder = 1 + deepest - a.depth;   // innermost draws first
    if (glass && a.depth > 0) {
      // contents draw over the glass, so tint them by the glass they're seen through
      // (white syrup in an amber bottle looks amber); clear glass leaves them as they are
      const shell = items.filter((b) => b.depth === 0 && inside(a, b)).sort((x, y) => x.vol - y.vol)[0];
      const sm = shell && (Array.isArray(shell.o.material) ? shell.o.material[0] : shell.o.material);
      const tint = sm && sm.color ? sm.color.clone() : null;
      if (tint && Math.min(tint.r, tint.g, tint.b) < 0.8 * Math.max(tint.r, tint.g, tint.b)) {
        tint.multiplyScalar(1 / Math.max(tint.r, tint.g, tint.b, 1e-3));
        const tinted = (m) => { if (!m || !m.color) return m; const c = m.clone(); c.color.multiply(tint); return c; };
        a.o.material = Array.isArray(a.o.material) ? a.o.material.map(tinted) : tinted(a.o.material);
      }
    }
    if (glass && a.depth === 0) {
      const toGlass = (m) => !m || !m.transparent ? m : new THREE.MeshPhysicalMaterial({
        name: m.name, color: m.color, map: m.map, normalMap: m.normalMap, roughness: m.roughness,
        roughnessMap: m.roughnessMap, metalness: 0, transmission: 1, thickness: 0, ior: 1.5,
        side: m.side, depthWrite: false,
      });
      a.o.material = Array.isArray(a.o.material) ? a.o.material.map(toGlass) : toGlass(a.o.material);
    }
  }
}

export function createViewer() {
  const root = document.createElement("div");
  root.className = "viewer3d";
  const stage = document.createElement("div");
  stage.className = "viewer3d-stage";
  const status = document.createElement("div");
  status.className = "viewer3d-status";
  status.setAttribute("role", "status");
  stage.append(status);
  root.append(stage);

  const renderer = new THREE.WebGLRenderer({ antialias: true });
  renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
  renderer.outputColorSpace = THREE.SRGBColorSpace;
  renderer.toneMapping = THREE.ACESFilmicToneMapping;
  renderer.toneMappingExposure = 0.85;
  renderer.shadowMap.enabled = true;
  renderer.shadowMap.type = THREE.PCFSoftShadowMap;
  stage.prepend(renderer.domElement);

  const scene = new THREE.Scene();
  scene.background = new THREE.Color().setRGB(...SKY.horizon.map((c) => c / 255), THREE.SRGBColorSpace);
  const sky = skyDome();
  scene.add(sky);
  const fade = { center: { value: new THREE.Vector3() }, range: { value: new THREE.Vector2(10, 50) } };
  const pmrem = new THREE.PMREMGenerator(renderer);
  scene.environment = studioEnvironment(pmrem);
  const hemi = new THREE.HemisphereLight(0xffffff, 0x6a6d72, 0.5);
  scene.add(hemi);
  const fill = new THREE.DirectionalLight(0xffffff, 0.45);  // opposite the key, no shadow
  const rim = new THREE.DirectionalLight(0xffffff, 0.4);    // from behind, lights the back
  scene.add(fill, fill.target, rim, rim.target);
  const key = new THREE.DirectionalLight(0xffffff, 1.25);
  new RGBELoader().loadAsync(spaceUrl(HDRI)).then((hdr) => {
    hdr.mapping = THREE.EquirectangularReflectionMapping;
    const old = scene.environment;
    scene.environment = pmrem.fromEquirectangular(hdr).texture;
    hdr.dispose();
    if (old) old.dispose();
    // the HDRI lights every side, so the extra fill lights go; the key stays for the shadow
    hemi.intensity = HDRI_LIGHTS.hemi; fill.intensity = HDRI_LIGHTS.fill; rim.intensity = HDRI_LIGHTS.rim;
    key.intensity = HDRI_LIGHTS.key;
    renderer.toneMappingExposure = HDRI_LIGHTS.exposure;
    floor.material.color.set(HDRI_LIGHTS.floor);   // bluer than the studio floor: cancels the HDRI's warm light so the floor stays neutral grey
  }).catch((e) => console.warn("HDRI lighting didn't load; using the studio lights", e));
  key.castShadow = true;
  key.shadow.mapSize.set(2048, 2048);
  key.shadow.radius = 5;
  key.shadow.bias = -0.0004;
  scene.add(key, key.target);
  const floor = new THREE.Mesh(new THREE.PlaneGeometry(1, 1),
    new THREE.MeshStandardMaterial({ color: STUDIO.floor, roughness: 1, metalness: 0 }));
  floor.rotation.x = -Math.PI / 2;
  floor.receiveShadow = true;
  fadeWithDistance(floor.material, fade);
  floor.visible = false;
  scene.add(floor);
  const camera = new THREE.PerspectiveCamera(35, 1, 0.01, 100);
  const controls = new OrbitControls(camera, renderer.domElement);
  controls.enableDamping = true;
  controls.dampingFactor = 0.15;
  controls.zoomSpeed = 3;          // ~14% per wheel step (three's default is 5%)
  controls.zoomToCursor = true;
  controls.screenSpacePanning = true;

  const loader = new GLTFLoader();
  const draco = new DRACOLoader();
  draco.setDecoderPath("https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/libs/draco/");
  loader.setDRACOLoader(draco);

  let model = null, grid = null, rig = [], grabMeshes = [], drag = null, gen = 0, theme = "dark", sizeM = 1, interior = false;
  let groundY = null, settleDirty = false;   // see settle()
  let onJoint = () => {};

  function setTheme(t) { theme = t === "light" ? "light" : "dark"; }  // the studio is the same grey in both
  // Floor, grid, their fade into the horizon and the key light's shadow box, sized to the current model.
  function placeGrid() {
    if (grid) { scene.remove(grid); grid.geometry.dispose(); grid.material.dispose(); grid = null; }
    floor.visible = !!model;
    if (!model) return;
    const box = new THREE.Box3().setFromObject(model);
    const c = box.getCenter(new THREE.Vector3());
    const s = Math.max(sizeM, 0.05);
    const y = box.min.y - s * 0.002;
    floor.scale.set(s * 80, s * 80, 1);
    floor.position.set(c.x, y, c.z);
    const cell = Math.pow(10, Math.floor(Math.log10(s / 4)));   // 1 cm / 10 cm / 1 m cells
    const span = cell * 400;
    grid = new THREE.GridHelper(span, 400, STUDIO.grid, STUDIO.grid);
    grid.material.transparent = true;
    grid.material.opacity = 0.45;
    fadeWithDistance(grid.material, fade);
    grid.renderOrder = 1;
    grid.position.set(c.x, y + s * 0.0005, c.z);
    scene.add(grid);
    fade.center.value.set(c.x, y, c.z);
    fade.range.value.set(s * 1.5, s * 7);   // the floor and grid melt into the horizon colour
    key.position.set(c.x - s * 1.3, c.y + s * 1.9, c.z + s * 0.6);  // from the left, so the shadow falls to the right
    key.target.position.copy(c);
    fill.position.set(c.x + s * 1.5, c.y + s * 0.8, c.z + s * 0.4);
    rim.position.set(c.x + s * 0.3, c.y + s * 1.2, c.z - s * 1.6);
    fill.target.position.copy(c);
    rim.target.position.copy(c);
    const sc = key.shadow.camera;
    sc.left = sc.bottom = -s * 1.5; sc.right = sc.top = s * 1.5;
    sc.near = s * 0.1; sc.far = s * 6;
    sc.updateProjectionMatrix();
    key.shadow.normalBias = s * 0.002;
  }

  function resize() {
    const w = stage.clientWidth, h = stage.clientHeight;
    if (!w || !h) return;
    renderer.setSize(w, h, false);
    camera.aspect = w / h;
    camera.updateProjectionMatrix();
  }
  new ResizeObserver(resize).observe(stage);

  // Back the camera up along its current direction until the whole model fits the frame
  // (used when the view is expanded). Rooms are viewed from inside, so they're left alone.
  function fit(margin = 1.08) {
    if (!model || interior) return;
    resize();
    const sphere = new THREE.Box3().setFromObject(model).getBoundingSphere(new THREE.Sphere());
    const vfov = THREE.MathUtils.degToRad(camera.fov);
    const hfov = 2 * Math.atan(Math.tan(vfov / 2) * camera.aspect);
    const dist = (sphere.radius * margin) / Math.sin(Math.min(vfov, hfov) / 2);
    const dir = camera.position.clone().sub(controls.target).normalize();
    controls.target.copy(sphere.center);
    camera.position.copy(sphere.center).addScaledVector(dir, dist);
    controls.update();
  }
  const getView = () => ({ position: camera.position.clone(), target: controls.target.clone() });
  function setView(v) {
    if (!v) return;
    camera.position.copy(v.position);
    controls.target.copy(v.target);
    controls.update();
  }

  // Joint dots (HTML overlay, like NVIDIA's viewer): one per moving part, at its joint.
  // Hover a dot or a part to highlight the part and see its state; drag either to move it.
  const overlay = document.createElement("div");
  overlay.className = "viewer3d-overlay";
  const tip = document.createElement("div");
  tip.className = "viewer3d-tip";
  tip.hidden = true;
  const toggle = document.createElement("button");
  toggle.type = "button";
  toggle.className = "viewer3d-toggle";
  toggle.setAttribute("aria-pressed", "true");
  toggle.setAttribute("aria-label", "Show joint markers");
  toggle.title = "Show joint markers";
  let showDots = true;
  toggle.addEventListener("click", () => {
    showDots = !showDots;
    toggle.setAttribute("aria-pressed", String(showDots));
    overlay.hidden = !showDots;
    if (!showDots) setHot(null);
  });
  stage.append(overlay, tip, toggle);

  const HIGHLIGHT = new THREE.Color(0xf29b38);
  let hot = null;
  function highlight(r, on) {
    for (const g of r.linked || [r]) for (const x of [g, ...(g.drives || [])]) highlightOne(x, on);
  }
  function highlightOne(r, on) {
    for (const mesh of r.meshes) for (const m of [].concat(mesh.material)) {
      if (!m.emissive) continue;
      if (on) {
        if (!m.userData.e0) { m.userData.e0 = m.emissive.clone(); m.userData.ei0 = m.emissiveIntensity; }
        m.emissive.copy(HIGHLIGHT); m.emissiveIntensity = 0.45;
      } else if (m.userData.e0) {
        m.emissive.copy(m.userData.e0); m.emissiveIntensity = m.userData.ei0;
      }
    }
    if (r.dot) r.dot.classList.toggle("active", on);
  }
  function setHot(r) {
    if (hot === r) return;
    if (hot) highlight(hot, false);
    hot = r;
    if (hot) highlight(hot, true);
    tip.hidden = !hot;
  }
  function rest(r) { return Math.min(r.hi, Math.max(r.lo, 0)); }
  function label(r) {
    const len = (m) => Math.abs(m) >= 0.01 ? `${(Math.abs(m) * 100).toFixed(1)} cm` : `${(Math.abs(m) * 1000).toFixed(1)} mm`;
    if (r.free) return r.type === "hinge" ? `Rotating part · ${Math.round(r.val)}°` : `Sliding part · ${len(r.val)}`;
    const r0 = rest(r), span = Math.max(Math.abs(r.hi - r0), Math.abs(r.lo - r0)) || 1;
    const pct = Math.round((Math.abs(r.val - r0) / span) * 100);
    return r.type === "hinge" ? `Hinged part · ${Math.round(r.val)}° · ${pct}% open` : `Sliding part · ${pct}% open`;
  }

  function clear() {
    setHot(null);
    overlay.replaceChildren();
    if (model) {
      scene.remove(model);
      model.traverse((o) => {
        if (o.geometry) o.geometry.dispose();
        for (const m of [].concat(o.material || [])) {
          for (const k in m) if (m[k] && m[k].isTexture) m[k].dispose();
          m.dispose();
        }
      });
    }
    model = null; rig = []; grabMeshes = []; drag = null; groundY = null;
    placeGrid();
  }

  // A material choice from the asset's "Material" variant set: { name, color (linear RGB),
  // metallic, roughness }. Only materials called `name` (the variant's Material prim) change,
  // or every material if none has that name. null leaves the GLB's own materials.
  let look = null;
  function applyLook() {
    if (!model || !look) return;
    const mats = [];
    model.traverse((o) => { if (o.isMesh) mats.push(...[].concat(o.material)); });
    const named = mats.filter((m) => m.name === look.name);
    for (const m of named.length ? named : mats) {
      if (look.color && m.color) m.color.setRGB(...look.color);   // linear, like the GLB's baseColorFactor
      if (look.metallic != null && "metalness" in m) m.metalness = look.metallic;
      if (look.roughness != null && "roughness" in m) m.roughness = look.roughness;
    }
  }
  function setLook(l) { look = l || null; applyLook(); }

  const clean = (s) => String(s || "").replace(/[\s.:/[\]]/g, "");
  // Linked joints follow a reference joint: follower = -(gearing * reference + offset), as
  // Isaac Sim applies it. Two kinds:
  // - two-way (PhysX mimic joints, e.g. a scissor or accordion linkage): moving any of them
  //   moves the reference, which places every joint linked to it;
  // - one-way (oneWay, the package's OmniGraph coupling, e.g. a pedal bin's lid): the
  //   reference drives the follower within the follower's limits, and the follower can
  //   still be moved on its own, as its compliant drive allows in Isaac.
  function place(r, v, depth = 0) {
    r.val = v;
    if (r.type === "hinge") r.group.quaternion.setFromAxisAngle(r.axis, THREE.MathUtils.degToRad(v));
    else r.group.position.copy(r.base).addScaledVector(r.axis, v);
    onJoint(r.index, v);
    settleDirty = true;
    if (depth < 8) for (const f of r.followers || []) {
      const x = -(f.mimic.gearing * v + f.mimic.offset);
      place(f, f.mimic.oneWay && !f.free ? Math.min(f.hi, Math.max(f.lo, x)) : x, depth + 1);
    }
  }
  // Objects stand on the floor the way a free-standing one would: when a moving part swings
  // below the base the object lifts, and when a low part folds up it settles back down, so
  // nothing passes through the floor. groundY is the lowest point in the rest pose.
  function lowest() {
    model.position.y = 0;
    model.updateMatrixWorld(true);
    return new THREE.Box3().setFromObject(model, true).min.y;
  }
  function settle() {
    settleDirty = false;
    if (!model || interior || groundY === null) return;
    model.position.y = groundY - lowest();
    model.updateMatrixWorld(true);
  }
  function setJoint(r, v) {
    for (let n = 0; r.mimic && !r.mimic.oneWay && n < 8; n++) { v = -(v + r.mimic.offset) / r.mimic.gearing; r = r.mimic.ref; }
    place(r, Math.min(r.hi, Math.max(r.lo, v)));
  }
  const leaders = () => rig.filter((r) => !r.mimic);
  function linkJoints(joints) {
    const byName = Object.fromEntries(rig.map((r) => [r.name, r]));
    for (const j of joints) {
      const r = byName[j.name], ref = j.mimic && byName[j.mimic.ref];
      if (!r || !ref || ref === r || !j.mimic.gearing) continue;
      r.mimic = { ref, gearing: j.mimic.gearing, offset: j.mimic.offset || 0, oneWay: !!j.mimic.one_way };
      (ref.followers = ref.followers || []).push(r);
    }
    // a driver lights up the parts it drives one-way (and the parts those drive)
    const drives = (r, out, n = 0) => {
      for (const f of r.followers || []) if (f.mimic.oneWay && n < 8 && !out.includes(f)) { out.push(f); drives(f, out, n + 1); }
      return out;
    };
    for (const r of rig) r.drives = drives(r, []);
    const top = (r, n = 0) => (r.mimic && !r.mimic.oneWay && n < 8 ? top(r.mimic.ref, n + 1) : r);
    for (const r of rig) {
      if (!r.mimic || r.mimic.oneWay) continue;
      const t = top(r);
      t.linked = t.linked || [t];
      t.linked.push(r);
      r.linked = t.linked;
      // the reference can only go as far as its followers' limits allow
      if (r.free) continue;
      const { ref, gearing: g, offset: o } = r.mimic;
      const ends = [r.lo, r.hi].map((x) => -(x + o) / g);
      ref.lo = Math.max(ref.free ? -Infinity : ref.lo, Math.min(...ends));
      ref.hi = Math.min(ref.free ? Infinity : ref.hi, Math.max(...ends));
      ref.free = false;
      if (ref.lo > ref.hi) ref.lo = ref.hi = (ref.lo + ref.hi) / 2;   // contradictory limits: hold still rather than tear apart
    }
  }

  // opts.interior: a room. Start inside at eye height, no shadows; opts.enclosed keeps the camera inside the walls.
  // opts.look: the material choice to show (see setLook).
  async function load(glbUrl, rigUrl, opts = {}) {
    const mine = ++gen;
    clear();
    look = opts.look || null;
    status.textContent = "Loading 3D preview…";
    status.hidden = false;
    let gltf, data;
    try {
      [gltf, data] = await Promise.all([loader.loadAsync(glbUrl),
        rigUrl ? fetch(rigUrl).then((r) => r.ok ? r.json() : { joints: [] }) : { joints: [] }]);
    } catch (e) {
      console.error("3D preview failed to load", glbUrl, e);
      if (mine === gen) status.textContent = `The 3D preview didn't load (${String((e && e.message) || e).slice(0, 120)}).`;
      return [];
    }
    if (mine !== gen) return [];
    model = new THREE.Group();
    const inner = new THREE.Group();
    inner.add(gltf.scene);
    model.add(inner);
    scene.add(model);
    model.updateMatrixWorld(true);
    model.traverse((o) => { if (o.isMesh) o.castShadow = !opts.interior; });
    prepareTransparent(model, { glass: !opts.interior });
    applyLook();

    const byName = {};
    gltf.scene.traverse((n) => { if (n.name && !(clean(n.name) in byName)) byName[clean(n.name)] = n; });
    const groupOf = {};
    const box0 = new THREE.Box3().setFromObject(model);
    sizeM = box0.getSize(new THREE.Vector3()).length();
    for (const j of data.joints || []) {
      const node = byName[clean(j.child)];
      if (!node || groupOf[j.child]) continue;
      const group = new THREE.Group();
      group.position.set(...j.pivot);
      inner.add(group);
      const parent = groupOf[j.parent];
      if (parent) parent.attach(group);
      group.attach(node);
      groupOf[j.child] = group;
      const free = j.lower == null || j.upper == null;
      const lo = free ? (j.type === "hinge" ? -180 : -0.25 * sizeM) : j.lower;
      const hi = free ? (j.type === "hinge" ? 180 : 0.25 * sizeM) : j.upper;
      const r = { index: rig.length, name: j.name, type: j.type, group, node, meshes: [],
        axis: new THREE.Vector3(...j.axis).normalize(), base: group.position.clone(), lo, hi, free, val: 0 };
      node.traverse((c) => {
        if (!c.isMesh) return;
        // own material copies, so highlighting this part doesn't tint parts that share a material
        c.material = Array.isArray(c.material) ? c.material.map((m) => m.clone()) : c.material.clone();
        c.userData.rig = r; grabMeshes.push(c); r.meshes.push(c);
      });
      const dot = document.createElement("button");
      dot.type = "button";
      dot.className = "joint-dot";
      dot.setAttribute("aria-label", `${j.name}: drag to move`);
      dot.addEventListener("pointerenter", () => { if (!drag) setHot(r); });
      dot.addEventListener("pointerleave", () => { if (!drag) setHot(null); });
      dot.addEventListener("pointerdown", (e) => {
        e.preventDefault();
        const center = new THREE.Box3().setFromObject(r.node).getCenter(new THREE.Vector3());
        startDrag(r, e, center);
      });
      overlay.append(dot);
      r.dot = dot;
      rig.push(r);
    }
    linkJoints(data.joints || []);
    leaders().forEach((r) => setJoint(r, rest(r)));
    groundY = rig.length && !opts.interior ? lowest() : null;
    settleDirty = false;

    const box = new THREE.Box3().setFromObject(model);
    const c = box.getCenter(new THREE.Vector3());
    const dims = box.getSize(new THREE.Vector3());
    const size = Math.max(dims.length(), 0.02);
    camera.near = size / 400; camera.far = size * 80;
    sky.scale.setScalar(camera.far * 0.5);
    interior = !!opts.interior;
    camera.fov = opts.interior ? 68 : 35;   // a room needs a wide, photo-like lens
    if (opts.interior) {
      const eye = box.min.y + Math.min(1.6, dims.y * 0.55);
      camera.near = 0.02;
      camera.position.set(c.x + dims.x * 0.4, eye, c.z + dims.z * 0.4);   // near a corner
      controls.target.set(c.x, eye - 0.55, c.z);                           // looking into the room
      controls.minDistance = 0.1;
      controls.maxDistance = opts.enclosed ? Math.min(dims.x, dims.z) * 0.45 : size * 3;
    } else {
      camera.position.set(c.x + size * 0.85, c.y + size * 0.55, c.z + size * 1.05);
      controls.target.copy(c);
      controls.minDistance = size * 0.05; controls.maxDistance = size * 10;
    }
    camera.updateProjectionMatrix();
    placeGrid();
    status.hidden = true;
    toggle.hidden = !rig.length;
    return rig.map((r) => ({ name: r.name, type: r.type, lo: r.lo, hi: r.hi, free: r.free, val: r.val,
      follows: r.mimic ? r.mimic.ref.name : null, oneWay: !!(r.mimic && r.mimic.oneWay) }));
  }

  // Drag a part or its dot: hinges swing around their axis (following the pointer around
  // the pivot), sliders follow the pointer along their axis.
  const ray = new THREE.Raycaster();
  const ptr = new THREE.Vector2();
  function aim(e) {
    const rect = renderer.domElement.getBoundingClientRect();
    ptr.x = ((e.clientX - rect.left) / rect.width) * 2 - 1;
    ptr.y = -((e.clientY - rect.top) / rect.height) * 2 + 1;
    ray.setFromCamera(ptr, camera);
  }
  function startDrag(r, e, point) {
    const pivot = r.group.getWorldPosition(new THREE.Vector3());
    const axis = r.axis.clone().transformDirection(r.group.parent.matrixWorld).normalize();
    if (r.type === "hinge") {
      const v0 = point.clone().sub(pivot).projectOnPlane(axis);
      // a part centred on its own axis (wheel, knob): turn it by horizontal pointer movement
      drag = v0.lengthSq() < 1e-10 * sizeM * sizeM
        ? { r, kind: "spin", x0: e.clientX, start: r.val }
        : { r, kind: "hinge", pivot, axis, v0: v0.normalize(), start: r.val, lift0: model.position.y };
    } else {
      const n = camera.getWorldDirection(new THREE.Vector3());
      drag = { r, kind: "slider", axis, start: r.val, p0: point.clone(), lift0: model.position.y,
        plane: new THREE.Plane().setFromNormalAndCoplanarPoint(n, point) };
    }
    setHot(r);
    controls.enabled = false;
    stage.classList.add("dragging");
    window.addEventListener("pointermove", moveDrag);
    window.addEventListener("pointerup", endDrag);
    window.addEventListener("pointercancel", endDrag);
  }
  function moveDrag(e) {
    if (!drag) return;
    if (drag.kind === "spin") { setJoint(drag.r, drag.start + (e.clientX - drag.x0) * 0.8); return; }
    aim(e);
    const p = new THREE.Vector3();
    const lift = new THREE.Vector3(0, model.position.y - drag.lift0, 0);   // the object rose or settled since the drag began
    if (drag.kind === "hinge") {
      const pivot = drag.pivot.clone().add(lift);
      if (!ray.ray.intersectPlane(new THREE.Plane().setFromNormalAndCoplanarPoint(drag.axis, pivot), p)) return;
      const v1 = p.sub(pivot).projectOnPlane(drag.axis);
      if (v1.lengthSq() < 1e-12) return;
      v1.normalize();
      const delta = Math.atan2(new THREE.Vector3().crossVectors(drag.v0, v1).dot(drag.axis), drag.v0.dot(v1));
      setJoint(drag.r, drag.start + THREE.MathUtils.radToDeg(delta));
    } else {
      if (!ray.ray.intersectPlane(drag.plane.clone().translate(lift), p)) return;
      setJoint(drag.r, drag.start + p.sub(drag.p0).sub(lift).dot(drag.axis));
    }
  }
  function endDrag() {
    if (!drag) return;
    drag = null;
    controls.enabled = true;
    stage.classList.remove("dragging");
    window.removeEventListener("pointermove", moveDrag);
    window.removeEventListener("pointerup", endDrag);
    window.removeEventListener("pointercancel", endDrag);
    setHot(null);
  }
  renderer.domElement.addEventListener("pointerdown", (e) => {
    if (!grabMeshes.length || e.button !== 0) return;
    aim(e);
    const hit = ray.intersectObjects(grabMeshes, false)[0];
    if (!hit) return;
    startDrag(hit.object.userData.rig, e, hit.point);
  });
  renderer.domElement.addEventListener("pointermove", (e) => {
    if (drag || !grabMeshes.length) return;
    aim(e);
    const hit = ray.intersectObjects(grabMeshes, false)[0];
    renderer.domElement.style.cursor = hit ? "grab" : "";
    setHot(hit && showDots ? hit.object.userData.rig : null);
  });
  renderer.domElement.addEventListener("pointerleave", () => { if (!drag) setHot(null); });

  // Keep dots and the label on their joints as the camera or the parts move.
  const tmp = new THREE.Vector3();
  function placeDots() {
    if (!rig.length || overlay.hidden) return;
    const w = stage.clientWidth, h = stage.clientHeight;
    for (const r of rig) {
      r.group.getWorldPosition(tmp).project(camera);
      const visible = tmp.z < 1 && Math.abs(tmp.x) <= 1.05 && Math.abs(tmp.y) <= 1.05;
      r.dot.hidden = !visible;
      if (!visible) continue;
      r.sx = (tmp.x + 1) / 2 * w; r.sy = (1 - tmp.y) / 2 * h;
      r.dot.style.transform = `translate(${r.sx}px, ${r.sy}px)`;
    }
    if (hot && !hot.dot.hidden) {
      tip.textContent = label(hot);
      tip.style.transform = `translate(${Math.min(hot.sx + 14, w - tip.offsetWidth - 6)}px, ${Math.max(hot.sy - 34, 6)}px)`;
    }
  }

  let running = true;
  (function tick() {
    if (!running) return;
    requestAnimationFrame(tick);
    if (settleDirty) settle();
    controls.update();
    sky.position.copy(camera.position);
    renderer.render(scene, camera);
    placeDots();
  })();

  setTheme(theme);
  return {
    element: root,
    load,
    setLook,
    setTheme,
    setJoint: (i, v) => rig[i] && setJoint(rig[i], v),
    resetJoints: () => leaders().forEach((r) => setJoint(r, rest(r))),
    openJoints: () => leaders().forEach((r) => setJoint(r, r.free ? r.val : r.lo + (r.hi - r.lo) * (Math.abs(r.hi) >= Math.abs(r.lo) ? 0.85 : 0.15))),
    onJoint: (fn) => { onJoint = fn; },
    resize,
    fit,
    getView,
    setView,
    dispose: () => { running = false; clear(); renderer.dispose(); },
  };
}