@floless/app 0.130.0 → 0.131.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.
@@ -147,6 +147,8 @@ let dimDraft3d = null; // { a:[x,y,z] } once the first point is place
147
147
  let dimLastAlt = false; // last-seen Alt state (the hover rAF rebuilds a synthetic event)
148
148
  let hoverTeklaMod = false; // last-seen Ctrl+Shift state — arms the drag-out-to-Tekla cursor hint
149
149
  let pointerOverCanvas = false; // is the cursor actually on the 3D canvas right now (lastHoverXY outlives the pointer leaving)
150
+ let inputActive = true; // does this view own the keyboard? The editor sets it false when the 2D pane
151
+ // is the active one in a split — see setInputActive.
150
152
  let dims3dGroup = null; // THREE.Group of placed-dim lines (+ the live preview line)
151
153
  let dimPreviewLine = null; // reused preview line (point 1 → cursor)
152
154
  let dimLabelHost = null; // fixed-position container for label overlays
@@ -268,7 +270,7 @@ function init(canvas, theApi) {
268
270
  * THE FOUR MODEL-GLUED LABEL HOSTS SIT UNDER THE 3D CHROME, and the numbers below are the whole rule.
269
271
  *
270
272
  * Each is `position:fixed` on `<body>` and projected per frame, so it is painted in the ROOT stacking
271
- * context (`#stagewrap` and `<main>` are `position:relative; z-index:auto`, which creates none) — it
273
+ * context (`#pane3d`, `#stagewrap` and `<main>` are `position:relative; z-index:auto`, which creates none) — it
272
274
  * competes directly with the panels. They shipped at 56/57, above every panel, and a chip landing over
273
275
  * the expanded Objects panel drew ON TOP of it: unreadable itself, and hiding a control the user was
274
276
  * reading. Reported against the 3D property labels, but it was never theirs — the mark/id, dimension
@@ -381,6 +383,7 @@ function loop() {
381
383
  sizeEndpoints();
382
384
  sizeClipHandles();
383
385
  sizeFrameHandle();
386
+ sizeGridLabels();
384
387
  positionDimLabels();
385
388
  positionOverlayLabels();
386
389
  positionMemberLabels();
@@ -1253,6 +1256,151 @@ function clearReferencePreview() {
1253
1256
  }
1254
1257
  }
1255
1258
 
1259
+ // ── GHOSTS: where an object USED to be (#734, design §6.4) ──
1260
+ //
1261
+ // A `removed` row in the change list names an object that is in the previous version of a reference and
1262
+ // not in the new one. These are its shapes, re-read from that previous file, drawn where it stood.
1263
+ //
1264
+ // A SIBLING OF `xrefGroup`, NEVER A CHILD, for exactly the reason the preview above is one — and here the
1265
+ // requirement is sharper, because "never snappable and never counted in bounds" is a promise this feature
1266
+ // makes explicitly. Every reference-interaction entry point reads that group or `xrefById` directly:
1267
+ // `pickReferenceAt` raycasts `xrefGroup.children`, `referenceCandidates` and `referenceBounds` walk
1268
+ // `xrefById`, and `visibleWorldBox` — what Fit, Home, the ViewCube and the work-area box all measure —
1269
+ // unions `sceneBox` with `xrefGroup.children` and nothing else. Parented outside both, a ghost cannot be
1270
+ // picked, cannot be snapped to and cannot drag the Fit box out to a building that is no longer there. A
1271
+ // rule someone has to remember would not survive; this is structural.
1272
+ //
1273
+ // ONE MATERIAL, in the `removed` chip's own ink, so the shape on the canvas and the badge in the list are
1274
+ // visibly the same fact. Transparent and `depthWrite:false` behind the model, like every other borrowed
1275
+ // geometry here — a deletion must never occlude the steel you are checking it against.
1276
+
1277
+ /**
1278
+ * `--err` AS THE DARK THEME DRAWS IT (#fca5a5) — the same value the change list's `removed` chip takes,
1279
+ * so the shape on the canvas and the badge in the list read as one fact.
1280
+ *
1281
+ * A COPY, AND IT DOES NOT FOLLOW `[data-theme=light]`, which is correct rather than an oversight twice
1282
+ * over: WebGL cannot read a CSS custom property, and this canvas is dark in BOTH themes anyway —
1283
+ * `scene.background` is a fixed 0x020817 and `#stage3d` is in the light theme's re-anchor list, which
1284
+ * restates the dark tokens for exactly this subtree. On light, the chip moves to `--err`'s light stop
1285
+ * and the ghost stays where the canvas it sits on stayed.
1286
+ */
1287
+ const XREF_GHOST_COLOR = 0xfca5a5;
1288
+ const XREF_GHOST_OPACITY = 0.3;
1289
+ let xrefGhostGroup = null; // the ghosts' meshes, or null when none are drawn
1290
+ let xrefGhostMat = null; // its ONE material — ghosts are uniform, so one is enough
1291
+ let xrefGhostRef = null; // which reference these belong to, so a stale set cannot outlive it
1292
+ const xrefGhostById = new Map(); // globalId -> mesh, so one ghost can be framed
1293
+
1294
+ /**
1295
+ * Draw ghosts for one reference, appending to whatever is already there.
1296
+ *
1297
+ * APPENDS rather than rebuilds, because they arrive lazily — the panel asks only for the removed rows a
1298
+ * user has actually scrolled to, so a revision with 3,000 deletions never tessellates 3,000 objects.
1299
+ * A different `refId` clears first: ghosts belong to one reference's history, and two sets overlaid would
1300
+ * be two buildings' deletions with nothing on screen saying which is which.
1301
+ *
1302
+ * `placement` is the reference's own, applied to the group exactly as the real one's is, so a ghost sits
1303
+ * where the object stood rather than at the world origin.
1304
+ */
1305
+ function setReferenceGhosts(refId, objects, placement) {
1306
+ // THE OWNERSHIP CHECK COMES FIRST, before the empty-list guard. The other order leaves the PREVIOUS
1307
+ // reference's ghosts standing — under the previous reference's placement matrix — whenever a
1308
+ // different reference asks with nothing to draw. Not reachable from today's single caller, which
1309
+ // guards on `objects.length` itself, and that is exactly what makes it worth closing: this branch is
1310
+ // the same latent seam mismatch review already caught once on this change. (Review.)
1311
+ if (xrefGhostRef !== null && xrefGhostRef !== refId) clearReferenceGhosts();
1312
+ if (!scene || !Array.isArray(objects) || !objects.length) return { drawn: 0, skipped: 0 };
1313
+ if (!xrefGhostGroup) {
1314
+ xrefGhostGroup = new THREE.Group();
1315
+ xrefGhostGroup.renderOrder = -1;
1316
+ xrefGhostGroup.applyMatrix4(xrefMatrix(placement));
1317
+ scene.add(xrefGhostGroup);
1318
+ xrefGhostMat = newXrefMaterial(XREF_GHOST_COLOR, XREF_GHOST_OPACITY);
1319
+ xrefGhostMat.opacity = XREF_GHOST_OPACITY;
1320
+ xrefGhostRef = refId;
1321
+ }
1322
+ // COUNTED PER CALL, NOT CUMULATIVELY, and both halves are returned. `xrefGhostById.size` is a running
1323
+ // total, so a caller reading it could not tell "I drew nothing" from "I drew nothing NEW" — and the
1324
+ // two skips below are silent by construction: an object whose tessellation came back empty, and one
1325
+ // with no `globalId` (which gets a mesh but can never be framed, because framing is by id). The
1326
+ // caller reconciles this against what it asked for, so a shortfall is stated rather than looking
1327
+ // like a smaller deletion. (Review.)
1328
+ let drawn = 0, skipped = 0;
1329
+ for (const o of objects) {
1330
+ if (!o || !Array.isArray(o.positions) || !o.positions.length) { skipped++; continue; }
1331
+ const gid = (o && typeof o.globalId === 'string' && o.globalId) ? o.globalId : null;
1332
+ if (!gid) { skipped++; continue; } // unframeable and uncountable — drawing it would be a shape nothing can reach
1333
+ // ALREADY DRAWN IS NOT DRAWN AGAIN. The panel can legitimately ask for a row twice — scroll away and
1334
+ // back — and a second mesh at the same coordinates doubles the fill and leaves the first unreachable.
1335
+ if (xrefGhostById.has(gid)) continue;
1336
+ const g = new THREE.BufferGeometry();
1337
+ g.setAttribute('position', new THREE.Float32BufferAttribute(o.positions, 3));
1338
+ if (Array.isArray(o.indices) && o.indices.length) g.setIndex(o.indices);
1339
+ g.computeVertexNormals();
1340
+ const mesh = new THREE.Mesh(g, xrefGhostMat);
1341
+ // NOT PICKABLE EVEN IF SOMETHING EVER RAYCASTS THE WHOLE SCENE. The parenting above is what makes
1342
+ // this true today; this is the belt to that pair of braces, and it costs one field.
1343
+ mesh.raycast = () => {};
1344
+ mesh.userData.ghost = true;
1345
+ mesh.userData.globalId = gid;
1346
+ xrefGhostById.set(gid, mesh);
1347
+ xrefGhostGroup.add(mesh);
1348
+ drawn++;
1349
+ }
1350
+ return { drawn, skipped };
1351
+ }
1352
+
1353
+ /**
1354
+ * What the ghosts are ACTUALLY painted in, read off the material the renderer will use.
1355
+ *
1356
+ * The same reason `referenceProbe` exists: a screenshot cannot distinguish the authored colour from a
1357
+ * plausible one, and 30% alpha over a dark canvas makes every pale ink look alike. The rendered value is
1358
+ * the only thing entitled to answer "is this drawn in the `removed` chip's ink". `parent` is here because
1359
+ * the whole promise of this layer — never snappable, never in the Fit box — rests on WHERE the group is
1360
+ * parented, and that is otherwise unobservable from outside.
1361
+ */
1362
+ function referenceGhostPaint() {
1363
+ if (!xrefGhostGroup || !xrefGhostMat) return null;
1364
+ return {
1365
+ color: `#${xrefGhostMat.color.getHexString()}`,
1366
+ opacity: xrefGhostMat.opacity,
1367
+ meshes: xrefGhostGroup.children.length,
1368
+ /** 'scene' is correct; 'xref' would mean the ghosts had become snappable, pickable and framed. */
1369
+ parent: xrefGhostGroup.parent === scene ? 'scene' : xrefGhostGroup.parent === xrefGroup ? 'xref' : 'other',
1370
+ };
1371
+ }
1372
+
1373
+ /** Frame one ghost — what a click on a `removed` row asks for, since there is nothing to select. */
1374
+ function frameReferenceGhost(globalId) {
1375
+ const mesh = xrefGhostById.get(globalId);
1376
+ if (!mesh) return false;
1377
+ const box = new THREE.Box3().setFromObject(mesh);
1378
+ if (box.isEmpty()) return false;
1379
+ fitCamera(box);
1380
+ return true;
1381
+ }
1382
+
1383
+ /**
1384
+ * Remove every ghost and free what they hold. Idempotent — every terminal path in the panel calls it.
1385
+ *
1386
+ * The RESET IS IN `finally` for the reason the preview's is: a half-disposed group that stays referenced
1387
+ * is worse than a leak, because the next `setReferenceGhosts` would see a live group, skip its init, and
1388
+ * append a new reference's deletions into the old one's placement matrix.
1389
+ */
1390
+ function clearReferenceGhosts() {
1391
+ if (!xrefGhostGroup) { xrefGhostById.clear(); xrefGhostRef = null; return; }
1392
+ try {
1393
+ xrefGhostGroup.traverse((o) => { o.geometry?.dispose?.(); });
1394
+ scene?.remove(xrefGhostGroup);
1395
+ xrefGhostMat?.dispose?.();
1396
+ } finally {
1397
+ xrefGhostGroup = null;
1398
+ xrefGhostMat = null;
1399
+ xrefGhostRef = null;
1400
+ xrefGhostById.clear();
1401
+ }
1402
+ }
1403
+
1256
1404
  /** Unique world points for snapping, quantised so a tessellated corner is one target and not thirty. */
1257
1405
  function xrefSnapPoints(objects) {
1258
1406
  const seen = new Set(); const out = [];
@@ -1374,6 +1522,11 @@ function setReferences(list) {
1374
1522
  // a second lookup. `objectId` is the file's GlobalId and may be `''` (see `xrefSubSelected`), so
1375
1523
  // it is normalised to null here rather than being allowed to masquerade as a real, empty id.
1376
1524
  mesh.userData.objectId = (o && typeof o.id === 'string' && o.id) ? o.id : null;
1525
+ // THE FILE'S OWN GlobalId, and it is NOT `objectId` above. `objectId` is the reader's `id`, which
1526
+ // falls back to the expressID when a file records no GlobalId — a file-local sequence number that
1527
+ // two reads of two files share freely. Anything asking "is this the SAME object as before" must
1528
+ // use this one; anything merely addressing an object in THIS read may keep using `objectId`.
1529
+ mesh.userData.globalId = (o && typeof o.globalId === 'string' && o.globalId) ? o.globalId : null;
1377
1530
  mesh.userData.objectIndex = i;
1378
1531
  mesh.userData.colorRuns = runs;
1379
1532
  group.add(mesh);
@@ -1403,12 +1556,36 @@ function setReferences(list) {
1403
1556
  dupIds: (() => {
1404
1557
  const seen = new Set(), dup = new Set();
1405
1558
  for (const o of objects) {
1406
- const oid = (o && typeof o.id === 'string' && o.id) ? o.id : null;
1559
+ // KEYED ON `globalId`, not `id`. Keyed on `id` this set was near-empty against a current
1560
+ // reader — the reader substitutes a unique expressID wherever a GlobalId is missing, so
1561
+ // duplicates could not appear and neither could blanks. It was guarding a case that cannot
1562
+ // occur while the real one passed straight through.
1563
+ const oid = (o && typeof o.globalId === 'string' && o.globalId) ? o.globalId : null;
1407
1564
  if (oid === null) continue;
1408
1565
  if (seen.has(oid)) dup.add(oid); else seen.add(oid);
1409
1566
  }
1410
1567
  return dup;
1411
1568
  })(),
1569
+ /**
1570
+ * `globalId` -> the index its object now sits at, for ids that appear exactly ONCE.
1571
+ *
1572
+ * This is what makes `revalidateSubSelection` a REMAP rather than a re-check. Checking the same
1573
+ * array slot means an IFC that merely REORDERS its objects drops a perfectly valid drill even
1574
+ * though the object is still there under the same GlobalId — which does not lie to the user, but
1575
+ * throws away the identity this whole feature exists to supply. Duplicated ids are excluded for
1576
+ * the same reason `dupIds` refuses them: an id shared by two objects cannot say which one you
1577
+ * were on. Built here, in the loop that already walks every object, rather than per rebuild.
1578
+ */
1579
+ byGlobalId: (() => {
1580
+ const at = new Map();
1581
+ for (let i = 0; i < objects.length; i++) {
1582
+ const o = objects[i];
1583
+ const oid = (o && typeof o.globalId === 'string' && o.globalId) ? o.globalId : null;
1584
+ if (oid === null) continue;
1585
+ at.set(oid, i);
1586
+ }
1587
+ return at;
1588
+ })(),
1412
1589
  // `painted` is what `applyReferenceDisplay` compares against to decide whether re-materialling
1413
1590
  // every mesh is necessary at all. Opacity is dragged live and must stay a per-material write.
1414
1591
  mats, painted: null,
@@ -1448,17 +1625,28 @@ function setReferences(list) {
1448
1625
  * the selection and ask nothing further. Only a genuine re-read hands over a new array. (Codex review
1449
1626
  * caught this: the first cut dropped a perfectly valid drill every time an unrelated reference loaded.)
1450
1627
  *
1451
- * When the array HAS changed, the remembered `objectId` is checked — and TWO IDS THAT CANNOT DISTINGUISH
1452
- * ANYTHING CANNOT PASS:
1628
+ * When the array HAS changed, this REMAPS rather than re-checks, and the difference matters. The old
1629
+ * version asked whether `group.children[index]` still held the same id — so an IFC that merely REORDERED
1630
+ * its objects dropped a perfectly valid drill even though the object was still there, unchanged, under
1631
+ * the same GlobalId. That never lied to the user, but it threw away the identity this feature exists to
1632
+ * supply. Now the remembered `globalId` is looked up in the rebuilt entry and the selection MOVES to
1633
+ * wherever that object now sits.
1453
1634
  *
1454
- * null — `setReferences` normalises a missing or empty GlobalId to null, so in a file whose
1455
- * objects carry no ids EVERY slot answers null and the "check" would wave through whatever
1456
- * landed at index N. That is the failure this function exists to prevent, arriving through
1457
- * the front door.
1458
- * duplicate — the same, one step subtler: two objects sharing an id make "the id at index N still
1459
- * matches" true after a reorder that swapped them. Nothing validates GlobalId uniqueness —
1460
- * not the file, not the reader, not us — so the ids that repeat inside one reference are
1461
- * collected at build time and refused here.
1635
+ * IT KEYS ON `globalId`, NOT `objectId`, and that is a fix rather than a rename. `objectId` is the
1636
+ * reader's `id`, which falls back to the expressID when a file records no GlobalId — so against a
1637
+ * current reader the blank case below was UNREACHABLE (the reader always substitutes something
1638
+ * non-empty and unique) while the real failure, an expressID landing on a different object across two
1639
+ * reads, passed straight through. The branch was guarding a case that could not occur. `globalId` is
1640
+ * the file's own value or null, so blank is reachable and means what it says.
1641
+ *
1642
+ * TWO IDS THAT CANNOT DISTINGUISH ANYTHING STILL CANNOT PASS:
1643
+ *
1644
+ * null — a file whose objects carry no GlobalId gives every slot the same answer, so any check
1645
+ * against it would wave through whatever landed at index N. That is the failure this
1646
+ * function exists to prevent, arriving through the front door.
1647
+ * duplicate — the same, one step subtler: two objects sharing an id cannot say which one you were on.
1648
+ * Nothing validates GlobalId uniqueness — not the file, not the reader, not us — so the
1649
+ * ids that repeat inside one reference are collected at build time and refused here.
1462
1650
  *
1463
1651
  * The cost is stated rather than hidden: after a genuine re-read, a drill into an object with no id (or a
1464
1652
  * duplicated one) does not survive. It is not much of a cost — such a file gives us nothing to tell two
@@ -1468,14 +1656,27 @@ function setReferences(list) {
1468
1656
  function revalidateSubSelection(prevObjects) {
1469
1657
  if (!xrefSubSelected) return;
1470
1658
  const entry = xrefById.get(xrefSubSelected.refId);
1471
- const mesh = entry && entry.group.children[xrefSubSelected.index];
1472
- if (!mesh || !mesh.isMesh) { xrefSubSelected = null; return; }
1659
+ if (!entry) { xrefSubSelected = null; return; }
1473
1660
  // The cheap, total answer first: nothing was re-read, so nothing can have moved.
1474
1661
  const prev = prevObjects && prevObjects.get(xrefSubSelected.refId);
1475
- if (prev && prev === entry.objects) return;
1476
- const id = xrefSubSelected.objectId;
1477
- const same = id !== null && !entry.dupIds.has(id) && mesh.userData.objectId === id;
1478
- if (!same) xrefSubSelected = null;
1662
+ if (prev && prev === entry.objects) {
1663
+ const held = entry.group.children[xrefSubSelected.index];
1664
+ if (!held || !held.isMesh) xrefSubSelected = null;
1665
+ return;
1666
+ }
1667
+ // A GENUINE RE-READ. Find the object by IDENTITY and move the selection to wherever it now sits —
1668
+ // rather than asking whether the same array slot still holds it, which fails an IFC that merely
1669
+ // reordered its objects while the object itself is still present and unchanged.
1670
+ const gid = xrefSubSelected.globalId;
1671
+ if (gid === null || gid === undefined || entry.dupIds.has(gid)) { xrefSubSelected = null; return; }
1672
+ const index = entry.byGlobalId.get(gid);
1673
+ if (index === undefined) { xrefSubSelected = null; return; }
1674
+ const mesh = entry.group.children[index];
1675
+ if (!mesh || !mesh.isMesh) { xrefSubSelected = null; return; }
1676
+ // REMAPPED, and `objectId` is refreshed with it: `id` may legitimately differ between two reads of
1677
+ // the same object (it falls back to the expressID), so carrying the old one forward would leave the
1678
+ // panel addressing a slot by a number this read never used.
1679
+ xrefSubSelected = { refId: xrefSubSelected.refId, index, objectId: mesh.userData.objectId ?? null, globalId: gid };
1479
1680
  }
1480
1681
 
1481
1682
  /**
@@ -1634,6 +1835,19 @@ function setReferencePlacement(id, placement) {
1634
1835
  entry.group.position.set(0, 0, 0); entry.group.quaternion.identity(); entry.group.scale.set(1, 1, 1);
1635
1836
  entry.group.applyMatrix4(xrefMatrix(placement));
1636
1837
  entry.group.updateMatrixWorld(true);
1838
+ // THE GHOSTS MOVE WITH THE REFERENCE THEY BELONG TO. Their group takes the same matrix at creation
1839
+ // and would otherwise keep it forever — so Scale, "move it next to your model", or the heuristic's
1840
+ // fix button would leave red shapes standing at coordinates the removed objects never occupied,
1841
+ // which is precisely the "geometry asserting something nothing says" the ghost layer's own header
1842
+ // argues against. Newly REACHABLE because the change list is deliberately non-modal: the panel
1843
+ // floats over a live canvas, so a placement can change while ghosts are on screen. Batches that
1844
+ // arrive afterwards then land in the corrected matrix too, so one layer cannot hold two placements.
1845
+ if (xrefGhostGroup && xrefGhostRef === id) {
1846
+ xrefGhostGroup.matrix.identity();
1847
+ xrefGhostGroup.position.set(0, 0, 0); xrefGhostGroup.quaternion.identity(); xrefGhostGroup.scale.set(1, 1, 1);
1848
+ xrefGhostGroup.applyMatrix4(xrefMatrix(placement));
1849
+ xrefGhostGroup.updateMatrixWorld(true);
1850
+ }
1637
1851
  invalidateClipFloor(); // this reference just MOVED, so any floor measured from where it used to be is now wrong
1638
1852
  if (refMeasure3d && refMeasure3d.refId === id) {
1639
1853
  // The cache holds points BAKED through the old matrix, so every one of them now points at where
@@ -1822,7 +2036,7 @@ function selectReferenceObject(refId, index) {
1822
2036
  const mesh = entry && Number.isInteger(index) && index >= 0 ? entry.group.children[index] : null;
1823
2037
  if (!mesh || !mesh.isMesh) return false;
1824
2038
  xrefSelected = refId;
1825
- xrefSubSelected = { refId, index, objectId: mesh.userData.objectId ?? null };
2039
+ xrefSubSelected = { refId, index, objectId: mesh.userData.objectId ?? null, globalId: mesh.userData.globalId ?? null };
1826
2040
  paintReferenceSelection();
1827
2041
  paintReferenceSubSelection();
1828
2042
  emitReferenceSelect();
@@ -1923,6 +2137,28 @@ function frameReference(id) {
1923
2137
  return true;
1924
2138
  }
1925
2139
 
2140
+ /**
2141
+ * Frame ONE object inside a reference (#734, the change list's row click).
2142
+ *
2143
+ * `selectReferenceObject` lights an object; it does not move the camera, which is right for Ctrl+click —
2144
+ * you are already looking at the thing you clicked. It is wrong for a row in a list: "56 changed" is a
2145
+ * list of objects the user has NOT found yet, and highlighting one somewhere off-screen answers nothing.
2146
+ *
2147
+ * SEPARATE FROM THE SELECTION rather than folded into it, so the canvas gesture keeps its behaviour
2148
+ * 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
2150
+ * `selectReferenceObject`: quietly framing something else is worse than not moving.
2151
+ */
2152
+ function frameReferenceObject(refId, index) {
2153
+ 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);
2157
+ if (box.isEmpty()) return false;
2158
+ fitCamera(box);
2159
+ return true;
2160
+ }
2161
+
1926
2162
  /**
1927
2163
  * The reference snap candidates for a drag, in the shape `snapPoint` consumes.
1928
2164
  *
@@ -2231,6 +2467,12 @@ const structGridLines = new Map();
2231
2467
  let selectedGridIds = new Set();
2232
2468
  let structGridSignature = null;
2233
2469
  const gridTexCache = new Map(); // 'b:LABEL' bubble / 't:LABEL' tag -> CanvasTexture (kept until dispose)
2470
+ // How big a grid bubble is ON SCREEN, in px — the user's setting (⋯ ▸ Display ▸ Grid label size), shared
2471
+ // with the 2D plan so one grid reads the same in both views. It is a VIEW preference, not model data, so
2472
+ // it lives in localStorage next to the other per-browser display prefs and never touches the contract.
2473
+ const GRID_LABEL_PX_DEFAULT = 26, GRID_LABEL_PX_MIN = 14, GRID_LABEL_PX_MAX = 48;
2474
+ 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; } })();
2234
2476
 
2235
2477
  // Snap targets for the 3D tools. Members come from the WHOLE model — every sheet, not just the active
2236
2478
  // one — so "3D snapping on" can grab any member at any elevation (the 3D scene shows all sheets; snapping
@@ -2266,14 +2508,25 @@ function allCandidates(excludeId) {
2266
2508
  function gridBubbleTexture(label) {
2267
2509
  const key = 'b:' + label;
2268
2510
  if (gridTexCache.has(key)) return gridTexCache.get(key);
2269
- const S = 128, cv = document.createElement('canvas'); cv.width = cv.height = S;
2511
+ // 256, not 128: the bubble is drawn at up to GRID_LABEL_PX_MAX on a 2× display, and the old texture
2512
+ // went visibly soft at the top of the size range.
2513
+ const S = 256, cv = document.createElement('canvas'); cv.width = cv.height = S;
2270
2514
  const g = cv.getContext('2d');
2271
- g.beginPath(); g.arc(S / 2, S / 2, S / 2 - 5, 0, Math.PI * 2);
2515
+ const R = S / 2 - 10;
2516
+ g.beginPath(); g.arc(S / 2, S / 2, R, 0, Math.PI * 2);
2272
2517
  g.fillStyle = '#0f172a'; g.fill();
2273
- g.lineWidth = 5; g.strokeStyle = '#64748b'; g.stroke();
2274
- g.fillStyle = '#e2e8f0'; g.font = 'bold ' + (label.length > 2 ? 44 : 58) + 'px system-ui';
2518
+ g.lineWidth = 10; g.strokeStyle = '#64748b'; g.stroke();
2519
+ // Shrink to fit the CIRCLE, not to a fraction of the diameter — the same closed form the 2D plan uses
2520
+ // (see gridLabelFontPx there for the derivation), so the two views agree about what "fits" means. The
2521
+ // old `width > R * 1.5` rule is blind to where the text sits: a centred line is widest at its own
2522
+ // half-height, where the circle has already narrowed, and R*1.5 let the ink reach the rim stroke.
2523
+ g.fillStyle = '#e2e8f0';
2524
+ g.font = 'bold 100px system-ui';
2525
+ const wEm = g.measureText(label).width / 100, Ri = R - 10; // inner radius: the rim is a 10 px stroke centred on R
2526
+ const fs = Math.min(120, 0.95 * Ri / Math.sqrt(wEm * wEm / 4 + 0.1296));
2527
+ g.font = 'bold ' + fs + 'px system-ui';
2275
2528
  g.textAlign = 'center'; g.textBaseline = 'middle';
2276
- g.fillText(label, S / 2, S / 2 + 3);
2529
+ g.fillText(label, S / 2, S / 2 + 4);
2277
2530
  const tex = new THREE.CanvasTexture(cv);
2278
2531
  gridTexCache.set(key, tex);
2279
2532
  return tex;
@@ -2331,25 +2584,244 @@ function buildStructGrid() {
2331
2584
  (geo.lines||[]).forEach((l,i)=>addLogical('gl:'+(l.id!=null?l.id:i),[[mmX(l.a[0]),mmY(l.a[1])],[mmX(l.b[0]),mmY(l.b[1])]]));
2332
2585
  scene.add(structGridGroup);
2333
2586
  gridLabelGroup = new THREE.Group();
2334
- const span = Math.max((geo.x1 - geo.x0) * k, (geo.y1 - geo.y0) * k, 1);
2335
- const dia = Math.min(Math.max(span * 0.035, 400), 3000); // bubble ⌀ scales with the grid, clamped sane
2336
2587
  const z0 = levels[0].mm;
2337
- const sprite = (tex, x, y, z, w, h, label, gridId) => {
2588
+ // Every label records its ANCHOR (the point it belongs to) and, for a bubble, the OUTWARD direction
2589
+ // along its own line. Neither the position nor the scale is final here — sizeGridLabels() sets both
2590
+ // every frame, because both are camera-dependent (see there for why that is the CAD behaviour).
2591
+ const sprite = (tex, label, gridId) => {
2338
2592
  // depthTest ON so steel in FRONT occludes the bubble/level tag (B7). The overlay pass runs with the
2339
2593
  // depth buffer from pass 1 (members) intact — autoClear is off — so this occludes against the steel
2340
2594
  // WITHOUT moving the labels out of overlayScene: they stay unclipped, so a section plane still can't
2341
2595
  // cut them (the clip-regression guard above holds).
2342
2596
  const s = new THREE.Sprite(new THREE.SpriteMaterial({ map: tex, depthTest: true, depthWrite: false, transparent: true }));
2343
2597
  s.userData.label=String(label||'');s.userData.gridId=gridId||null;
2344
- s.position.set(x, y, z); s.scale.set(w, h, 1); s.renderOrder = 994;
2598
+ s.renderOrder = 994;
2345
2599
  gridLabelGroup.add(s);
2600
+ return s;
2601
+ };
2602
+ // A bubble at (ax,ay), on the line whose OTHER end is (ox,oy) — so it can hang off the end away from
2603
+ // the model, the way a grid bubble does on a drawing.
2604
+ const bubble = (label, gridId, ax, ay, ox, oy) => {
2605
+ const s = sprite(gridBubbleTexture(label), label, gridId);
2606
+ // AWAY from the other end: (anchor - other), normalised. Getting this sign wrong hangs every bubble
2607
+ // INTO the model, onto the perimeter columns — the exact thing the placement exists to prevent.
2608
+ const dx = ax - ox, dy = ay - oy, len = Math.hypot(dx, dy);
2609
+ s.userData.anchor = V(ax, ay, z0);
2610
+ // A zero-length line has no outward direction to compute. `|| 1` used to guard the division and hand
2611
+ // back a ZERO vector, which reads as handled and silently parks the bubble on the model. +X is
2612
+ // arbitrary but it is a real direction, so the bubble still clears the end it belongs to.
2613
+ s.userData.outward = len > 1e-9 ? V(dx / len, dy / len, 0) : V(1, 0, 0);
2614
+ s.position.copy(s.userData.anchor);
2346
2615
  };
2347
- geo.v.forEach((l,i)=>{const id='gv:'+i;sprite(gridBubbleTexture(l.label), mmX(l.x), mmY(l.lo), z0, dia, dia,l.label,id); sprite(gridBubbleTexture(l.label), mmX(l.x), mmY(l.hi), z0, dia, dia,l.label,id);});
2348
- geo.h.forEach((l,i)=>{const id='gh:'+i;sprite(gridBubbleTexture(l.label), mmX(l.lo), mmY(l.y), z0, dia, dia,l.label,id); sprite(gridBubbleTexture(l.label), mmX(l.hi), mmY(l.y), z0, dia, dia,l.label,id);});
2349
- (geo.lines || []).forEach((l,i)=>{const id='gl:'+(l.id!=null?l.id:i);sprite(gridBubbleTexture(l.label), mmX(l.a[0]), mmY(l.a[1]), z0, dia, dia,l.label,id); sprite(gridBubbleTexture(l.label), mmX(l.b[0]), mmY(l.b[1]), z0, dia, dia,l.label,id);});
2350
- if (geo.zs.length) for (const lv of levels) sprite(gridTagTexture(lv.label), mmX(geo.x0), mmY(geo.y1), lv.mm, dia * 4.8, dia * 0.75,lv.label); // 6.4:1 sprite matches the tag texture, so long elevation labels stay undistorted
2616
+ geo.v.forEach((l,i)=>{const id='gv:'+i,x=mmX(l.x),lo=mmY(l.lo),hi=mmY(l.hi);bubble(l.label,id,x,lo,x,hi);bubble(l.label,id,x,hi,x,lo);});
2617
+ geo.h.forEach((l,i)=>{const id='gh:'+i,y=mmY(l.y),lo=mmX(l.lo),hi=mmX(l.hi);bubble(l.label,id,lo,y,hi,y);bubble(l.label,id,hi,y,lo,y);});
2618
+ (geo.lines || []).forEach((l,i)=>{const id='gl:'+(l.id!=null?l.id:i),ax=mmX(l.a[0]),ay=mmY(l.a[1]),bx=mmX(l.b[0]),by=mmY(l.b[1]);bubble(l.label,id,ax,ay,bx,by);bubble(l.label,id,bx,by,ax,ay);});
2619
+ if (geo.zs.length) for (const lv of levels) { // one elevation tag per level, parked off the grid's top-left corner
2620
+ const s = sprite(gridTagTexture(lv.label), lv.label, null);
2621
+ s.userData.anchor = V(mmX(geo.x0), mmY(geo.y1), lv.mm);
2622
+ // The sprite's aspect is width/HEIGHT, and the height below is 0.75·d — so this is 4.8, not the
2623
+ // texture's 6.4. Reading the 6.4 out of the old comment and using it as the width multiplier gives
2624
+ // 6.4/0.75 = 8.53:1 against a 6.4:1 bitmap, i.e. every elevation tag 33% too wide.
2625
+ s.userData.tagAspect = 4.8; // 4.8 / 0.75 == the tag texture's 512×80, so a long elevation label stays undistorted
2626
+ s.position.copy(s.userData.anchor);
2627
+ }
2351
2628
  overlayScene.add(gridLabelGroup);
2352
2629
  finish();
2630
+ sizeGridLabels(); // place + size them NOW, so a pick or a probe between this build and the next frame sees where they really are
2631
+ }
2632
+
2633
+ // Grid labels are CAD ANNOTATION, not model geometry, and three things follow from that — all three
2634
+ // camera-dependent, hence per frame:
2635
+ //
2636
+ // SIZE. They hold ONE size on screen (gridLabelPx) however far you zoom, exactly like Tekla's and
2637
+ // Revit's grid heads. They used to be world-space sprites of ⌀ span*0.035 (400–3000 mm), which is a
2638
+ // 3 m disc on a big job: unreadably small framed out, and swallowing whole bays zoomed in.
2639
+ //
2640
+ // PLACE. A bubble sits TANGENT to the end of its line, on the far side from the model — the line
2641
+ // stops at the circle rather than running to its centre. That is the convention gridFromDrawing
2642
+ // already measures on real sheets ("the line stops at the bubble's edge, end-gap ≈ r"), and it is
2643
+ // what keeps a bubble off the perimeter columns that stand at the grid ends.
2644
+ //
2645
+ // Tangency has to be solved ON SCREEN, which is the whole subtlety here. The standoff runs ALONG the
2646
+ // grid line in world space, so it foreshortens with that line's angle to the camera — but the bubble
2647
+ // is a camera-facing sprite whose radius does NOT foreshorten. Offsetting by half a bubble in world
2648
+ // units therefore lands the centre closer than one radius on screen, and the line visibly runs INSIDE
2649
+ // the circle: measured at 8.8 px against a 13.0 px radius on an ordinary iso view. So the offset is
2650
+ // the world distance whose PROJECTION is one radius, found by projecting the line direction and
2651
+ // dividing (see screenPxPerWorld). A line pointing nearly at the camera projects to almost nothing
2652
+ // and would demand a runaway offset, so it is capped — at that angle the line is a dot and there is
2653
+ // no visible tangency left to get right.
2654
+ //
2655
+ // DECLUTTER. A drawing never prints two bubbles on top of each other. Screen-constant labels on a
2656
+ // tight grid do collide once you frame out, so a bubble whose disc would TOUCH one already kept drops
2657
+ // out — centres nearer than 0.9 × the diameter, which is nearly two radii, not one. (Said as "centre
2658
+ // inside one already kept" here at first, which describes a rule ~1.8× looser than the code's.)
2659
+ // SELECTED lines are placed first and so always survive: losing the label AND the pick target of the
2660
+ // grid you are working on, to an unrelated line that merely sorted earlier, is not decluttering. Past
2661
+ // that, build order decides, so the survivors don't flicker as the camera moves. Elevation tags are
2662
+ // exempt entirely: there is one per level and they are the last wayfinding left when bubbles thin out.
2663
+ // Between two bubble CENTRES on screen, × gridLabelPx — so it must be ≥ 1, because gridLabelPx IS the
2664
+ // diameter and two discs whose centres are a diameter apart are exactly touching. At 0.9 they overlapped
2665
+ // by ~1 px for one zoom step before the pass fired (QA measured 24.4 px centres against 25.5 px discs);
2666
+ // 1.05 leaves a hair of clearance so the rims never kiss either.
2667
+ const GRID_LABEL_MIN_GAP = 1.05;
2668
+ // × the bubble radius — how far along its own line a bubble may be pushed to reach tangency. Generous:
2669
+ // it is bounded only so a line pointing straight at the camera cannot demand an unbounded world offset
2670
+ // (which would fly the sprite through the near/far planes and reorder it against the steel). Past this
2671
+ // the bubble is hidden instead — see the refusal in sizeGridLabels.
2672
+ const GRID_LABEL_MAX_STANDOFF = 60;
2673
+ let anchorlessLabelWarned = false, badLabelScaleWarned = false; // warn once each; a per-frame loop must never flood the console
2674
+ // Screen px per world unit ALONG `dir` at `from` — the foreshortening of that direction under the
2675
+ // current camera. Measured over a real span (`len`) rather than differentiated, so it is right for a
2676
+ // perspective camera too. Returns 0 when the span does not project (behind the camera), which the
2677
+ // caller reads as "unknown" and falls back from.
2678
+ // Answers null, not 0, when it cannot measure: 0 would read as a real "zero px per world unit" to the
2679
+ // next person, and it is numerically adjacent to the legitimate near-on-axis case the cap exists for.
2680
+ // The world size that reads as `px` on screen at `pos` — DEPTH-correct under perspective.
2681
+ //
2682
+ // A camera-facing sprite's projected size is set by the point's depth along the view axis, because that
2683
+ // is what the projection divides by. pxToWorldAt uses `camera.position.distanceTo(pos)`, which is the
2684
+ // RADIAL distance — the same number only on the axis, and larger everywhere else by 1/cos(angle). So a
2685
+ // bubble out at the corner of a wide viewport drew about 15% over its setting, and the re-measure at the
2686
+ // placed position repeated the error rather than cancelling it. Ortho has no distance term at all, and
2687
+ // it is this view's default, which is why every measurement so far read exactly 26.0 px.
2688
+ //
2689
+ // Deliberately NOT a fix inside pxToWorldAt: that helper is shared by sizeEndpoints, sizeClipHandles and
2690
+ // sizeFrameHandle, whose sizes are separately verified, so the same correction there is its own change
2691
+ // with its own evidence. Falls back to the shared helper whenever depth is unusable.
2692
+ const _depthV = new THREE.Vector3();
2693
+ function pxToWorldDepth(px, pos) {
2694
+ if (camera === orthoCam) return pxToWorldAt(px, pos);
2695
+ const depth = -_depthV.copy(pos).applyMatrix4(camera.matrixWorldInverse).z;
2696
+ if (!(depth > 0) || !Number.isFinite(depth)) return pxToWorldAt(px, pos); // at or behind the camera plane — no meaningful depth
2697
+ const h = (canvasEl && canvasEl.clientHeight) || 1;
2698
+ return px * (2 * Math.tan(THREE.MathUtils.degToRad(perspCam.fov) / 2) * depth) / h;
2699
+ }
2700
+ const _spA = new THREE.Vector3(), _spB = new THREE.Vector3();
2701
+ function screenPxPerWorld(from, dir, len, w, h) {
2702
+ if (!(len > 0)) return null;
2703
+ _spA.copy(from).project(camera);
2704
+ _spB.copy(from).addScaledVector(dir, len).project(camera);
2705
+ // BOTH components, not just .x — a NaN landing only in .y used to pass this and reach the caller as a
2706
+ // NaN ratio, which fell back only because `NaN > 1e-9` happens to be false. Right answer by accident.
2707
+ if (![_spA.x, _spA.y, _spB.x, _spB.y].every(Number.isFinite)) return null;
2708
+ const dx = (_spB.x - _spA.x) * 0.5 * w, dy = (_spB.y - _spA.y) * 0.5 * h;
2709
+ return Math.hypot(dx, dy) / len;
2710
+ }
2711
+ function sizeGridLabels() {
2712
+ if (!gridLabelGroup || !gridLabelGroup.children.length || !camera) return;
2713
+ const w = (canvasEl && canvasEl.clientWidth) || 1, h = (canvasEl && canvasEl.clientHeight) || 1;
2714
+ camera.updateMatrixWorld();
2715
+ const placed = [];
2716
+ for (const s of gridLabelGroup.children) {
2717
+ const ud = s.userData;
2718
+ // Every child is built by sprite() with an anchor, so this is unreachable today — but sprite() no
2719
+ // longer sets position or scale, so a future anchorless one would be a 1 mm disc at the world origin
2720
+ // that also escapes the visibility filter below. A per-frame loop must be total, so it still skips;
2721
+ // it just does not do so in silence.
2722
+ if (!ud || !ud.anchor) { if (!anchorlessLabelWarned) { anchorlessLabelWarned = true; console.warn('[steel-3d] a grid label has no anchor — it will not be placed, sized, or hidden with its line'); } continue; }
2723
+ s.visible = ud.allowed !== false; // applyGridVisibility owns WHETHER it may show; this owns where and how big
2724
+ if (!s.visible) continue;
2725
+ const d = pxToWorldDepth(gridLabelPx, ud.anchor); // the world size that reads as gridLabelPx on screen, measured AT the anchor
2726
+ // A degenerate ortho frustum, or a camera sitting exactly on the anchor, makes this 0 or NaN, and
2727
+ // `scale.set(0,0,1)` / `scale.set(NaN,NaN,1)` both render NOTHING while three.js throws on neither.
2728
+ // That is the undiagnosable disappearance: identical on screen to declutter, to an isolate filter,
2729
+ // and to "the grid failed to build". Keep the last good size instead of writing the bad one.
2730
+ if (!(d > 0) || !Number.isFinite(d)) { if (!badLabelScaleWarned) { badLabelScaleWarned = true; console.warn('[steel-3d] grid label size came out as ' + d + ' — keeping the last good size (check the camera frustum)'); } continue; }
2731
+ if (ud.tagAspect) {
2732
+ const tw = d * ud.tagAspect, th = d * 0.75, gap = d * 0.4;
2733
+ s.scale.set(tw, th, 1);
2734
+ s.position.set(ud.anchor.x - tw / 2 - gap, ud.anchor.y + th / 2 + gap, ud.anchor.z); // clear of the corner, not centred on it
2735
+ continue;
2736
+ }
2737
+ // Tangent ON SCREEN: push out far enough along the line that its projection is exactly one radius,
2738
+ // so the line stops at the rim instead of running into the circle. d/2 is the un-foreshortened
2739
+ // case (a line lying in the screen plane) and so is also the right fallback and the floor.
2740
+ const k = screenPxPerWorld(ud.anchor, ud.outward, d, w, h);
2741
+ const want = (k !== null && k > 1e-9) ? Math.max((gridLabelPx / 2) / k, d / 2) : d / 2;
2742
+ const standoff = Math.min(want, (d / 2) * GRID_LABEL_MAX_STANDOFF);
2743
+ s.position.copy(ud.anchor).addScaledVector(ud.outward, standoff);
2744
+ // The cap has to be able to REFUSE. Look almost straight down a grid line and k collapses, so the
2745
+ // distance needed for tangency runs away; capping it silently draws the line clean through the disc
2746
+ // and across the label — QA measured exactly that at a near-elevation angle, the line reaching 0.8 px
2747
+ // of the centre against a 13 px rim. (The first cap was 6 radii, with a comment claiming such a line
2748
+ // is "a dot with no visible tangency left to get right". It is not: QA's was 9 px long and its label
2749
+ // perfectly readable.) So the cap is generous enough to place any line you can still read along, and
2750
+ // when even that cannot clear the disc the bubble is HIDDEN rather than drawn crossed — you cannot
2751
+ // label a line you are looking down, and a missing mark beats a struck-through one.
2752
+ if (standoff < want * 0.999) { s.visible = false; continue; }
2753
+ // Re-measure at where it ENDED UP. Under perspective the standoff moves the sprite toward or away
2754
+ // from the camera, so a size taken at the anchor is off by that much — up to ~8% when the cap
2755
+ // engages. Ortho is unaffected (no distance term), but "constant size on screen" should be literally
2756
+ // true in both. Cheap, and the standoff is already fixed by the time it runs.
2757
+ const dAt = pxToWorldDepth(gridLabelPx, s.position);
2758
+ s.scale.setScalar(Number.isFinite(dAt) && dAt > 0 ? dAt : d);
2759
+ s.scale.z = 1;
2760
+ placed.push(s);
2761
+ }
2762
+ // THE OTHER LEVELS. A grid line is drawn once PER LEVEL (addLogical stacks a segment at every visible
2763
+ // Z), but a bubble exists only at the base level and can only be tangent to the segment it is anchored
2764
+ // to. Come at the grid from near-elevation and the upper segments project nearly collinear with the
2765
+ // lower one — and, having no bubble of their own to stop at, run straight through the disc. QA measured
2766
+ // an untrimmed upper segment reaching 2.7 px from the centre of a 13 px bubble, in 5 of 230
2767
+ // observations, and it was invisible to every earlier check because those all measured the bubble
2768
+ // against its OWN endpoint, which was tangent to 0.00 px throughout.
2769
+ //
2770
+ // Tangency cannot solve this — one disc, several lines. So the same rule as the cap: a bubble that
2771
+ // cannot be shown uncrossed is not shown. Distance is measured to the SEGMENT, not to its endpoints,
2772
+ // because the offending part is the middle of the segment passing over the disc.
2773
+ const lineSegs = new Map(); // gridId -> [[x1,y1,x2,y2], …] on screen, this frame
2774
+ for (const [id, line] of structGridLines) {
2775
+ if (!line.visible) continue;
2776
+ const pts = line.userData.segments || [], segs = [];
2777
+ for (let i = 0; i + 1 < pts.length; i += 2) {
2778
+ const a = _spA.set(pts[i][0], pts[i][1], pts[i][2]).project(camera);
2779
+ if (!Number.isFinite(a.x) || a.z > 1 || a.z < -1) continue;
2780
+ const ax = (a.x * 0.5 + 0.5) * w, ay = (-a.y * 0.5 + 0.5) * h;
2781
+ const b = _spB.set(pts[i + 1][0], pts[i + 1][1], pts[i + 1][2]).project(camera);
2782
+ if (!Number.isFinite(b.x) || b.z > 1 || b.z < -1) continue;
2783
+ segs.push([ax, ay, (b.x * 0.5 + 0.5) * w, (-b.y * 0.5 + 0.5) * h]);
2784
+ }
2785
+ if (segs.length) lineSegs.set(id, segs);
2786
+ }
2787
+ const distToSeg = (px, py, x1, y1, x2, y2) => {
2788
+ const vx = x2 - x1, vy = y2 - y1, len2 = vx * vx + vy * vy;
2789
+ const t = len2 > 0 ? Math.max(0, Math.min(1, ((px - x1) * vx + (py - y1) * vy) / len2)) : 0;
2790
+ return Math.hypot(px - (x1 + t * vx), py - (y1 + t * vy));
2791
+ };
2792
+ const survivors = [];
2793
+ for (const s of placed) {
2794
+ const p = _spA.copy(s.position).project(camera);
2795
+ if (!Number.isFinite(p.x) || !Number.isFinite(p.y) || p.z > 1 || p.z < -1) { survivors.push(s); continue; } // off screen — nothing to cross it there
2796
+ const cx = (p.x * 0.5 + 0.5) * w, cy = (-p.y * 0.5 + 0.5) * h;
2797
+ const segs = lineSegs.get(s.userData.gridId) || [];
2798
+ // The tangent segment sits at exactly one radius, so only something meaningfully INSIDE the rim
2799
+ // counts — 1.5 px of slack keeps float noise on the tangent one from hiding a perfectly good bubble.
2800
+ const crossed = segs.some((g) => distToSeg(cx, cy, g[0], g[1], g[2], g[3]) < gridLabelPx / 2 - 1.5);
2801
+ if (crossed) { s.visible = false; continue; }
2802
+ survivors.push(s);
2803
+ }
2804
+ placed.length = 0; placed.push(...survivors);
2805
+ // Selected lines first, so the grid the user is working on can never be the one whose label and pick
2806
+ // target get dropped in favour of an unrelated line that merely sorted earlier.
2807
+ if (selectedGridIds.size) placed.sort((a, b) => (selectedGridIds.has(b.userData.gridId) ? 1 : 0) - (selectedGridIds.has(a.userData.gridId) ? 1 : 0));
2808
+ const kept = [];
2809
+ const min = gridLabelPx * GRID_LABEL_MIN_GAP;
2810
+ for (const s of placed) {
2811
+ const p = _spA.copy(s.position).project(camera); // scratch, not a per-frame clone() — same reason screenPxPerWorld uses one
2812
+ // `z < -1` matters as much as `z > 1`, and ORTHO is this view's default. Under perspective a
2813
+ // behind-camera point flips w and lands z > 1; under ortho w is 1, so it lands z < -1 and used to
2814
+ // sail through — while its x/y stay the geometrically correct in-plane coordinates. It would then
2815
+ // enter `kept` and suppress a bubble that really is on screen.
2816
+ if (!Number.isFinite(p.x) || !Number.isFinite(p.y) || p.z > 1 || p.z < -1) continue; // not on screen, so it can't crowd anything
2817
+ const x = (p.x * 0.5 + 0.5) * w, y = (-p.y * 0.5 + 0.5) * h;
2818
+ if (kept.some((c) => Math.hypot(c.x - x, c.y - y) < min)) { s.visible = false; continue; }
2819
+ kept.push({ x, y });
2820
+ }
2821
+ // pickGridAt raycasts and gridBubblesScreen projects, and both read matrixWorld — which is refreshed
2822
+ // by the render pass, not by writing .position. Without this the build-time call above leaves a probe
2823
+ // in that sub-frame window reporting every bubble at the world origin.
2824
+ gridLabelGroup.updateMatrixWorld(true);
2353
2825
  }
2354
2826
 
2355
2827
  // The ortho frustum half-height in world units (set by a fit to the box, or by a projection toggle
@@ -3315,7 +3787,11 @@ function panView(dx, dy) { // dx/dy in "steps" along the camera's screen right/u
3315
3787
  const ARROWS = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, 1], ArrowDown: [0, -1] };
3316
3788
  const VIEW_KEYS = { t: 'top', f: 'front', r: 'right', b: 'back', l: 'left' }; // single-key ortho views, mirrors the ViewCube + AWARE viewer-3d
3317
3789
  function onKey(e) {
3318
- if (!renderer || !canvasEl || canvasEl.style.display === 'none') return; // only when 3D is active
3790
+ // NOT "is the canvas visible" — that predicate was written when 2D and 3D were mutually exclusive,
3791
+ // where visible and active were the same fact. In a split both canvases are on screen at once, and a
3792
+ // visibility test would let an arrow key orbit the model while the user is dimensioning the plan, and
3793
+ // let Escape in the 2D pane cancel an in-flight clip-handle drag in here. The editor owns the answer.
3794
+ if (!renderer || !canvasEl || canvasEl.style.display === 'none' || !inputActive) return;
3319
3795
  const ae = document.activeElement; if (ae && /^(INPUT|SELECT|TEXTAREA)$/.test(ae.tagName)) return;
3320
3796
  // Esc mid-drag-out → nothing is sent, even if the pointer is then released over Tekla: ending the
3321
3797
  // gesture here leaves the release with no drag to complete. (A native HTML5 drag never delivered
@@ -4155,7 +4631,11 @@ function pickGridAt(cx,cy){
4155
4631
  function applyGridVisibility(){
4156
4632
  let anyLine=false;
4157
4633
  for(const [id,line] of structGridLines){const on=(isolatedGridIds===null||isolatedGridIds.has(id))&&!gridSelectionHidden.has(id);line.visible=on;if(on)anyLine=true;}
4158
- if(gridLabelGroup)for(const label of gridLabelGroup.children){const id=label.userData&&label.userData.gridId;label.visible=id?((isolatedGridIds===null||isolatedGridIds.has(id))&&!gridSelectionHidden.has(id)):anyLine;}
4634
+ // `allowed` is the visibility DECISION; sizeGridLabels() re-applies it every frame and may additionally
4635
+ // drop a bubble that collides with another on screen. Split in two so the declutter pass can never be
4636
+ // mistaken for an isolate/hide filter, and so this one stays the single authority on which grid shows.
4637
+ if(gridLabelGroup)for(const label of gridLabelGroup.children){const id=label.userData&&label.userData.gridId;const allowed=id?((isolatedGridIds===null||isolatedGridIds.has(id))&&!gridSelectionHidden.has(id)):anyLine;label.userData.allowed=allowed;label.visible=allowed;}
4638
+ sizeGridLabels();
4159
4639
  }
4160
4640
  function reconcileGridVisibilityState(scopeChanged=false){
4161
4641
  const next=reconcileGridTransientState({
@@ -6075,6 +6555,9 @@ function hide() {
6075
6555
  endTeklaDrag(); // and a live drag-out to Tekla — a stranded one would leave its badge on screen and swallow every later pointer move
6076
6556
  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; }
6077
6557
  }
6558
+ // The editor's active-pane state, pushed in. Defaults true so every existing caller — and vector-3d.html,
6559
+ // which has no split and never calls this — keeps today's behaviour with no change.
6560
+ function setInputActive(on) { inputActive = on !== false; }
6078
6561
  function isReady() { return built; }
6079
6562
 
6080
6563
  function dispose() {
@@ -6126,6 +6609,9 @@ function dispose() {
6126
6609
  // The reference layer owns real GPU buffers — a whole tessellated building's worth. Leaving them
6127
6610
  // attached to a torn-down scene is the kind of leak that only shows up after the fifth 2D↔3D switch.
6128
6611
  if (xrefGroup) { disposeReferenceMaterials(); xrefGroup.traverse((o) => { o.geometry?.dispose?.(); }); if (scene) scene.remove(xrefGroup); }
6612
+ // The ghost layer owns real buffers too, and it is a SIBLING of that group rather than a child — which
6613
+ // is the whole point of it, and also the reason the sweep above cannot reach it.
6614
+ clearReferenceGhosts();
6129
6615
  xrefGroup = null; xrefById.clear(); xrefSelected = null;
6130
6616
  xrefSubSelected = null; xrefSubMesh = null; xrefSubMats = null;
6131
6617
  clearStructGrid();
@@ -6269,7 +6755,7 @@ function gridSegmentsScreen() {
6269
6755
  }
6270
6756
  function gridBubblesScreen(){if(!gridLabelGroup)return [];const rect=canvasEl.getBoundingClientRect();return gridLabelGroup.children.filter(s=>s.visible&&s.userData.gridId).map(s=>{const p=s.getWorldPosition(new THREE.Vector3()).project(camera);return {id:s.userData.gridId,x:rect.left+(p.x*.5+.5)*rect.width,y:rect.top+(-p.y*.5+.5)*rect.height};});}
6271
6757
  window.Steel3DView = {
6272
- init, show, hide, rebuild, setSelection, setGridSelection, isReady, dispose,
6758
+ init, show, hide, setInputActive, rebuild, setSelection, setGridSelection, isReady, dispose,
6273
6759
  setProjection, projection, setDisplayMode, mode: () => displayMode, frameAll, frameSelection, applyView,
6274
6760
  setRefLine, refLine: () => refLineOn,
6275
6761
  setInsertMode, insertMode: insertModeOn, // arm/query the detail-placement pick (Slice 4)
@@ -6290,6 +6776,16 @@ window.Steel3DView = {
6290
6776
  // Stage A: drilling into ONE object inside a reference. `selectReferenceObject` is what Ctrl+click and
6291
6777
  // (later) an object-tree row both call, so the two routes cannot drift into different selections.
6292
6778
  selectReferenceObject, selectedReferenceObject,
6779
+ // …and framing one, which the change list's rows need and Ctrl+click deliberately does not do.
6780
+ frameReferenceObject,
6781
+ // The GHOST layer (#734): where removed objects used to be. A third sibling group, outside `xrefById`
6782
+ // and outside `xrefGroup`, which is what makes "never snappable, never in the Fit box" structural.
6783
+ // `referenceGhostCount` and `referenceGhostIds` are test probes — a function having been called is not
6784
+ // evidence that anything was drawn, and the E2E has to be able to assert both halves of that promise.
6785
+ setReferenceGhosts, clearReferenceGhosts, frameReferenceGhost,
6786
+ referenceGhostCount: () => xrefGhostById.size,
6787
+ referenceGhostIds: () => [...xrefGhostById.keys()],
6788
+ referenceGhostPaint,
6293
6789
  // Stage D: the two-point measure. `armRefMeasure3d(id)` arms it, `armRefMeasure3d(null)` disarms;
6294
6790
  // `clearRefMeasure3d()` drops the kept segment. The three probes below are what the E2E asserts against,
6295
6791
  // because "a function was called" is not evidence that anything was drawn.
@@ -6318,6 +6814,8 @@ window.Steel3DView = {
6318
6814
  selLenLabelTexts: () => selLenLabelPool.filter((el) => el.style.display !== 'none' && el.style.visibility !== 'hidden').map((el) => el.textContent), // visible on-select length chips — for tests
6319
6815
  epScreen: (id) => { const m = memberById(id); if (!m || !canvasEl) return null; const g = geoOf(m); const rect = canvasEl.getBoundingClientRect(); const proj = (p) => { const v = new THREE.Vector3(p[0], p[1], p[2]).project(camera); return { x: rect.left + (v.x * 0.5 + 0.5) * rect.width, y: rect.top + (-v.y * 0.5 + 0.5) * rect.height }; }; return { a: proj(g.line[0]), b: proj(g.line[1]) }; }, // project a member's endpoints to viewport px — test probe for endpoint-drag tests
6320
6816
  refreshGrid: buildStructGrid, // grid edited in the panel → re-render without a full rebuild
6817
+ setGridLabelPx: (px) => { gridLabelPx = clampGridLabelPx(px); sizeGridLabels(); }, // ⋯ ▸ Display ▸ Grid label size — no rebuild needed, the labels are re-placed every frame anyway
6818
+ gridLabelPx: () => gridLabelPx,
6321
6819
  armGridLinePick3d, gridLinePick3dState: () => (gridLinePick3d ? { armed: true, hasFirst: !!gridLinePick3d.a, a: gridLinePick3d.a || null } : { armed: false, hasFirst: false, a: null }), // grid panel "Add single line" in 3D (+ test probe)
6322
6820
  gridInfo: () => ({ lines: structGridLines.size, labels: gridLabelGroup ? gridLabelGroup.children.length : 0,labelTexts:gridLabelGroup?[...new Set(gridLabelGroup.children.map(s=>s.userData.label).filter(Boolean))]:[],selected:[...selectedGridIds],ids:[...structGridLines.keys()],visible:visibleGridIds(),hidden:[...gridSelectionHidden],isolated:isolatedGridIds===null?null:[...isolatedGridIds] }), // test helper
6323
6821
  wpProbe: () => { // test helper: the "Show plane" reference surface — asserts no grid, bbox-sized surface, light-blue colour. `extent` is the projected u/v footprint the surface was actually sized to (work-area/tilted-plane aware), null for the fallback square. Surface w == extent.uSpan + 2*extent.margin.