@floless/app 0.131.1 → 0.132.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/dist/floless-server.cjs +2374 -1901
  2. package/dist/schemas/steel.model.v2.schema.json +3 -1
  3. package/dist/skills/floless-app-onboarding/SKILL.md +12 -2
  4. package/dist/skills/floless-app-queue/SKILL.md +2 -2
  5. package/dist/web/app.css +359 -0
  6. package/dist/web/app.js +22 -0
  7. package/dist/web/aware.js +121 -13
  8. package/dist/web/commands-filter.js +157 -0
  9. package/dist/web/commands-shell.js +1316 -0
  10. package/dist/web/commands-steel.js +1829 -0
  11. package/dist/web/commands-vector.js +154 -0
  12. package/dist/web/commands-vector3d.js +96 -0
  13. package/dist/web/commands.js +316 -0
  14. package/dist/web/grid-core.js +124 -23
  15. package/dist/web/index.html +269 -164
  16. package/dist/web/instructor-reporter.js +201 -0
  17. package/dist/web/instructor.js +1178 -0
  18. package/dist/web/reference-geometry-worker.js +194 -0
  19. package/dist/web/steel-3d-core.js +486 -107
  20. package/dist/web/steel-3d-view.js +847 -204
  21. package/dist/web/steel-canvas-guidance.js +7 -4
  22. package/dist/web/steel-editor.html +1620 -1799
  23. package/dist/web/steel-filter-core.js +13 -5
  24. package/dist/web/steel-filter.html +36 -22
  25. package/dist/web/steel-model-adapter.js +17 -22
  26. package/dist/web/steel-model-commands.js +23 -10
  27. package/dist/web/steel-model-v2-client-validation.js +20 -3
  28. package/dist/web/steel-model-v2-commands.js +91 -3
  29. package/dist/web/steel-model-v2-projection.js +4 -5
  30. package/dist/web/steel-plan-transform.js +4 -8
  31. package/dist/web/steel-split-view.js +33 -0
  32. package/dist/web/vector-3d.html +19 -7
  33. package/dist/web/vector-editor.html +21 -8
  34. package/dist/web/workspaces.js +12 -25
  35. package/package.json +10 -1
@@ -20,9 +20,9 @@ import { RoomEnvironment } from 'three/addons/RoomEnvironment.js';
20
20
  import { surfaceTextures, applyTriplanar, TILE_MM, DIRECTIONAL } from './steel-materials.js';
21
21
  import { canvasToolGuidanceState } from './steel-canvas-guidance.js';
22
22
  import { Brush, Evaluator, SUBTRACTION } from 'three-bvh-csg';
23
- import { snapPoint, planPointToWp, memberGeometry, snapElevation, dim3dGeom, dominantAxis3d, planeBasis, planeFrom3Points, frameFrom3Points, frameFromAngle, worldToLocal, identityFrame, resolvePointEntry, offsetsFor, candidateOnPlane, snapGridPoint, clipSegmentToPlanes, pointSegmentDistance2d, perspectiveSegmentParameter, gridDepthWins, segmentHitsRect2d, projectedFootprintHitsRect2d, pickGridLevel, selectedLengthLabelAnchors, sectionKindOf } from './steel-3d-core.js';
24
- // `gridGeometry`, `gridCandidates3d` and `mmPerPx` moved behind the host's model read half (unit 5, P7d):
25
- // each takes a `ptPerFt`, which is a v1 PLAN default and meaningless on a world-mm model grid.
23
+ import { snapPoint, planPointToWp, memberGeometry, snapElevation, dim3dGeom, dominantAxis3d, planeBasis, planeFrom3Points, frameFrom3Points, frameFromAngle, worldToLocal, identityFrame, resolvePointEntry, offsetsFor, candidateOnPlane, snapGridPoint, clipSegmentToPlanes, pointSegmentDistance2d, perspectiveSegmentParameter, gridDepthWins, segmentHitsRect2d, projectedFootprintHitsRect2d, pickGridLevel, selectedLengthLabelAnchors, sectionKindOf, sectionOutlinePts, memberMeshAxes } from './steel-3d-core.js';
24
+ // `gridGeometry`, `gridCandidates3d` and `mmPerPx` live behind the host's model read boundary because
25
+ // their display-scale argument is meaningless on a world-mm model grid.
26
26
  import { visibleGridLevels, gridTransientScopeSignature, reconcileGridTransientState, objectSelectionStatus } from './grid-core.js';
27
27
 
28
28
  let renderer, scene, perspCam, orthoCam, camera, controls, root, api, canvasEl, ro, rafId, grid, raycaster, downXY, lastPick = '(none)';
