@floless/app 0.131.1 → 0.132.0

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.
@@ -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 } 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) {
@@ -503,9 +544,13 @@ function orientMember(mesh, dir, el) {
503
544
  if (rollRad) q.premultiply(new THREE.Quaternion().setFromAxisAngle(m, rollRad));
504
545
  } else if (el && typeof el.rot === 'number') {
505
546
  // 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).
547
+ // authored plan rotation instead of an arbitrary default.
548
+ // Apply `el.rot` directly — do NOT re-negate. It arrives as a WORLD rotation: v2 work points are already
549
+ // right-handed world mm with no flip anywhere in the bake, so contract-to-scene passes `rot` through
550
+ // untouched and says so outright (the v1 arm that negated, to undo v1's display-space Y flip, went with v1
551
+ // in #741). Negating here would mirror every rolled section. That makes this branch right-handed about
552
+ // start→end, like every other branch above — and the 2D plan footprint is placed to match
553
+ // (SteelCore.sectionOutlinePx), which it did not do until the plan stopped rotating in raw sheet px.
509
554
  q.premultiply(new THREE.Quaternion().setFromAxisAngle(m, el.rot * Math.PI / 180));
510
555
  }
511
556
  mesh.quaternion.copy(q);
@@ -964,9 +1009,8 @@ function buildRefLines() {
964
1009
  if (!refLineOn || !api) return;
965
1010
  const pts = [];
966
1011
  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)
1012
+ // Ask the read boundary whether this canonical member has a work line rather than testing for a
1013
+ // projected `m.wp`; that guard would silently skip every native member.
970
1014
  const g = m && geoOf(m);
971
1015
  if (!g || !g.line) continue;
972
1016
  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 +1037,7 @@ function setRefLine(on) { refLineOn = !!on; buildRefLines(); }
993
1037
  // raycasts `meshById` only, and reference meshes are never in that map, so member picking, drag,
994
1038
  // box-select and Ctrl+A cannot see them however this layer changes.
995
1039
 
996
- let xrefGroup = null; // one child Group per reference, each holding its meshes
1040
+ let xrefGroup = null; // one child Group per reference, each holding its draw batches
997
1041
  const xrefById = new Map(); // id -> { group, display, points, capped, total, bounds }
998
1042
  let xrefSelected = null; // the whole-selected reference, or null
999
1043
  /**
@@ -1003,9 +1047,9 @@ let xrefSelected = null; // the whole-selected reference, or
1003
1047
  * `toReferenceObjects` writes `''` for an object whose id was not a string and `setReferences` maps that
1004
1048
  * to null — so on a file whose objects carry no ids, OUR ids collide by construction and cannot address
1005
1049
  * 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.
1050
+ * index into `ref.objects` is exact — each BatchedMesh instance maps back to that same logical array —
1051
+ * so it is what selects, and the id rides along so a rebuild can CHECK that the index still means the
1052
+ * same object. The compatibility renderer preserves the older one-child-per-object mapping.
1009
1053
  *
1010
1054
  * That check has teeth only where the file gives its objects ids; `revalidateSubSelection` says what it
1011
1055
  * does in the case where it does not, and it does not pretend to a guarantee it cannot make.
@@ -1037,10 +1081,10 @@ const XREF_COLOR = 0x94a3b8;
1037
1081
  /**
1038
1082
  * The drilled-into object's own lift, and why it is not simply "the whole-model highlight, on one mesh".
1039
1083
  *
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.
1084
+ * A reference normally draws fully solid; a user can still lower its opacity, and a file may carry
1085
+ * genuinely translucent materials. One object inside a building at either setting is not findable by
1086
+ * an emissive nudge alone, so the sub-selection gets a stronger lift and is pushed towards opaque —
1087
+ * which is what makes "that one, there" legible at a glance.
1044
1088
  *
1045
1089
  * RAISING OPACITY IS A SELECTION AFFORDANCE, NOT A CHANGE TO THE REFERENCE. It applies to a CLONE of
1046
1090
  * the object's own material, lasts exactly as long as the selection, and never touches the slider's
@@ -1056,6 +1100,7 @@ const XREF_SUB_INTENSITY = 0.9;
1056
1100
  const XREF_SUB_MIN_OPACITY = 0.85;
1057
1101
 
1058
1102
  const XREF_MODES = new Set(['file', 'uniform', 'custom']);
1103
+ const XREF_DEFAULT_OPACITY = 1; // omitted legacy values and new imports are fully solid
1059
1104
  const xrefMode = (d) => (XREF_MODES.has(d && d.colorMode) ? d.colorMode : 'file');
1060
1105
  /**
1061
1106
  * The custom colour as a number, or null if it is not a colour.
@@ -1173,8 +1218,8 @@ function appendReferencePreview(objects, placement) {
1173
1218
  if (!scene || !Array.isArray(objects) || !objects.length) return 0;
1174
1219
  if (!xrefPreviewGroup) {
1175
1220
  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.
1221
+ // Behind our steel in render order, but fully opaque like the committed default. Provisional grey
1222
+ // distinguishes the preview without reviving the transparency/depth-write failure this change removes.
1178
1223
  xrefPreviewGroup.renderOrder = -1;
1179
1224
  xrefPreviewGroup.applyMatrix4(xrefMatrix(placement));
1180
1225
  scene.add(xrefPreviewGroup);
@@ -1182,8 +1227,8 @@ function appendReferencePreview(objects, placement) {
1182
1227
  // same "not your content" slate this app already spends on references, it reads honestly as
1183
1228
  // provisional — the real colours appear when the import commits — and it lets the server strip
1184
1229
  // 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;
1230
+ xrefPreviewMat = newXrefMaterial(XREF_COLOR, 1);
1231
+ xrefPreviewMat.opacity = 1;
1187
1232
  xrefPreviewCount = 0;
1188
1233
  xrefPreviewFramed = false;
1189
1234
  // Cleared when a preview BEGINS, not on dispose: the question is whether the user has moved the
@@ -1191,14 +1236,26 @@ function appendReferencePreview(objects, placement) {
1191
1236
  // to frame a reference that needs it.
1192
1237
  xrefPreviewCamTouched = false;
1193
1238
  }
1194
- for (const o of objects) {
1195
- if (!o || !Array.isArray(o.positions) || !o.positions.length) continue;
1239
+ const valid = objects.filter((o) => o && Array.isArray(o.positions) && o.positions.length >= 9);
1240
+ if (valid.length && typeof THREE.BatchedMesh === 'function') {
1241
+ const vertices = valid.reduce((n, o) => n + o.positions.length / 3, 0);
1242
+ const indices = valid.reduce((n, o) => n + (Array.isArray(o.indices) && o.indices.length ? o.indices.length : o.positions.length / 3), 0);
1243
+ const batch = new THREE.BatchedMesh(valid.length, vertices, indices, xrefPreviewMat);
1244
+ batch.perObjectFrustumCulled = false; batch.sortObjects = false;
1245
+ const identity = new THREE.Matrix4();
1246
+ for (const o of valid) {
1247
+ const g = new THREE.BufferGeometry();
1248
+ g.setAttribute('position', new THREE.Float32BufferAttribute(o.positions, 3));
1249
+ g.setIndex(Array.isArray(o.indices) && o.indices.length ? o.indices : Array.from({ length: o.positions.length / 3 }, (_, i) => i));
1250
+ g.computeVertexNormals(); const geometryId = batch.addGeometry(g), instanceId = batch.addInstance(geometryId);
1251
+ batch.setMatrixAt(instanceId, identity); g.dispose(); xrefPreviewCount++;
1252
+ }
1253
+ xrefPreviewGroup.add(batch);
1254
+ } else for (const o of valid) {
1196
1255
  const g = new THREE.BufferGeometry();
1197
1256
  g.setAttribute('position', new THREE.Float32BufferAttribute(o.positions, 3));
1198
1257
  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++;
1258
+ g.computeVertexNormals(); xrefPreviewGroup.add(new THREE.Mesh(g, xrefPreviewMat)); xrefPreviewCount++;
1202
1259
  }
1203
1260
  // No explicit redraw: this view runs a continuous rAF loop (see `loop`), so adding to the scene is
1204
1261
  // all a batch has to do to appear.
@@ -1239,7 +1296,9 @@ function frameReferencePreview() {
1239
1296
  function clearReferencePreview() {
1240
1297
  if (!xrefPreviewGroup) return;
1241
1298
  try {
1242
- xrefPreviewGroup.traverse((o) => { o.geometry?.dispose?.(); });
1299
+ xrefPreviewGroup.traverse((o) => {
1300
+ if (o.isBatchedMesh) o.dispose?.(); else o.geometry?.dispose?.();
1301
+ });
1243
1302
  scene?.remove(xrefPreviewGroup);
1244
1303
  xrefPreviewMat?.dispose?.();
1245
1304
  } finally {
@@ -1319,6 +1378,7 @@ function setReferenceGhosts(refId, objects, placement) {
1319
1378
  xrefGhostMat.opacity = XREF_GHOST_OPACITY;
1320
1379
  xrefGhostRef = refId;
1321
1380
  }
1381
+ const ghostAnchor = xrefAnchor(objects);
1322
1382
  // COUNTED PER CALL, NOT CUMULATIVELY, and both halves are returned. `xrefGhostById.size` is a running
1323
1383
  // total, so a caller reading it could not tell "I drew nothing" from "I drew nothing NEW" — and the
1324
1384
  // two skips below are silent by construction: an object whose tessellation came back empty, and one
@@ -1334,10 +1394,17 @@ function setReferenceGhosts(refId, objects, placement) {
1334
1394
  // back — and a second mesh at the same coordinates doubles the fill and leaves the first unreachable.
1335
1395
  if (xrefGhostById.has(gid)) continue;
1336
1396
  const g = new THREE.BufferGeometry();
1337
- g.setAttribute('position', new THREE.Float32BufferAttribute(o.positions, 3));
1397
+ const local = new Float32Array(o.positions.length);
1398
+ for (let i = 0; i + 2 < o.positions.length; i += 3) {
1399
+ local[i] = o.positions[i] - ghostAnchor[0];
1400
+ local[i + 1] = o.positions[i + 1] - ghostAnchor[1];
1401
+ local[i + 2] = o.positions[i + 2] - ghostAnchor[2];
1402
+ }
1403
+ g.setAttribute('position', new THREE.Float32BufferAttribute(local, 3));
1338
1404
  if (Array.isArray(o.indices) && o.indices.length) g.setIndex(o.indices);
1339
1405
  g.computeVertexNormals();
1340
1406
  const mesh = new THREE.Mesh(g, xrefGhostMat);
1407
+ mesh.position.set(ghostAnchor[0], ghostAnchor[1], ghostAnchor[2]);
1341
1408
  // NOT PICKABLE EVEN IF SOMETHING EVER RAYCASTS THE WHOLE SCENE. The parenting above is what makes
1342
1409
  // this true today; this is the belt to that pair of braces, and it costs one field.
1343
1410
  mesh.raycast = () => {};
@@ -1406,11 +1473,13 @@ function xrefSnapPoints(objects) {
1406
1473
  const seen = new Set(); const out = [];
1407
1474
  for (const o of objects || []) {
1408
1475
  const pos = o.positions || [];
1476
+ const a = Array.isArray(o.geometryAnchor) ? o.geometryAnchor : [0, 0, 0];
1409
1477
  for (let i = 0; i + 2 < pos.length; i += 3) {
1410
1478
  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)}`;
1479
+ const x = pos[i] + a[0], y = pos[i + 1] + a[1], z = pos[i + 2] + a[2];
1480
+ const k = `${Math.round(x / XREF_SNAP_QUANT_MM)},${Math.round(y / XREF_SNAP_QUANT_MM)},${Math.round(z / XREF_SNAP_QUANT_MM)}`;
1412
1481
  if (seen.has(k)) continue;
1413
- seen.add(k); out.push([pos[i], pos[i + 1], pos[i + 2]]);
1482
+ seen.add(k); out.push([x, y, z]);
1414
1483
  }
1415
1484
  }
1416
1485
  return { points: out, capped: false };
@@ -1460,7 +1529,245 @@ function disposeReferenceMaterials() {
1460
1529
  * cache streaming in behind the native steel) simply carries no `objects` and renders nothing, which is
1461
1530
  * the honest encoding of "not here yet" and keeps project open from ever blocking on someone else's model.
1462
1531
  */
1532
+ function xrefAnchor(objects) {
1533
+ let lo = [Infinity, Infinity, Infinity], hi = [-Infinity, -Infinity, -Infinity];
1534
+ for (const o of objects || []) {
1535
+ const p = (Array.isArray(o?.positions) || ArrayBuffer.isView(o?.positions)) ? o.positions : [];
1536
+ const supplied = Array.isArray(o?.geometryAnchor) && o.geometryAnchor.length === 3 ? o.geometryAnchor : null;
1537
+ if (supplied) return supplied.slice();
1538
+ for (let i = 0; i + 2 < p.length; i += 3) {
1539
+ const x = Number(p[i]), y = Number(p[i + 1]), z = Number(p[i + 2]);
1540
+ if (!Number.isFinite(x) || !Number.isFinite(y) || !Number.isFinite(z)) continue;
1541
+ if (x < lo[0]) lo[0] = x; if (x > hi[0]) hi[0] = x;
1542
+ if (y < lo[1]) lo[1] = y; if (y > hi[1]) hi[1] = y;
1543
+ if (z < lo[2]) lo[2] = z; if (z > hi[2]) hi[2] = z;
1544
+ }
1545
+ }
1546
+ if (!Number.isFinite(lo[0])) return [0, 0, 0];
1547
+ return [(lo[0] + hi[0]) / 2, (lo[1] + hi[1]) / 2, (lo[2] + hi[2]) / 2];
1548
+ }
1549
+
1550
+ function xrefFragments(objects, anchor, bucket) {
1551
+ const fragments = [];
1552
+ for (let objectIndex = 0; objectIndex < objects.length; objectIndex++) {
1553
+ const o = objects[objectIndex];
1554
+ // Current v7 workers deliver colour-run-correct, bounded shards. One logical IFC object may span
1555
+ // several of them, but every shard maps back to the same object index for picking/Inspect.
1556
+ if (Array.isArray(o?.renderFragments)) {
1557
+ for (const fragment of o.renderFragments) {
1558
+ const authoredTransparent = fragment.authoredTransparent === true;
1559
+ if (bucket === 'opaque' && authoredTransparent || bucket === 'translucent' && !authoredTransparent) continue;
1560
+ fragments.push({
1561
+ objectIndex,
1562
+ positions: fragment.positions,
1563
+ indices: fragment.indices,
1564
+ colors: fragment.vertexColors,
1565
+ colorsNormalized: fragment.vertexColors instanceof Uint8Array,
1566
+ normals: fragment.normals,
1567
+ });
1568
+ }
1569
+ continue;
1570
+ }
1571
+ const src = (Array.isArray(o?.positions) || ArrayBuffer.isView(o?.positions)) ? o.positions : [];
1572
+ if (src.length < 9) continue;
1573
+ const localSource = Array.isArray(o.geometryAnchor);
1574
+ const positions = localSource && ArrayBuffer.isView(src) ? src : new Float32Array(src.length);
1575
+ if (positions !== src) for (let i = 0; i + 2 < src.length; i += 3) {
1576
+ positions[i] = src[i] - anchor[0]; positions[i + 1] = src[i + 1] - anchor[1]; positions[i + 2] = src[i + 2] - anchor[2];
1577
+ }
1578
+ const indices = (Array.isArray(o.indices) || ArrayBuffer.isView(o.indices)) && o.indices.length
1579
+ ? o.indices : Uint32Array.from({ length: positions.length / 3 }, (_, i) => i);
1580
+ const runs = Array.isArray(o.colors) && o.colors.length ? o.colors : [{ start: 0, count: indices.length, rgba: [0.58, 0.64, 0.72, 1] }];
1581
+ const authoredTransparent = o.authoredTransparent === true || runs.some((run) => (run.rgba?.[3] ?? 1) < 0.999);
1582
+ if (bucket === 'opaque' && authoredTransparent || bucket === 'translucent' && !authoredTransparent) continue;
1583
+ let colors = ArrayBuffer.isView(o.vertexColors) ? o.vertexColors : null;
1584
+ if (!colors) {
1585
+ 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; }
1586
+ 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++) {
1587
+ 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];
1588
+ }
1589
+ }
1590
+ fragments.push({ objectIndex, positions, indices, colors, normals: ArrayBuffer.isView(o.vertexNormals) ? o.vertexNormals : null });
1591
+ }
1592
+ return fragments;
1593
+ }
1594
+
1595
+ function xrefBatchMaterial(kind) {
1596
+ const material = new THREE.MeshStandardMaterial({
1597
+ color: 0xffffff, vertexColors: true, metalness: 0, roughness: 0.95,
1598
+ transparent: kind !== 'opaque', opacity: 1, depthWrite: kind === 'opaque',
1599
+ side: kind === 'opaque' ? THREE.FrontSide : THREE.DoubleSide,
1600
+ });
1601
+ material.userData.alpha = 1;
1602
+ return material;
1603
+ }
1604
+
1605
+ async function xrefBuildBatch(refId, fragments, kind, anchor, alive) {
1606
+ if (!fragments.length) return null;
1607
+ const vertices = fragments.reduce((n, f) => n + f.positions.length / 3, 0);
1608
+ const indices = fragments.reduce((n, f) => n + f.indices.length, 0);
1609
+ const batch = new THREE.BatchedMesh(fragments.length, vertices, indices, xrefBatchMaterial(kind));
1610
+ // The binary cache already groups a whole reference behind one proven world bound. Walking every
1611
+ // object again on every frame to frustum-test it recreates the 18k-object CPU bottleneck the batch
1612
+ // exists to remove. Opaque and override batches need no object sort either; authored translucency
1613
+ // keeps sorting because painter order is part of its visual meaning.
1614
+ batch.perObjectFrustumCulled = false;
1615
+ batch.sortObjects = kind !== 'opaque';
1616
+ batch.name = `reference-${refId}-${kind}`;
1617
+ batch.position.set(anchor[0], anchor[1], anchor[2]);
1618
+ batch.renderOrder = -1;
1619
+ batch.userData.referenceId = refId;
1620
+ batch.userData.kind = kind;
1621
+ batch.userData.batchToObject = [];
1622
+ const identity = new THREE.Matrix4();
1623
+ try {
1624
+ for (let at = 0; at < fragments.length; at++) {
1625
+ if (alive && !alive()) { disposeXrefBatch(batch); return null; }
1626
+ const f = fragments[at];
1627
+ const g = new THREE.BufferGeometry();
1628
+ try {
1629
+ g.setAttribute('position', new THREE.BufferAttribute(f.positions, 3));
1630
+ g.setAttribute('color', new THREE.BufferAttribute(f.colors, 4, f.colorsNormalized === true));
1631
+ g.setIndex(new THREE.BufferAttribute(f.indices, 1));
1632
+ if (f.normals) g.setAttribute('normal', new THREE.BufferAttribute(f.normals, 3)); else g.computeVertexNormals();
1633
+ g.computeBoundingBox(); g.computeBoundingSphere();
1634
+ const geometryId = batch.addGeometry(g);
1635
+ const instanceId = batch.addInstance(geometryId);
1636
+ batch.setMatrixAt(instanceId, identity);
1637
+ batch.userData.batchToObject[instanceId] = f.objectIndex;
1638
+ } finally { g.dispose(); }
1639
+ // BatchedMesh copies each object's attributes into its GPU-sized backing buffers. Yielding at a
1640
+ // bounded cadence turns the old multi-second long task into ordinary frames while keeping the
1641
+ // half-built batch detached: the reference swaps onto the canvas only when it is complete.
1642
+ // A zero-delay task yield is deliberate. requestAnimationFrame is throttled to roughly 1 Hz when
1643
+ // an editor iframe is backgrounded, which turned a safe 47-yield upload into a minute-long one.
1644
+ if (at && at % 64 === 0) await new Promise((resolve) => setTimeout(resolve, 0));
1645
+ }
1646
+ batch.computeBoundingBox(); batch.computeBoundingSphere();
1647
+ return batch;
1648
+ } catch (error) {
1649
+ // `addGeometry` can throw after allocating the batch's full backing buffers. The caller cannot see
1650
+ // this local until the promise resolves, so this function owns releasing it on every thrown path.
1651
+ disposeXrefBatch(batch);
1652
+ throw error;
1653
+ }
1654
+ }
1655
+
1656
+ function disposeXrefEntry(entry) {
1657
+ if (!entry) return;
1658
+ entry.disposed = true;
1659
+ 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?.()); } });
1660
+ entry.flat?.dispose?.();
1661
+ for (const material of entry.mats?.values?.() || []) material?.dispose?.();
1662
+ entry.group?.parent?.remove(entry.group);
1663
+ }
1664
+
1665
+ function disposeXrefBatch(batch) {
1666
+ if (!batch) return;
1667
+ batch.parent?.remove(batch);
1668
+ // BatchedMesh owns matrix/indirect/colour textures in addition to its geometry. Calling only the
1669
+ // geometry disposer leaks those textures on every topology switch and every cancelled replacement.
1670
+ if (batch.isBatchedMesh) batch.dispose?.(); else batch.geometry?.dispose?.();
1671
+ const materials = Array.isArray(batch.material) ? batch.material : [batch.material];
1672
+ materials.forEach((material) => material?.dispose?.());
1673
+ }
1674
+
1675
+ const pendingXrefReplacements = new Map();
1676
+ let pendingFrameReference = null;
1677
+
1678
+ function cancelStagedReference(id, staged, reason, options = {}) {
1679
+ if (!staged) return;
1680
+ if (pendingXrefReplacements.get(id) === staged) pendingXrefReplacements.delete(id);
1681
+ staged.onTopologyReady = null;
1682
+ disposeXrefEntry(staged);
1683
+ // The editor owns the promise waiting for this exact object array. Teardown must resolve that promise
1684
+ // without asking the editor to push a replacement back into a renderer that is actively disposing.
1685
+ if (options.resolutionOnly) api?.onReferenceGeometryCancel?.(staged.objects);
1686
+ else if (api?.onReferenceGeometryError) api.onReferenceGeometryError(id, staged.objects, reason);
1687
+ }
1688
+
1689
+ function createBatchedReference(ref) {
1690
+ const objects = Array.isArray(ref.objects) ? ref.objects : [];
1691
+ const anchor = xrefAnchor(objects);
1692
+ const group = new THREE.Group();
1693
+ group.userData.referenceId = ref.id;
1694
+ group.applyMatrix4(xrefMatrix(ref.placement));
1695
+ const { points, capped: keptCapped } = xrefSnapPoints(objects);
1696
+ const seen = new Set(), dupIds = new Set(), byGlobalId = new Map();
1697
+ for (let i = 0; i < objects.length; i++) {
1698
+ const gid = typeof objects[i]?.globalId === 'string' && objects[i].globalId ? objects[i].globalId : null;
1699
+ if (gid === null) continue;
1700
+ if (seen.has(gid)) dupIds.add(gid); else seen.add(gid);
1701
+ byGlobalId.set(gid, i);
1702
+ }
1703
+ return {
1704
+ batched: true, group, combined: null, opaque: null, translucent: null, anchor,
1705
+ display: ref.display || {}, name: ref.name || ref.id, objects,
1706
+ points, total: points.length, capped: keptCapped, keptCapped, dupIds, byGlobalId,
1707
+ mats: new Map(), flat: xrefBatchMaterial('combined'), painted: null,
1708
+ pendingTopologies: new Set(), resolvedTopologies: new Set(), activeTopology: null,
1709
+ desiredTopology: 'combined', staging: false, disposed: false, onTopologyReady: null,
1710
+ };
1711
+ }
1712
+
1713
+ /** Incremental BatchedMesh reference reconciliation. Unchanged object arrays retain their GPU entry. */
1463
1714
  function setReferences(list) {
1715
+ // Keep the established one-mesh path as a compatibility fallback for a host that supplies an older
1716
+ // Three build. Current FloLess ships BatchedMesh, so production takes the bounded-draw path below.
1717
+ if (typeof THREE.BatchedMesh !== 'function') return _legacySetReferences(list);
1718
+ refMeasureCands = null; invalidateClipFloor();
1719
+ if (!scene) return;
1720
+ if (!xrefGroup) { xrefGroup = new THREE.Group(); scene.add(xrefGroup); }
1721
+ const desired = new Map((list || []).filter((r) => r?.id).map((r) => [r.id, r]));
1722
+ const prevObjects = new Map([...xrefById].map(([id, e]) => [id, e.objects]));
1723
+ for (const [id, entry] of [...xrefById]) {
1724
+ const ref = desired.get(id);
1725
+ if (!ref) { disposeXrefEntry(entry); xrefById.delete(id); }
1726
+ }
1727
+ for (const ref of desired.values()) {
1728
+ let entry = xrefById.get(ref.id);
1729
+ if (!entry || entry.objects !== ref.objects) {
1730
+ let staged = pendingXrefReplacements.get(ref.id);
1731
+ if (staged && staged.objects === ref.objects) {
1732
+ staged.name = ref.name || ref.id;
1733
+ setReferencePlacement(ref.id, ref.placement || null);
1734
+ applyReferenceDisplay(ref.id, ref.display || {});
1735
+ continue;
1736
+ }
1737
+ if (staged) cancelStagedReference(ref.id, staged, 'a newer geometry load replaced this upload');
1738
+ staged = createBatchedReference(ref); staged.staging = true;
1739
+ pendingXrefReplacements.set(ref.id, staged);
1740
+ staged.onTopologyReady = () => {
1741
+ if (pendingXrefReplacements.get(ref.id) !== staged || staged.disposed) return;
1742
+ pendingXrefReplacements.delete(ref.id); staged.staging = false; staged.onTopologyReady = null;
1743
+ const old = xrefById.get(ref.id);
1744
+ xrefGroup.add(staged.group); xrefById.set(ref.id, staged);
1745
+ applyReferenceDisplay(ref.id, staged.display);
1746
+ if (old && old !== staged) disposeXrefEntry(old);
1747
+ const selectedObjectWasHere = xrefSubSelected?.refId === ref.id;
1748
+ revalidateSubSelection(new Map(old ? [[ref.id, old.objects]] : []));
1749
+ paintReferenceSelection(); paintReferenceSubSelection();
1750
+ if (selectedObjectWasHere) emitReferenceSelect();
1751
+ if (api?.onReferenceGeometryCommit) api.onReferenceGeometryCommit(ref.id, staged.objects);
1752
+ if (pendingFrameReference === ref.id) { pendingFrameReference = null; frameReference(ref.id); }
1753
+ };
1754
+ ensureXrefTopology(staged, ref.id);
1755
+ continue;
1756
+ } else {
1757
+ entry.group.matrix.identity(); entry.group.matrixAutoUpdate = false; entry.group.applyMatrix4(xrefMatrix(ref.placement));
1758
+ entry.name = ref.name || ref.id;
1759
+ }
1760
+ applyReferenceDisplay(ref.id, ref.display || {});
1761
+ }
1762
+ for (const [id, staged] of [...pendingXrefReplacements]) if (!desired.has(id)) {
1763
+ cancelStagedReference(id, staged, 'the reference was removed before its geometry finished uploading');
1764
+ }
1765
+ if (xrefSelected && !xrefById.has(xrefSelected)) xrefSelected = null;
1766
+ revalidateSubSelection(prevObjects);
1767
+ paintReferenceSelection(); paintReferenceSubSelection();
1768
+ }
1769
+
1770
+ function _legacySetReferences(list) {
1464
1771
  refMeasureCands = null; // the measure's frustum-filtered snap set is derived from this — see setReferencePlacement
1465
1772
  invalidateClipFloor(); // the reference layer IS part of the clip-box floor: a reference arriving, being re-read, hidden or removed moves it
1466
1773
 
@@ -1660,8 +1967,8 @@ function revalidateSubSelection(prevObjects) {
1660
1967
  // The cheap, total answer first: nothing was re-read, so nothing can have moved.
1661
1968
  const prev = prevObjects && prevObjects.get(xrefSubSelected.refId);
1662
1969
  if (prev && prev === entry.objects) {
1663
- const held = entry.group.children[xrefSubSelected.index];
1664
- if (!held || !held.isMesh) xrefSubSelected = null;
1970
+ const held = entry.batched ? entry.objects?.[xrefSubSelected.index] : entry.group.children[xrefSubSelected.index];
1971
+ if (!held || (!entry.batched && !held.isMesh)) xrefSubSelected = null;
1665
1972
  return;
1666
1973
  }
1667
1974
  // A GENUINE RE-READ. Find the object by IDENTITY and move the selection to wherever it now sits —
@@ -1671,12 +1978,68 @@ function revalidateSubSelection(prevObjects) {
1671
1978
  if (gid === null || gid === undefined || entry.dupIds.has(gid)) { xrefSubSelected = null; return; }
1672
1979
  const index = entry.byGlobalId.get(gid);
1673
1980
  if (index === undefined) { xrefSubSelected = null; return; }
1674
- const mesh = entry.group.children[index];
1675
- if (!mesh || !mesh.isMesh) { xrefSubSelected = null; return; }
1981
+ const object = entry.objects?.[index];
1982
+ if (!object) { xrefSubSelected = null; return; }
1676
1983
  // REMAPPED, and `objectId` is refreshed with it: `id` may legitimately differ between two reads of
1677
1984
  // the same object (it falls back to the expressID), so carrying the old one forward would leave the
1678
1985
  // panel addressing a slot by a number this read never used.
1679
- xrefSubSelected = { refId: xrefSubSelected.refId, index, objectId: mesh.userData.objectId ?? null, globalId: gid };
1986
+ xrefSubSelected = { refId: xrefSubSelected.refId, index, objectId: object.id || null, globalId: gid };
1987
+ }
1988
+
1989
+ function ensureXrefTopology(entry, refId) {
1990
+ if (!entry?.batched) return;
1991
+ const topology = 'combined';
1992
+ if (entry.resolvedTopologies.has(topology)) return;
1993
+ if (entry.pendingTopologies.has(topology)) return;
1994
+ if (entry.combined) return;
1995
+ entry.pendingTopologies.add(topology);
1996
+ const alive = () => !entry.disposed && (entry.staging ? pendingXrefReplacements.get(refId) === entry : xrefById.get(refId) === entry);
1997
+ void (async () => {
1998
+ let completed = false;
1999
+ let combined = null;
2000
+ let expectedDrawable = false;
2001
+ try {
2002
+ const combinedFragments = xrefFragments(entry.objects, entry.anchor, 'combined');
2003
+ expectedDrawable = combinedFragments.length > 0;
2004
+ combined = await xrefBuildBatch(refId, combinedFragments, 'combined', entry.anchor, alive);
2005
+ if (!alive() || entry.desiredTopology !== topology) {
2006
+ disposeXrefBatch(combined);
2007
+ return;
2008
+ }
2009
+ if (expectedDrawable && !combined) {
2010
+ throw new Error('the decoded reference contained no drawable triangles');
2011
+ }
2012
+ // One combined topology serves File, Grey and custom colours. A colour-mode click now changes
2013
+ // material state only: it never repeats the building-sized GPU upload or retains a second copy.
2014
+ if (combined) entry.group.add(combined);
2015
+ entry.combined = combined;
2016
+ entry.activeTopology = topology;
2017
+ completed = true;
2018
+ } catch (error) {
2019
+ console.error('[reference] batched geometry upload failed', refId, error);
2020
+ disposeXrefBatch(combined);
2021
+ if (entry.staging && pendingXrefReplacements.get(refId) === entry) {
2022
+ // A staged replacement is deliberately detached, so the old entry is still the honest picture.
2023
+ // Cancel this replacement and tell the editor to restore the metadata array that picture uses;
2024
+ // otherwise Inspect describes the new file while the canvas continues to show the old one.
2025
+ pendingXrefReplacements.delete(refId);
2026
+ entry.onTopologyReady = null;
2027
+ disposeXrefEntry(entry);
2028
+ if (api?.onReferenceGeometryError) api.onReferenceGeometryError(
2029
+ refId, entry.objects, error?.message || 'the graphics device could not upload the reference',
2030
+ );
2031
+ } else if (api?.toast) api.toast('Could not update that reference view — keeping the previous view');
2032
+ } finally {
2033
+ entry.pendingTopologies.delete(topology);
2034
+ // A display pass may have run while no finished batch existed. Force the first pass over the
2035
+ // newly attached material so Grey/custom state cannot inherit the builder's file-colour default.
2036
+ if (alive() && completed) {
2037
+ entry.resolvedTopologies.add(topology);
2038
+ entry.painted = null;
2039
+ if (entry.onTopologyReady) entry.onTopologyReady(); else applyReferenceDisplay(refId, entry.display);
2040
+ }
2041
+ }
2042
+ })();
1680
2043
  }
1681
2044
 
1682
2045
  /**
@@ -1692,10 +2055,16 @@ function revalidateSubSelection(prevObjects) {
1692
2055
  * unlocked one.
1693
2056
  */
1694
2057
  function applyReferenceDisplay(id, display) {
2058
+ const staged = pendingXrefReplacements.get(id);
2059
+ if (staged) {
2060
+ staged.display = display || {};
2061
+ staged.group.visible = staged.display.visible !== false;
2062
+ ensureXrefTopology(staged, id);
2063
+ }
1695
2064
  const entry = xrefById.get(id); if (!entry) return;
1696
2065
  entry.display = display || {};
1697
2066
  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;
2067
+ const opacity = Number.isFinite(entry.display.opacity) ? Math.max(0, Math.min(1, entry.display.opacity)) : XREF_DEFAULT_OPACITY;
1699
2068
  entry.group.visible = visible;
1700
2069
  invalidateClipFloor(); // visibility decides whether this reference counts towards the clip-box floor at all — the eye toggle moves it
1701
2070
 
@@ -1711,6 +2080,49 @@ function applyReferenceDisplay(id, display) {
1711
2080
  const dropped = !visible && !!xrefSubSelected && xrefSubSelected.refId === id;
1712
2081
  if (dropped) { xrefSubSelected = null; paintReferenceSubSelection(); }
1713
2082
 
2083
+ if (entry.batched) {
2084
+ const mode = xrefMode(entry.display), custom = xrefCustom(entry.display);
2085
+ const shape = mode === 'file' ? 'file' : 'flat';
2086
+ const exactOpaque = opacity >= 0.999999;
2087
+ ensureXrefTopology(entry, id);
2088
+ if (entry.painted !== shape || (shape === 'flat' && entry.paintedHex !== (mode === 'custom' && custom !== null ? custom : XREF_COLOR))) {
2089
+ const flatHex = mode === 'custom' && custom !== null ? custom : XREF_COLOR;
2090
+ const flat = new THREE.Color(flatHex);
2091
+ for (const batch of [entry.combined, entry.opaque, entry.translucent]) {
2092
+ if (!batch) continue;
2093
+ batch.material.vertexColors = shape === 'file';
2094
+ batch.material.color.copy(shape === 'file' ? new THREE.Color(0xffffff) : flat);
2095
+ batch.material.needsUpdate = true;
2096
+ }
2097
+ entry.painted = shape; entry.paintedHex = flatHex;
2098
+ }
2099
+ if (entry.combined) {
2100
+ entry.combined.visible = entry.activeTopology === 'combined';
2101
+ // 100% means fully opaque in every colour mode, including File. Authored alpha remains in the
2102
+ // decoded colour data but does not silently turn the default into a transparent blend mode.
2103
+ const opaqueCombined = exactOpaque;
2104
+ const m = entry.combined.material;
2105
+ m.opacity = opaqueCombined ? 1 : opacity;
2106
+ m.transparent = !opaqueCombined;
2107
+ m.depthWrite = opaqueCombined;
2108
+ m.side = opaqueCombined ? THREE.FrontSide : THREE.DoubleSide;
2109
+ // At the 100% default the combined topology is genuinely opaque, so
2110
+ // Three's per-frame object sort is pure O(N log N) work over all 18k fragments. Turn it back on
2111
+ // only when this same topology is actually translucent and painter order has visual meaning.
2112
+ entry.combined.sortObjects = !opaqueCombined;
2113
+ m.needsUpdate = true;
2114
+ }
2115
+ if (xrefSubMats && xrefSubMesh?.userData.referenceId === id) {
2116
+ for (const material of xrefSubMats) {
2117
+ material.opacity = Math.max(opacity, XREF_SUB_MIN_OPACITY);
2118
+ material.needsUpdate = true;
2119
+ }
2120
+ }
2121
+ paintReferenceSelection();
2122
+ if (dropped) emitReferenceSelect();
2123
+ return;
2124
+ }
2125
+
1714
2126
  // ONLY A CHANGE OF SHAPE RE-MATERIALS, and "shape" means file-colours-vs-one-colour, NOT which
1715
2127
  // colour. Both the opacity slider and the colour picker fire on every pointer move, and reassigning
1716
2128
  // `mesh.material` across 17,000 meshes per move would turn either drag into a slideshow.
@@ -1733,8 +2145,16 @@ function applyReferenceDisplay(id, display) {
1733
2145
  // position. Only in `file` mode: overriding the colour means "paint this whole model one colour",
1734
2146
  // and keeping per-object alpha under an override would leave it patchy for no reason the user
1735
2147
  // 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;
2148
+ for (const m of entry.mats.values()) {
2149
+ const effective = opacity * m.userData.alpha;
2150
+ const opaque = effective >= 0.999999;
2151
+ m.opacity = effective; m.transparent = !opaque; m.depthWrite = opaque;
2152
+ m.side = opaque ? THREE.FrontSide : THREE.DoubleSide; m.needsUpdate = true;
2153
+ }
2154
+ entry.flat.opacity = opacity;
2155
+ entry.flat.transparent = opacity < 0.999999; entry.flat.depthWrite = opacity >= 0.999999;
2156
+ entry.flat.side = opacity >= 0.999999 ? THREE.FrontSide : THREE.DoubleSide;
2157
+ entry.flat.needsUpdate = true;
1738
2158
 
1739
2159
  // KEEP THE DRILLED-INTO OBJECT'S CLONES IN STEP, and choose the cheap path unless the expensive one
1740
2160
  // is actually required. A repaint reassigned every mesh's material, so the clones are now orphaned and
@@ -1773,9 +2193,10 @@ function xrefMaterial(entry, rgb, alpha) {
1773
2193
  }
1774
2194
 
1775
2195
  function newXrefMaterial(rgb, alpha) {
2196
+ const opaque = alpha >= 0.999999;
1776
2197
  const m = new THREE.MeshStandardMaterial({
1777
2198
  color: rgb, metalness: 0, roughness: 0.95,
1778
- transparent: true, opacity: 1, depthWrite: false, side: THREE.DoubleSide,
2199
+ transparent: !opaque, opacity: 1, depthWrite: opaque, side: opaque ? THREE.FrontSide : THREE.DoubleSide,
1779
2200
  });
1780
2201
  m.userData.alpha = alpha;
1781
2202
  return m;
@@ -1825,6 +2246,13 @@ function xrefBaseMaterial(entry, mesh, shape) {
1825
2246
  * not pay that on every keystroke — a transform is a 4×4 matrix, so it is applied as one.
1826
2247
  */
1827
2248
  function setReferencePlacement(id, placement) {
2249
+ const staged = pendingXrefReplacements.get(id);
2250
+ if (staged) {
2251
+ staged.group.matrix.identity();
2252
+ staged.group.position.set(0, 0, 0); staged.group.quaternion.identity(); staged.group.scale.set(1, 1, 1);
2253
+ staged.group.applyMatrix4(xrefMatrix(placement));
2254
+ staged.group.updateMatrixWorld(true);
2255
+ }
1828
2256
  const entry = xrefById.get(id); if (!entry) return;
1829
2257
  // THE OLD MATRIX, kept because three pieces of Stage D state are expressed in the world space it
1830
2258
  // defines. This function is the ONLY writer of that matrix, which is why the invalidation belongs
@@ -1903,7 +2331,8 @@ function paintReferenceSelection() {
1903
2331
  // several meshes share each one. Walking the entry's materials reaches every one exactly once and
1904
2332
  // cannot miss the members of an array the way `o.material.emissive` silently did. `flat` is not in
1905
2333
  // `mats` and must be lifted too, or selecting an OVERRIDDEN reference would highlight nothing.
1906
- for (const m of [...entry.mats.values(), entry.flat]) {
2334
+ const batchMats = entry.batched ? [entry.combined?.material, entry.opaque?.material, entry.translucent?.material].filter(Boolean) : [];
2335
+ for (const m of [...entry.mats.values(), entry.flat, ...batchMats]) {
1907
2336
  m.emissive.setHex(on ? 0xe2e8f0 : 0x000000);
1908
2337
  m.emissiveIntensity = on ? 0.35 : 0;
1909
2338
  }
@@ -1927,8 +2356,8 @@ function paintReferenceSelection() {
1927
2356
  * (`xrefBaseMaterial`). At most a handful of materials exist at a time — one per colour run of ONE
1928
2357
  * object — and they are disposed the moment the selection moves.
1929
2358
  */
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
2359
+ let xrefSubMats = null; // the clone(s) currently painted on the sub-selected mesh/overlay
2360
+ let xrefSubMesh = null; // the mesh or batched overlay they are painted on, so release never has to guess
1932
2361
 
1933
2362
  function paintReferenceSubSelection() {
1934
2363
  // RELEASE FIRST, ALWAYS — including when the new selection is the same mesh. A colour-MODE change
@@ -1937,13 +2366,72 @@ function paintReferenceSubSelection() {
1937
2366
  // (An opacity drag does NOT reach here — `applyReferenceDisplay` copies onto the existing clones in
1938
2367
  // place precisely so a drag allocates nothing. An earlier draft of this comment named it anyway.)
1939
2368
  if (xrefSubMesh) {
2369
+ const overlay = xrefSubMesh.userData?.batchedOverlay;
1940
2370
  const prev = xrefById.get(xrefSubMesh.userData.referenceId);
1941
- if (prev) xrefSubMesh.material = xrefBaseMaterial(prev, xrefSubMesh, prev.painted);
2371
+ if (overlay) {
2372
+ xrefSubMesh.parent?.remove(xrefSubMesh);
2373
+ // A logical IFC object may have several colour-correct render fragments. Their tiny wrapper
2374
+ // geometries share the worker's typed arrays; disposing the wrappers releases only GPU state.
2375
+ xrefSubMesh.traverse?.((o) => { if (o.isMesh) o.geometry?.dispose?.(); });
2376
+ }
2377
+ else if (prev) xrefSubMesh.material = xrefBaseMaterial(prev, xrefSubMesh, prev.painted);
1942
2378
  for (const m of xrefSubMats || []) m.dispose?.();
1943
2379
  xrefSubMesh = null; xrefSubMats = null;
1944
2380
  }
1945
2381
  if (!xrefSubSelected) return;
1946
2382
  const entry = xrefById.get(xrefSubSelected.refId);
2383
+ if (entry?.batched) {
2384
+ const object = entry.objects?.[xrefSubSelected.index];
2385
+ if (!object) return;
2386
+ const fragments = Array.isArray(object.renderFragments) ? object.renderFragments : [];
2387
+ const mode = xrefMode(entry.display), fileColors = mode === 'file';
2388
+ const baseColor = fileColors ? 0xffffff : (mode === 'custom' && xrefCustom(entry.display) !== null ? xrefCustom(entry.display) : XREF_COLOR);
2389
+ const m = new THREE.MeshStandardMaterial({ color: baseColor, vertexColors: fileColors, emissive: XREF_SUB_EMISSIVE,
2390
+ emissiveIntensity: XREF_SUB_INTENSITY, transparent: true,
2391
+ opacity: Math.max(Number.isFinite(entry.display?.opacity) ? entry.display.opacity : XREF_DEFAULT_OPACITY, XREF_SUB_MIN_OPACITY),
2392
+ depthWrite: false, side: THREE.DoubleSide });
2393
+ if (fragments.length) {
2394
+ // Do not copy/re-normal a potentially enormous slab on every click. The worker already produced
2395
+ // anchored, colour-correct shards with normals for the batch; a selected-object overlay can point
2396
+ // at those same immutable arrays and be ready within the interaction frame budget.
2397
+ const overlay = new THREE.Group();
2398
+ overlay.position.set(entry.anchor[0], entry.anchor[1], entry.anchor[2]);
2399
+ overlay.renderOrder = 2;
2400
+ overlay.userData = { referenceId: xrefSubSelected.refId, objectIndex: xrefSubSelected.index,
2401
+ objectId: object.id || null, globalId: object.globalId || null, batchedOverlay: true };
2402
+ for (const fragment of fragments) {
2403
+ const g = new THREE.BufferGeometry();
2404
+ g.setAttribute('position', new THREE.BufferAttribute(fragment.positions, 3));
2405
+ if (fileColors && fragment.vertexColors) g.setAttribute('color', new THREE.BufferAttribute(fragment.vertexColors, 4, true));
2406
+ if (fragment.normals) g.setAttribute('normal', new THREE.BufferAttribute(fragment.normals, 3)); else g.computeVertexNormals();
2407
+ if (fragment.indices?.length) g.setIndex(new THREE.BufferAttribute(fragment.indices, 1));
2408
+ const mesh = new THREE.Mesh(g, m);
2409
+ mesh.renderOrder = 2;
2410
+ mesh.userData = overlay.userData;
2411
+ overlay.add(mesh);
2412
+ }
2413
+ entry.group.add(overlay); xrefSubMesh = overlay; xrefSubMats = [m];
2414
+ return;
2415
+ }
2416
+ const positions = (Array.isArray(object.positions) || ArrayBuffer.isView(object.positions)) ? object.positions : [];
2417
+ const localSource = Array.isArray(object.geometryAnchor) && object.geometryAnchor.length === 3;
2418
+ const local = new Float32Array(positions.length);
2419
+ for (let i = 0; i + 2 < positions.length; i += 3) {
2420
+ 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]);
2421
+ }
2422
+ const g = new THREE.BufferGeometry();
2423
+ g.setAttribute('position', new THREE.BufferAttribute(local, 3));
2424
+ if (ArrayBuffer.isView(object.indices) && object.indices.length) g.setIndex(new THREE.BufferAttribute(object.indices, 1));
2425
+ else if (Array.isArray(object.indices) && object.indices.length) g.setIndex(object.indices);
2426
+ g.computeVertexNormals();
2427
+ const mesh = new THREE.Mesh(g, m);
2428
+ mesh.position.set(entry.anchor[0], entry.anchor[1], entry.anchor[2]);
2429
+ mesh.renderOrder = 2;
2430
+ mesh.userData = { referenceId: xrefSubSelected.refId, objectIndex: xrefSubSelected.index,
2431
+ objectId: object.id || null, globalId: object.globalId || null, batchedOverlay: true };
2432
+ entry.group.add(mesh); xrefSubMesh = mesh; xrefSubMats = [m];
2433
+ return;
2434
+ }
1947
2435
  const mesh = entry && entry.group.children[xrefSubSelected.index];
1948
2436
  if (!mesh || !mesh.isMesh) return;
1949
2437
  const base = xrefBaseMaterial(entry, mesh, entry.painted);
@@ -1988,13 +2476,16 @@ function pickReferenceAt(cx, cy) {
1988
2476
  if (!hit) return null;
1989
2477
  const u = hit.object.userData || {};
1990
2478
  if (!u.referenceId) return null;
2479
+ const batchedIndex = Number.isInteger(hit.batchId) && Array.isArray(u.batchToObject)
2480
+ ? u.batchToObject[hit.batchId] : null;
2481
+ const batchedObject = Number.isInteger(batchedIndex) ? xrefById.get(u.referenceId)?.objects?.[batchedIndex] : null;
1991
2482
  // AN OBJECT-SHAPED ANSWER, ALWAYS — never the bare id this used to return. Both callers want to know
1992
2483
  // WHICH object was under the pointer as well as which reference, and a function that answered one of
1993
2484
  // those questions with a string and the other with an object would be read wrong exactly once.
1994
2485
  return {
1995
2486
  referenceId: u.referenceId,
1996
- objectId: u.objectId ?? null,
1997
- objectIndex: Number.isInteger(u.objectIndex) ? u.objectIndex : -1,
2487
+ objectId: batchedObject?.id ?? u.objectId ?? null,
2488
+ objectIndex: Number.isInteger(batchedIndex) ? batchedIndex : (Number.isInteger(u.objectIndex) ? u.objectIndex : -1),
1998
2489
  };
1999
2490
  }
2000
2491
 
@@ -2026,17 +2517,17 @@ function selectReference(id) {
2026
2517
  /**
2027
2518
  * Drill into ONE object inside a reference.
2028
2519
  *
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:
2520
+ * Returns false and selects nothing when the index does not name a logical object — a stale index from a
2521
+ * tree row built before a reload, say. Falling back to "select the whole reference" would be worse than refusing:
2031
2522
  * the caller asked for an object, and quietly answering a different question is how a panel comes to
2032
2523
  * describe something the user did not pick.
2033
2524
  */
2034
2525
  function selectReferenceObject(refId, index) {
2035
2526
  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;
2527
+ const object = entry && Number.isInteger(index) && index >= 0 ? entry.objects?.[index] : null;
2528
+ if (!object) return false;
2038
2529
  xrefSelected = refId;
2039
- xrefSubSelected = { refId, index, objectId: mesh.userData.objectId ?? null, globalId: mesh.userData.globalId ?? null };
2530
+ xrefSubSelected = { refId, index, objectId: object.id || null, globalId: object.globalId || null };
2040
2531
  paintReferenceSelection();
2041
2532
  paintReferenceSubSelection();
2042
2533
  emitReferenceSelect();
@@ -2085,8 +2576,9 @@ function referenceProbe(id) {
2085
2576
  const ms = Array.isArray(o.material) ? o.material : (o.material ? [o.material] : []);
2086
2577
  if (Array.isArray(o.material)) { arrayMeshes++; runs += o.material.length; }
2087
2578
  for (const m of ms) inUse.add(m);
2088
- if (ms.some((m) => m.emissiveIntensity > 0)) lit.push(o.userData.objectIndex);
2579
+ if (!entry.batched && ms.some((m) => m.emissiveIntensity > 0)) lit.push(o.userData.objectIndex);
2089
2580
  });
2581
+ if (entry.batched && xrefSubSelected?.refId === id) lit.push(xrefSubSelected.index);
2090
2582
  return {
2091
2583
  mode: xrefMode(entry.display), painted: entry.painted,
2092
2584
  meshes, arrayMeshes, runs, materials: inUse.size, cached: entry.mats.size,
@@ -2132,7 +2624,10 @@ function referenceBounds(id) {
2132
2624
  */
2133
2625
  function frameReference(id) {
2134
2626
  const b = referenceBounds(id); // measures regardless of visibility, so this frames a hidden reference too
2135
- if (!b) return false;
2627
+ if (!b) {
2628
+ if (pendingXrefReplacements.has(id)) pendingFrameReference = id;
2629
+ return false;
2630
+ }
2136
2631
  fitCamera(new THREE.Box3(new THREE.Vector3(...b.min), new THREE.Vector3(...b.max)));
2137
2632
  return true;
2138
2633
  }
@@ -2146,19 +2641,26 @@ function frameReference(id) {
2146
2641
  *
2147
2642
  * SEPARATE FROM THE SELECTION rather than folded into it, so the canvas gesture keeps its behaviour
2148
2643
  * 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
2644
+ * Returns false when the index does not name a logical object — the same refusal, for the same reason, as
2150
2645
  * `selectReferenceObject`: quietly framing something else is worse than not moving.
2151
2646
  */
2152
2647
  function frameReferenceObject(refId, index) {
2153
2648
  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);
2649
+ if (!entry || !Number.isInteger(index) || index < 0 || !entry.objects?.[index]) return false;
2650
+ const box = xrefObjectWorldBox(entry, index);
2157
2651
  if (box.isEmpty()) return false;
2158
2652
  fitCamera(box);
2159
2653
  return true;
2160
2654
  }
2161
2655
 
2656
+ function xrefObjectWorldBox(entry, index) {
2657
+ const box = new THREE.Box3(), p = entry.objects?.[index]?.positions || [];
2658
+ const v = new THREE.Vector3(); entry.group.updateMatrixWorld(true);
2659
+ const local = Array.isArray(entry.objects?.[index]?.geometryAnchor);
2660
+ 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));
2661
+ return box;
2662
+ }
2663
+
2162
2664
  /**
2163
2665
  * The reference snap candidates for a drag, in the shape `snapPoint` consumes.
2164
2666
  *
@@ -2224,17 +2726,33 @@ function referenceCandidates(onlyId) {
2224
2726
 
2225
2727
  /** Test/panel probe: what the layer is actually holding, per reference. */
2226
2728
  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
- }));
2729
+ return [...xrefById.entries()].map(([id, e]) => {
2730
+ const draws = e.group.children.filter((child) => child.visible && child.isMesh);
2731
+ const materials = draws.flatMap((draw) => (Array.isArray(draw.material) ? draw.material : [draw.material]).map((material) => ({
2732
+ kind: draw.userData?.kind || null,
2733
+ opacity: material.opacity,
2734
+ transparent: material.transparent,
2735
+ depthWrite: material.depthWrite,
2736
+ side: material.side === THREE.FrontSide ? 'front' : material.side === THREE.DoubleSide ? 'double' : 'back',
2737
+ })));
2738
+ const materialOpacity = materials.length ? Math.min(...materials.map((material) => material.opacity)) : null;
2739
+ return {
2740
+ id, name: e.name,
2741
+ gpuId: e.group.id,
2742
+ meshes: e.objects?.length || 0,
2743
+ drawMeshes: e.group.visible ? draws.length : 0,
2744
+ visible: e.group.visible,
2745
+ opacity: materialOpacity,
2746
+ materials,
2747
+ topology: e.activeTopology,
2748
+ topologyPending: [...e.pendingTopologies],
2749
+ snap: e.display.snap !== false,
2750
+ locked: !!e.display.locked,
2751
+ selected: id === xrefSelected,
2752
+ snapPoints: e.total, snapCapped: e.capped || !!e.keptCapped,
2753
+ bounds: referenceBounds(id),
2754
+ };
2755
+ });
2238
2756
  }
2239
2757
 
2240
2758
  // ---- Insert a vectored detail (Slice 4): arm a placement pick; the editor owns the entry ----
@@ -2335,9 +2853,8 @@ function syncMemberLabels() {
2335
2853
  }
2336
2854
  for (let i = 0; i < memberLabelPool.length; i++) {
2337
2855
  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
2856
+ // ASK THE READ BOUNDARY FOR A WORK LINE, never for projected `m.wp` (see buildRefLines). A canonical
2857
+ // member has `from`/`to`, so the old guard skipped every member of a native
2341
2858
  // model and the toggle drew nothing at all. MEASURED in a real browser on a v2 document: both pools
2342
2859
  // allocated their divs and left every one `display:none` with empty text (#614).
2343
2860
  const g = m && geoOf(m);
@@ -2472,7 +2989,7 @@ const gridTexCache = new Map(); // 'b:LABEL' bubble / 't:LABEL' tag -> CanvasTex
2472
2989
  // it lives in localStorage next to the other per-browser display prefs and never touches the contract.
2473
2990
  const GRID_LABEL_PX_DEFAULT = 26, GRID_LABEL_PX_MIN = 14, GRID_LABEL_PX_MAX = 48;
2474
2991
  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; } })();
2992
+ 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
2993
 
2477
2994
  // Snap targets for the 3D tools. Members come from the WHOLE model — every sheet, not just the active
2478
2995
  // one — so "3D snapping on" can grab any member at any elevation (the 3D scene shows all sheets; snapping
@@ -2556,10 +3073,8 @@ function clearStructGrid() {
2556
3073
  }
2557
3074
  function buildStructGrid() {
2558
3075
  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.
3076
+ // The native grid is already world mm with Y up. Handing it to the display-space conversion would not
3077
+ // throw; it would draw the whole grid mirrored about Y, plausibly, at 1/12 scale.
2563
3078
  // So the read half answers with the drawable geometry AND the two facts needed to place it.
2564
3079
  let d = null;
2565
3080
  try { if(api&&scene)d = MODEL().gridDraw(); }
@@ -2891,6 +3406,7 @@ function fitCamera(box, dir) {
2891
3406
  orthoBaseH = fit.orthoH; // tight, aspect-preserving box fit (no ortho under-frame)
2892
3407
  if (camera === orthoCam) reframeOrtho();
2893
3408
  controls.update();
3409
+ camFitted = camFramed = true; // the camera now frames something real → durable fact + the loop may paint (see camFitted/camFramed)
2894
3410
  }
2895
3411
 
2896
3412
  // CAD re-pivot (wired to OrbitControls' 'start' — fires for orbit/pan/wheel before the gesture is applied):
@@ -2920,9 +3436,28 @@ async function rebuild(fit = false) {
2920
3436
  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
3437
  if (fit) fitPending = true; // entering 3D re-fits; an edit-triggered rebuild keeps the camera put
2922
3438
  const seq = ++rebuildSeq;
2923
- const sc = await api.fetchScene(); // editor POSTs the current contract to /scene
3439
+ let sc;
3440
+ try {
3441
+ sc = await api.fetchScene(); // editor POSTs the current contract to /scene
3442
+ } catch (e) {
3443
+ /* A REJECTED FETCH STILL OPENS THE GATE, because the pane it belongs to may still be on screen.
3444
+ * Usually setView catches this, toasts and reverts to 2D — but not always: switch 3d→split while
3445
+ * the first open is in flight and nextMode reports show3d:false, so setView never rebuilds again
3446
+ * and the superseded open's catch returns without reverting. That pane stays visible, and a gate
3447
+ * left shut would leave it blank for ever.
3448
+ * This does NOT poison the retry, which is what an earlier cut of this change got wrong: show()
3449
+ * re-derives the gate from camFitted, which a rejection never sets, so the next open starts shut. */
3450
+ if (seq === rebuildSeq) camFramed = true;
3451
+ throw e; // callers still see the failure — setView toasts it
3452
+ }
2924
3453
  if (seq !== rebuildSeq) return; // a newer rebuild superseded this one → drop the stale scene (no out-of-order apply)
2925
- if (sc) buildFromScene(sc);
3454
+ if (sc) {
3455
+ buildFromScene(sc);
3456
+ // buildFromScene has already run fitCamera when a fit was pending, so this is the safety net for
3457
+ // the one case that legitimately has nothing to fit: an EMPTY model, where cameraFitForBox
3458
+ // declines the empty box and the pane would otherwise stay dark for good.
3459
+ camFramed = true;
3460
+ } 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
3461
  refreshDims(); // persisted dims appear + survive edit-rebuilds (re-coloured for the current selection)
2927
3462
  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
3463
  }
@@ -3164,8 +3699,8 @@ function applyObjectsPaneState(s) {
3164
3699
  // Tekla "isolate selected": show ONLY the currently-selected parts (a snapshot taken now — distinct from
3165
3700
  // soloToggle, which isolates a whole PROFILE group from the legend). clearIsolation / showAllGroups restore all.
3166
3701
  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.
3702
+ // Hide the current selection by explicit mesh id. This remains session-only because saved views require tagged
3703
+ // SceneRefs while the renderer owns raw ids; broadening that contract is separate from toolbar state.
3169
3704
  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
3705
  function clearIsolation() { if (isolatedIds === null && isolatedGridIds === null) return; isolatedIds = null; isolatedGridIds = null; applyGroupVisibility(); applyGridVisibility(); rebuildEndpoints(); refreshOverlayDims(); refreshDims(); updateStatusChip(); notifyVisibilityChange(); }
3171
3706
  function isIsolated() { return isolatedIds !== null || isolatedGridIds !== null; }
@@ -4863,16 +5398,10 @@ const memberById = (id) => { const all = (api && api.allMembers && api.allMember
4863
5398
  // pt_per_ft inverted the commit through the wrong scale and wrote a mis-scaled wp — while the target it
4864
5399
  // snapped to had been computed in the target sheet's own scale. One source ⇒ they cannot disagree.
4865
5400
  /*
4866
- * ---- THE MODEL READ HALF (unit 5, P7d) -----------------------------------------------------------
5401
+ * ---- THE MODEL READ BOUNDARY --------------------------------------------------------------------
4867
5402
  *
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.
4872
- *
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.
5403
+ * Every geometry read this view makes goes through ONE object the host injects, so canonical model
5404
+ * semantics stop at that boundary instead of branching through this renderer.
4876
5405
  *
4877
5406
  * WHAT LIVED HERE AND MOVED: `activeScale`, `planList`, `scaleIndex`, `scaleFor` and the scale cache.
4878
5407
  * P5's review round 4 corrected the understatement that geoOf was a delegation — it is a seam, and those
@@ -4883,8 +5412,8 @@ const memberById = (id) => { const all = (api && api.allMembers && api.allMember
4883
5412
  let modelReads = null;
4884
5413
  function MODEL() {
4885
5414
  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
5415
+ // NAMED rather than a fallback. A host without this seam cannot be served by quietly reading projected
5416
+ // fields: a canonical document has no `m.wp`/`m.col`, so that would yield
4888
5417
  // NaN geometry — a scene that draws, silently, in nowhere.
4889
5418
  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
5419
  modelReads = api.model();
@@ -4894,10 +5423,8 @@ function MODEL() {
4894
5423
  /** The model changed, or the grid did — drop whatever the read half cached off the old one. */
4895
5424
  function invalidateModelCache() { if (modelReads && typeof modelReads.invalidate === 'function') modelReads.invalidate(); }
4896
5425
  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.
5426
+ // A member's WORK LINE in world mm, resolved by the native adapter. Overlays, labels, and reference lines
5427
+ // must use the same geometry as the server-built mesh.
4901
5428
  const geoOf = (m) => MODEL().geometryOf(m);
4902
5429
  const geoMode = () => (api && api.geoMode && api.geoMode()) || null;
4903
5430
 
@@ -4906,7 +5433,7 @@ const geoMode = () => (api && api.geoMode && api.geoMode()) || null;
4906
5433
  let workPlane = null; // {origin:[x,y,z]mm, normal, xAxis} | null
4907
5434
  let wpMode = null; // 'face' | '3pt' — armed set-plane pick mode
4908
5435
  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
5436
+ 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
5437
  let wpGroup = null;
4911
5438
  let wpExtent = null; // test-observability: the projected u/v footprint the last-rendered "Show plane" surface was sized to (null = fallback square)
4912
5439
  // ---- 3D local drawing frame (UCS, stage 1): a SEPARATE rotate-about-Z frame for skewed framing.
@@ -5248,7 +5775,7 @@ function setWorkPlanePrincipal(kind, offsetMm) {
5248
5775
  wpMode = null; wpDraft = null; invalidatePointEntry('drift'); renderWorkPlane(); reflectWpBar(); updateStatusChip();
5249
5776
  }
5250
5777
  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(); }
5778
+ 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
5779
  function workPlaneInfo() { return { set: !!workPlane, mode: wpMode, visible: wpVisible, plane: workPlane ? { origin: [...workPlane.origin], normal: [...workPlane.normal], xAxis: [...workPlane.xAxis] } : null }; }
5253
5780
  /**
5254
5781
  * face pick: the same face → plane conversion the clip tool does, over the same `faceHitAt`, with the
@@ -5821,8 +6348,8 @@ function onDown(e) {
5821
6348
  let id = null; try { id = pickAt(e.clientX, e.clientY); } catch { id = null; }
5822
6349
  // Geometry-edit mode (Trim/Extend or Split armed in the inspector): a click does the edit, no drag.
5823
6350
  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:
6351
+ // An editable projected end node (the yellow/magenta dot) under the cursor → grab just that endpoint to
6352
+ // stretch the member. Canonical members still render selection endpoint dots, but are not edited here:
5826
6353
  // let those pixels fall through to the ordinary member-selection path below.
5827
6354
  if (MODEL().memberEditing !== false) {
5828
6355
  let ep = null; try { ep = pickEndpoint(e.clientX, e.clientY); } catch { ep = null; }
@@ -5868,9 +6395,9 @@ function onDown(e) {
5868
6395
  }
5869
6396
  }
5870
6397
  }
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
6398
+ // Canonical member geometry is deliberately not edited through the projected drag path. A press still
6399
+ // needs enough state for onUp to perform ordinary selection, but must not ask for an owning-sheet scale
6400
+ // or build display-space drag candidates. Keeping this boundary in the model adapter prevents selection from
5874
6401
  // failing before Member length (and every other selection-driven read) can see the chosen member.
5875
6402
  if (MODEL().memberEditing === false) { pending = { id, add }; return; }
5876
6403
  const { ptPerFt: ppf, defaultTosMm: dtos } = scaleFor(m); // the GRABBED member's sheet, not the active one
@@ -6001,6 +6528,7 @@ function onTeklaDragMove(e) {
6001
6528
  pending = dragging = null; boxSel = null; if (controls) controls.enabled = true;
6002
6529
  teklaDrag.badge = teklaBadge(teklaDrag.ids.length);
6003
6530
  updateStatusChip();
6531
+ notifyInstructor(); // a pointermove arm: no input event the reporter watches will follow
6004
6532
  }
6005
6533
  // The badge is ours to place; outside the window it simply clips away, and the status chip carries
6006
6534
  // the message from there.
@@ -6011,7 +6539,7 @@ function onTeklaDragMove(e) {
6011
6539
  // let go somewhere that abandons the gesture.
6012
6540
  const outside = pointerOutsideWindow(e);
6013
6541
  const nextTarget = outside ? hostUnderPointer(teklaDrag, e) : null;
6014
- if (nextTarget !== teklaDrag.target) { teklaDrag.target = nextTarget; updateStatusChip(); }
6542
+ if (nextTarget !== teklaDrag.target) { teklaDrag.target = nextTarget; updateStatusChip(); notifyInstructor(); }
6015
6543
  paintDragBadge(teklaDrag);
6016
6544
  if (canvasEl) canvasEl.style.cursor = outside ? 'default' : 'alias';
6017
6545
  }
@@ -6467,6 +6995,67 @@ function onHoverMove(e) {
6467
6995
  }
6468
6996
  // The shared axis-lock chip suffix (' · X, Y locked') from tfLock — used by both the Move/Copy and Add-member chips.
6469
6997
  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' : ''; }
6998
+
6999
+ /* ── Instructor seam ────────────────────────────────────────────────────────
7000
+ WHAT IS ARMED, answered here because this module owns the state — the same
7001
+ reason the editor's reporter lives inside its main(). One accessor rather
7002
+ than eight, so steel-editor.html never has to reach into this module's
7003
+ internals to work out what the user is doing.
7004
+ Returns a registry command id and the index of the step in flight, or null
7005
+ when no 3D command is armed. It composes NO text: the step SENTENCE for each
7006
+ of these ids is authored once, in web/commands-steel.js. */
7007
+ function instructorCommand() {
7008
+ if (teklaDrag && teklaDrag.active) return { armed: 'steel.host-drag', step: 0 };
7009
+ if (wpMode === 'face') return { armed: 'steel.work-plane-face', step: 0 };
7010
+ if (wpMode === '3pt') return { armed: 'steel.work-plane-3pt', step: (wpDraft || []).length };
7011
+ if (clipMode === 'box') return { armed: 'steel.clip-box', step: !clipBoxDraft ? 0 : (!clipBoxDraft.b ? 1 : 2) };
7012
+ if (clipMode === 'plane') return { armed: 'steel.clip-plane', step: 0 };
7013
+ if (refMeasure3d) return { armed: 'steel.reference-measure', step: refMeasure3d.a ? 1 : 0 };
7014
+ if (framePickStep() != null) return { armed: 'steel.local-frame', step: framePickStep() };
7015
+ if (frameMode) return { armed: 'steel.frame-adjust', step: 0 };
7016
+ if (insertMode) return { armed: 'steel.insert-detail', step: 0 };
7017
+ if (basePickCol) return { armed: 'steel.base-pick', step: 0 };
7018
+ if (gridLinePick3d) return { armed: 'steel.grid-line', step: gridLinePick3d.a ? 1 : 0 };
7019
+ if (dimMode3d) return { armed: 'steel.dimension', step: dimDraft3d ? 1 : 0 };
7020
+ /* Extend/trim and Split. Omitting these left canvasToolGuidanceState composing
7021
+ their prose while the band narrated the registry's — one command, two
7022
+ sentences on screen at once, which is the exact thing this phase removes. */
7023
+ if (geoMode() === 'el') return { armed: 'steel.extend-trim', step: 0 };
7024
+ if (geoMode() === 'split') return { armed: 'steel.split', step: 0 };
7025
+ if (addActive()) return { armed: 'steel.add-member', step: drDraft ? 1 : 0 };
7026
+ if (cmActive()) { const st = cmActive();
7027
+ return { armed: st.tool === 'move' ? 'steel.move' : (st.array ? 'steel.copy-array' : 'steel.copy'),
7028
+ step: !tfDraft ? 0 : (st.array && !tfDraft.vA ? 1 : st.array ? 2 : 1) }; }
7029
+ return null;
7030
+ }
7031
+
7032
+ /* THE guidance slot for this surface. Its whole body is "keep what the shell
7033
+ produced, repaint" — it assembles no narration, which is what stops this chip
7034
+ drifting back into being a third independent narrator. The step sentences it
7035
+ paints came from the registry, via the shell's one producer. */
7036
+ let guidancePayload = null;
7037
+ function renderGuidance(payload) { guidancePayload = payload; updateStatusChip(); }
7038
+
7039
+ /* Ask the reporter to publish. Needed where an arm/disarm happens on a POINTERMOVE
7040
+ — the drag-out into a CAD host is the live case — because pointermove is not one
7041
+ of the events the reporter watches, and render() is deliberately off that path.
7042
+ Without this the shell never hears the drag start, and the chip that is the only
7043
+ thing on screen once the badge clips away falls back to a bare label. */
7044
+ function notifyInstructor() {
7045
+ try { if (window.__instructor && window.__instructor.notifyChanged) window.__instructor.notifyChanged(); }
7046
+ catch (e) { /* no shell above us */ }
7047
+ }
7048
+
7049
+ /** The step sentence the shell produced FOR THIS COMMAND, or null.
7050
+ The id check is the point: without it, a payload that has not caught up yet
7051
+ paints another command's instruction verbatim — a guidance surface being
7052
+ confidently wrong is worse than one saying nothing. */
7053
+ function armedStepText(commandId) {
7054
+ const g = guidancePayload;
7055
+ if (!g || g.tone !== 'armed' || !g.parts || !g.parts.length) return null;
7056
+ if (commandId && g.commandId && g.commandId !== commandId) return null;
7057
+ return g.parts[0];
7058
+ }
6470
7059
  function updateStatusChip() {
6471
7060
  if (!hoverChip || !canvasEl) return;
6472
7061
  const rect = canvasEl.getBoundingClientRect();
@@ -6482,32 +7071,39 @@ function updateStatusChip() {
6482
7071
  });
6483
7072
  const forceOpen = toolGuidance.forceOpen;
6484
7073
  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';
7074
+ /* ── the armed-command branch, now ONE branch ────────────────────────────
7075
+ Every armed tool used to compose its own step prose here, which is exactly
7076
+ how this chip became a narrator independent of the Instructor band and the
7077
+ 2D panel. It now paints the sentence the shell produced from the registry,
7078
+ and the only thing added on top is live state this surface alone knows:
7079
+ the axis lock, and the reference-measure's kept result. Those are affordance
7080
+ detail about THIS canvas, not narration of the command's step — the test in
7081
+ server/instructor-narrators.test.ts pins that boundary.
7082
+
7083
+ No payload yet (standalone, or before the first report) → fall through to a
7084
+ degraded label-only readout rather than inventing a step sentence here. */
7085
+ const cmd3d = instructorCommand();
7086
+ const stepTxt = cmd3d ? armedStepText(cmd3d.armed) : null;
7087
+ if (cmd3d && stepTxt) {
7088
+ const suffix = (cmd3d.armed === 'steel.add-member' || cmd3d.armed === 'steel.move'
7089
+ || cmd3d.armed === 'steel.copy' || cmd3d.armed === 'steel.copy-array') ? lockChipTxt() : '';
7090
+ // The measure keeps a result the user can still act on; that is live state, not a step.
7091
+ const kept = (cmd3d.armed === 'steel.reference-measure' && refMeasureKept && !refMeasure3d.a)
7092
+ ? ' · last measurement is in the panel' : '';
7093
+ /* The drag badge follows the cursor and clips away at the window edge, so from
7094
+ there this chip is the only thing still saying what releasing will do —
7095
+ which host is under the pointer, and how many members go. Both are live
7096
+ facts about this drag, not the step. */
7097
+ let drag = '';
7098
+ if (cmd3d.armed === 'steel.host-drag' && teklaDrag) {
7099
+ const n = teklaDrag.ids.length;
7100
+ drag = ` · ${n} ${n === 1 ? 'member' : 'members'}`
7101
+ + (teklaDrag.target ? ` · over ${HOST_SHORT[teklaDrag.target]}` : '');
7102
+ }
7103
+ txt = stepTxt + suffix + kept + drag + ' · Esc to cancel';
7104
+ }
7105
+ else if (cmd3d) { const meta = window.Commands && window.Commands.get(cmd3d.armed);
7106
+ txt = (meta ? meta.label : cmd3d.armed) + ' · Esc to cancel'; } // reporter-unavailable fallback
6511
7107
  else if (toolGuidance.text) txt = toolGuidance.text;
6512
7108
  else if (showId) { const m = memberById(showId); txt = m ? `${m.id} · ${m.profile || '—'}` : ''; }
6513
7109
  else if (selectionStatus) txt = selectionStatus;
@@ -6535,7 +7131,12 @@ function updateStatusChip() {
6535
7131
  }
6536
7132
  }
6537
7133
 
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)
7134
+ // RE-DERIVE THE PAINT GATE FROM THE DURABLE FACT on every open. An ordinary 2D→3D re-entry has a
7135
+ // fitted camera, so this keeps painting instantly; a retry after a failed open does not (a rejection
7136
+ // opened the gate so the pane would not sit blank, but never fitted anything), so this re-closes it
7137
+ // and the retry is as clean as a first open. unframedFrames/unframedWarned reset with it, or two
7138
+ // short stalls would add up into one bogus warning.
7139
+ 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
7140
  function hide() {
6540
7141
  invalidatePointEntry('hide'); // leaving 3D → drop any open typed entry + stale base/start
6541
7142
  if (dimMode3d) toggleDimTool(); // disarm the dim tool + sync its toolbar (no stale draft/armed state on return)
@@ -6548,9 +7149,7 @@ function hide() {
6548
7149
  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
7150
  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
7151
  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
7152
+ 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
7153
  clearCopyGhost(); // drop a stale Ctrl+drag copy ghost on the way out
6555
7154
  endTeklaDrag(); // and a live drag-out to Tekla — a stranded one would leave its badge on screen and swallow every later pointer move
6556
7155
  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 +7172,18 @@ function dispose() {
6573
7172
  // it — a view disposed mid-import would leak its meshes and their material. It owns its own
6574
7173
  // disposal for exactly that reason; this is the one caller that has to remember to ask.
6575
7174
  clearReferencePreview();
6576
- if (rafId) cancelAnimationFrame(rafId);
6577
- if (hoverRAF) cancelAnimationFrame(hoverRAF);
7175
+ /* CANCEL **AND** CLEAR. Both of these handles are read back as "is a frame already queued?", so
7176
+ * cancelling without clearing leaves a teardown that permanently disables the thing it tore down:
7177
+ * rafId — show() restarts the loop only on `if (!rafId) loop()`, so a stale handle means a
7178
+ * dispose()/init()/show() cycle never repaints at all. hide() has always got this
7179
+ * right (`rafId = null` in the same statement); dispose had drifted from it.
7180
+ * hoverRAF — scheduleHover bails on `if (hoverRAF || …) return`, so a stale handle kills hover
7181
+ * highlighting for the rest of the page. Same defect, one line down; fixing only the
7182
+ * first would re-open the drift this pair is pinned against.
7183
+ * Cleared to the same falsy values the live code uses (null / 0), not merged, because both are
7184
+ * compared truthily and the types are already established at their declarations. */
7185
+ if (rafId) { cancelAnimationFrame(rafId); rafId = null; }
7186
+ if (hoverRAF) { cancelAnimationFrame(hoverRAF); hoverRAF = 0; }
6578
7187
  if (ro) ro.disconnect();
6579
7188
  if (canvasEl) { canvasEl.removeEventListener('pointerdown', onDown, true); canvasEl.removeEventListener('pointermove', onHoverMove); canvasEl.removeEventListener('dblclick', onDblClick); canvasEl.removeEventListener('wheel', onWheelHover, true); }
6580
7189
  if (controls) controls.removeEventListener('start', repivotToCursor);
@@ -6608,7 +7217,14 @@ function dispose() {
6608
7217
  dims3dGroup = dimPreviewLine = overlayDimsGroup = null;
6609
7218
  // The reference layer owns real GPU buffers — a whole tessellated building's worth. Leaving them
6610
7219
  // 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); }
7220
+ // Detached replacements are not descendants of xrefGroup yet, so cancel them explicitly first. Their
7221
+ // async builders consult this map through `alive()`; clearing it prevents a late completion from
7222
+ // attaching to the renderer after its scene has already gone away.
7223
+ for (const [id, staged] of [...pendingXrefReplacements]) {
7224
+ cancelStagedReference(id, staged, 'the 3D view closed before geometry finished uploading', { resolutionOnly: true });
7225
+ }
7226
+ pendingFrameReference = null;
7227
+ if (xrefGroup) { disposeReferenceMaterials(); xrefGroup.traverse((o) => { if (o.isBatchedMesh) o.dispose?.(); else o.geometry?.dispose?.(); }); if (scene) scene.remove(xrefGroup); }
6612
7228
  // The ghost layer owns real buffers too, and it is a SIBLING of that group rather than a child — which
6613
7229
  // is the whole point of it, and also the reason the sweep above cannot reach it.
6614
7230
  clearReferenceGhosts();
@@ -6625,6 +7241,14 @@ function dispose() {
6625
7241
  clips = []; workArea = null; clipMode = null; selectedClipIds.clear(); clipBoxDraft = null; // clips live on the renderer; drop them with the renderer
6626
7242
  if (renderer) renderer.dispose();
6627
7243
  renderer = scene = camera = perspCam = orthoCam = controls = root = api = canvasEl = ro = null; built = false;
7244
+ // …and re-arm the first-frame gate, because camFramed is module state and would otherwise outlive
7245
+ // the cameras it describes: init() mints fresh, never-framed ones, so a gate left open paints them
7246
+ // straight away and the flat top view is back. This became load-bearing with the rafId fix above —
7247
+ // while dispose leaked that handle, show() could not restart the loop at all, so the cycle failed
7248
+ // dead rather than flashing. Stated honestly about reach: dispose() still has NO caller today (the
7249
+ // editor tears down by reloading, which resets module state anyway), so this guards the exported
7250
+ // teardown surface, not a path the app drives.
7251
+ camFitted = camFramed = false; unframedFrames = 0; unframedWarned = false; // the LATCH resets too, or a working re-init after dispose could never warn again
6628
7252
  }
6629
7253
 
6630
7254
  function debug() {
@@ -6632,6 +7256,7 @@ function debug() {
6632
7256
  const s = box.getSize(new THREE.Vector3()), c = box.getCenter(new THREE.Vector3());
6633
7257
  return {
6634
7258
  meshes: meshById.size,
7259
+ camFramed, // the first-frame gate — exposed so a browser pass can ASSERT the unframed window instead of photographing it
6635
7260
  triangles: renderer ? renderer.info.render.triangles : -1,
6636
7261
  bboxEmpty: box.isEmpty(), bboxSize: [s.x, s.y, s.z], bboxCenter: [c.x, c.y, c.z],
6637
7262
  firstId: meshById.keys().next().value ?? null,
@@ -6724,12 +7349,10 @@ function referenceObjectsScreen(refId, opts) {
6724
7349
  const want = opts && Array.isArray(opts.indices) ? new Set(opts.indices) : null;
6725
7350
  const limit = opts && Number.isFinite(opts.limit) ? opts.limit : 40;
6726
7351
  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;
7352
+ const rect = canvasEl.getBoundingClientRect(), c = new THREE.Vector3(), out = [];
7353
+ for (let i = 0; i < entry.objects.length; i++) {
6731
7354
  if (want && !want.has(i)) continue;
6732
- box.setFromObject(mesh); if (box.isEmpty()) continue;
7355
+ const box = xrefObjectWorldBox(entry, i); if (box.isEmpty()) continue;
6733
7356
  box.getCenter(c);
6734
7357
  const s = c.clone().project(camera);
6735
7358
  if (!Number.isFinite(s.x) || s.z > 1 || Math.abs(s.x) > 1 || Math.abs(s.y) > 1) continue;
@@ -6738,7 +7361,7 @@ function referenceObjectsScreen(refId, opts) {
6738
7361
  if (ours.length) continue;
6739
7362
  let hit = null; try { hit = pickReferenceAt(x, y); } catch { hit = null; }
6740
7363
  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) });
7364
+ out.push({ index: i, objectId: entry.objects[i]?.id ?? null, x: Math.round(x), y: Math.round(y) });
6742
7365
  if (out.length >= limit) break;
6743
7366
  }
6744
7367
  return out;
@@ -6824,6 +7447,8 @@ window.Steel3DView = {
6824
7447
  },
6825
7448
  toggleGroup, setGroupsHidden, setIdsHidden, connHiddenIds: () => [...connHidden], selectionHiddenIds: () => [...selectionHidden], soloToggle, setSoloGroups, showAllGroups, groupState, getGroups, visibleMemberIds, visibleObjectIds, visibleGridIds,
6826
7449
  setClipMode, clipMode: clipModeOn, toggleClip, removeClip, clearClips, getClips, renameClip, selectClip, setSelectedClips, selectedClips, deleteSelectedClips, clipState, setClipState,
7450
+ // Instructor seam: what this module has armed, and the one slot that paints what the shell produced.
7451
+ instructorCommand, renderGuidance,
6827
7452
  isolateSelected, hideSelected, clearIsolation, isIsolated, hasVisibilityFilter,
6828
7453
  cameraState, setCameraState, sectionViewState, sceneBounds, objectsPaneState, applyObjectsPaneState, // saved-view snapshot surface (Views Organizer + F11 generated cuts)
6829
7454
  workAreaSetAll, workAreaFromSelection, workAreaToggle, workAreaSetWhole, clearWorkArea, workAreaState,