@@ -172,6 +172,7 @@ function init(canvas, theApi) {
172
172
  renderer.localClippingEnabled = true; // enable clip planes/boxes + the work area (Tekla-style sectioning) — driven via renderer.clippingPlanes (applyClips)
173
173
  scene = new THREE.Scene();
174
174
  scene.background = new THREE.Color(0x020817); // match the app --bg (the mode change reads from the geometry, not a tint)
175
+ renderer.setClearColor(0x020817); // the same colour for the bare clear the loop does while unframed (see camFramed) — scene.background still owns the ordinary render
175
176
  perspCam = new THREE.PerspectiveCamera(50, 1, 1, 50_000_000);
176
177
  perspCam.up.set(0, 0, 1); // Z-up to match the scene
177
178
  orthoCam = new THREE.OrthographicCamera(-1, 1, 1, -1, 1, 50_000_000);
@@ -314,7 +315,7 @@ function init(canvas, theApi) {
314
315
  const statusDock = document.getElementById('bottomDockLeft');
315
316
  hoverChip = document.createElement('span');
316
317
  if (statusDock) {
317
- try { hoverChipIdleCollapsed = localStorage.getItem('steel:canvasStatusCollapsed:v1') === '1'; } catch (_) { hoverChipIdleCollapsed = false; }
318
+ try { hoverChipIdleCollapsed = localStorage.getItem('steel:canvasStatusCollapsed:v2') === '1'; } catch (_) { hoverChipIdleCollapsed = false; }
318
319
  hoverChipShell = document.createElement('div'); hoverChipShell.id = 'canvasStatus';
319
320
  hoverChipToggle = document.createElement('button'); hoverChipToggle.type = 'button'; hoverChipToggle.id = 'canvasStatusToggle';
320
321
  hoverChipToggle.setAttribute('aria-controls', 'canvasStatusText');
@@ -323,7 +324,7 @@ function init(canvas, theApi) {
323
324
  hoverChipToggle.onclick = () => {
324
325
  if (hoverChipToggle.getAttribute('aria-disabled') === 'true') return;
325
326
  hoverChipIdleCollapsed = !hoverChipIdleCollapsed;
326
- try { localStorage.setItem('steel:canvasStatusCollapsed:v1', hoverChipIdleCollapsed ? '1' : '0'); } catch (_) {}
327
+ try { localStorage.setItem('steel:canvasStatusCollapsed:v2', hoverChipIdleCollapsed ? '1' : '0'); } catch (_) {}
327
328
  updateStatusChip(); hoverChipToggle.focus();
328
329
  };
329
330
  hoverChipShell.append(hoverChipToggle, hoverChip); statusDock.appendChild(hoverChipShell);
@@ -377,8 +378,51 @@ function resize() {
377
378
  if (camera === orthoCam) reframeOrtho();
378
379
  }
379
380
 
381
+ // NOTHING IS PAINTED BEFORE THE CAMERA HAS BEEN FRAMED ONCE, and that is what this flag is for.
382
+ // show() starts the loop the moment the 3D pane opens, but the box to frame against only exists once
383
+ // rebuild()'s /scene POST resolves — a second or so later. Until then the camera sits where init() left
384
+ // it, position === target, which lookAt resolves to a straight-down TOP view; reframeOrtho's `|| 1`
385
+ // fallback then sizes the frustum off a zero distance, giving a sub-millimetre window on the world.
386
+ // That is the "3D opens flat from the top, then flips to the iso view" report: the pane painted the
387
+ // frame gizmo, the ViewCube reading TOP and the axis triad, all off that degenerate camera (photographed
388
+ // before and after — see the QA doc cited in server/steel-3d-first-frame.test.ts). A bare clear paints
389
+ // what an empty 3D pane should look like instead, so what the user sees first is the fitted iso view —
390
+ // or, on the failure paths, the dark pane it was already showing.
391
+ //
392
+ // TWO FLAGS, because "may we paint?" and "has the camera ever been framed?" are different questions
393
+ // and one flag could not answer both without a hole at each end:
394
+ // camFitted — ONLY fitCamera sets this. A durable fact about the cameras themselves.
395
+ // camFramed — the paint gate. Opened by a fit, and also by rebuild settling either way, because a
396
+ // pane that is still on screen must not stay blank for ever.
397
+ // show() re-derives the gate from camFitted, and that is what makes the pair safe: a retry after a
398
+ // failed open (view3dReady is latched, so init() is skipped and the same never-framed cameras come
399
+ // back) re-closes the gate, while an ordinary 2D→3D re-entry keeps it open and paints instantly.
400
+ // With one flag, opening on rejection poisoned the retry and NOT opening left a superseded-then-
401
+ // rejected open blank for ever — 3d→split during the first load yields show3d:false, so setView
402
+ // never rebuilds again and its superseded catch returns without reverting.
403
+ let camFitted = false, camFramed = false;
404
+ let unframedFrames = 0, unframedWarned = false; // a gate that never opens looks exactly like a correctly-rendered empty model — see loop()
405
+ // The HTML label hosts are PLACED by the render loop, so any frame the loop does not reach has to hide
406
+ // them: an absolutely-positioned label that has never been positioned sits at the viewport's top-left
407
+ // corner, over the 2D UI. On the way IN that bites dimLabelHost specifically — it is the one host whose
408
+ // cssText carries no `display:none`, and show() repopulates the dim labels right after starting the
409
+ // loop, so a model with saved dims would stack its chips in the corner for the length of the gate.
410
+ // (Hiding the HOST, not the chips, is what makes that safe.) The other three are hidden here anyway so
411
+ // that one helper is the single answer for both directions — hide() had open-coded three of the four
412
+ // and left selLenLabelHost out, which this closes.
413
+ function hideLabelHosts() {
414
+ for (const host of [dimLabelHost, memberLabelHost, propLabelHost, selLenLabelHost]) if (host) host.style.display = 'none';
415
+ }
380
416
  function loop() {
381
- rafId = requestAnimationFrame(loop);
417
+ rafId = requestAnimationFrame(loop); // MUST stay above the gate: schedule the next frame first, or a shut gate stops the loop dead and the pane never recovers without a re-entry
418
+ if (!camFramed) {
419
+ // Say so once rather than clear in silence for ever. A permanently shut gate — a /scene POST that
420
+ // never settles, a rebuild that never ran — is pixel-identical to a correctly-rendered empty model,
421
+ // so it is the one failure here with no visible tell. Same warn-once convention as
422
+ // badLabelScaleWarned / staleBubbleWarned below.
423
+ if (++unframedFrames === 240 && !unframedWarned) { unframedWarned = true; console.warn('[steel-3d] still unframed after ~240 frames — the scene fetch has not settled, so the 3D pane is blank rather than empty'); }
424
+ hideLabelHosts(); renderer.clear(); return; // see camFramed — no unframed camera reaches the screen
425
+ }
382
426
  controls.update();
383
427
  sizeEndpoints();
384
428
  sizeClipHandles();
@@ -420,7 +464,12 @@ function lengthAxisOf(el) {
420
464
  }
421
465
  function shapeOf(el) {
422
466
  const explicit = (el.section && el.section.shape || '').toString().toUpperCase().trim();
423
- if (/^(I|C|L|TUBE|BOX)$/.test(explicit)) return explicit; // explicit section.shape override wins
467
+ if (/^(I|C|L|TUBE|BOX|ROUND)$/.test(explicit)) return explicit; // explicit section.shape override wins
468
+ // A ROUND section cannot be told from its designation here: `sectionKindOf` matches a literal prefix and
469
+ // answers TUBE for both `HSS6X6X3/8` (rectangular) and `HSS6.625X0.280` (round). The bake parses the
470
+ // numerics and says so on `section.round` — without it a pipe drew as a rectangle whose corner reaches
471
+ // 0.707·OD, putting a rolled pipe's flush face 23.7 mm off its reference line.
472
+ if (el.section && el.section.round === true) return 'ROUND';
424
473
  // The designation itself goes to the shared classifier (steel-3d-core.js), which the 2D plan outline
425
474
  // and the base-plate weld also use. The copy that lived here drew MC channels as I-sections (#647).
426
475
  return sectionKindOf((el.meta && el.meta.profile) || '');
@@ -437,26 +486,18 @@ function realThk(xs, key, half) {
437
486
  // in a member that was drawn nearly twice too thick. The estimates remain as the fallback for sections we
438
487
  // have no data for; they are the reason a member can still be drawn at all.
439
488
  function profileShape(kind, w, d, xs) {
440
- const s = new THREE.Shape(), hw = w / 2, hd = d / 2;
441
- if (kind === 'I') {
442
- const tf = realThk(xs, 'tf', hd) ?? Math.min(d * 0.5, Math.max(d * 0.10, 6));
443
- const tw = realThk(xs, 'tw', hw) ?? Math.min(w * 0.5, Math.max(w * 0.10, 5));
444
- s.moveTo(-hw, -hd); s.lineTo(hw, -hd); s.lineTo(hw, -hd + tf); s.lineTo(tw / 2, -hd + tf);
445
- s.lineTo(tw / 2, hd - tf); s.lineTo(hw, hd - tf); s.lineTo(hw, hd); s.lineTo(-hw, hd);
446
- s.lineTo(-hw, hd - tf); s.lineTo(-tw / 2, hd - tf); s.lineTo(-tw / 2, -hd + tf); s.lineTo(-hw, -hd + tf); s.closePath();
447
- } else if (kind === 'C') {
448
- const tf = realThk(xs, 'tf', hd) ?? Math.max(d * 0.10, 5);
449
- const tw = realThk(xs, 'tw', hw) ?? Math.max(w * 0.12, 5);
450
- s.moveTo(-hw, -hd); s.lineTo(hw, -hd); s.lineTo(hw, -hd + tf); s.lineTo(-hw + tw, -hd + tf);
451
- s.lineTo(-hw + tw, hd - tf); s.lineTo(hw, hd - tf); s.lineTo(hw, hd); s.lineTo(-hw, hd); s.closePath();
452
- } else if (kind === 'L') {
453
- const t = realThk(xs, 't', Math.min(hw, hd)) ?? Math.max(Math.min(w, d) * 0.18, 5);
454
- s.moveTo(-hw, -hd); s.lineTo(hw, -hd); s.lineTo(hw, -hd + t); s.lineTo(-hw + t, -hd + t); s.lineTo(-hw + t, hd); s.lineTo(-hw, hd); s.closePath();
455
- } else if (kind === 'TUBE') {
456
- const t = realThk(xs, 't', Math.min(hw, hd)) ?? Math.max(Math.min(w, d) * 0.12, 4);
457
- s.moveTo(-hw, -hd); s.lineTo(hw, -hd); s.lineTo(hw, hd); s.lineTo(-hw, hd); s.closePath();
458
- const h = new THREE.Path(); h.moveTo(-hw + t, -hd + t); h.lineTo(hw - t, -hd + t); h.lineTo(hw - t, hd - t); h.lineTo(-hw + t, hd - t); h.closePath(); s.holes.push(h);
459
- } else { s.moveTo(-hw, -hd); s.lineTo(hw, -hd); s.lineTo(hw, hd); s.lineTo(-hw, hd); s.closePath(); }
489
+ // The outline itself comes from steel-3d-core.js, which the 2D plan draws from too — one set of points,
490
+ // so a section whose real thickness is known cannot be extruded as one shape and drawn as another (see
491
+ // sectionOutlinePts). Two differences survive on purpose: 3D punches a tube's bore below where the plan
492
+ // draws a tube solid, and a section with NO thickness source falls back to estimates whose floors are
493
+ // absolute in each caller's own unit. All that is left here is turning the points into a THREE.Shape.
494
+ const { outer, hole } = sectionOutlinePts(kind, w, d, {
495
+ tw: realThk(xs, 'tw', w / 2), tf: realThk(xs, 'tf', d / 2), t: realThk(xs, 't', Math.min(w, d) / 2),
496
+ });
497
+ const s = new THREE.Shape();
498
+ const trace = (path, pts) => { pts.forEach(([x, y], i) => (i ? path.lineTo(x, y) : path.moveTo(x, y))); path.closePath(); };
499
+ trace(s, outer);
500
+ if (hole) { const h = new THREE.Path(); trace(h, hole); s.holes.push(h); }
460
501
  return s;
461
502
  }
462
503
  function memberGeom(el, w, d, len) {
@@ -466,47 +507,69 @@ function memberGeom(el, w, d, len) {
466
507
  g.translate(0, 0, -len / 2); return g; // extruded +Z, centred
467
508
  }
468
509
  const _ZA = new THREE.Vector3(0, 0, 1), _YA = new THREE.Vector3(0, 1, 0);
469
- // NOTE vs AWARE viewer-3d: AWARE converts the Z-up scene into Three's Y-up world before orienting, so
470
- // its roll targets world-Y. We render the scene NATIVELY Z-up (camera.up=Z), so the roll must target
471
- // world-Z (_ZA) — else the web rolls flat (horizontal) instead of standing vertical.
472
- function orientMember(mesh, dir, el) {
473
- const m = dir.clone().normalize();
474
- // el.rot (section roll about the reference line) applies to ANY member — columns AND beams. A member
475
- // rendered as an explicit BOX (traced section, no profile) rolls about its length axis (local Y here).
476
- // For a non-plumb BOX, first align its authored depth axis with world-up; a plumb member has no
477
- // plan direction and `positionH` is unavailable, so its roll below only establishes display facing.
478
- const rollRad = (el && typeof el.rot === 'number' && el.rot) ? el.rot * Math.PI / 180 : 0;
479
- if (mesh.geometry.type === 'BoxGeometry') {
480
- const q = new THREE.Quaternion().setFromUnitVectors(_YA, m); // length on local Y
481
- const proj = _ZA.clone().sub(m.clone().multiplyScalar(_ZA.dot(m)));
482
- if (proj.lengthSq() > 1e-6) {
483
- proj.normalize();
484
- const lz = _ZA.clone().applyQuaternion(q); // local depth axis
485
- const ang = Math.atan2(lz.clone().cross(proj).dot(m), lz.dot(proj));
486
- q.premultiply(new THREE.Quaternion().setFromAxisAngle(m, ang));
487
- if (rollRad) q.premultiply(new THREE.Quaternion().setFromAxisAngle(m, rollRad));
488
- } else if (el && typeof el.rot === 'number') {
489
- q.premultiply(new THREE.Quaternion().setFromAxisAngle(m, el.rot * Math.PI / 180));
490
- }
491
- mesh.quaternion.copy(q);
492
- return;
493
- }
494
- const q = new THREE.Quaternion().setFromUnitVectors(_ZA, m); // member axis = extrude (local Z)
495
- const proj = _ZA.clone().sub(m.clone().multiplyScalar(_ZA.dot(m))); // world-UP (Z) perpendicular to member
496
- if (proj.lengthSq() > 1e-6) {
497
- proj.normalize();
498
- const ly = _YA.clone().applyQuaternion(q); // where the section depth (local Y) points
499
- const ang = Math.atan2(ly.clone().cross(proj).dot(m), ly.dot(proj));
500
- q.premultiply(new THREE.Quaternion().setFromAxisAngle(m, ang)); // roll so the web stands vertical (depth → world-Z)
501
- // then apply the authored roll about the member axis — for a beam this spins the section around its
502
- // reference line (0 = web vertical, as before). Columns take the degenerate branch below instead.
503
- if (rollRad) q.premultiply(new THREE.Quaternion().setFromAxisAngle(m, rollRad));
504
- } else if (el && typeof el.rot === 'number') {
505
- // A vertical member (column): the world-up roll above is degenerate, so face the section by the
506
- // authored plan rotation instead of an arbitrary default. Matches the 2D editor's section angle.
507
- // `el.rot` is ALREADY Y-flip-corrected (negated) in contract-to-scene, so a skewed column now reads
508
- // the same way as its 2D footprint — apply it directly here (do NOT re-negate).
509
- q.premultiply(new THREE.Quaternion().setFromAxisAngle(m, el.rot * Math.PI / 180));
510
+ // NOTE vs AWARE viewer-3d: AWARE converts the Z-up scene into Three's Y-up world before orienting, so its
511
+ // depth axis targets world-Y. We render the scene NATIVELY Z-up (camera.up=Z), so depth must target
512
+ // world-Z — else the web lies flat (horizontal) instead of standing vertical. That convention is no longer
513
+ // spelled out here: it is `partFrame`'s `up` parameter, which defaults to world Z (see `memberMeshAxes`).
514
+ /**
515
+ * Orient a member from its two raw world endpoints. `from` and `to` are endpoint triples, never a
516
+ * pre-normalized direction; normalizing before `partFrame` can select the other inclusive boundary branch.
517
+ * @param {THREE.Object3D & {geometry: THREE.BufferGeometry}} mesh
518
+ * @param {[number, number, number]} from raw world start endpoint
519
+ * @param {[number, number, number]} to raw world end endpoint
520
+ * @param {object} el scene member, optionally carrying the authored `refFrom`/`refTo` frame line
521
+ */
522
+ function orientMember(mesh, from, to, el) {
523
+ // The basis comes from `memberMeshAxes` (steel-3d-core.js), which is `partFrame` — the SAME frame the
524
+ // bake, the flush offsets and the 2D plan footprint place a section in — reordered into this geometry's
525
+ // local axes. It used to be derived here instead, from `setFromUnitVectors(_ZA, m)` plus a corrective
526
+ // roll, which agreed with the bake for every ordinary member and came out 180° about the reference line
527
+ // for one stored top→base: an asymmetric L or C faced the wrong way in 3D while the plan and the export
528
+ // had it right (#770). One frame, so the tie-break and the near-plumb cut cannot drift apart again.
529
+ //
530
+ // THE AUTHORED REFERENCE LINE selects the frame, and the operands must be the bake's own — not a
531
+ // direction recovered from anywhere else. `partFrame`'s near-plumb predicate (`1 − dot² ≤ 1e−6`) is
532
+ // INCLUSIVE, so for a member on the cut a single last-bit difference decides the branch and swings the
533
+ // depth axis 90°. Two roundings had to go (both found by Codex on #801):
534
+ //
535
+ // - normalizing here first, then letting `partFrame` normalize again. `[5, 0, √(5000²−5²)]` is
536
+ // `sin θ = 1e−3` dead on and flips from the ordinary branch to the degenerate one.
537
+ // - subtracting the PLACED endpoints. `el.from`/`el.to` are `refFrom + o` / `refTo + o` for the same
538
+ // section-position offset, so `to − from` is not bit-identical to `refTo − refFrom`. Swept on that
539
+ // same member, 98,755 of 400,000 legal offsets flipped the branch.
540
+ //
541
+ // So `contract-to-scene` ships `refFrom`/`refTo` alongside the placed line and they are what comes in
542
+ // here; `from`/`to` remain the fallback for a scene that predates them or an element with no authored
543
+ // line, which is the pre-#801 behaviour rather than a new guess. Connection trims make the same
544
+ // distinction: the physical solid can be shorter while its authored frame line must stay unchanged.
545
+ const p3 = (v) => (Array.isArray(v) && v.length === 3
546
+ && v.every((n) => typeof n === 'number' && isFinite(n)) ? v : null);
547
+ const ref = el && p3(el.refFrom) && p3(el.refTo) ? [el.refFrom, el.refTo] : [from, to];
548
+ const frameFrom = ref[0], frameTo = ref[1];
549
+ const axes = memberMeshAxes(frameFrom, frameTo, mesh.geometry.type === 'BoxGeometry');
550
+ // A zero-length member has no direction to orient by, and it IS reachable: `placeMember` floors the
551
+ // LENGTH at 1 mm but not the direction, and `Vector3.normalize` leaves (0,0,0) at (0,0,0). Reset rather
552
+ // than return, so this function fully determines the orientation for every input instead of leaving a
553
+ // degenerate member wearing whatever quaternion its mesh arrived with. `buildFromScene` — the only
554
+ // caller — hands over a fresh `THREE.Mesh`, whose quaternion is already identity, so this is not
555
+ // repairing a live defect; it is refusing to make the contract depend on that staying true.
556
+ if (!axes) { mesh.quaternion.identity(); return; }
557
+ const q = new THREE.Quaternion().setFromRotationMatrix(
558
+ new THREE.Matrix4().makeBasis(V(...axes.x), V(...axes.y), V(...axes.z)));
559
+ // el.rot (section roll about the reference line) applies to ANY member — columns AND beams — and is a
560
+ // WORLD rotation about start→end: v2 work points are already right-handed world mm with no flip anywhere
561
+ // in the bake, so contract-to-scene passes `rot` through untouched. Do NOT re-negate (the v1 arm that
562
+ // did, to undo v1's display-space Y flip, went with v1 in #741) — negating mirrors every rolled section.
563
+ // The 2D plan footprint is placed to match (SteelCore.sectionOutlinePx). A non-finite `rot` reads as 0,
564
+ // as it does in `positionOffsetVector`: an Infinity would otherwise reach setFromAxisAngle as NaN and
565
+ // blank the member out of the scene entirely.
566
+ const rot = el && typeof el.rot === 'number' && isFinite(el.rot) ? el.rot : 0;
567
+ if (rot) {
568
+ // The roll axis is normalized here and that is safe: unlike the frame above it feeds no predicate, so
569
+ // a last-bit difference from `partFrame`'s own `x` turns the section by an immaterial angle rather
570
+ // than selecting a different branch. `setFromAxisAngle` requires a unit axis.
571
+ const m = V(frameTo[0] - frameFrom[0], frameTo[1] - frameFrom[1], frameTo[2] - frameFrom[2]).normalize();
572
+ q.premultiply(new THREE.Quaternion().setFromAxisAngle(m, rot * Math.PI / 180));
510
573
  }
511
574
  mesh.quaternion.copy(q);
512
575
  }
@@ -516,7 +579,7 @@ function placeMember(mesh, a, b, el) {
516
579
  const dir = new THREE.Vector3().subVectors(B, A); const len = dir.length() || 1; dir.normalize();
517
580
  const w = Math.max((el.section && el.section.w) || 50, 1), d = Math.max((el.section && el.section.d) || 50, 1);
518
581
  mesh.geometry = memberGeom(el, w, d, len);
519
- orientMember(mesh, dir, el);
582
+ orientMember(mesh, a, b, el); // raw physical endpoints; orientMember selects the authored frame line when present
520
583
  mesh.position.copy(A).addScaledVector(dir, len / 2);
521
584
  }
522
585
 
@@ -964,9 +1027,8 @@ function buildRefLines() {
964
1027
  if (!refLineOn || !api) return;
965
1028
  const pts = [];
966
1029
  for (const m of members()) {
967
- // Ask the READ HALF whether this member has a work line, rather than testing for `m.wp` — that is a
968
- // v1 STORAGE shape, and a v2 member has none, so the old guard skipped every member of a canonical
969
- // model and drew no reference lines at all. Silently: an empty `pts` just returns. (unit 5, P7d)
1030
+ // Ask the read boundary whether this canonical member has a work line rather than testing for a
1031
+ // projected `m.wp`; that guard would silently skip every native member.
970
1032
  const g = m && geoOf(m);
971
1033
  if (!g || !g.line) continue;
972
1034
  pts.push(new THREE.Vector3(g.line[0][0], g.line[0][1], g.line[0][2]), new THREE.Vector3(g.line[1][0], g.line[1][1], g.line[1][2]));
@@ -993,7 +1055,7 @@ function setRefLine(on) { refLineOn = !!on; buildRefLines(); }
993
1055
  // raycasts `meshById` only, and reference meshes are never in that map, so member picking, drag,
994
1056
  // box-select and Ctrl+A cannot see them however this layer changes.
995
1057
 
996
- let xrefGroup = null; // one child Group per reference, each holding its meshes
1058
+ let xrefGroup = null; // one child Group per reference, each holding its draw batches
997
1059
  const xrefById = new Map(); // id -> { group, display, points, capped, total, bounds }
998
1060
  let xrefSelected = null; // the whole-selected reference, or null
999
1061
  /**
@@ -1003,9 +1065,9 @@ let xrefSelected = null; // the whole-selected reference, or
1003
1065
  * `toReferenceObjects` writes `''` for an object whose id was not a string and `setReferences` maps that
1004
1066
  * to null — so on a file whose objects carry no ids, OUR ids collide by construction and cannot address
1005
1067
  * a mesh. (Whether real GlobalIds are ever duplicated is a separate question this does not rest on.) The
1006
- * index into `ref.objects` is exact — `setReferences` adds exactly one mesh per object, in order — so it
1007
- * is what selects, and the id rides along so a rebuild can CHECK that the index still means the same
1008
- * object.
1068
+ * index into `ref.objects` is exact — each BatchedMesh instance maps back to that same logical array —
1069
+ * so it is what selects, and the id rides along so a rebuild can CHECK that the index still means the
1070
+ * same object. The compatibility renderer preserves the older one-child-per-object mapping.
1009
1071
  *
1010
1072
  * That check has teeth only where the file gives its objects ids; `revalidateSubSelection` says what it
1011
1073
  * does in the case where it does not, and it does not pretend to a guarantee it cannot make.
@@ -1037,10 +1099,10 @@ const XREF_COLOR = 0x94a3b8;
1037
1099
  /**
1038
1100
  * The drilled-into object's own lift, and why it is not simply "the whole-model highlight, on one mesh".
1039
1101
  *
1040
- * A reference draws at 50% opacity, `depthWrite:false`, BEHIND everything of ours. One object inside a
1041
- * building at those settings is not findable by an emissive nudge — it is a slightly paler pane among
1042
- * two hundred identical translucent panes. So the sub-selection gets a stronger lift AND is pushed
1043
- * towards opaque, which is what makes "that one, there" legible at a glance.
1102
+ * A reference normally draws fully solid; a user can still lower its opacity, and a file may carry
1103
+ * genuinely translucent materials. One object inside a building at either setting is not findable by
1104
+ * an emissive nudge alone, so the sub-selection gets a stronger lift and is pushed towards opaque —
1105
+ * which is what makes "that one, there" legible at a glance.
1044
1106
  *
1045
1107
  * RAISING OPACITY IS A SELECTION AFFORDANCE, NOT A CHANGE TO THE REFERENCE. It applies to a CLONE of
1046
1108
  * the object's own material, lasts exactly as long as the selection, and never touches the slider's
@@ -1056,6 +1118,7 @@ const XREF_SUB_INTENSITY = 0.9;
1056
1118
  const XREF_SUB_MIN_OPACITY = 0.85;
1057
1119
 
1058
1120
  const XREF_MODES = new Set(['file', 'uniform', 'custom']);
1121
+ const XREF_DEFAULT_OPACITY = 1; // omitted legacy values and new imports are fully solid
1059
1122
  const xrefMode = (d) => (XREF_MODES.has(d && d.colorMode) ? d.colorMode : 'file');
1060
1123
  /**
1061
1124
  * The custom colour as a number, or null if it is not a colour.
@@ -1173,8 +1236,8 @@ function appendReferencePreview(objects, placement) {
1173
1236
  if (!scene || !Array.isArray(objects) || !objects.length) return 0;
1174
1237
  if (!xrefPreviewGroup) {
1175
1238
  xrefPreviewGroup = new THREE.Group();
1176
- // BEHIND our steel, exactly as a reference is: `renderOrder` -1 with `depthWrite:false`. A preview
1177
- // that occluded the model it exists to be compared against would be worse than no preview.
1239
+ // Behind our steel in render order, but fully opaque like the committed default. Provisional grey
1240
+ // distinguishes the preview without reviving the transparency/depth-write failure this change removes.
1178
1241
  xrefPreviewGroup.renderOrder = -1;
1179
1242
  xrefPreviewGroup.applyMatrix4(xrefMatrix(placement));
1180
1243
  scene.add(xrefPreviewGroup);
@@ -1182,8 +1245,8 @@ function appendReferencePreview(objects, placement) {
1182
1245
  // same "not your content" slate this app already spends on references, it reads honestly as
1183
1246
  // provisional — the real colours appear when the import commits — and it lets the server strip
1184
1247
  // colour runs from the wire entirely. One material, because there is only ever one colour.
1185
- xrefPreviewMat = newXrefMaterial(XREF_COLOR, 0.5);
1186
- xrefPreviewMat.opacity = 0.5;
1248
+ xrefPreviewMat = newXrefMaterial(XREF_COLOR, 1);
1249
+ xrefPreviewMat.opacity = 1;
1187
1250
  xrefPreviewCount = 0;
1188
1251
  xrefPreviewFramed = false;
1189
1252
  // Cleared when a preview BEGINS, not on dispose: the question is whether the user has moved the
@@ -1191,14 +1254,26 @@ function appendReferencePreview(objects, placement) {
1191
1254
  // to frame a reference that needs it.
1192
1255
  xrefPreviewCamTouched = false;
1193
1256
  }
1194
- for (const o of objects) {
1195
- if (!o || !Array.isArray(o.positions) || !o.positions.length) continue;
1257
+ const valid = objects.filter((o) => o && Array.isArray(o.positions) && o.positions.length >= 9);
1258
+ if (valid.length && typeof THREE.BatchedMesh === 'function') {
1259
+ const vertices = valid.reduce((n, o) => n + o.positions.length / 3, 0);
1260
+ const indices = valid.reduce((n, o) => n + (Array.isArray(o.indices) && o.indices.length ? o.indices.length : o.positions.length / 3), 0);
1261
+ const batch = new THREE.BatchedMesh(valid.length, vertices, indices, xrefPreviewMat);
1262
+ batch.perObjectFrustumCulled = false; batch.sortObjects = false;
1263
+ const identity = new THREE.Matrix4();
1264
+ for (const o of valid) {
1265
+ const g = new THREE.BufferGeometry();
1266
+ g.setAttribute('position', new THREE.Float32BufferAttribute(o.positions, 3));
1267
+ g.setIndex(Array.isArray(o.indices) && o.indices.length ? o.indices : Array.from({ length: o.positions.length / 3 }, (_, i) => i));
1268
+ g.computeVertexNormals(); const geometryId = batch.addGeometry(g), instanceId = batch.addInstance(geometryId);
1269
+ batch.setMatrixAt(instanceId, identity); g.dispose(); xrefPreviewCount++;
1270
+ }
1271
+ xrefPreviewGroup.add(batch);
1272
+ } else for (const o of valid) {
1196
1273
  const g = new THREE.BufferGeometry();
1197
1274
  g.setAttribute('position', new THREE.Float32BufferAttribute(o.positions, 3));
1198
1275
  if (Array.isArray(o.indices) && o.indices.length) g.setIndex(o.indices);
1199
- g.computeVertexNormals();
1200
- xrefPreviewGroup.add(new THREE.Mesh(g, xrefPreviewMat));
1201
- xrefPreviewCount++;
1276
+ g.computeVertexNormals(); xrefPreviewGroup.add(new THREE.Mesh(g, xrefPreviewMat)); xrefPreviewCount++;
1202
1277
  }
1203
1278
  // No explicit redraw: this view runs a continuous rAF loop (see `loop`), so adding to the scene is
1204
1279
  // all a batch has to do to appear.
@@ -1239,7 +1314,9 @@ function frameReferencePreview() {
1239
1314
  function clearReferencePreview() {
1240
1315
  if (!xrefPreviewGroup) return;
1241
1316
  try {
1242
- xrefPreviewGroup.traverse((o) => { o.geometry?.dispose?.(); });
1317
+ xrefPreviewGroup.traverse((o) => {
1318
+ if (o.isBatchedMesh) o.dispose?.(); else o.geometry?.dispose?.();
1319
+ });
1243
1320
  scene?.remove(xrefPreviewGroup);
1244
1321
  xrefPreviewMat?.dispose?.();
1245
1322
  } finally {
@@ -1319,6 +1396,7 @@ function setReferenceGhosts(refId, objects, placement) {
1319
1396
  xrefGhostMat.opacity = XREF_GHOST_OPACITY;
1320
1397
  xrefGhostRef = refId;
1321
1398
  }
1399
+ const ghostAnchor = xrefAnchor(objects);
1322
1400
  // COUNTED PER CALL, NOT CUMULATIVELY, and both halves are returned. `xrefGhostById.size` is a running
1323
1401
  // total, so a caller reading it could not tell "I drew nothing" from "I drew nothing NEW" — and the
1324
1402
  // two skips below are silent by construction: an object whose tessellation came back empty, and one
@@ -1334,10 +1412,17 @@ function setReferenceGhosts(refId, objects, placement) {
1334
1412
  // back — and a second mesh at the same coordinates doubles the fill and leaves the first unreachable.
1335
1413
  if (xrefGhostById.has(gid)) continue;
1336
1414
  const g = new THREE.BufferGeometry();
1337
- g.setAttribute('position', new THREE.Float32BufferAttribute(o.positions, 3));
1415
+ const local = new Float32Array(o.positions.length);
1416
+ for (let i = 0; i + 2 < o.positions.length; i += 3) {
1417
+ local[i] = o.positions[i] - ghostAnchor[0];
1418
+ local[i + 1] = o.positions[i + 1] - ghostAnchor[1];
1419
+ local[i + 2] = o.positions[i + 2] - ghostAnchor[2];
1420
+ }
1421
+ g.setAttribute('position', new THREE.Float32BufferAttribute(local, 3));
1338
1422
  if (Array.isArray(o.indices) && o.indices.length) g.setIndex(o.indices);
1339
1423
  g.computeVertexNormals();
1340
1424
  const mesh = new THREE.Mesh(g, xrefGhostMat);
1425
+ mesh.position.set(ghostAnchor[0], ghostAnchor[1], ghostAnchor[2]);
1341
1426
  // NOT PICKABLE EVEN IF SOMETHING EVER RAYCASTS THE WHOLE SCENE. The parenting above is what makes
1342
1427
  // this true today; this is the belt to that pair of braces, and it costs one field.
1343
1428
  mesh.raycast = () => {};
@@ -1406,11 +1491,13 @@ function xrefSnapPoints(objects) {
1406
1491
  const seen = new Set(); const out = [];
1407
1492
  for (const o of objects || []) {
1408
1493
  const pos = o.positions || [];
1494
+ const a = Array.isArray(o.geometryAnchor) ? o.geometryAnchor : [0, 0, 0];
1409
1495
  for (let i = 0; i + 2 < pos.length; i += 3) {
1410
1496
  if (out.length >= XREF_SNAP_KEEP) return { points: out, capped: true }; // bail BEFORE allocating more
1411
- const k = `${Math.round(pos[i] / XREF_SNAP_QUANT_MM)},${Math.round(pos[i + 1] / XREF_SNAP_QUANT_MM)},${Math.round(pos[i + 2] / XREF_SNAP_QUANT_MM)}`;
1497
+ const x = pos[i] + a[0], y = pos[i + 1] + a[1], z = pos[i + 2] + a[2];
1498
+ const k = `${Math.round(x / XREF_SNAP_QUANT_MM)},${Math.round(y / XREF_SNAP_QUANT_MM)},${Math.round(z / XREF_SNAP_QUANT_MM)}`;
1412
1499
  if (seen.has(k)) continue;
1413
- seen.add(k); out.push([pos[i], pos[i + 1], pos[i + 2]]);
1500
+ seen.add(k); out.push([x, y, z]);
1414
1501
  }
1415
1502
  }
1416
1503
  return { points: out, capped: false };
@@ -1460,7 +1547,245 @@ function disposeReferenceMaterials() {
1460
1547
  * cache streaming in behind the native steel) simply carries no `objects` and renders nothing, which is
1461
1548
  * the honest encoding of "not here yet" and keeps project open from ever blocking on someone else's model.
1462
1549
  */
1550
+ function xrefAnchor(objects) {
1551
+ let lo = [Infinity, Infinity, Infinity], hi = [-Infinity, -Infinity, -Infinity];
1552
+ for (const o of objects || []) {
1553
+ const p = (Array.isArray(o?.positions) || ArrayBuffer.isView(o?.positions)) ? o.positions : [];
1554
+ const supplied = Array.isArray(o?.geometryAnchor) && o.geometryAnchor.length === 3 ? o.geometryAnchor : null;
1555
+ if (supplied) return supplied.slice();
1556
+ for (let i = 0; i + 2 < p.length; i += 3) {
1557
+ const x = Number(p[i]), y = Number(p[i + 1]), z = Number(p[i + 2]);
1558
+ if (!Number.isFinite(x) || !Number.isFinite(y) || !Number.isFinite(z)) continue;
1559
+ if (x < lo[0]) lo[0] = x; if (x > hi[0]) hi[0] = x;
1560
+ if (y < lo[1]) lo[1] = y; if (y > hi[1]) hi[1] = y;
1561
+ if (z < lo[2]) lo[2] = z; if (z > hi[2]) hi[2] = z;
1562
+ }
1563
+ }
1564
+ if (!Number.isFinite(lo[0])) return [0, 0, 0];
1565
+ return [(lo[0] + hi[0]) / 2, (lo[1] + hi[1]) / 2, (lo[2] + hi[2]) / 2];
1566
+ }
1567
+
1568
+ function xrefFragments(objects, anchor, bucket) {
1569
+ const fragments = [];
1570
+ for (let objectIndex = 0; objectIndex < objects.length; objectIndex++) {
1571
+ const o = objects[objectIndex];
1572
+ // Current v7 workers deliver colour-run-correct, bounded shards. One logical IFC object may span
1573
+ // several of them, but every shard maps back to the same object index for picking/Inspect.
1574
+ if (Array.isArray(o?.renderFragments)) {
1575
+ for (const fragment of o.renderFragments) {
1576
+ const authoredTransparent = fragment.authoredTransparent === true;
1577
+ if (bucket === 'opaque' && authoredTransparent || bucket === 'translucent' && !authoredTransparent) continue;
1578
+ fragments.push({
1579
+ objectIndex,
1580
+ positions: fragment.positions,
1581
+ indices: fragment.indices,
1582
+ colors: fragment.vertexColors,
1583
+ colorsNormalized: fragment.vertexColors instanceof Uint8Array,
1584
+ normals: fragment.normals,
1585
+ });
1586
+ }
1587
+ continue;
1588
+ }
1589
+ const src = (Array.isArray(o?.positions) || ArrayBuffer.isView(o?.positions)) ? o.positions : [];
1590
+ if (src.length < 9) continue;
1591
+ const localSource = Array.isArray(o.geometryAnchor);
1592
+ const positions = localSource && ArrayBuffer.isView(src) ? src : new Float32Array(src.length);
1593
+ if (positions !== src) for (let i = 0; i + 2 < src.length; i += 3) {
1594
+ positions[i] = src[i] - anchor[0]; positions[i + 1] = src[i + 1] - anchor[1]; positions[i + 2] = src[i + 2] - anchor[2];
1595
+ }
1596
+ const indices = (Array.isArray(o.indices) || ArrayBuffer.isView(o.indices)) && o.indices.length
1597
+ ? o.indices : Uint32Array.from({ length: positions.length / 3 }, (_, i) => i);
1598
+ const runs = Array.isArray(o.colors) && o.colors.length ? o.colors : [{ start: 0, count: indices.length, rgba: [0.58, 0.64, 0.72, 1] }];
1599
+ const authoredTransparent = o.authoredTransparent === true || runs.some((run) => (run.rgba?.[3] ?? 1) < 0.999);
1600
+ if (bucket === 'opaque' && authoredTransparent || bucket === 'translucent' && !authoredTransparent) continue;
1601
+ let colors = ArrayBuffer.isView(o.vertexColors) ? o.vertexColors : null;
1602
+ if (!colors) {
1603
+ colors = new Float32Array((positions.length / 3) * 4); for (let i = 0; i < colors.length; i += 4) { colors[i] = 0.58; colors[i + 1] = 0.64; colors[i + 2] = 0.72; colors[i + 3] = 1; }
1604
+ for (const run of runs) for (let at = Math.max(0, run.start | 0), end = Math.min(indices.length, (run.start | 0) + Math.max(0, run.count | 0)); at < end; at++) {
1605
+ const v = indices[at] * 4, rgba = run.rgba || [0.58, 0.64, 0.72, 1]; colors[v] = rgba[0]; colors[v + 1] = rgba[1]; colors[v + 2] = rgba[2]; colors[v + 3] = rgba[3];
1606
+ }
1607
+ }
1608
+ fragments.push({ objectIndex, positions, indices, colors, normals: ArrayBuffer.isView(o.vertexNormals) ? o.vertexNormals : null });
1609
+ }
1610
+ return fragments;
1611
+ }
1612
+
1613
+ function xrefBatchMaterial(kind) {
1614
+ const material = new THREE.MeshStandardMaterial({
1615
+ color: 0xffffff, vertexColors: true, metalness: 0, roughness: 0.95,
1616
+ transparent: kind !== 'opaque', opacity: 1, depthWrite: kind === 'opaque',
1617
+ side: kind === 'opaque' ? THREE.FrontSide : THREE.DoubleSide,
1618
+ });
1619
+ material.userData.alpha = 1;
1620
+ return material;
1621
+ }
1622
+
1623
+ async function xrefBuildBatch(refId, fragments, kind, anchor, alive) {
1624
+ if (!fragments.length) return null;
1625
+ const vertices = fragments.reduce((n, f) => n + f.positions.length / 3, 0);
1626
+ const indices = fragments.reduce((n, f) => n + f.indices.length, 0);
1627
+ const batch = new THREE.BatchedMesh(fragments.length, vertices, indices, xrefBatchMaterial(kind));
1628
+ // The binary cache already groups a whole reference behind one proven world bound. Walking every
1629
+ // object again on every frame to frustum-test it recreates the 18k-object CPU bottleneck the batch
1630
+ // exists to remove. Opaque and override batches need no object sort either; authored translucency
1631
+ // keeps sorting because painter order is part of its visual meaning.
1632
+ batch.perObjectFrustumCulled = false;
1633
+ batch.sortObjects = kind !== 'opaque';
1634
+ batch.name = `reference-${refId}-${kind}`;
1635
+ batch.position.set(anchor[0], anchor[1], anchor[2]);
1636
+ batch.renderOrder = -1;
1637
+ batch.userData.referenceId = refId;
1638
+ batch.userData.kind = kind;
1639
+ batch.userData.batchToObject = [];
1640
+ const identity = new THREE.Matrix4();
1641
+ try {
1642
+ for (let at = 0; at < fragments.length; at++) {
1643
+ if (alive && !alive()) { disposeXrefBatch(batch); return null; }
1644
+ const f = fragments[at];
1645
+ const g = new THREE.BufferGeometry();
1646
+ try {
1647
+ g.setAttribute('position', new THREE.BufferAttribute(f.positions, 3));
1648
+ g.setAttribute('color', new THREE.BufferAttribute(f.colors, 4, f.colorsNormalized === true));
1649
+ g.setIndex(new THREE.BufferAttribute(f.indices, 1));
1650
+ if (f.normals) g.setAttribute('normal', new THREE.BufferAttribute(f.normals, 3)); else g.computeVertexNormals();
1651
+ g.computeBoundingBox(); g.computeBoundingSphere();
1652
+ const geometryId = batch.addGeometry(g);
1653
+ const instanceId = batch.addInstance(geometryId);
1654
+ batch.setMatrixAt(instanceId, identity);
1655
+ batch.userData.batchToObject[instanceId] = f.objectIndex;
1656
+ } finally { g.dispose(); }
1657
+ // BatchedMesh copies each object's attributes into its GPU-sized backing buffers. Yielding at a
1658
+ // bounded cadence turns the old multi-second long task into ordinary frames while keeping the
1659
+ // half-built batch detached: the reference swaps onto the canvas only when it is complete.
1660
+ // A zero-delay task yield is deliberate. requestAnimationFrame is throttled to roughly 1 Hz when
1661
+ // an editor iframe is backgrounded, which turned a safe 47-yield upload into a minute-long one.
1662
+ if (at && at % 64 === 0) await new Promise((resolve) => setTimeout(resolve, 0));
1663
+ }
1664
+ batch.computeBoundingBox(); batch.computeBoundingSphere();
1665
+ return batch;
1666
+ } catch (error) {
1667
+ // `addGeometry` can throw after allocating the batch's full backing buffers. The caller cannot see
1668
+ // this local until the promise resolves, so this function owns releasing it on every thrown path.
1669
+ disposeXrefBatch(batch);
1670
+ throw error;
1671
+ }
1672
+ }
1673
+
1674
+ function disposeXrefEntry(entry) {
1675
+ if (!entry) return;
1676
+ entry.disposed = true;
1677
+ entry.group?.traverse?.((o) => { if (o.isMesh) { if (o.isBatchedMesh) o.dispose?.(); else o.geometry?.dispose?.(); const ms = Array.isArray(o.material) ? o.material : [o.material]; ms.forEach((m) => m?.dispose?.()); } });
1678
+ entry.flat?.dispose?.();
1679
+ for (const material of entry.mats?.values?.() || []) material?.dispose?.();
1680
+ entry.group?.parent?.remove(entry.group);
1681
+ }
1682
+
1683
+ function disposeXrefBatch(batch) {
1684
+ if (!batch) return;
1685
+ batch.parent?.remove(batch);
1686
+ // BatchedMesh owns matrix/indirect/colour textures in addition to its geometry. Calling only the
1687
+ // geometry disposer leaks those textures on every topology switch and every cancelled replacement.
1688
+ if (batch.isBatchedMesh) batch.dispose?.(); else batch.geometry?.dispose?.();
1689
+ const materials = Array.isArray(batch.material) ? batch.material : [batch.material];
1690
+ materials.forEach((material) => material?.dispose?.());
1691
+ }
1692
+
1693
+ const pendingXrefReplacements = new Map();
1694
+ let pendingFrameReference = null;
1695
+
1696
+ function cancelStagedReference(id, staged, reason, options = {}) {
1697
+ if (!staged) return;
1698
+ if (pendingXrefReplacements.get(id) === staged) pendingXrefReplacements.delete(id);
1699
+ staged.onTopologyReady = null;
1700
+ disposeXrefEntry(staged);
1701
+ // The editor owns the promise waiting for this exact object array. Teardown must resolve that promise
1702
+ // without asking the editor to push a replacement back into a renderer that is actively disposing.
1703
+ if (options.resolutionOnly) api?.onReferenceGeometryCancel?.(staged.objects);
1704
+ else if (api?.onReferenceGeometryError) api.onReferenceGeometryError(id, staged.objects, reason);
1705
+ }
1706
+
1707
+ function createBatchedReference(ref) {
1708
+ const objects = Array.isArray(ref.objects) ? ref.objects : [];
1709
+ const anchor = xrefAnchor(objects);
1710
+ const group = new THREE.Group();
1711
+ group.userData.referenceId = ref.id;
1712
+ group.applyMatrix4(xrefMatrix(ref.placement));
1713
+ const { points, capped: keptCapped } = xrefSnapPoints(objects);
1714
+ const seen = new Set(), dupIds = new Set(), byGlobalId = new Map();
1715
+ for (let i = 0; i < objects.length; i++) {
1716
+ const gid = typeof objects[i]?.globalId === 'string' && objects[i].globalId ? objects[i].globalId : null;
1717
+ if (gid === null) continue;
1718
+ if (seen.has(gid)) dupIds.add(gid); else seen.add(gid);
1719
+ byGlobalId.set(gid, i);
1720
+ }
1721
+ return {
1722
+ batched: true, group, combined: null, opaque: null, translucent: null, anchor,
1723
+ display: ref.display || {}, name: ref.name || ref.id, objects,
1724
+ points, total: points.length, capped: keptCapped, keptCapped, dupIds, byGlobalId,
1725
+ mats: new Map(), flat: xrefBatchMaterial('combined'), painted: null,
1726
+ pendingTopologies: new Set(), resolvedTopologies: new Set(), activeTopology: null,
1727
+ desiredTopology: 'combined', staging: false, disposed: false, onTopologyReady: null,
1728
+ };
1729
+ }
1730
+
1731
+ /** Incremental BatchedMesh reference reconciliation. Unchanged object arrays retain their GPU entry. */
1463
1732
  function setReferences(list) {
1733
+ // Keep the established one-mesh path as a compatibility fallback for a host that supplies an older
1734
+ // Three build. Current FloLess ships BatchedMesh, so production takes the bounded-draw path below.
1735
+ if (typeof THREE.BatchedMesh !== 'function') return _legacySetReferences(list);
1736
+ refMeasureCands = null; invalidateClipFloor();
1737
+ if (!scene) return;
1738
+ if (!xrefGroup) { xrefGroup = new THREE.Group(); scene.add(xrefGroup); }
1739
+ const desired = new Map((list || []).filter((r) => r?.id).map((r) => [r.id, r]));
1740
+ const prevObjects = new Map([...xrefById].map(([id, e]) => [id, e.objects]));
1741
+ for (const [id, entry] of [...xrefById]) {
1742
+ const ref = desired.get(id);
1743
+ if (!ref) { disposeXrefEntry(entry); xrefById.delete(id); }
1744
+ }
1745
+ for (const ref of desired.values()) {
1746
+ let entry = xrefById.get(ref.id);
1747
+ if (!entry || entry.objects !== ref.objects) {
1748
+ let staged = pendingXrefReplacements.get(ref.id);
1749
+ if (staged && staged.objects === ref.objects) {
1750
+ staged.name = ref.name || ref.id;
1751
+ setReferencePlacement(ref.id, ref.placement || null);
1752
+ applyReferenceDisplay(ref.id, ref.display || {});
1753
+ continue;
1754
+ }
1755
+ if (staged) cancelStagedReference(ref.id, staged, 'a newer geometry load replaced this upload');
1756
+ staged = createBatchedReference(ref); staged.staging = true;
1757
+ pendingXrefReplacements.set(ref.id, staged);
1758
+ staged.onTopologyReady = () => {
1759
+ if (pendingXrefReplacements.get(ref.id) !== staged || staged.disposed) return;
1760
+ pendingXrefReplacements.delete(ref.id); staged.staging = false; staged.onTopologyReady = null;
1761
+ const old = xrefById.get(ref.id);
1762
+ xrefGroup.add(staged.group); xrefById.set(ref.id, staged);
1763
+ applyReferenceDisplay(ref.id, staged.display);
1764
+ if (old && old !== staged) disposeXrefEntry(old);
1765
+ const selectedObjectWasHere = xrefSubSelected?.refId === ref.id;
1766
+ revalidateSubSelection(new Map(old ? [[ref.id, old.objects]] : []));
1767
+ paintReferenceSelection(); paintReferenceSubSelection();
1768
+ if (selectedObjectWasHere) emitReferenceSelect();
1769
+ if (api?.onReferenceGeometryCommit) api.onReferenceGeometryCommit(ref.id, staged.objects);
1770
+ if (pendingFrameReference === ref.id) { pendingFrameReference = null; frameReference(ref.id); }
1771
+ };
1772
+ ensureXrefTopology(staged, ref.id);
1773
+ continue;
1774
+ } else {
1775
+ entry.group.matrix.identity(); entry.group.matrixAutoUpdate = false; entry.group.applyMatrix4(xrefMatrix(ref.placement));
1776
+ entry.name = ref.name || ref.id;
1777
+ }
1778
+ applyReferenceDisplay(ref.id, ref.display || {});
1779
+ }
1780
+ for (const [id, staged] of [...pendingXrefReplacements]) if (!desired.has(id)) {
1781
+ cancelStagedReference(id, staged, 'the reference was removed before its geometry finished uploading');
1782
+ }
1783
+ if (xrefSelected && !xrefById.has(xrefSelected)) xrefSelected = null;
1784
+ revalidateSubSelection(prevObjects);
1785
+ paintReferenceSelection(); paintReferenceSubSelection();
1786
+ }
1787
+
1788
+ function _legacySetReferences(list) {
1464
1789
  refMeasureCands = null; // the measure's frustum-filtered snap set is derived from this — see setReferencePlacement
1465
1790
  invalidateClipFloor(); // the reference layer IS part of the clip-box floor: a reference arriving, being re-read, hidden or removed moves it
1466
1791
 
@@ -1660,8 +1985,8 @@ function revalidateSubSelection(prevObjects) {
1660
1985
  // The cheap, total answer first: nothing was re-read, so nothing can have moved.
1661
1986
  const prev = prevObjects && prevObjects.get(xrefSubSelected.refId);
1662
1987
  if (prev && prev === entry.objects) {
1663
- const held = entry.group.children[xrefSubSelected.index];
1664
- if (!held || !held.isMesh) xrefSubSelected = null;
1988
+ const held = entry.batched ? entry.objects?.[xrefSubSelected.index] : entry.group.children[xrefSubSelected.index];
1989
+ if (!held || (!entry.batched && !held.isMesh)) xrefSubSelected = null;
1665
1990
  return;
1666
1991
  }
1667
1992
  // A GENUINE RE-READ. Find the object by IDENTITY and move the selection to wherever it now sits —
@@ -1671,12 +1996,68 @@ function revalidateSubSelection(prevObjects) {
1671
1996
  if (gid === null || gid === undefined || entry.dupIds.has(gid)) { xrefSubSelected = null; return; }
1672
1997
  const index = entry.byGlobalId.get(gid);
1673
1998
  if (index === undefined) { xrefSubSelected = null; return; }
1674
- const mesh = entry.group.children[index];
1675
- if (!mesh || !mesh.isMesh) { xrefSubSelected = null; return; }
1999
+ const object = entry.objects?.[index];
2000
+ if (!object) { xrefSubSelected = null; return; }
1676
2001
  // REMAPPED, and `objectId` is refreshed with it: `id` may legitimately differ between two reads of
1677
2002
  // the same object (it falls back to the expressID), so carrying the old one forward would leave the
1678
2003
  // panel addressing a slot by a number this read never used.
1679
- xrefSubSelected = { refId: xrefSubSelected.refId, index, objectId: mesh.userData.objectId ?? null, globalId: gid };
2004
+ xrefSubSelected = { refId: xrefSubSelected.refId, index, objectId: object.id || null, globalId: gid };
2005
+ }
2006
+
2007
+ function ensureXrefTopology(entry, refId) {
2008
+ if (!entry?.batched) return;
2009
+ const topology = 'combined';
2010
+ if (entry.resolvedTopologies.has(topology)) return;
2011
+ if (entry.pendingTopologies.has(topology)) return;
2012
+ if (entry.combined) return;
2013
+ entry.pendingTopologies.add(topology);
2014
+ const alive = () => !entry.disposed && (entry.staging ? pendingXrefReplacements.get(refId) === entry : xrefById.get(refId) === entry);
2015
+ void (async () => {
2016
+ let completed = false;
2017
+ let combined = null;
2018
+ let expectedDrawable = false;
2019
+ try {
2020
+ const combinedFragments = xrefFragments(entry.objects, entry.anchor, 'combined');
2021
+ expectedDrawable = combinedFragments.length > 0;
2022
+ combined = await xrefBuildBatch(refId, combinedFragments, 'combined', entry.anchor, alive);
2023
+ if (!alive() || entry.desiredTopology !== topology) {
2024
+ disposeXrefBatch(combined);
2025
+ return;
2026
+ }
2027
+ if (expectedDrawable && !combined) {
2028
+ throw new Error('the decoded reference contained no drawable triangles');
2029
+ }
2030
+ // One combined topology serves File, Grey and custom colours. A colour-mode click now changes
2031
+ // material state only: it never repeats the building-sized GPU upload or retains a second copy.
2032
+ if (combined) entry.group.add(combined);
2033
+ entry.combined = combined;
2034
+ entry.activeTopology = topology;
2035
+ completed = true;
2036
+ } catch (error) {
2037
+ console.error('[reference] batched geometry upload failed', refId, error);
2038
+ disposeXrefBatch(combined);
2039
+ if (entry.staging && pendingXrefReplacements.get(refId) === entry) {
2040
+ // A staged replacement is deliberately detached, so the old entry is still the honest picture.
2041
+ // Cancel this replacement and tell the editor to restore the metadata array that picture uses;
2042
+ // otherwise Inspect describes the new file while the canvas continues to show the old one.
2043
+ pendingXrefReplacements.delete(refId);
2044
+ entry.onTopologyReady = null;
2045
+ disposeXrefEntry(entry);
2046
+ if (api?.onReferenceGeometryError) api.onReferenceGeometryError(
2047
+ refId, entry.objects, error?.message || 'the graphics device could not upload the reference',
2048
+ );
2049
+ } else if (api?.toast) api.toast('Could not update that reference view — keeping the previous view');
2050
+ } finally {
2051
+ entry.pendingTopologies.delete(topology);
2052
+ // A display pass may have run while no finished batch existed. Force the first pass over the
2053
+ // newly attached material so Grey/custom state cannot inherit the builder's file-colour default.
2054
+ if (alive() && completed) {
2055
+ entry.resolvedTopologies.add(topology);
2056
+ entry.painted = null;
2057
+ if (entry.onTopologyReady) entry.onTopologyReady(); else applyReferenceDisplay(refId, entry.display);
2058
+ }
2059
+ }
2060
+ })();
1680
2061
  }
1681
2062
 
1682
2063
  /**
@@ -1692,10 +2073,16 @@ function revalidateSubSelection(prevObjects) {
1692
2073
  * unlocked one.
1693
2074
  */
1694
2075
  function applyReferenceDisplay(id, display) {
2076
+ const staged = pendingXrefReplacements.get(id);
2077
+ if (staged) {
2078
+ staged.display = display || {};
2079
+ staged.group.visible = staged.display.visible !== false;
2080
+ ensureXrefTopology(staged, id);
2081
+ }
1695
2082
  const entry = xrefById.get(id); if (!entry) return;
1696
2083
  entry.display = display || {};
1697
2084
  const visible = entry.display.visible !== false;
1698
- const opacity = Number.isFinite(entry.display.opacity) ? Math.max(0, Math.min(1, entry.display.opacity)) : 0.5;
2085
+ const opacity = Number.isFinite(entry.display.opacity) ? Math.max(0, Math.min(1, entry.display.opacity)) : XREF_DEFAULT_OPACITY;
1699
2086
  entry.group.visible = visible;
1700
2087
  invalidateClipFloor(); // visibility decides whether this reference counts towards the clip-box floor at all — the eye toggle moves it
1701
2088
 
@@ -1711,6 +2098,49 @@ function applyReferenceDisplay(id, display) {
1711
2098
  const dropped = !visible && !!xrefSubSelected && xrefSubSelected.refId === id;
1712
2099
  if (dropped) { xrefSubSelected = null; paintReferenceSubSelection(); }
1713
2100
 
2101
+ if (entry.batched) {
2102
+ const mode = xrefMode(entry.display), custom = xrefCustom(entry.display);
2103
+ const shape = mode === 'file' ? 'file' : 'flat';
2104
+ const exactOpaque = opacity >= 0.999999;
2105
+ ensureXrefTopology(entry, id);
2106
+ if (entry.painted !== shape || (shape === 'flat' && entry.paintedHex !== (mode === 'custom' && custom !== null ? custom : XREF_COLOR))) {
2107
+ const flatHex = mode === 'custom' && custom !== null ? custom : XREF_COLOR;
2108
+ const flat = new THREE.Color(flatHex);
2109
+ for (const batch of [entry.combined, entry.opaque, entry.translucent]) {
2110
+ if (!batch) continue;
2111
+ batch.material.vertexColors = shape === 'file';
2112
+ batch.material.color.copy(shape === 'file' ? new THREE.Color(0xffffff) : flat);
2113
+ batch.material.needsUpdate = true;
2114
+ }
2115
+ entry.painted = shape; entry.paintedHex = flatHex;
2116
+ }
2117
+ if (entry.combined) {
2118
+ entry.combined.visible = entry.activeTopology === 'combined';
2119
+ // 100% means fully opaque in every colour mode, including File. Authored alpha remains in the
2120
+ // decoded colour data but does not silently turn the default into a transparent blend mode.
2121
+ const opaqueCombined = exactOpaque;
2122
+ const m = entry.combined.material;
2123
+ m.opacity = opaqueCombined ? 1 : opacity;
2124
+ m.transparent = !opaqueCombined;
2125
+ m.depthWrite = opaqueCombined;
2126
+ m.side = opaqueCombined ? THREE.FrontSide : THREE.DoubleSide;
2127
+ // At the 100% default the combined topology is genuinely opaque, so
2128
+ // Three's per-frame object sort is pure O(N log N) work over all 18k fragments. Turn it back on
2129
+ // only when this same topology is actually translucent and painter order has visual meaning.
2130
+ entry.combined.sortObjects = !opaqueCombined;
2131
+ m.needsUpdate = true;
2132
+ }
2133
+ if (xrefSubMats && xrefSubMesh?.userData.referenceId === id) {
2134
+ for (const material of xrefSubMats) {
2135
+ material.opacity = Math.max(opacity, XREF_SUB_MIN_OPACITY);
2136
+ material.needsUpdate = true;
2137
+ }
2138
+ }
2139
+ paintReferenceSelection();
2140
+ if (dropped) emitReferenceSelect();
2141
+ return;
2142
+ }
2143
+
1714
2144
  // ONLY A CHANGE OF SHAPE RE-MATERIALS, and "shape" means file-colours-vs-one-colour, NOT which
1715
2145
  // colour. Both the opacity slider and the colour picker fire on every pointer move, and reassigning
1716
2146
  // `mesh.material` across 17,000 meshes per move would turn either drag into a slideshow.
@@ -1733,8 +2163,16 @@ function applyReferenceDisplay(id, display) {
1733
2163
  // position. Only in `file` mode: overriding the colour means "paint this whole model one colour",
1734
2164
  // and keeping per-object alpha under an override would leave it patchy for no reason the user
1735
2165
  // could act on.
1736
- for (const m of entry.mats.values()) { m.opacity = opacity * m.userData.alpha; m.needsUpdate = true; }
1737
- entry.flat.opacity = opacity; entry.flat.needsUpdate = true;
2166
+ for (const m of entry.mats.values()) {
2167
+ const effective = opacity * m.userData.alpha;
2168
+ const opaque = effective >= 0.999999;
2169
+ m.opacity = effective; m.transparent = !opaque; m.depthWrite = opaque;
2170
+ m.side = opaque ? THREE.FrontSide : THREE.DoubleSide; m.needsUpdate = true;
2171
+ }
2172
+ entry.flat.opacity = opacity;
2173
+ entry.flat.transparent = opacity < 0.999999; entry.flat.depthWrite = opacity >= 0.999999;
2174
+ entry.flat.side = opacity >= 0.999999 ? THREE.FrontSide : THREE.DoubleSide;
2175
+ entry.flat.needsUpdate = true;
1738
2176
 
1739
2177
  // KEEP THE DRILLED-INTO OBJECT'S CLONES IN STEP, and choose the cheap path unless the expensive one
1740
2178
  // is actually required. A repaint reassigned every mesh's material, so the clones are now orphaned and
@@ -1773,9 +2211,10 @@ function xrefMaterial(entry, rgb, alpha) {
1773
2211
  }
1774
2212
 
1775
2213
  function newXrefMaterial(rgb, alpha) {
2214
+ const opaque = alpha >= 0.999999;
1776
2215
  const m = new THREE.MeshStandardMaterial({
1777
2216
  color: rgb, metalness: 0, roughness: 0.95,
1778
- transparent: true, opacity: 1, depthWrite: false, side: THREE.DoubleSide,
2217
+ transparent: !opaque, opacity: 1, depthWrite: opaque, side: opaque ? THREE.FrontSide : THREE.DoubleSide,
1779
2218
  });
1780
2219
  m.userData.alpha = alpha;
1781
2220
  return m;
@@ -1825,6 +2264,13 @@ function xrefBaseMaterial(entry, mesh, shape) {
1825
2264
  * not pay that on every keystroke — a transform is a 4×4 matrix, so it is applied as one.
1826
2265
  */
1827
2266
  function setReferencePlacement(id, placement) {
2267
+ const staged = pendingXrefReplacements.get(id);
2268
+ if (staged) {
2269
+ staged.group.matrix.identity();
2270
+ staged.group.position.set(0, 0, 0); staged.group.quaternion.identity(); staged.group.scale.set(1, 1, 1);
2271
+ staged.group.applyMatrix4(xrefMatrix(placement));
2272
+ staged.group.updateMatrixWorld(true);
2273
+ }
1828
2274
  const entry = xrefById.get(id); if (!entry) return;
1829
2275
  // THE OLD MATRIX, kept because three pieces of Stage D state are expressed in the world space it
1830
2276
  // defines. This function is the ONLY writer of that matrix, which is why the invalidation belongs
@@ -1903,7 +2349,8 @@ function paintReferenceSelection() {
1903
2349
  // several meshes share each one. Walking the entry's materials reaches every one exactly once and
1904
2350
  // cannot miss the members of an array the way `o.material.emissive` silently did. `flat` is not in
1905
2351
  // `mats` and must be lifted too, or selecting an OVERRIDDEN reference would highlight nothing.
1906
- for (const m of [...entry.mats.values(), entry.flat]) {
2352
+ const batchMats = entry.batched ? [entry.combined?.material, entry.opaque?.material, entry.translucent?.material].filter(Boolean) : [];
2353
+ for (const m of [...entry.mats.values(), entry.flat, ...batchMats]) {
1907
2354
  m.emissive.setHex(on ? 0xe2e8f0 : 0x000000);
1908
2355
  m.emissiveIntensity = on ? 0.35 : 0;
1909
2356
  }
@@ -1927,8 +2374,8 @@ function paintReferenceSelection() {
1927
2374
  * (`xrefBaseMaterial`). At most a handful of materials exist at a time — one per colour run of ONE
1928
2375
  * object — and they are disposed the moment the selection moves.
1929
2376
  */
1930
- let xrefSubMats = null; // the clone(s) currently painted on the sub-selected mesh
1931
- let xrefSubMesh = null; // the mesh they are painted on, so the restore never has to guess
2377
+ let xrefSubMats = null; // the clone(s) currently painted on the sub-selected mesh/overlay
2378
+ let xrefSubMesh = null; // the mesh or batched overlay they are painted on, so release never has to guess
1932
2379
 
1933
2380
  function paintReferenceSubSelection() {
1934
2381
  // RELEASE FIRST, ALWAYS — including when the new selection is the same mesh. A colour-MODE change
@@ -1937,13 +2384,72 @@ function paintReferenceSubSelection() {
1937
2384
  // (An opacity drag does NOT reach here — `applyReferenceDisplay` copies onto the existing clones in
1938
2385
  // place precisely so a drag allocates nothing. An earlier draft of this comment named it anyway.)
1939
2386
  if (xrefSubMesh) {
2387
+ const overlay = xrefSubMesh.userData?.batchedOverlay;
1940
2388
  const prev = xrefById.get(xrefSubMesh.userData.referenceId);
1941
- if (prev) xrefSubMesh.material = xrefBaseMaterial(prev, xrefSubMesh, prev.painted);
2389
+ if (overlay) {
2390
+ xrefSubMesh.parent?.remove(xrefSubMesh);
2391
+ // A logical IFC object may have several colour-correct render fragments. Their tiny wrapper
2392
+ // geometries share the worker's typed arrays; disposing the wrappers releases only GPU state.
2393
+ xrefSubMesh.traverse?.((o) => { if (o.isMesh) o.geometry?.dispose?.(); });
2394
+ }
2395
+ else if (prev) xrefSubMesh.material = xrefBaseMaterial(prev, xrefSubMesh, prev.painted);
1942
2396
  for (const m of xrefSubMats || []) m.dispose?.();
1943
2397
  xrefSubMesh = null; xrefSubMats = null;
1944
2398
  }
1945
2399
  if (!xrefSubSelected) return;
1946
2400
  const entry = xrefById.get(xrefSubSelected.refId);
2401
+ if (entry?.batched) {
2402
+ const object = entry.objects?.[xrefSubSelected.index];
2403
+ if (!object) return;
2404
+ const fragments = Array.isArray(object.renderFragments) ? object.renderFragments : [];
2405
+ const mode = xrefMode(entry.display), fileColors = mode === 'file';
2406
+ const baseColor = fileColors ? 0xffffff : (mode === 'custom' && xrefCustom(entry.display) !== null ? xrefCustom(entry.display) : XREF_COLOR);
2407
+ const m = new THREE.MeshStandardMaterial({ color: baseColor, vertexColors: fileColors, emissive: XREF_SUB_EMISSIVE,
2408
+ emissiveIntensity: XREF_SUB_INTENSITY, transparent: true,
2409
+ opacity: Math.max(Number.isFinite(entry.display?.opacity) ? entry.display.opacity : XREF_DEFAULT_OPACITY, XREF_SUB_MIN_OPACITY),
2410
+ depthWrite: false, side: THREE.DoubleSide });
2411
+ if (fragments.length) {
2412
+ // Do not copy/re-normal a potentially enormous slab on every click. The worker already produced
2413
+ // anchored, colour-correct shards with normals for the batch; a selected-object overlay can point
2414
+ // at those same immutable arrays and be ready within the interaction frame budget.
2415
+ const overlay = new THREE.Group();
2416
+ overlay.position.set(entry.anchor[0], entry.anchor[1], entry.anchor[2]);
2417
+ overlay.renderOrder = 2;
2418
+ overlay.userData = { referenceId: xrefSubSelected.refId, objectIndex: xrefSubSelected.index,
2419
+ objectId: object.id || null, globalId: object.globalId || null, batchedOverlay: true };
2420
+ for (const fragment of fragments) {
2421
+ const g = new THREE.BufferGeometry();
2422
+ g.setAttribute('position', new THREE.BufferAttribute(fragment.positions, 3));
2423
+ if (fileColors && fragment.vertexColors) g.setAttribute('color', new THREE.BufferAttribute(fragment.vertexColors, 4, true));
2424
+ if (fragment.normals) g.setAttribute('normal', new THREE.BufferAttribute(fragment.normals, 3)); else g.computeVertexNormals();
2425
+ if (fragment.indices?.length) g.setIndex(new THREE.BufferAttribute(fragment.indices, 1));
2426
+ const mesh = new THREE.Mesh(g, m);
2427
+ mesh.renderOrder = 2;
2428
+ mesh.userData = overlay.userData;
2429
+ overlay.add(mesh);
2430
+ }
2431
+ entry.group.add(overlay); xrefSubMesh = overlay; xrefSubMats = [m];
2432
+ return;
2433
+ }
2434
+ const positions = (Array.isArray(object.positions) || ArrayBuffer.isView(object.positions)) ? object.positions : [];
2435
+ const localSource = Array.isArray(object.geometryAnchor) && object.geometryAnchor.length === 3;
2436
+ const local = new Float32Array(positions.length);
2437
+ for (let i = 0; i + 2 < positions.length; i += 3) {
2438
+ local[i] = positions[i] - (localSource ? 0 : entry.anchor[0]); local[i + 1] = positions[i + 1] - (localSource ? 0 : entry.anchor[1]); local[i + 2] = positions[i + 2] - (localSource ? 0 : entry.anchor[2]);
2439
+ }
2440
+ const g = new THREE.BufferGeometry();
2441
+ g.setAttribute('position', new THREE.BufferAttribute(local, 3));
2442
+ if (ArrayBuffer.isView(object.indices) && object.indices.length) g.setIndex(new THREE.BufferAttribute(object.indices, 1));
2443
+ else if (Array.isArray(object.indices) && object.indices.length) g.setIndex(object.indices);
2444
+ g.computeVertexNormals();
2445
+ const mesh = new THREE.Mesh(g, m);
2446
+ mesh.position.set(entry.anchor[0], entry.anchor[1], entry.anchor[2]);
2447
+ mesh.renderOrder = 2;
2448
+ mesh.userData = { referenceId: xrefSubSelected.refId, objectIndex: xrefSubSelected.index,
2449
+ objectId: object.id || null, globalId: object.globalId || null, batchedOverlay: true };
2450
+ entry.group.add(mesh); xrefSubMesh = mesh; xrefSubMats = [m];
2451
+ return;
2452
+ }
1947
2453
  const mesh = entry && entry.group.children[xrefSubSelected.index];
1948
2454
  if (!mesh || !mesh.isMesh) return;
1949
2455
  const base = xrefBaseMaterial(entry, mesh, entry.painted);
@@ -1988,13 +2494,16 @@ function pickReferenceAt(cx, cy) {
1988
2494
  if (!hit) return null;
1989
2495
  const u = hit.object.userData || {};
1990
2496
  if (!u.referenceId) return null;
2497
+ const batchedIndex = Number.isInteger(hit.batchId) && Array.isArray(u.batchToObject)
2498
+ ? u.batchToObject[hit.batchId] : null;
2499
+ const batchedObject = Number.isInteger(batchedIndex) ? xrefById.get(u.referenceId)?.objects?.[batchedIndex] : null;
1991
2500
  // AN OBJECT-SHAPED ANSWER, ALWAYS — never the bare id this used to return. Both callers want to know
1992
2501
  // WHICH object was under the pointer as well as which reference, and a function that answered one of
1993
2502
  // those questions with a string and the other with an object would be read wrong exactly once.
1994
2503
  return {
1995
2504
  referenceId: u.referenceId,
1996
- objectId: u.objectId ?? null,
1997
- objectIndex: Number.isInteger(u.objectIndex) ? u.objectIndex : -1,
2505
+ objectId: batchedObject?.id ?? u.objectId ?? null,
2506
+ objectIndex: Number.isInteger(batchedIndex) ? batchedIndex : (Number.isInteger(u.objectIndex) ? u.objectIndex : -1),
1998
2507
  };
1999
2508
  }
2000
2509
 
@@ -2026,17 +2535,17 @@ function selectReference(id) {
2026
2535
  /**
2027
2536
  * Drill into ONE object inside a reference.
2028
2537
  *
2029
- * Returns false and selects nothing when the index does not name a mesh — a stale index from a tree row
2030
- * built before a reload, say. Falling back to "select the whole reference" would be worse than refusing:
2538
+ * Returns false and selects nothing when the index does not name a logical object — a stale index from a
2539
+ * tree row built before a reload, say. Falling back to "select the whole reference" would be worse than refusing:
2031
2540
  * the caller asked for an object, and quietly answering a different question is how a panel comes to
2032
2541
  * describe something the user did not pick.
2033
2542
  */
2034
2543
  function selectReferenceObject(refId, index) {
2035
2544
  const entry = xrefById.get(refId);
2036
- const mesh = entry && Number.isInteger(index) && index >= 0 ? entry.group.children[index] : null;
2037
- if (!mesh || !mesh.isMesh) return false;
2545
+ const object = entry && Number.isInteger(index) && index >= 0 ? entry.objects?.[index] : null;
2546
+ if (!object) return false;
2038
2547
  xrefSelected = refId;
2039
- xrefSubSelected = { refId, index, objectId: mesh.userData.objectId ?? null, globalId: mesh.userData.globalId ?? null };
2548
+ xrefSubSelected = { refId, index, objectId: object.id || null, globalId: object.globalId || null };
2040
2549
  paintReferenceSelection();
2041
2550
  paintReferenceSubSelection();
2042
2551
  emitReferenceSelect();
@@ -2085,8 +2594,9 @@ function referenceProbe(id) {
2085
2594
  const ms = Array.isArray(o.material) ? o.material : (o.material ? [o.material] : []);
2086
2595
  if (Array.isArray(o.material)) { arrayMeshes++; runs += o.material.length; }
2087
2596
  for (const m of ms) inUse.add(m);
2088
- if (ms.some((m) => m.emissiveIntensity > 0)) lit.push(o.userData.objectIndex);
2597
+ if (!entry.batched && ms.some((m) => m.emissiveIntensity > 0)) lit.push(o.userData.objectIndex);
2089
2598
  });
2599
+ if (entry.batched && xrefSubSelected?.refId === id) lit.push(xrefSubSelected.index);
2090
2600
  return {
2091
2601
  mode: xrefMode(entry.display), painted: entry.painted,
2092
2602
  meshes, arrayMeshes, runs, materials: inUse.size, cached: entry.mats.size,
@@ -2132,7 +2642,10 @@ function referenceBounds(id) {
2132
2642
  */
2133
2643
  function frameReference(id) {
2134
2644
  const b = referenceBounds(id); // measures regardless of visibility, so this frames a hidden reference too
2135
- if (!b) return false;
2645
+ if (!b) {
2646
+ if (pendingXrefReplacements.has(id)) pendingFrameReference = id;
2647
+ return false;
2648
+ }
2136
2649
  fitCamera(new THREE.Box3(new THREE.Vector3(...b.min), new THREE.Vector3(...b.max)));
2137
2650
  return true;
2138
2651
  }
@@ -2146,19 +2659,26 @@ function frameReference(id) {
2146
2659
  *
2147
2660
  * SEPARATE FROM THE SELECTION rather than folded into it, so the canvas gesture keeps its behaviour
2148
2661
  * exactly: two callers, two questions, and the panel is the only one that asks the camera to move.
2149
- * Returns false when the index does not name a mesh — the same refusal, for the same reason, as
2662
+ * Returns false when the index does not name a logical object — the same refusal, for the same reason, as
2150
2663
  * `selectReferenceObject`: quietly framing something else is worse than not moving.
2151
2664
  */
2152
2665
  function frameReferenceObject(refId, index) {
2153
2666
  const entry = xrefById.get(refId);
2154
- const mesh = entry && Number.isInteger(index) && index >= 0 ? entry.group.children[index] : null;
2155
- if (!mesh || !mesh.isMesh) return false;
2156
- const box = new THREE.Box3().setFromObject(mesh);
2667
+ if (!entry || !Number.isInteger(index) || index < 0 || !entry.objects?.[index]) return false;
2668
+ const box = xrefObjectWorldBox(entry, index);
2157
2669
  if (box.isEmpty()) return false;
2158
2670
  fitCamera(box);
2159
2671
  return true;
2160
2672
  }
2161
2673
 
2674
+ function xrefObjectWorldBox(entry, index) {
2675
+ const box = new THREE.Box3(), p = entry.objects?.[index]?.positions || [];
2676
+ const v = new THREE.Vector3(); entry.group.updateMatrixWorld(true);
2677
+ const local = Array.isArray(entry.objects?.[index]?.geometryAnchor);
2678
+ for (let i = 0; i + 2 < p.length; i += 3) box.expandByPoint(v.set(p[i] + (local ? entry.anchor[0] : 0), p[i + 1] + (local ? entry.anchor[1] : 0), p[i + 2] + (local ? entry.anchor[2] : 0)).applyMatrix4(entry.group.matrixWorld));
2679
+ return box;
2680
+ }
2681
+
2162
2682
  /**
2163
2683
  * The reference snap candidates for a drag, in the shape `snapPoint` consumes.
2164
2684
  *
@@ -2224,17 +2744,33 @@ function referenceCandidates(onlyId) {
2224
2744
 
2225
2745
  /** Test/panel probe: what the layer is actually holding, per reference. */
2226
2746
  function referenceInfo() {
2227
- return [...xrefById.entries()].map(([id, e]) => ({
2228
- id, name: e.name,
2229
- meshes: e.group.children.length,
2230
- visible: e.group.visible,
2231
- opacity: e.group.children[0]?.material?.opacity ?? null,
2232
- snap: e.display.snap !== false,
2233
- locked: !!e.display.locked,
2234
- selected: id === xrefSelected,
2235
- snapPoints: e.total, snapCapped: e.capped || !!e.keptCapped,
2236
- bounds: referenceBounds(id),
2237
- }));
2747
+ return [...xrefById.entries()].map(([id, e]) => {
2748
+ const draws = e.group.children.filter((child) => child.visible && child.isMesh);
2749
+ const materials = draws.flatMap((draw) => (Array.isArray(draw.material) ? draw.material : [draw.material]).map((material) => ({
2750
+ kind: draw.userData?.kind || null,
2751
+ opacity: material.opacity,
2752
+ transparent: material.transparent,
2753
+ depthWrite: material.depthWrite,
2754
+ side: material.side === THREE.FrontSide ? 'front' : material.side === THREE.DoubleSide ? 'double' : 'back',
2755
+ })));
2756
+ const materialOpacity = materials.length ? Math.min(...materials.map((material) => material.opacity)) : null;
2757
+ return {
2758
+ id, name: e.name,
2759
+ gpuId: e.group.id,
2760
+ meshes: e.objects?.length || 0,
2761
+ drawMeshes: e.group.visible ? draws.length : 0,
2762
+ visible: e.group.visible,
2763
+ opacity: materialOpacity,
2764
+ materials,
2765
+ topology: e.activeTopology,
2766
+ topologyPending: [...e.pendingTopologies],
2767
+ snap: e.display.snap !== false,
2768
+ locked: !!e.display.locked,
2769
+ selected: id === xrefSelected,
2770
+ snapPoints: e.total, snapCapped: e.capped || !!e.keptCapped,
2771
+ bounds: referenceBounds(id),
2772
+ };
2773
+ });
2238
2774
  }
2239
2775
 
2240
2776
  // ---- Insert a vectored detail (Slice 4): arm a placement pick; the editor owns the entry ----
@@ -2335,9 +2871,8 @@ function syncMemberLabels() {
2335
2871
  }
2336
2872
  for (let i = 0; i < memberLabelPool.length; i++) {
2337
2873
  const el = memberLabelPool[i], m = ms[i];
2338
- // ASK THE READ HALF FOR A WORK LINE, never for `m.wp` — the same repair the reference lines got in
2339
- // P7d (see buildRefLines), applied to the two label pools that sweep missed. `wp` is a v1 STORAGE
2340
- // shape; a v2 canonical member has `from`/`to`, so this guard skipped every member of a canonical
2874
+ // ASK THE READ BOUNDARY FOR A WORK LINE, never for projected `m.wp` (see buildRefLines). A canonical
2875
+ // member has `from`/`to`, so the old guard skipped every member of a native
2341
2876
  // model and the toggle drew nothing at all. MEASURED in a real browser on a v2 document: both pools
2342
2877
  // allocated their divs and left every one `display:none` with empty text (#614).
2343
2878
  const g = m && geoOf(m);
@@ -2472,7 +3007,7 @@ const gridTexCache = new Map(); // 'b:LABEL' bubble / 't:LABEL' tag -> CanvasTex
2472
3007
  // it lives in localStorage next to the other per-browser display prefs and never touches the contract.
2473
3008
  const GRID_LABEL_PX_DEFAULT = 26, GRID_LABEL_PX_MIN = 14, GRID_LABEL_PX_MAX = 48;
2474
3009
  function clampGridLabelPx(v) { const n = Math.round(+v); return Number.isFinite(n) && n > 0 ? Math.min(GRID_LABEL_PX_MAX, Math.max(GRID_LABEL_PX_MIN, n)) : GRID_LABEL_PX_DEFAULT; }
2475
- let gridLabelPx = (() => { try { const raw = localStorage.getItem('steel:gridLabelPx:v1'); return raw === null ? GRID_LABEL_PX_DEFAULT : clampGridLabelPx(raw); } catch { return GRID_LABEL_PX_DEFAULT; } })();
3010
+ let gridLabelPx = (() => { try { const raw = localStorage.getItem('steel:gridLabelPx:v2'); return raw === null ? GRID_LABEL_PX_DEFAULT : clampGridLabelPx(raw); } catch { return GRID_LABEL_PX_DEFAULT; } })();
2476
3011
 
2477
3012
  // Snap targets for the 3D tools. Members come from the WHOLE model — every sheet, not just the active
2478
3013
  // one — so "3D snapping on" can grab any member at any elevation (the 3D scene shows all sheets; snapping
@@ -2556,10 +3091,8 @@ function clearStructGrid() {
2556
3091
  }
2557
3092
  function buildStructGrid() {
2558
3093
  dimCandidates3d = null; tfCandidates = null; clipCandidates = null; clipLevels = null; invalidateModelCache(); // the grid just changed → EVERY cached snap set built from the OLD one is stale (dim, Move/Copy + Add, clip-box draw). rebuild() already nulls these, but refresh3DGrid() (grid panel edits, and the plan switch setPlan now fires) reaches us without it, which would pair one sheet's grid X/Y with another's elevations.
2559
- // THE GRID NEEDS ITS OWN v2 PATH, and this is the one place it shows (§8.3). v1's grid is stored in the
2560
- // active sheet's DISPLAY space — px, with Y growing DOWN the page — so the two conversions below are a
2561
- // scale AND a reflection. v2's grid is already world mm with Y up. Handing a world-mm grid to the v1
2562
- // conversion would not throw; it would draw the whole grid mirrored about Y, plausibly, at 1/12 scale.
3094
+ // The native grid is already world mm with Y up. Handing it to the display-space conversion would not
3095
+ // throw; it would draw the whole grid mirrored about Y, plausibly, at 1/12 scale.
2563
3096
  // So the read half answers with the drawable geometry AND the two facts needed to place it.
2564
3097
  let d = null;
2565
3098
  try { if(api&&scene)d = MODEL().gridDraw(); }
@@ -2891,6 +3424,7 @@ function fitCamera(box, dir) {
2891
3424
  orthoBaseH = fit.orthoH; // tight, aspect-preserving box fit (no ortho under-frame)
2892
3425
  if (camera === orthoCam) reframeOrtho();
2893
3426
  controls.update();
3427
+ camFitted = camFramed = true; // the camera now frames something real → durable fact + the loop may paint (see camFitted/camFramed)
2894
3428
  }
2895
3429
 
2896
3430
  // CAD re-pivot (wired to OrbitControls' 'start' — fires for orbit/pan/wheel before the gesture is applied):
@@ -2920,9 +3454,28 @@ async function rebuild(fit = false) {
2920
3454
  if (marker && clipMode === 'box') marker.visible = false; // a model change under an armed box draw invalidates the reticle position — drop it (the next hover re-snaps)
2921
3455
  if (fit) fitPending = true; // entering 3D re-fits; an edit-triggered rebuild keeps the camera put
2922
3456
  const seq = ++rebuildSeq;
2923
- const sc = await api.fetchScene(); // editor POSTs the current contract to /scene
3457
+ let sc;
3458
+ try {
3459
+ sc = await api.fetchScene(); // editor POSTs the current contract to /scene
3460
+ } catch (e) {
3461
+ /* A REJECTED FETCH STILL OPENS THE GATE, because the pane it belongs to may still be on screen.
3462
+ * Usually setView catches this, toasts and reverts to 2D — but not always: switch 3d→split while
3463
+ * the first open is in flight and nextMode reports show3d:false, so setView never rebuilds again
3464
+ * and the superseded open's catch returns without reverting. That pane stays visible, and a gate
3465
+ * left shut would leave it blank for ever.
3466
+ * This does NOT poison the retry, which is what an earlier cut of this change got wrong: show()
3467
+ * re-derives the gate from camFitted, which a rejection never sets, so the next open starts shut. */
3468
+ if (seq === rebuildSeq) camFramed = true;
3469
+ throw e; // callers still see the failure — setView toasts it
3470
+ }
2924
3471
  if (seq !== rebuildSeq) return; // a newer rebuild superseded this one → drop the stale scene (no out-of-order apply)
2925
- if (sc) buildFromScene(sc);
3472
+ if (sc) {
3473
+ buildFromScene(sc);
3474
+ // buildFromScene has already run fitCamera when a fit was pending, so this is the safety net for
3475
+ // the one case that legitimately has nothing to fit: an EMPTY model, where cameraFitForBox
3476
+ // declines the empty box and the pane would otherwise stay dark for good.
3477
+ camFramed = true;
3478
+ } else { camFramed = true; console.warn('[steel-3d] the scene fetch resolved empty — nothing was rebuilt'); } // dead-defensive (fetchScenePayload throws on !ok), but a falsy scene must not pass for a normal one — and must not strand the pane blank either
2926
3479
  refreshDims(); // persisted dims appear + survive edit-rebuilds (re-coloured for the current selection)
2927
3480
  try { refreshOverlayDims(); } catch (e) { console.warn('dim overlays skipped (bad part)', e); } // a malformed part drops its overlay, never the whole rebuild (mirrors applyCopes' containment)
2928
3481
  }
@@ -3164,8 +3717,8 @@ function applyObjectsPaneState(s) {
3164
3717
  // Tekla "isolate selected": show ONLY the currently-selected parts (a snapshot taken now — distinct from
3165
3718
  // soloToggle, which isolates a whole PROFILE group from the legend). clearIsolation / showAllGroups restore all.
3166
3719
  function isolateSelected() { if (!selIds.size && !selectedGridIds.size) return false; isolatedIds = new Set(selIds); isolatedGridIds = new Set(selectedGridIds); applyGroupVisibility(); applyGridVisibility(); rebuildEndpoints(); refreshOverlayDims(); refreshDims(); updateStatusChip(); notifyVisibilityChange(); return true; }
3167
- // Hide the current selection by explicit mesh id. This remains session-only because v2 saved views require tagged
3168
- // SceneRefs while the renderer owns raw ids; broadening that contract is a separate migration, not toolbar state.
3720
+ // Hide the current selection by explicit mesh id. This remains session-only because saved views require tagged
3721
+ // SceneRefs while the renderer owns raw ids; broadening that contract is separate from toolbar state.
3169
3722
  function hideSelected() { const ids = [...selIds].filter((id) => meshById.has(id)), gridIds = [...selectedGridIds].filter((id) => structGridLines.has(id)); if (!ids.length && !gridIds.length) return 0; for (const id of ids) selectionHidden.add(id); for (const id of gridIds) gridSelectionHidden.add(id); applyGroupVisibility(); applyGridVisibility(); rebuildEndpoints(); refreshOverlayDims(); refreshDims(); updateStatusChip(); notifyVisibilityChange(); return ids.length + gridIds.length; }
3170
3723
  function clearIsolation() { if (isolatedIds === null && isolatedGridIds === null) return; isolatedIds = null; isolatedGridIds = null; applyGroupVisibility(); applyGridVisibility(); rebuildEndpoints(); refreshOverlayDims(); refreshDims(); updateStatusChip(); notifyVisibilityChange(); }
3171
3724
  function isIsolated() { return isolatedIds !== null || isolatedGridIds !== null; }
@@ -4863,16 +5416,10 @@ const memberById = (id) => { const all = (api && api.allMembers && api.allMember
4863
5416
  // pt_per_ft inverted the commit through the wrong scale and wrote a mis-scaled wp — while the target it
4864
5417
  // snapped to had been computed in the target sheet's own scale. One source ⇒ they cannot disagree.
4865
5418
  /*
4866
- * ---- THE MODEL READ HALF (unit 5, P7d) -----------------------------------------------------------
4867
- *
4868
- * Every geometry read this view makes goes through ONE object the host injects, so the contract VERSION
4869
- * stops at that boundary instead of branching through 4,400 lines. Epic §15 answer 4: "the gate at the
4870
- * ADAPTER boundary, not scattered `if (v2)` branches through the editor closure" — a branch per geometry
4871
- * site is the shape this epic has rejected three times.
5419
+ * ---- THE MODEL READ BOUNDARY --------------------------------------------------------------------
4872
5420
  *
4873
- * The host supplies the native steel.model/v2 computation — the per-plan
4874
- * scale index, `planScaleOf`, `memberGeometryInOwnPlan` — so v1 stays byte-identical by construction
4875
- * rather than by test. steel.model/v2's answers from world-mm members and needs none of it.
5421
+ * Every geometry read this view makes goes through ONE object the host injects, so canonical model
5422
+ * semantics stop at that boundary instead of branching through this renderer.
4876
5423
  *
4877
5424
  * WHAT LIVED HERE AND MOVED: `activeScale`, `planList`, `scaleIndex`, `scaleFor` and the scale cache.
4878
5425
  * P5's review round 4 corrected the understatement that geoOf was a delegation — it is a seam, and those
@@ -4883,8 +5430,8 @@ const memberById = (id) => { const all = (api && api.allMembers && api.allMember
4883
5430
  let modelReads = null;
4884
5431
  function MODEL() {
4885
5432
  if (!modelReads) {
4886
- // NAMED rather than a fallback. A host without this seam cannot be served by quietly reverting to v1's
4887
- // computation: for a v2 document that would read `m.wp`/`m.col` off members that have neither and yield
5433
+ // NAMED rather than a fallback. A host without this seam cannot be served by quietly reading projected
5434
+ // fields: a canonical document has no `m.wp`/`m.col`, so that would yield
4888
5435
  // NaN geometry — a scene that draws, silently, in nowhere.
4889
5436
  if (!api || typeof api.model !== 'function') throw new Error('steel-3d-view: the host supplied no api.model() — the model read half is required');
4890
5437
  modelReads = api.model();
@@ -4894,10 +5441,8 @@ function MODEL() {
4894
5441
  /** The model changed, or the grid did — drop whatever the read half cached off the old one. */
4895
5442
  function invalidateModelCache() { if (modelReads && typeof modelReads.invalidate === 'function') modelReads.invalidate(); }
4896
5443
  const scaleFor = (m) => MODEL().scaleOf(m); // keyed by the member OBJECT — ids are only sheet-unique
4897
- // A member's WORK LINE in world mm. For v1 that is its OWN sheet's scale + default T.O.S — matching the
4898
- // server bake, which resolves per-plan (contract-to-scene: per-plan pt_per_ft + `default_tos ?? 0`). Using
4899
- // the ACTIVE sheet's default T.O.S put every overlay (handles, labels, reference lines) for an off-sheet
4900
- // member whose T.O.S is unset at the WRONG elevation, while its server-built mesh sat at the right one.
5444
+ // A member's WORK LINE in world mm, resolved by the native adapter. Overlays, labels, and reference lines
5445
+ // must use the same geometry as the server-built mesh.
4901
5446
  const geoOf = (m) => MODEL().geometryOf(m);
4902
5447
  const geoMode = () => (api && api.geoMode && api.geoMode()) || null;
4903
5448
 
@@ -4906,7 +5451,7 @@ const geoMode = () => (api && api.geoMode && api.geoMode()) || null;
4906
5451
  let workPlane = null; // {origin:[x,y,z]mm, normal, xAxis} | null
4907
5452
  let wpMode = null; // 'face' | '3pt' — armed set-plane pick mode
4908
5453
  let wpDraft = null; // 3pt picks collected so far
4909
- let wpVisible = (() => { try { return localStorage.getItem('steel:wpVisible:v1') === '1'; } catch { return false; } })(); // reference surface is opt-in; remember both on and off without changing the active plane
5454
+ let wpVisible = (() => { try { return localStorage.getItem('steel:wpVisible:v2') === '1'; } catch { return false; } })(); // reference surface is opt-in; remember both on and off without changing the active plane
4910
5455
  let wpGroup = null;
4911
5456
  let wpExtent = null; // test-observability: the projected u/v footprint the last-rendered "Show plane" surface was sized to (null = fallback square)
4912
5457
  // ---- 3D local drawing frame (UCS, stage 1): a SEPARATE rotate-about-Z frame for skewed framing.
@@ -5248,7 +5793,7 @@ function setWorkPlanePrincipal(kind, offsetMm) {
5248
5793
  wpMode = null; wpDraft = null; invalidatePointEntry('drift'); renderWorkPlane(); reflectWpBar(); updateStatusChip();
5249
5794
  }
5250
5795
  function clearWorkPlane() { workPlane = null; wpMode = null; wpDraft = null; invalidatePointEntry('drift'); renderWorkPlane(); reflectWpBar(); updateStatusChip(); }
5251
- function toggleWorkPlaneVisible(on) { wpVisible = on === undefined ? !wpVisible : !!on; try { localStorage.setItem('steel:wpVisible:v1', wpVisible ? '1' : '0'); } catch { /* storage can be unavailable; keep the session preference */ } renderWorkPlane(); }
5796
+ function toggleWorkPlaneVisible(on) { wpVisible = on === undefined ? !wpVisible : !!on; try { localStorage.setItem('steel:wpVisible:v2', wpVisible ? '1' : '0'); } catch { /* storage can be unavailable; keep the session preference */ } renderWorkPlane(); }
5252
5797
  function workPlaneInfo() { return { set: !!workPlane, mode: wpMode, visible: wpVisible, plane: workPlane ? { origin: [...workPlane.origin], normal: [...workPlane.normal], xAxis: [...workPlane.xAxis] } : null }; }
5253
5798
  /**
5254
5799
  * face pick: the same face → plane conversion the clip tool does, over the same `faceHitAt`, with the
@@ -5821,8 +6366,8 @@ function onDown(e) {
5821
6366
  let id = null; try { id = pickAt(e.clientX, e.clientY); } catch { id = null; }
5822
6367
  // Geometry-edit mode (Trim/Extend or Split armed in the inspector): a click does the edit, no drag.
5823
6368
  if (geoMode() && (geoMode() === 'el' ? selIds.size >= 1 : selIds.size === 1)) { e.stopPropagation(); pending = { geo: geoMode(), selId: [...selIds][0], targetId: id }; return; } // Split: single; Extend/Trim: any selection
5824
- // An editable v1 end node (the yellow/magenta dot) under the cursor → grab just that endpoint to
5825
- // stretch the member. Canonical v2 still renders selection endpoint dots, but is read-only here:
6369
+ // An editable projected end node (the yellow/magenta dot) under the cursor → grab just that endpoint to
6370
+ // stretch the member. Canonical members still render selection endpoint dots, but are not edited here:
5826
6371
  // let those pixels fall through to the ordinary member-selection path below.
5827
6372
  if (MODEL().memberEditing !== false) {
5828
6373
  let ep = null; try { ep = pickEndpoint(e.clientX, e.clientY); } catch { ep = null; }
@@ -5868,9 +6413,9 @@ function onDown(e) {
5868
6413
  }
5869
6414
  }
5870
6415
  }
5871
- // A canonical v2 model is deliberately read-only here. A press still needs enough state for onUp to
5872
- // perform the ordinary member selection, but must not ask for a v1 owning-sheet scale or build drag
5873
- // candidates: v2 has neither. Keeping this boundary in the model read half prevents selection from
6416
+ // Canonical member geometry is deliberately not edited through the projected drag path. A press still
6417
+ // needs enough state for onUp to perform ordinary selection, but must not ask for an owning-sheet scale
6418
+ // or build display-space drag candidates. Keeping this boundary in the model adapter prevents selection from
5874
6419
  // failing before Member length (and every other selection-driven read) can see the chosen member.
5875
6420
  if (MODEL().memberEditing === false) { pending = { id, add }; return; }
5876
6421
  const { ptPerFt: ppf, defaultTosMm: dtos } = scaleFor(m); // the GRABBED member's sheet, not the active one
@@ -6001,6 +6546,7 @@ function onTeklaDragMove(e) {
6001
6546
  pending = dragging = null; boxSel = null; if (controls) controls.enabled = true;
6002
6547
  teklaDrag.badge = teklaBadge(teklaDrag.ids.length);
6003
6548
  updateStatusChip();
6549
+ notifyInstructor(); // a pointermove arm: no input event the reporter watches will follow
6004
6550
  }
6005
6551
  // The badge is ours to place; outside the window it simply clips away, and the status chip carries
6006
6552
  // the message from there.
@@ -6011,7 +6557,7 @@ function onTeklaDragMove(e) {
6011
6557
  // let go somewhere that abandons the gesture.
6012
6558
  const outside = pointerOutsideWindow(e);
6013
6559
  const nextTarget = outside ? hostUnderPointer(teklaDrag, e) : null;
6014
- if (nextTarget !== teklaDrag.target) { teklaDrag.target = nextTarget; updateStatusChip(); }
6560
+ if (nextTarget !== teklaDrag.target) { teklaDrag.target = nextTarget; updateStatusChip(); notifyInstructor(); }
6015
6561
  paintDragBadge(teklaDrag);
6016
6562
  if (canvasEl) canvasEl.style.cursor = outside ? 'default' : 'alias';
6017
6563
  }
@@ -6467,6 +7013,67 @@ function onHoverMove(e) {
6467
7013
  }
6468
7014
  // The shared axis-lock chip suffix (' · X, Y locked') from tfLock — used by both the Move/Copy and Add-member chips.
6469
7015
  function lockChipTxt() { const _lk = ['u', 'v', 'n'].filter((a) => tfLock.has(a)); return _lk.length ? ' · ' + _lk.map((a) => (a === 'u' ? 'X' : a === 'v' ? 'Y' : 'Z')).join(', ') + ' locked' : ''; }
7016
+
7017
+ /* ── Instructor seam ────────────────────────────────────────────────────────
7018
+ WHAT IS ARMED, answered here because this module owns the state — the same
7019
+ reason the editor's reporter lives inside its main(). One accessor rather
7020
+ than eight, so steel-editor.html never has to reach into this module's
7021
+ internals to work out what the user is doing.
7022
+ Returns a registry command id and the index of the step in flight, or null
7023
+ when no 3D command is armed. It composes NO text: the step SENTENCE for each
7024
+ of these ids is authored once, in web/commands-steel.js. */
7025
+ function instructorCommand() {
7026
+ if (teklaDrag && teklaDrag.active) return { armed: 'steel.host-drag', step: 0 };
7027
+ if (wpMode === 'face') return { armed: 'steel.work-plane-face', step: 0 };
7028
+ if (wpMode === '3pt') return { armed: 'steel.work-plane-3pt', step: (wpDraft || []).length };
7029
+ if (clipMode === 'box') return { armed: 'steel.clip-box', step: !clipBoxDraft ? 0 : (!clipBoxDraft.b ? 1 : 2) };
7030
+ if (clipMode === 'plane') return { armed: 'steel.clip-plane', step: 0 };
7031
+ if (refMeasure3d) return { armed: 'steel.reference-measure', step: refMeasure3d.a ? 1 : 0 };
7032
+ if (framePickStep() != null) return { armed: 'steel.local-frame', step: framePickStep() };
7033
+ if (frameMode) return { armed: 'steel.frame-adjust', step: 0 };
7034
+ if (insertMode) return { armed: 'steel.insert-detail', step: 0 };
7035
+ if (basePickCol) return { armed: 'steel.base-pick', step: 0 };
7036
+ if (gridLinePick3d) return { armed: 'steel.grid-line', step: gridLinePick3d.a ? 1 : 0 };
7037
+ if (dimMode3d) return { armed: 'steel.dimension', step: dimDraft3d ? 1 : 0 };
7038
+ /* Extend/trim and Split. Omitting these left canvasToolGuidanceState composing
7039
+ their prose while the band narrated the registry's — one command, two
7040
+ sentences on screen at once, which is the exact thing this phase removes. */
7041
+ if (geoMode() === 'el') return { armed: 'steel.extend-trim', step: 0 };
7042
+ if (geoMode() === 'split') return { armed: 'steel.split', step: 0 };
7043
+ if (addActive()) return { armed: 'steel.add-member', step: drDraft ? 1 : 0 };
7044
+ if (cmActive()) { const st = cmActive();
7045
+ return { armed: st.tool === 'move' ? 'steel.move' : (st.array ? 'steel.copy-array' : 'steel.copy'),
7046
+ step: !tfDraft ? 0 : (st.array && !tfDraft.vA ? 1 : st.array ? 2 : 1) }; }
7047
+ return null;
7048
+ }
7049
+
7050
+ /* THE guidance slot for this surface. Its whole body is "keep what the shell
7051
+ produced, repaint" — it assembles no narration, which is what stops this chip
7052
+ drifting back into being a third independent narrator. The step sentences it
7053
+ paints came from the registry, via the shell's one producer. */
7054
+ let guidancePayload = null;
7055
+ function renderGuidance(payload) { guidancePayload = payload; updateStatusChip(); }
7056
+
7057
+ /* Ask the reporter to publish. Needed where an arm/disarm happens on a POINTERMOVE
7058
+ — the drag-out into a CAD host is the live case — because pointermove is not one
7059
+ of the events the reporter watches, and render() is deliberately off that path.
7060
+ Without this the shell never hears the drag start, and the chip that is the only
7061
+ thing on screen once the badge clips away falls back to a bare label. */
7062
+ function notifyInstructor() {
7063
+ try { if (window.__instructor && window.__instructor.notifyChanged) window.__instructor.notifyChanged(); }
7064
+ catch (e) { /* no shell above us */ }
7065
+ }
7066
+
7067
+ /** The step sentence the shell produced FOR THIS COMMAND, or null.
7068
+ The id check is the point: without it, a payload that has not caught up yet
7069
+ paints another command's instruction verbatim — a guidance surface being
7070
+ confidently wrong is worse than one saying nothing. */
7071
+ function armedStepText(commandId) {
7072
+ const g = guidancePayload;
7073
+ if (!g || g.tone !== 'armed' || !g.parts || !g.parts.length) return null;
7074
+ if (commandId && g.commandId && g.commandId !== commandId) return null;
7075
+ return g.parts[0];
7076
+ }
6470
7077
  function updateStatusChip() {
6471
7078
  if (!hoverChip || !canvasEl) return;
6472
7079
  const rect = canvasEl.getBoundingClientRect();
@@ -6482,32 +7089,39 @@ function updateStatusChip() {
6482
7089
  });
6483
7090
  const forceOpen = toolGuidance.forceOpen;
6484
7091
  const selectionStatus=objectSelectionStatus(selIds.size,selectedGridIds.size),showId=hoverId||(!selectionStatus&&selIds.size===1?[...selIds][0]:null);
6485
- // The badge follows the cursor and so clips away at the window edge — from there this chip is the
6486
- // only thing still telling the user what releasing will do.
6487
- if (teklaDrag && teklaDrag.active) {
6488
- const n = teklaDrag.ids.length, noun = n === 1 ? 'member' : 'members';
6489
- // Name the app the pointer is actually over, so the chip and the badge never disagree.
6490
- txt = teklaDrag.target
6491
- ? `Release to insert ${n} ${noun} into ${HOST_SHORT[teklaDrag.target]} · release here or Esc to cancel`
6492
- : `Release over Tekla, Revit, SketchUp or Rhino to insert ${n} ${noun} · release here or Esc to cancel`;
6493
- }
6494
- else if (wpMode === 'face') txt = 'Click any face — member or reference — the working plane lands on it · Esc to cancel';
6495
- else if (wpMode === '3pt') txt = ['Click the plane origin (snapped) · Esc to cancel', 'Click the local-X direction point · Esc to cancel', 'Click a point on the plane’s Y side · Esc to cancel'][(wpDraft || []).length] || '';
6496
- else if (addActive()) txt = drDraft ? 'Click the member end · X/Y/Z lock to the local axes, Shift straight · Esc drops the start' + lockChipTxt() : 'Draw a member on the working plane — click the start point · Esc exits';
6497
- else if (cmActive()) { const st = cmActive(), lock = lockChipTxt();
6498
- txt = (!tfDraft ? ((st.tool === 'move' ? 'Move' : (st.array ? 'Copy array' : 'Copy')) + ' — click the base point on the working plane · type after the pick for an exact value')
6499
- : (st.array && !tfDraft.vA ? 'Click the direction-A point — or type its spacing' : st.array ? 'Click the direction-B point — the grid previews live' : 'Click the destination — X/Y lock to the plane axes · Esc cancels')) + lock; }
6500
- // Above the showId/default branches for the reason the grid-line branch below states. Three states, not
6501
- // two: unlike every sibling two-click tool this one has a RESULT the user can still act on, and while
6502
- // that is up the chip has to say where it went (the panel) and that a fresh pick just replaces it.
6503
- else if (refMeasure3d) txt = refMeasure3d.a
6504
- ? 'Click the second point on this reference · Esc to step back'
6505
- : refMeasureKept
6506
- ? 'Measured — see the panel · click two new points to try again · Esc to finish'
6507
- : 'Click the first point on this reference · Esc to cancel';
6508
- else if (gridLinePick3d) txt = gridLinePick3d.a ? 'Click the second point of the grid line · Esc to cancel' : 'Click the first point of the grid line · Esc to cancel'; // must sit above the showId/default branches, else an armed two-click tool shows the hovered member or the drag-move hint the user can't act on
6509
- else if (clipMode === 'plane') txt = 'Click a face to set a clip plane · Esc to cancel';
6510
- else if (clipMode === 'box') txt = !clipBoxDraft ? 'Click the first floor corner of the clip box · Esc to cancel' : !clipBoxDraft.b ? 'Click the opposite floor corner · Esc to cancel' : 'Move up/down to set the height, then click · Esc to step back';
7092
+ /* ── the armed-command branch, now ONE branch ────────────────────────────
7093
+ Every armed tool used to compose its own step prose here, which is exactly
7094
+ how this chip became a narrator independent of the Instructor band and the
7095
+ 2D panel. It now paints the sentence the shell produced from the registry,
7096
+ and the only thing added on top is live state this surface alone knows:
7097
+ the axis lock, and the reference-measure's kept result. Those are affordance
7098
+ detail about THIS canvas, not narration of the command's step — the test in
7099
+ server/instructor-narrators.test.ts pins that boundary.
7100
+
7101
+ No payload yet (standalone, or before the first report) → fall through to a
7102
+ degraded label-only readout rather than inventing a step sentence here. */
7103
+ const cmd3d = instructorCommand();
7104
+ const stepTxt = cmd3d ? armedStepText(cmd3d.armed) : null;
7105
+ if (cmd3d && stepTxt) {
7106
+ const suffix = (cmd3d.armed === 'steel.add-member' || cmd3d.armed === 'steel.move'
7107
+ || cmd3d.armed === 'steel.copy' || cmd3d.armed === 'steel.copy-array') ? lockChipTxt() : '';
7108
+ // The measure keeps a result the user can still act on; that is live state, not a step.
7109
+ const kept = (cmd3d.armed === 'steel.reference-measure' && refMeasureKept && !refMeasure3d.a)
7110
+ ? ' · last measurement is in the panel' : '';
7111
+ /* The drag badge follows the cursor and clips away at the window edge, so from
7112
+ there this chip is the only thing still saying what releasing will do —
7113
+ which host is under the pointer, and how many members go. Both are live
7114
+ facts about this drag, not the step. */
7115
+ let drag = '';
7116
+ if (cmd3d.armed === 'steel.host-drag' && teklaDrag) {
7117
+ const n = teklaDrag.ids.length;
7118
+ drag = ` · ${n} ${n === 1 ? 'member' : 'members'}`
7119
+ + (teklaDrag.target ? ` · over ${HOST_SHORT[teklaDrag.target]}` : '');
7120
+ }
7121
+ txt = stepTxt + suffix + kept + drag + ' · Esc to cancel';
7122
+ }
7123
+ else if (cmd3d) { const meta = window.Commands && window.Commands.get(cmd3d.armed);
7124
+ txt = (meta ? meta.label : cmd3d.armed) + ' · Esc to cancel'; } // reporter-unavailable fallback
6511
7125
  else if (toolGuidance.text) txt = toolGuidance.text;
6512
7126
  else if (showId) { const m = memberById(showId); txt = m ? `${m.id} · ${m.profile || '—'}` : ''; }
6513
7127
  else if (selectionStatus) txt = selectionStatus;
@@ -6535,7 +7149,12 @@ function updateStatusChip() {
6535
7149
  }
6536
7150
  }
6537
7151
 
6538
- function show() { if (controls) controls.enabled = true; if (canvasEl) { canvasEl.style.display = 'block'; resize(); } if (!rafId) loop(); updateStatusChip(); refreshDims(); refreshOverlayDims(); renderFrameGizmo(); } // resume the render loop (reset orbit in case a gesture was stranded by a mid-drag hide)
7152
+ // RE-DERIVE THE PAINT GATE FROM THE DURABLE FACT on every open. An ordinary 2D→3D re-entry has a
7153
+ // fitted camera, so this keeps painting instantly; a retry after a failed open does not (a rejection
7154
+ // opened the gate so the pane would not sit blank, but never fitted anything), so this re-closes it
7155
+ // and the retry is as clean as a first open. unframedFrames/unframedWarned reset with it, or two
7156
+ // short stalls would add up into one bogus warning.
7157
+ function show() { camFramed = camFitted; unframedFrames = 0; unframedWarned = false; if (controls) controls.enabled = true; if (canvasEl) { canvasEl.style.display = 'block'; resize(); } if (!rafId) loop(); updateStatusChip(); refreshDims(); refreshOverlayDims(); renderFrameGizmo(); } // resume the render loop (reset orbit in case a gesture was stranded by a mid-drag hide)
6539
7158
  function hide() {
6540
7159
  invalidatePointEntry('hide'); // leaving 3D → drop any open typed entry + stale base/start
6541
7160
  if (dimMode3d) toggleDimTool(); // disarm the dim tool + sync its toolbar (no stale draft/armed state on return)
@@ -6548,9 +7167,7 @@ function hide() {
6548
7167
  if (wpMode) { wpMode = null; wpDraft = null; if (marker) marker.visible = false; reflectWpBar(); } // drop an in-progress set-plane pick — else a stale face/3pt pick steals the first click on return
6549
7168
  if (frameMode || (pending && pending.frameDrag) || framePicking()) { if (pending && pending.frameDrag && frame3d && pending.preFrame) frame3d = cloneFrame(pending.preFrame); cancelFramePick(); frameMode = false; if (pending && pending.frameDrag) pending = dragging = null; if (readout) readout.style.display = 'none'; fireFrameChange(); } // leaving 3D disarms the local-frame manipulator + cancels an in-progress pick/drag
6550
7169
  cmClear3d(); drClear3d(); // and any 3D Move/Copy or draw draft/ghosts
6551
- if (dimLabelHost) dimLabelHost.style.display = 'none'; // the loop that hides labels is about to stop — hide synchronously so none are stranded
6552
- if (memberLabelHost) memberLabelHost.style.display = 'none'; // member labels ride the same about-to-stop loop — hide them too, or they strand over the 2D UI
6553
- if (propLabelHost) propLabelHost.style.display = 'none'; // property labels ride the same loop — hide synchronously so none strand over the 2D UI
7170
+ hideLabelHosts(); // the loop that PLACES the labels is about to stop — hide synchronously (same helper the camFramed gate uses on the way in) so none strand over the 2D UI
6554
7171
  clearCopyGhost(); // drop a stale Ctrl+drag copy ghost on the way out
6555
7172
  endTeklaDrag(); // and a live drag-out to Tekla — a stranded one would leave its badge on screen and swallow every later pointer move
6556
7173
  if (canvasEl) canvasEl.style.display = 'none'; if (hoverChipShell) hoverChipShell.style.display = 'none'; else if (hoverChip) hoverChip.style.display = 'none'; if (rafId) { cancelAnimationFrame(rafId); rafId = null; }
@@ -6573,8 +7190,18 @@ function dispose() {
6573
7190
  // it — a view disposed mid-import would leak its meshes and their material. It owns its own
6574
7191
  // disposal for exactly that reason; this is the one caller that has to remember to ask.
6575
7192
  clearReferencePreview();
6576
- if (rafId) cancelAnimationFrame(rafId);
6577
- if (hoverRAF) cancelAnimationFrame(hoverRAF);
7193
+ /* CANCEL **AND** CLEAR. Both of these handles are read back as "is a frame already queued?", so
7194
+ * cancelling without clearing leaves a teardown that permanently disables the thing it tore down:
7195
+ * rafId — show() restarts the loop only on `if (!rafId) loop()`, so a stale handle means a
7196
+ * dispose()/init()/show() cycle never repaints at all. hide() has always got this
7197
+ * right (`rafId = null` in the same statement); dispose had drifted from it.
7198
+ * hoverRAF — scheduleHover bails on `if (hoverRAF || …) return`, so a stale handle kills hover
7199
+ * highlighting for the rest of the page. Same defect, one line down; fixing only the
7200
+ * first would re-open the drift this pair is pinned against.
7201
+ * Cleared to the same falsy values the live code uses (null / 0), not merged, because both are
7202
+ * compared truthily and the types are already established at their declarations. */
7203
+ if (rafId) { cancelAnimationFrame(rafId); rafId = null; }
7204
+ if (hoverRAF) { cancelAnimationFrame(hoverRAF); hoverRAF = 0; }
6578
7205
  if (ro) ro.disconnect();
6579
7206
  if (canvasEl) { canvasEl.removeEventListener('pointerdown', onDown, true); canvasEl.removeEventListener('pointermove', onHoverMove); canvasEl.removeEventListener('dblclick', onDblClick); canvasEl.removeEventListener('wheel', onWheelHover, true); }
6580
7207
  if (controls) controls.removeEventListener('start', repivotToCursor);
@@ -6608,7 +7235,14 @@ function dispose() {
6608
7235
  dims3dGroup = dimPreviewLine = overlayDimsGroup = null;
6609
7236
  // The reference layer owns real GPU buffers — a whole tessellated building's worth. Leaving them
6610
7237
  // attached to a torn-down scene is the kind of leak that only shows up after the fifth 2D↔3D switch.
6611
- if (xrefGroup) { disposeReferenceMaterials(); xrefGroup.traverse((o) => { o.geometry?.dispose?.(); }); if (scene) scene.remove(xrefGroup); }
7238
+ // Detached replacements are not descendants of xrefGroup yet, so cancel them explicitly first. Their
7239
+ // async builders consult this map through `alive()`; clearing it prevents a late completion from
7240
+ // attaching to the renderer after its scene has already gone away.
7241
+ for (const [id, staged] of [...pendingXrefReplacements]) {
7242
+ cancelStagedReference(id, staged, 'the 3D view closed before geometry finished uploading', { resolutionOnly: true });
7243
+ }
7244
+ pendingFrameReference = null;
7245
+ if (xrefGroup) { disposeReferenceMaterials(); xrefGroup.traverse((o) => { if (o.isBatchedMesh) o.dispose?.(); else o.geometry?.dispose?.(); }); if (scene) scene.remove(xrefGroup); }
6612
7246
  // The ghost layer owns real buffers too, and it is a SIBLING of that group rather than a child — which
6613
7247
  // is the whole point of it, and also the reason the sweep above cannot reach it.
6614
7248
  clearReferenceGhosts();
@@ -6625,6 +7259,14 @@ function dispose() {
6625
7259
  clips = []; workArea = null; clipMode = null; selectedClipIds.clear(); clipBoxDraft = null; // clips live on the renderer; drop them with the renderer
6626
7260
  if (renderer) renderer.dispose();
6627
7261
  renderer = scene = camera = perspCam = orthoCam = controls = root = api = canvasEl = ro = null; built = false;
7262
+ // …and re-arm the first-frame gate, because camFramed is module state and would otherwise outlive
7263
+ // the cameras it describes: init() mints fresh, never-framed ones, so a gate left open paints them
7264
+ // straight away and the flat top view is back. This became load-bearing with the rafId fix above —
7265
+ // while dispose leaked that handle, show() could not restart the loop at all, so the cycle failed
7266
+ // dead rather than flashing. Stated honestly about reach: dispose() still has NO caller today (the
7267
+ // editor tears down by reloading, which resets module state anyway), so this guards the exported
7268
+ // teardown surface, not a path the app drives.
7269
+ camFitted = camFramed = false; unframedFrames = 0; unframedWarned = false; // the LATCH resets too, or a working re-init after dispose could never warn again
6628
7270
  }
6629
7271
 
6630
7272
  function debug() {
@@ -6632,6 +7274,7 @@ function debug() {
6632
7274
  const s = box.getSize(new THREE.Vector3()), c = box.getCenter(new THREE.Vector3());
6633
7275
  return {
6634
7276
  meshes: meshById.size,
7277
+ camFramed, // the first-frame gate — exposed so a browser pass can ASSERT the unframed window instead of photographing it
6635
7278
  triangles: renderer ? renderer.info.render.triangles : -1,
6636
7279
  bboxEmpty: box.isEmpty(), bboxSize: [s.x, s.y, s.z], bboxCenter: [c.x, c.y, c.z],
6637
7280
  firstId: meshById.keys().next().value ?? null,
@@ -6724,12 +7367,10 @@ function referenceObjectsScreen(refId, opts) {
6724
7367
  const want = opts && Array.isArray(opts.indices) ? new Set(opts.indices) : null;
6725
7368
  const limit = opts && Number.isFinite(opts.limit) ? opts.limit : 40;
6726
7369
  camera.updateMatrixWorld(); entry.group.updateMatrixWorld(true);
6727
- const rect = canvasEl.getBoundingClientRect(), box = new THREE.Box3(), c = new THREE.Vector3(), out = [];
6728
- for (const mesh of entry.group.children) {
6729
- if (!mesh.isMesh) continue;
6730
- const i = mesh.userData.objectIndex;
7370
+ const rect = canvasEl.getBoundingClientRect(), c = new THREE.Vector3(), out = [];
7371
+ for (let i = 0; i < entry.objects.length; i++) {
6731
7372
  if (want && !want.has(i)) continue;
6732
- box.setFromObject(mesh); if (box.isEmpty()) continue;
7373
+ const box = xrefObjectWorldBox(entry, i); if (box.isEmpty()) continue;
6733
7374
  box.getCenter(c);
6734
7375
  const s = c.clone().project(camera);
6735
7376
  if (!Number.isFinite(s.x) || s.z > 1 || Math.abs(s.x) > 1 || Math.abs(s.y) > 1) continue;
@@ -6738,7 +7379,7 @@ function referenceObjectsScreen(refId, opts) {
6738
7379
  if (ours.length) continue;
6739
7380
  let hit = null; try { hit = pickReferenceAt(x, y); } catch { hit = null; }
6740
7381
  if (!hit || hit.referenceId !== refId || hit.objectIndex !== i) continue;
6741
- out.push({ index: i, objectId: mesh.userData.objectId ?? null, x: Math.round(x), y: Math.round(y) });
7382
+ out.push({ index: i, objectId: entry.objects[i]?.id ?? null, x: Math.round(x), y: Math.round(y) });
6742
7383
  if (out.length >= limit) break;
6743
7384
  }
6744
7385
  return out;
@@ -6824,6 +7465,8 @@ window.Steel3DView = {
6824
7465
  },
6825
7466
  toggleGroup, setGroupsHidden, setIdsHidden, connHiddenIds: () => [...connHidden], selectionHiddenIds: () => [...selectionHidden], soloToggle, setSoloGroups, showAllGroups, groupState, getGroups, visibleMemberIds, visibleObjectIds, visibleGridIds,
6826
7467
  setClipMode, clipMode: clipModeOn, toggleClip, removeClip, clearClips, getClips, renameClip, selectClip, setSelectedClips, selectedClips, deleteSelectedClips, clipState, setClipState,
7468
+ // Instructor seam: what this module has armed, and the one slot that paints what the shell produced.
7469
+ instructorCommand, renderGuidance,
6827
7470
  isolateSelected, hideSelected, clearIsolation, isIsolated, hasVisibilityFilter,
6828
7471
  cameraState, setCameraState, sectionViewState, sceneBounds, objectsPaneState, applyObjectsPaneState, // saved-view snapshot surface (Views Organizer + F11 generated cuts)
6829
7472
  workAreaSetAll, workAreaFromSelection, workAreaToggle, workAreaSetWhole, clearWorkArea, workAreaState,