@floless/app 0.122.0 → 0.123.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -19,7 +19,7 @@ import { OrbitControls } from 'three/addons/OrbitControls.js';
19
19
  import { RoomEnvironment } from 'three/addons/RoomEnvironment.js';
20
20
  import { surfaceTextures, applyTriplanar, TILE_MM, DIRECTIONAL } from './steel-materials.js';
21
21
  import { Brush, Evaluator, SUBTRACTION } from 'three-bvh-csg';
22
- import { snapPoint, planPointToWp, memberGeometry, snapElevation, dim3dGeom, dominantAxis3d, planeBasis, planeFrom3Points, vecToPlane, frameFrom3Points, frameFromAngle, worldToLocal, identityFrame, resolvePointEntry, offsetsFor, candidateOnPlane, snapGridPoint, clipSegmentToPlanes, pointSegmentDistance2d, perspectiveSegmentParameter, gridDepthWins, segmentHitsRect2d, projectedFootprintHitsRect2d, pickGridLevel, selectedLengthLabelAnchors } from './steel-3d-core.js';
22
+ 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 } from './steel-3d-core.js';
23
23
  // `gridGeometry`, `gridCandidates3d` and `mmPerPx` moved behind the host's model read half (unit 5, P7d):
24
24
  // each takes a `ptPerFt`, which is a v1 PLAN default and meaningless on a world-mm model grid.
25
25
  import { visibleGridLevels } from './grid-core.js';
@@ -880,6 +880,21 @@ function setRefLine(on) { refLineOn = !!on; buildRefLines(); }
880
880
  let xrefGroup = null; // one child Group per reference, each holding its meshes
881
881
  const xrefById = new Map(); // id -> { group, display, points, capped, total, bounds }
882
882
  let xrefSelected = null; // the whole-selected reference, or null
883
+ /**
884
+ * The ONE object drilled into inside `xrefSelected`, or null — `{ refId, index, objectId }`.
885
+ *
886
+ * INDEX IS THE HANDLE, `objectId` IS ONLY THE RECEIPT. An IFC GlobalId is what a user recognises, but
887
+ * `toReferenceObjects` writes `''` for an object whose id was not a string and `setReferences` maps that
888
+ * to null — so on a file whose objects carry no ids, OUR ids collide by construction and cannot address
889
+ * a mesh. (Whether real GlobalIds are ever duplicated is a separate question this does not rest on.) The
890
+ * index into `ref.objects` is exact — `setReferences` adds exactly one mesh per object, in order — so it
891
+ * is what selects, and the id rides along so a rebuild can CHECK that the index still means the same
892
+ * object.
893
+ *
894
+ * That check has teeth only where the file gives its objects ids; `revalidateSubSelection` says what it
895
+ * does in the case where it does not, and it does not pretend to a guarantee it cannot make.
896
+ */
897
+ let xrefSubSelected = null;
883
898
  let xrefCandWarned = false; // one warning per session if snap candidates ever fail
884
899
 
885
900
  /**
@@ -891,6 +906,53 @@ let xrefCandWarned = false; // one warning per session if snap c
891
906
  * from the one thing this feature must never let a user believe.
892
907
  */
893
908
  const XREF_COLOR = 0x94a3b8;
909
+
910
+ /**
911
+ * The reference colour modes, and why `file` is the default.
912
+ *
913
+ * `file` paints each object the colour the IFC styles it with. `uniform` is XREF_COLOR everywhere —
914
+ * the signal above, kept as a one-click way back. `custom` paints the whole reference one colour the
915
+ * user picked.
916
+ *
917
+ * An ABSENT `colorMode` means `file`, which is what lets a reference imported before this existed pick
918
+ * its colours up on the next read. Defaulting to `uniform` would have been the conservative-looking
919
+ * choice and the wrong one: every old row would stay grey and read as "this file has no colours".
920
+ */
921
+ /**
922
+ * The drilled-into object's own lift, and why it is not simply "the whole-model highlight, on one mesh".
923
+ *
924
+ * A reference draws at 50% opacity, `depthWrite:false`, BEHIND everything of ours. One object inside a
925
+ * building at those settings is not findable by an emissive nudge — it is a slightly paler pane among
926
+ * two hundred identical translucent panes. So the sub-selection gets a stronger lift AND is pushed
927
+ * towards opaque, which is what makes "that one, there" legible at a glance.
928
+ *
929
+ * RAISING OPACITY IS A SELECTION AFFORDANCE, NOT A CHANGE TO THE REFERENCE. It applies to a CLONE of
930
+ * the object's own material, lasts exactly as long as the selection, and never touches the slider's
931
+ * value or any other object — deselect and the object returns to whatever the slider says. The slider
932
+ * still governs the model; this governs the one thing you pointed at.
933
+ *
934
+ * The emissive is the same neutral slate the whole-model highlight uses, deliberately: XREF_COLOR's
935
+ * note explains why nothing in this layer may drift towards the brand blue, and a sub-selection is
936
+ * still borrowed geometry.
937
+ */
938
+ const XREF_SUB_EMISSIVE = 0xe2e8f0;
939
+ const XREF_SUB_INTENSITY = 0.9;
940
+ const XREF_SUB_MIN_OPACITY = 0.85;
941
+
942
+ const XREF_MODES = new Set(['file', 'uniform', 'custom']);
943
+ const xrefMode = (d) => (XREF_MODES.has(d && d.colorMode) ? d.colorMode : 'file');
944
+ /**
945
+ * The custom colour as a number, or null if it is not a colour.
946
+ *
947
+ * VALIDATED HERE rather than trusted, because the contract is hand- and AI-editable and the schema can
948
+ * only check the length (this repo's validator has no `pattern`). `new THREE.Color('#zzzzzz')` warns to
949
+ * the console and leaves the material BLACK, which against a dark canvas is an invisible reference —
950
+ * a wrong colour a user would report as "it disappeared".
951
+ */
952
+ function xrefCustom(d) {
953
+ const s = d && typeof d.color === 'string' ? d.color.trim() : '';
954
+ return /^#[0-9a-fA-F]{6}$/.test(s) ? parseInt(s.slice(1), 16) : null;
955
+ }
894
956
  /** Vertices closer than this collapse into one snap point — a tessellated corner is many coincident ones. */
895
957
  const XREF_SNAP_QUANT_MM = 0.5;
896
958
  /**
@@ -963,6 +1025,42 @@ function xrefSnapPoints(objects) {
963
1025
  return { points: out, capped: false };
964
1026
  }
965
1027
 
1028
+ /**
1029
+ * Free every material the reference layer holds — from the SCENE GRAPH, not from a bookkeeping map.
1030
+ *
1031
+ * Two ways the obvious spellings miss, both of which shipped once and were caught in review:
1032
+ *
1033
+ * `o.material.dispose()` per mesh — in file mode `o.material` is an ARRAY, which has no
1034
+ * `dispose`, so `?.dispose?.()` silently frees nothing at all;
1035
+ * `entry.mats` only — a map keyed on reference id loses an entry the moment two
1036
+ * references share an id, and the orphaned group's materials
1037
+ * then have no owner that could ever free them.
1038
+ *
1039
+ * Walking the graph and collecting into a Set is immune to both: it sees arrays, it sees groups whose
1040
+ * map entry was overwritten, and a material shared by ten thousand meshes is disposed exactly once.
1041
+ * `entry.mats` and `entry.flat` are drained too — they deliberately retain materials attached to no
1042
+ * mesh (the file colours kept alive while a reference is overridden, so switching back is free).
1043
+ */
1044
+ function disposeReferenceMaterials() {
1045
+ const seen = new Set();
1046
+ xrefGroup?.traverse((o) => {
1047
+ if (!o.isMesh || !o.material) return;
1048
+ if (Array.isArray(o.material)) o.material.forEach((m) => seen.add(m)); else seen.add(o.material);
1049
+ });
1050
+ for (const entry of xrefById.values()) {
1051
+ for (const m of entry.mats.values()) seen.add(m);
1052
+ if (entry.flat) seen.add(entry.flat);
1053
+ }
1054
+ // REDUNDANT TODAY, and said so rather than justified with a case that does not exist. The clones are
1055
+ // always on a mesh that is always still in `xrefGroup` when this runs, so the traverse above already
1056
+ // has them — including the id-collision orphan, whose GROUP is still a child even though its map entry
1057
+ // was overwritten (that is exactly what the traverse was chosen for; an earlier draft of this comment
1058
+ // claimed the opposite and contradicted the function's own header). Kept as belt-and-braces so a
1059
+ // future path that detaches a mesh before disposing cannot leak them silently.
1060
+ for (const m of xrefSubMats || []) seen.add(m);
1061
+ for (const m of seen) m.dispose?.();
1062
+ }
1063
+
966
1064
  /**
967
1065
  * (Re)build the whole reference layer from what the editor holds.
968
1066
  *
@@ -974,8 +1072,18 @@ function xrefSnapPoints(objects) {
974
1072
  function setReferences(list) {
975
1073
  if (!scene) return;
976
1074
  if (!xrefGroup) { xrefGroup = new THREE.Group(); scene.add(xrefGroup); }
1075
+ disposeReferenceMaterials();
1076
+ // The sub-selection's clones were assigned to a mesh, so the traverse above has just freed them; what
1077
+ // is left is a pointer to a mesh that is about to be removed. Dropping it HERE rather than in the
1078
+ // restore path is the difference between "no highlight" and "restore a material onto a disposed mesh".
1079
+ xrefSubMesh = null; xrefSubMats = null;
1080
+ // WHAT EACH ENTRY WAS BUILT FROM, captured before the map is cleared. `revalidateSubSelection` uses
1081
+ // array identity to tell an ordinary redraw (another reference arriving, which rebuilds this one with
1082
+ // the very same objects) from a genuine re-read. Without it, every unrelated load asks an identity
1083
+ // question that has no good answer and drops a valid selection.
1084
+ const prevObjects = new Map([...xrefById].map(([id, e]) => [id, e.objects]));
977
1085
  for (const child of [...xrefGroup.children]) {
978
- child.traverse?.((o) => { o.geometry?.dispose?.(); o.material?.dispose?.(); });
1086
+ child.traverse?.((o) => { o.geometry?.dispose?.(); });
979
1087
  xrefGroup.remove(child);
980
1088
  }
981
1089
  xrefById.clear();
@@ -989,16 +1097,39 @@ function setReferences(list) {
989
1097
  // against is worse than no reference.
990
1098
  group.renderOrder = -1;
991
1099
  const objects = Array.isArray(ref.objects) ? ref.objects : [];
992
- for (const o of objects) {
1100
+ // MATERIALS ARE SHARED WITHIN ONE REFERENCE AND NEVER ACROSS ONE. A real model draws 77,000
1101
+ // objects from 16 colours, so a material per object would be 77,000 of them; but a cache shared
1102
+ // BETWEEN references would be worse than wasteful, because `applyReferenceDisplay` mutates
1103
+ // `opacity` in place — dragging one reference's slider would fade every other reference that
1104
+ // happened to use the same colour. Per-entry is the only version of this that is correct.
1105
+ const mats = new Map();
1106
+ // INDEXED, and the index is load-bearing rather than incidental: `group.children[i]` IS
1107
+ // `objects[i]`, which is what lets a pick, the panel and (later) the object tree address the same
1108
+ // object without shipping a second copy of the metadata into the renderer. Nothing below may
1109
+ // `continue` past an object — that would break the correspondence silently, and the meshes are
1110
+ // built unconditionally precisely so it cannot.
1111
+ for (let i = 0; i < objects.length; i++) {
1112
+ const o = objects[i];
993
1113
  const g = new THREE.BufferGeometry();
994
1114
  g.setAttribute('position', new THREE.Float32BufferAttribute(o.positions || [], 3));
995
1115
  if (Array.isArray(o.indices) && o.indices.length) g.setIndex(o.indices);
996
1116
  g.computeVertexNormals();
997
- const mesh = new THREE.Mesh(g, new THREE.MeshStandardMaterial({
998
- color: XREF_COLOR, metalness: 0, roughness: 0.95,
999
- transparent: true, opacity: 1, depthWrite: false, side: THREE.DoubleSide,
1000
- }));
1117
+ // No material yet — `applyReferenceDisplay` below assigns it from the colour mode, and it is
1118
+ // the only thing that knows which. THREE's own default stands in for the few statements until
1119
+ // then; passing an explicit null would leave the mesh unrenderable if that call ever moved.
1120
+ const mesh = new THREE.Mesh(g);
1121
+ // The colour runs, kept on the mesh so a mode change can re-material without re-uploading a
1122
+ // single vertex — the same economy `setReferencePlacement` exists for. A whole tessellated
1123
+ // building is tens of megabytes of GPU traffic; clicking "Grey" must not pay it.
1124
+ const runs = Array.isArray(o.colors) && o.colors.length ? o.colors : null;
1125
+ if (runs) { g.clearGroups(); runs.forEach((c, i) => g.addGroup(c.start, c.count, i)); }
1001
1126
  mesh.userData.referenceId = ref.id;
1127
+ // The object's own identity, carried on the mesh so a raycast hit answers "which object" without
1128
+ // a second lookup. `objectId` is the file's GlobalId and may be `''` (see `xrefSubSelected`), so
1129
+ // it is normalised to null here rather than being allowed to masquerade as a real, empty id.
1130
+ mesh.userData.objectId = (o && typeof o.id === 'string' && o.id) ? o.id : null;
1131
+ mesh.userData.objectIndex = i;
1132
+ mesh.userData.colorRuns = runs;
1002
1133
  group.add(mesh);
1003
1134
  }
1004
1135
  group.applyMatrix4(xrefMatrix(ref.placement));
@@ -1011,11 +1142,93 @@ function setReferences(list) {
1011
1142
  xrefById.set(ref.id, {
1012
1143
  group, display: ref.display || {}, name: ref.name || ref.id,
1013
1144
  points, total: points.length, capped: keptCapped, keptCapped,
1145
+ // The array this entry was built FROM, kept by identity (not copied) so a rebuild can tell "the
1146
+ // same objects again" from "a re-read". See `revalidateSubSelection`.
1147
+ objects,
1148
+ /**
1149
+ * The object ids that appear MORE THAN ONCE in this reference.
1150
+ *
1151
+ * Nothing guarantees an IFC GlobalId is unique — not the file, not the reader, not us — and a
1152
+ * duplicated one makes "the id at index N still matches" true across a reorder that swapped the
1153
+ * two, which is exactly the silent wrong-object outcome the receipt exists to prevent. Computed
1154
+ * once here, in a loop that already walks every object, rather than asked per rebuild.
1155
+ */
1156
+ dupIds: (() => {
1157
+ const seen = new Set(), dup = new Set();
1158
+ for (const o of objects) {
1159
+ const oid = (o && typeof o.id === 'string' && o.id) ? o.id : null;
1160
+ if (oid === null) continue;
1161
+ if (seen.has(oid)) dup.add(oid); else seen.add(oid);
1162
+ }
1163
+ return dup;
1164
+ })(),
1165
+ // `painted` is what `applyReferenceDisplay` compares against to decide whether re-materialling
1166
+ // every mesh is necessary at all. Opacity is dragged live and must stay a per-material write.
1167
+ mats, painted: null,
1168
+ // THE one material every override uses, made once and recoloured in place. Kept OUT of `mats`
1169
+ // because that map is keyed by colour and this material's colour changes — caching it there
1170
+ // would put a stale key in front of a live material, and is how the picker drag came to mint
1171
+ // (and strand) a material per pointer move.
1172
+ flat: newXrefMaterial(XREF_COLOR, 1),
1014
1173
  });
1015
1174
  applyReferenceDisplay(ref.id, ref.display || {});
1016
1175
  }
1176
+ const wasSelected = xrefSelected, wasSub = xrefSubSelected;
1017
1177
  if (xrefSelected && !xrefById.has(xrefSelected)) xrefSelected = null;
1178
+ revalidateSubSelection(prevObjects);
1018
1179
  paintReferenceSelection();
1180
+ paintReferenceSubSelection();
1181
+ // A REBUILD THAT DROPS A SELECTION MUST SAY SO. "Reload its geometry" re-reads the IFC, so the object
1182
+ // that was drilled into may simply not be there any more — and the Inspect panel is rendered from the
1183
+ // editor's own copy of that selection, which would otherwise go on describing an object no longer in
1184
+ // the scene. Silence here is the difference between "the selection cleared" and "the panel is lying".
1185
+ if (wasSelected !== xrefSelected || wasSub !== xrefSubSelected) emitReferenceSelect();
1186
+ }
1187
+
1188
+ /**
1189
+ * Does the drilled-into object still exist, and is it still the SAME object?
1190
+ *
1191
+ * A rebuild is not always a redraw of the same thing. `setReferences` runs again when a reference's
1192
+ * geometry finally arrives, when one is removed, and after "Reload its geometry" — and that last one
1193
+ * re-reads the IFC, so slot 47 may now hold a different element entirely. Keeping the index alone
1194
+ * would move the highlight and the whole Inspect panel onto some other object without a single visible
1195
+ * event, which is the quietest possible way to tell a user something false about a model.
1196
+ *
1197
+ * MOST REBUILDS ARE NOT RE-READS, and asking the hard question of all of them is its own bug. A rebuild
1198
+ * runs whenever ANY reference's geometry arrives or is removed, so reference B finishing its fetch
1199
+ * rebuilds reference A too — with the identical `objects` array. `prevObjects` carries the array the
1200
+ * entry was built from last time, and array identity settles it outright: same array, same objects, keep
1201
+ * the selection and ask nothing further. Only a genuine re-read hands over a new array. (Codex review
1202
+ * caught this: the first cut dropped a perfectly valid drill every time an unrelated reference loaded.)
1203
+ *
1204
+ * When the array HAS changed, the remembered `objectId` is checked — and TWO IDS THAT CANNOT DISTINGUISH
1205
+ * ANYTHING CANNOT PASS:
1206
+ *
1207
+ * null — `setReferences` normalises a missing or empty GlobalId to null, so in a file whose
1208
+ * objects carry no ids EVERY slot answers null and the "check" would wave through whatever
1209
+ * landed at index N. That is the failure this function exists to prevent, arriving through
1210
+ * the front door.
1211
+ * duplicate — the same, one step subtler: two objects sharing an id make "the id at index N still
1212
+ * matches" true after a reorder that swapped them. Nothing validates GlobalId uniqueness —
1213
+ * not the file, not the reader, not us — so the ids that repeat inside one reference are
1214
+ * collected at build time and refused here.
1215
+ *
1216
+ * The cost is stated rather than hidden: after a genuine re-read, a drill into an object with no id (or a
1217
+ * duplicated one) does not survive. It is not much of a cost — such a file gives us nothing to tell two
1218
+ * objects apart with, which is the same reason we cannot verify one — and a dropped selection is visible,
1219
+ * while a silently moved one is not.
1220
+ */
1221
+ function revalidateSubSelection(prevObjects) {
1222
+ if (!xrefSubSelected) return;
1223
+ const entry = xrefById.get(xrefSubSelected.refId);
1224
+ const mesh = entry && entry.group.children[xrefSubSelected.index];
1225
+ if (!mesh || !mesh.isMesh) { xrefSubSelected = null; return; }
1226
+ // The cheap, total answer first: nothing was re-read, so nothing can have moved.
1227
+ const prev = prevObjects && prevObjects.get(xrefSubSelected.refId);
1228
+ if (prev && prev === entry.objects) return;
1229
+ const id = xrefSubSelected.objectId;
1230
+ const same = id !== null && !entry.dupIds.has(id) && mesh.userData.objectId === id;
1231
+ if (!same) xrefSubSelected = null;
1019
1232
  }
1020
1233
 
1021
1234
  /**
@@ -1036,8 +1249,123 @@ function applyReferenceDisplay(id, display) {
1036
1249
  const visible = entry.display.visible !== false;
1037
1250
  const opacity = Number.isFinite(entry.display.opacity) ? Math.max(0, Math.min(1, entry.display.opacity)) : 0.5;
1038
1251
  entry.group.visible = visible;
1039
- entry.group.traverse((o) => { if (o.material) { o.material.opacity = opacity; o.material.needsUpdate = true; } });
1252
+
1253
+ // HIDING A REFERENCE DROPS ANY OBJECT DRILLED INTO IT — the other door into the state `pickReferenceAt`
1254
+ // refuses to create. That function now filters hidden groups so you cannot SELECT what you cannot see;
1255
+ // without this, you could select it first and then hide the reference, and the Inspect panel would go
1256
+ // on reading out the properties of an object that is no longer on screen. Same forbidden end state,
1257
+ // reached from the other side. (Code review.)
1258
+ //
1259
+ // Only the drill goes. The reference itself stays selected — hiding is a way to get something out of
1260
+ // your way while you keep working against it, and that argument does not extend to a single part of it
1261
+ // you can no longer point at.
1262
+ const dropped = !visible && !!xrefSubSelected && xrefSubSelected.refId === id;
1263
+ if (dropped) { xrefSubSelected = null; paintReferenceSubSelection(); }
1264
+
1265
+ // ONLY A CHANGE OF SHAPE RE-MATERIALS, and "shape" means file-colours-vs-one-colour, NOT which
1266
+ // colour. Both the opacity slider and the colour picker fire on every pointer move, and reassigning
1267
+ // `mesh.material` across 17,000 meshes per move would turn either drag into a slideshow.
1268
+ //
1269
+ // Keying on the colour was the first cut and review caught it: dragging through a gradient re-walked
1270
+ // every mesh per move AND minted a material per distinct colour, none of which was ever freed. An
1271
+ // override is one material by construction, so changing its colour is one `setHex` on that material
1272
+ // — no traverse, no allocation, however far the pointer travels.
1273
+ const mode = xrefMode(entry.display);
1274
+ const custom = xrefCustom(entry.display);
1275
+ const shape = mode === 'file' ? 'file' : 'flat';
1276
+ const repainted = entry.painted !== shape;
1277
+ if (repainted) { paintReferenceColors(entry, shape); entry.painted = shape; }
1278
+ if (shape === 'flat') entry.flat.color.setHex(mode === 'custom' && custom !== null ? custom : XREF_COLOR);
1279
+
1280
+ // Opacity reaches the MATERIALS, not the meshes — there are at most a handful of the former and
1281
+ // tens of thousands of the latter, and they are the same objects either way.
1282
+ //
1283
+ // FILE ALPHA MULTIPLIES THE SLIDER, so glass authored at 0.149 still reads as glass at any slider
1284
+ // position. Only in `file` mode: overriding the colour means "paint this whole model one colour",
1285
+ // and keeping per-object alpha under an override would leave it patchy for no reason the user
1286
+ // could act on.
1287
+ for (const m of entry.mats.values()) { m.opacity = opacity * m.userData.alpha; m.needsUpdate = true; }
1288
+ entry.flat.opacity = opacity; entry.flat.needsUpdate = true;
1289
+
1290
+ // KEEP THE DRILLED-INTO OBJECT'S CLONES IN STEP, and choose the cheap path unless the expensive one
1291
+ // is actually required. A repaint reassigned every mesh's material, so the clones are now orphaned and
1292
+ // must be made again — that is a discrete mode click. The sliders are not: opacity and the custom
1293
+ // colour both fire on every pointer move, and re-cloning per move is the per-move MATERIAL allocation
1294
+ // this whole section is written to avoid, so those are copied onto the existing clones in place. (Not
1295
+ // zero allocation — `xrefBaseMaterial` still builds one small array, bounded by one object's colour
1296
+ // runs. What it avoids is minting materials and walking 17,000 meshes.)
1297
+ if (repainted) paintReferenceSubSelection();
1298
+ else if (xrefSubMats && xrefSubMesh && xrefSubMesh.userData.referenceId === id) {
1299
+ const src = xrefBaseMaterial(entry, xrefSubMesh, shape);
1300
+ const list = Array.isArray(src) ? src : [src];
1301
+ for (let i = 0; i < xrefSubMats.length && i < list.length; i++) {
1302
+ xrefSubMats[i].color.copy(list[i].color);
1303
+ xrefSubMats[i].opacity = Math.max(list[i].opacity, XREF_SUB_MIN_OPACITY);
1304
+ xrefSubMats[i].needsUpdate = true;
1305
+ }
1306
+ }
1040
1307
  paintReferenceSelection();
1308
+ // AFTER the repaint, so the editor's own re-render sees the finished scene rather than a half-painted
1309
+ // one. `emitReferenceSelect` is what clears the Inspect panel's copy of the selection.
1310
+ if (dropped) emitReferenceSelect();
1311
+ }
1312
+
1313
+ /**
1314
+ * One reference's material for a given colour, made once and reused.
1315
+ *
1316
+ * `alpha` is stashed on the material rather than folded into `opacity` here, because the slider is
1317
+ * applied on top of it on every change and the file's own value has to survive being multiplied.
1318
+ */
1319
+ function xrefMaterial(entry, rgb, alpha) {
1320
+ const key = `${rgb}:${alpha}`;
1321
+ let m = entry.mats.get(key);
1322
+ if (!m) { m = newXrefMaterial(rgb, alpha); entry.mats.set(key, m); }
1323
+ return m;
1324
+ }
1325
+
1326
+ function newXrefMaterial(rgb, alpha) {
1327
+ const m = new THREE.MeshStandardMaterial({
1328
+ color: rgb, metalness: 0, roughness: 0.95,
1329
+ transparent: true, opacity: 1, depthWrite: false, side: THREE.DoubleSide,
1330
+ });
1331
+ m.userData.alpha = alpha;
1332
+ return m;
1333
+ }
1334
+
1335
+ /**
1336
+ * Point every mesh of one reference at the materials its colour mode calls for.
1337
+ *
1338
+ * `file` gives a mesh an ARRAY of materials, one per colour run, which is what makes a multi-coloured
1339
+ * object render as several colours — the geometry groups built in `setReferences` index into it. The
1340
+ * override modes give it a SINGLE material instead, and that is not merely a simplification: THREE
1341
+ * ignores geometry groups entirely when the material is not an array, so one override colour paints
1342
+ * the whole buffer in one draw call rather than N.
1343
+ *
1344
+ * An object with no runs — a file that authors no colour, or a bridge too old to say — falls back to
1345
+ * XREF_COLOR. Never to white, which is what web-ifc reports for unstyled geometry and what this whole
1346
+ * chain exists to keep off the screen.
1347
+ */
1348
+ function paintReferenceColors(entry, shape) {
1349
+ entry.group.traverse((o) => { if (o.isMesh) o.material = xrefBaseMaterial(entry, o, shape); });
1350
+ }
1351
+
1352
+ /**
1353
+ * What one mesh's material WOULD be with no selection on it — an array in `file` mode, `entry.flat`
1354
+ * otherwise.
1355
+ *
1356
+ * Split out of `paintReferenceColors` because the sub-selection needs exactly this answer twice: once
1357
+ * to clone from, and once to put back when the selection moves on. Re-deriving it (rather than
1358
+ * stashing the old `mesh.material`) is what makes the restore correct across a colour-mode change —
1359
+ * a stashed array from `file` mode would be handed back to a mesh the user has since switched to Grey.
1360
+ *
1361
+ * `shape` is passed rather than read off `entry.painted`, because the one caller that changes the mode
1362
+ * sets `painted` only AFTER repainting.
1363
+ */
1364
+ function xrefBaseMaterial(entry, mesh, shape) {
1365
+ const runs = shape === 'file' ? mesh.userData.colorRuns : null;
1366
+ return runs
1367
+ ? runs.map((c) => xrefMaterial(entry, (Math.round(c.rgba[0] * 255) << 16) | (Math.round(c.rgba[1] * 255) << 8) | Math.round(c.rgba[2] * 255), c.rgba[3]))
1368
+ : entry.flat;
1041
1369
  }
1042
1370
 
1043
1371
  /**
@@ -1058,15 +1386,73 @@ function setReferencePlacement(id, placement) {
1058
1386
  /** The whole-model selection highlight: an emissive lift, never the brand wash (see XREF_COLOR). */
1059
1387
  function paintReferenceSelection() {
1060
1388
  for (const [id, entry] of xrefById) {
1061
- const on = id === xrefSelected;
1062
- entry.group.traverse((o) => {
1063
- if (!o.material || !o.material.emissive) return;
1064
- o.material.emissive.setHex(on ? 0xe2e8f0 : 0x000000);
1065
- o.material.emissiveIntensity = on ? 0.35 : 0;
1066
- });
1389
+ // A DRILLED-INTO REFERENCE IS NOT A LIT ONE. The whole-model lift walks `entry.mats`, which every
1390
+ // mesh of that reference shares — so leaving it on while one object is sub-selected would light the
1391
+ // entire building and the object inside it, and "that one, there" would be exactly as findable as
1392
+ // before. The row in the References tab still shows the reference as selected; the 3D highlight is
1393
+ // the precise one, because that is the one the user just asked for.
1394
+ const on = id === xrefSelected && !xrefSubSelected;
1395
+ // THE MATERIALS, not the meshes — a mesh may now hold an ARRAY of them (one per colour run), and
1396
+ // several meshes share each one. Walking the entry's materials reaches every one exactly once and
1397
+ // cannot miss the members of an array the way `o.material.emissive` silently did. `flat` is not in
1398
+ // `mats` and must be lifted too, or selecting an OVERRIDDEN reference would highlight nothing.
1399
+ for (const m of [...entry.mats.values(), entry.flat]) {
1400
+ m.emissive.setHex(on ? 0xe2e8f0 : 0x000000);
1401
+ m.emissiveIntensity = on ? 0.35 : 0;
1402
+ }
1067
1403
  }
1068
1404
  }
1069
1405
 
1406
+ /**
1407
+ * The one object's highlight, painted onto a CLONE of its own material.
1408
+ *
1409
+ * A CLONE IS THE ONLY CORRECT UNIT HERE, and the obvious alternatives each light the wrong thing:
1410
+ *
1411
+ * set emissive on the material — materials are SHARED across a reference's meshes by design (one
1412
+ * material per colour, not per object), so every wall of that colour
1413
+ * would light up together;
1414
+ * swap in one dedicated material — throws away the object's own colour, so the highlight tells you
1415
+ * where it is and stops telling you what it is;
1416
+ * stash `mesh.material` to undo — restores a `file`-mode array onto a mesh the user has since
1417
+ * switched to Grey.
1418
+ *
1419
+ * So: clone what the mesh is actually wearing, lift it, and put the derived base back on release
1420
+ * (`xrefBaseMaterial`). At most a handful of materials exist at a time — one per colour run of ONE
1421
+ * object — and they are disposed the moment the selection moves.
1422
+ */
1423
+ let xrefSubMats = null; // the clone(s) currently painted on the sub-selected mesh
1424
+ let xrefSubMesh = null; // the mesh they are painted on, so the restore never has to guess
1425
+
1426
+ function paintReferenceSubSelection() {
1427
+ // RELEASE FIRST, ALWAYS — including when the new selection is the same mesh. A colour-MODE change
1428
+ // re-derives the shared materials underneath and reassigns every mesh, so a highlight that was not
1429
+ // re-cloned would be orphaned: the clone would be freed while the mesh wore the shared material.
1430
+ // (An opacity drag does NOT reach here — `applyReferenceDisplay` copies onto the existing clones in
1431
+ // place precisely so a drag allocates nothing. An earlier draft of this comment named it anyway.)
1432
+ if (xrefSubMesh) {
1433
+ const prev = xrefById.get(xrefSubMesh.userData.referenceId);
1434
+ if (prev) xrefSubMesh.material = xrefBaseMaterial(prev, xrefSubMesh, prev.painted);
1435
+ for (const m of xrefSubMats || []) m.dispose?.();
1436
+ xrefSubMesh = null; xrefSubMats = null;
1437
+ }
1438
+ if (!xrefSubSelected) return;
1439
+ const entry = xrefById.get(xrefSubSelected.refId);
1440
+ const mesh = entry && entry.group.children[xrefSubSelected.index];
1441
+ if (!mesh || !mesh.isMesh) return;
1442
+ const base = xrefBaseMaterial(entry, mesh, entry.painted);
1443
+ const lift = (m) => {
1444
+ const c = m.clone();
1445
+ c.emissive.setHex(XREF_SUB_EMISSIVE);
1446
+ c.emissiveIntensity = XREF_SUB_INTENSITY;
1447
+ c.opacity = Math.max(m.opacity, XREF_SUB_MIN_OPACITY);
1448
+ c.needsUpdate = true;
1449
+ return c;
1450
+ };
1451
+ xrefSubMats = (Array.isArray(base) ? base : [base]).map(lift);
1452
+ mesh.material = Array.isArray(base) ? xrefSubMats : xrefSubMats[0];
1453
+ xrefSubMesh = mesh;
1454
+ }
1455
+
1070
1456
  /**
1071
1457
  * The reference under the pointer, or null.
1072
1458
  *
@@ -1074,23 +1460,138 @@ function paintReferenceSelection() {
1074
1460
  * standing in front of a beam never steals the beam's click. The plan's acceptance list asks for the
1075
1461
  * negative ("native selection unchanged") and this is where it is earned rather than hoped for.
1076
1462
  *
1077
- * A HIDDEN reference is not pickable: `visible` is false on its group, and unlike snapping, picking
1078
- * something you cannot see has no case to make for itself.
1463
+ * A HIDDEN reference is not pickable, and the hidden groups are FILTERED OUT rather than left to THREE.
1464
+ * That filter is the whole of it: `Raycaster.intersectObjects` does NOT skip invisible objects — it
1465
+ * tests only `layers` — so this function used to claim, in this comment, a property it did not have.
1466
+ * Hiding a reference and clicking where it had been selected the thing you could not see, and after
1467
+ * Stage A it would have opened the Inspect panel on an invisible object's properties. `meshHitsAt` has
1468
+ * always filtered `m.visible` for our own members; this is the same rule, finally applied here.
1469
+ *
1470
+ * Unlike snapping, picking something you cannot see has no case to make for itself — §10.3's
1471
+ * hidden-but-still-snapping rule is deliberate and lives in `referenceCandidates`, which is a different
1472
+ * path and is untouched by this.
1079
1473
  */
1080
1474
  function pickReferenceAt(cx, cy) {
1081
1475
  if (!xrefGroup || !xrefGroup.children.length || !canvasEl) return null;
1082
1476
  camera.updateMatrixWorld(); xrefGroup.updateMatrixWorld(true);
1083
1477
  const rect = canvasEl.getBoundingClientRect();
1084
1478
  raycaster.setFromCamera(new THREE.Vector2(((cx - rect.left) / rect.width) * 2 - 1, -((cy - rect.top) / rect.height) * 2 + 1), camera);
1085
- const hit = raycaster.intersectObjects(xrefGroup.children, true)
1479
+ const hit = raycaster.intersectObjects(xrefGroup.children.filter((g) => g.visible), true)
1086
1480
  .filter((h) => !isPointClipped([h.point.x, h.point.y, h.point.z]))[0];
1087
- return hit ? (hit.object.userData.referenceId || null) : null;
1481
+ if (!hit) return null;
1482
+ const u = hit.object.userData || {};
1483
+ if (!u.referenceId) return null;
1484
+ // AN OBJECT-SHAPED ANSWER, ALWAYS — never the bare id this used to return. Both callers want to know
1485
+ // WHICH object was under the pointer as well as which reference, and a function that answered one of
1486
+ // those questions with a string and the other with an object would be read wrong exactly once.
1487
+ return {
1488
+ referenceId: u.referenceId,
1489
+ objectId: u.objectId ?? null,
1490
+ objectIndex: Number.isInteger(u.objectIndex) ? u.objectIndex : -1,
1491
+ };
1492
+ }
1493
+
1494
+ /** Tell the editor what is selected — the reference, and the one object inside it if there is one. */
1495
+ function emitReferenceSelect() {
1496
+ if (api && api.onReferenceSelect) {
1497
+ api.onReferenceSelect(xrefSelected, xrefSubSelected && xrefSelected === xrefSubSelected.refId
1498
+ ? { index: xrefSubSelected.index, id: xrefSubSelected.objectId }
1499
+ : null);
1500
+ }
1088
1501
  }
1089
1502
 
1503
+ /**
1504
+ * Select a WHOLE reference — and drop any object drilled into inside it.
1505
+ *
1506
+ * The drop is not tidiness. `selectReference` is what an ordinary click, a References-tab row click and
1507
+ * every deselect path call; if it left a sub-selection standing, clicking the row of the reference you
1508
+ * were inside would leave one object still lit and the Inspect panel still describing it, while the
1509
+ * user's mental model says they just selected the whole thing.
1510
+ */
1090
1511
  function selectReference(id) {
1091
1512
  xrefSelected = xrefById.has(id) ? id : null;
1513
+ xrefSubSelected = null;
1514
+ paintReferenceSubSelection();
1092
1515
  paintReferenceSelection();
1093
- if (api && api.onReferenceSelect) api.onReferenceSelect(xrefSelected);
1516
+ emitReferenceSelect();
1517
+ }
1518
+
1519
+ /**
1520
+ * Drill into ONE object inside a reference.
1521
+ *
1522
+ * Returns false and selects nothing when the index does not name a mesh — a stale index from a tree row
1523
+ * built before a reload, say. Falling back to "select the whole reference" would be worse than refusing:
1524
+ * the caller asked for an object, and quietly answering a different question is how a panel comes to
1525
+ * describe something the user did not pick.
1526
+ */
1527
+ function selectReferenceObject(refId, index) {
1528
+ const entry = xrefById.get(refId);
1529
+ const mesh = entry && Number.isInteger(index) && index >= 0 ? entry.group.children[index] : null;
1530
+ if (!mesh || !mesh.isMesh) return false;
1531
+ xrefSelected = refId;
1532
+ xrefSubSelected = { refId, index, objectId: mesh.userData.objectId ?? null };
1533
+ paintReferenceSelection();
1534
+ paintReferenceSubSelection();
1535
+ emitReferenceSelect();
1536
+ return true;
1537
+ }
1538
+
1539
+ /** What is drilled into right now — `{ referenceId, objectIndex, objectId }` or null. */
1540
+ function selectedReferenceObject() {
1541
+ return xrefSubSelected
1542
+ ? { referenceId: xrefSubSelected.refId, objectIndex: xrefSubSelected.index, objectId: xrefSubSelected.objectId }
1543
+ : null;
1544
+ }
1545
+
1546
+ /**
1547
+ * What is ACTUALLY painted on one reference right now — the colours, off the materials themselves.
1548
+ *
1549
+ * Exists because "is this reference showing the file's colours?" is otherwise unanswerable from
1550
+ * outside: a screenshot cannot distinguish a correct palette from a plausible one, and the contract
1551
+ * only records what was ASKED for. This reads back what the GPU was given, so a test can assert the
1552
+ * rendered result rather than the intent.
1553
+ *
1554
+ * `colors` are hex strings with the material's own alpha, `opacity` is what the slider multiplied it
1555
+ * to — the two are separate because a wrong answer in either looks identical on screen.
1556
+ */
1557
+ function referenceProbe(id) {
1558
+ const entry = xrefById.get(id);
1559
+ if (!entry) return null;
1560
+ let meshes = 0, arrayMeshes = 0, runs = 0;
1561
+ /**
1562
+ * WHICH mesh indices are actually lifted, read off the materials the renderer will use.
1563
+ *
1564
+ * This is the assertion a per-object selection needs and a screenshot cannot make: "exactly one
1565
+ * object is highlighted, and it is index 7". A count of highlighted things would pass with the whole
1566
+ * building lit; the whole building lit is precisely the bug this feature can regress into, because
1567
+ * the materials are shared. So the indices are listed, and a test asserts the LIST.
1568
+ */
1569
+ const lit = [];
1570
+ // COLLECTED OFF THE MESHES, not out of `entry.mats`. The cache deliberately KEEPS a reference's
1571
+ // file-colour materials while it is overridden, so switching back is free — which means reading the
1572
+ // cache would report a grey-overridden model as still carrying six colours. That is precisely the
1573
+ // question this probe exists to answer, so it walks what is actually assigned.
1574
+ const inUse = new Set();
1575
+ entry.group.traverse((o) => {
1576
+ if (!o.isMesh) return;
1577
+ meshes++;
1578
+ const ms = Array.isArray(o.material) ? o.material : (o.material ? [o.material] : []);
1579
+ if (Array.isArray(o.material)) { arrayMeshes++; runs += o.material.length; }
1580
+ for (const m of ms) inUse.add(m);
1581
+ if (ms.some((m) => m.emissiveIntensity > 0)) lit.push(o.userData.objectIndex);
1582
+ });
1583
+ return {
1584
+ mode: xrefMode(entry.display), painted: entry.painted,
1585
+ meshes, arrayMeshes, runs, materials: inUse.size, cached: entry.mats.size,
1586
+ selected: id === xrefSelected,
1587
+ subSelected: xrefSubSelected && xrefSubSelected.refId === id
1588
+ ? { index: xrefSubSelected.index, objectId: xrefSubSelected.objectId } : null,
1589
+ lit: lit.sort((a, b) => a - b),
1590
+ colors: [...inUse].map((m) => ({
1591
+ hex: `#${m.color.getHexString()}`, alpha: m.userData.alpha,
1592
+ opacity: Math.round(m.opacity * 1000) / 1000,
1593
+ })).sort((a, b) => (a.hex < b.hex ? -1 : 1)),
1594
+ };
1094
1595
  }
1095
1596
 
1096
1597
  /** World bounds of one reference — what zoom-to frames, and what the off-screen check measures. */
@@ -1703,19 +2204,29 @@ function setEnvironment(on) {
1703
2204
  // dropping the coplanar diagonals, keeping the true member outline. Built lazily on first Wire entry and
1704
2205
  // cached per mesh; the outline is a CHILD of the mesh (inherits its transform, hidden with it) and is never
1705
2206
  // picked (member raycasts are non-recursive over meshById). The outline is drawn in the MEMBER's colour
1706
- // (matches the Solid legend, incl. the selection highlight) — line materials are shared per colour so ~24
1707
- // profiles cost ~24 materials, not one per member.
2207
+ // (matches the Solid legend) unless it is selected or hovered — see wireEdgeColorOf — and line materials are
2208
+ // shared per colour so ~24 profiles cost ~24 materials, not one per member.
1708
2209
  const WIRE_EDGE_FALLBACK = 0x94a3b8; // slate — only if a mesh somehow has no colour
1709
2210
  const wireEdgeMats = new Map(); // colour hex -> shared LineBasicMaterial
1710
2211
  const wireEdges = new Map(); // meshId -> LineSegments (edge overlay child)
1711
- function wireEdgeColorOf(mesh) { const c = mesh.material && mesh.material.color; return c ? c.getHex() : WIRE_EDGE_FALLBACK; }
2212
+ // In Wire mode the solid fill is hidden (applyDisplayMode), so a member's hover/selection cue — which lives on
2213
+ // the fill's EMISSIVE — is invisible unless the OUTLINE adopts it. Mirror it here, selection beating hover
2214
+ // exactly as setHoverGlow does. This tracks live because the only two writers of these sets end in
2215
+ // applyDisplayMode — setSelection and setHover both assign BEFORE their call, and clearRoot's reset is picked
2216
+ // up by the rebuild's own sweep — which re-colours through wireEdgesFor. hoverGlowIds (not hoverId) is the set
2217
+ // actually lit, so hovering one part of a connection outlines the whole connection — the grouping the glow uses.
2218
+ function wireEdgeColorOf(id, mesh) {
2219
+ if (selIds.has(id)) return SELECT_EMISSIVE; // selected → brand-blue outline
2220
+ if (hoverGlowIds.includes(id)) return HOVER_EMISSIVE; // hovered → sky outline (matches Solid/X-ray)
2221
+ const c = mesh.material && mesh.material.color; return c ? c.getHex() : WIRE_EDGE_FALLBACK;
2222
+ }
1712
2223
  function wireEdgeMatFor(hex) { let m = wireEdgeMats.get(hex); if (!m) { m = new THREE.LineBasicMaterial({ color: hex }); wireEdgeMats.set(hex, m); } return m; }
1713
2224
  function wireEdgesFor(id, mesh) {
1714
2225
  let ls = wireEdges.get(id);
1715
2226
  if (ls && ls.parent !== mesh) { if (ls.parent) ls.parent.remove(ls); ls.geometry.dispose(); ls = null; } // mesh rebuilt under the same id → drop the stale outline
1716
- const mat = wireEdgeMatFor(wireEdgeColorOf(mesh));
2227
+ const mat = wireEdgeMatFor(wireEdgeColorOf(id, mesh));
1717
2228
  if (!ls) { ls = new THREE.LineSegments(new THREE.EdgesGeometry(mesh.geometry, 20), mat); mesh.add(ls); wireEdges.set(id, ls); } // 20° threshold: keep corners, drop the flat-face triangulation diagonals
1718
- else ls.material = mat; // re-colour if the member's colour changed (selection highlight / recolour) — applyDisplayMode re-runs on selection
2229
+ else ls.material = mat; // re-colour if the outline's colour changed (selection / hover cue, or a member recolour) — applyDisplayMode re-runs on both
1719
2230
  return ls;
1720
2231
  }
1721
2232
  function clearWireEdges() {
@@ -2350,6 +2861,13 @@ function onKey(e) {
2350
2861
  if (basePickCol && e.key === 'Escape') { e.preventDefault(); setBasePickMode(null); if (api && api.toast) api.toast('Trim cancelled'); return; } // Esc disarms the Mode B column-base pick
2351
2862
  if (clipMode && e.key === 'Escape') { e.preventDefault(); if (clipMode === 'box' && clipBoxDraft) { if (clipBoxDraft.b) clipBoxDraft.b = null; else clipBoxDraft = null; setClipPreview(null); if (marker) marker.visible = false; updateStatusChip(); } else setClipMode(null); return; } // Esc steps back: height→footprint→cancel, else disarms the pick
2352
2863
  if (isolatedIds && e.key === 'Escape' && !dimMode3d) { e.preventDefault(); clearIsolation(); return; } // Esc exits isolate-selected (the dim tool's own Esc wins while it's armed)
2864
+ // Esc ascends the REFERENCE drill: one object → the whole reference. ONE RUNG ONLY — unlike the
2865
+ // connection ladder below, which is part → whole → nothing. A reference is borrowed geometry you keep
2866
+ // selected while you build against it, so Esc stops at the reference rather than clearing it; the
2867
+ // References row stays open and its controls stay to hand. Guarded like its sibling so an armed tool's
2868
+ // Esc still wins. (An earlier draft claimed parity with the connection ladder, which the very next
2869
+ // line contradicts.)
2870
+ if (e.key === 'Escape' && !dimMode3d && !cmActive() && xrefSubSelected) { e.preventDefault(); selectReference(xrefSubSelected.refId); return; }
2353
2871
  if (e.key === 'Escape' && !dimMode3d && !cmActive() && ascendConn()) { e.preventDefault(); return; } // Esc ascends the connection drill: part → whole → nothing
2354
2872
  if ((e.key === ' ' && e.shiftKey) || ((e.key === 'z' || e.key === 'Z') && e.altKey && !tfDraft)) { e.preventDefault(); frameSelection(); return; } // zoom-selected (Tekla Shift+Space / viewer Alt+Z) — Alt+Z is suppressed while a Move/Copy base is active: there Alt is the normal-lock modifier, so a reflexive Alt+Z must not jerk the camera mid-move (UCS Stage 4)
2355
2873
  const k = e.key.toLowerCase();
@@ -2504,8 +3022,8 @@ function setSelection(ids) {
2504
3022
  mesh.material.emissive = new THREE.Color(on ? SELECT_EMISSIVE : 0x000000);
2505
3023
  mesh.material.emissiveIntensity = on ? 0.6 : 0;
2506
3024
  }
3025
+ selIds = new Set(set); // BEFORE applyDisplayMode: in Wire mode wireEdgeColorOf reads selIds to colour the outline, so it must already be current (mirrors the setHover ordering) — else a just-(de)selected outline keeps its old colour until the NEXT applyDisplayMode. The reglow re-sync below only fires when a still-hovered part was deselected, so it does not save the ordinary click-to-select case
2507
3026
  applyDisplayMode(); // selection swapped the materials → re-apply wire/xray
2508
- selIds = new Set(set);
2509
3027
  reconcileConnState(set); // any selection path (2D click, box-select, keyboard) must not leave a stale connection envelope/drill
2510
3028
  rebuildEndpoints(); // endpoint dots follow the selection
2511
3029
  let reglow = false; for (const g of hoverGlowIds) if (!set.has(g)) { setHoverGlow(g, true, false); reglow = true; } // still-hovered, now-unselected parts keep their glow (the material swap above cleared it)
@@ -3017,9 +3535,19 @@ function clickSelect(cx, cy, ctrl) {
3017
3535
  // Nothing of ours here — only NOW may a reference answer. Consulted second, never first, so a
3018
3536
  // reference standing in front of a beam can never steal the beam's click; that is how "native
3019
3537
  // selection behaviour is unchanged" is earned structurally rather than tested for and hoped.
3020
- // A whole reference is the only selectable unit: it is one borrowed thing, not a set of parts.
3538
+ // A plain click selects the WHOLE reference — it is one borrowed thing. Ctrl DRILLS INTO the one
3539
+ // object under the pointer, which is the same gesture this editor already uses to reach a part
3540
+ // stacked inside a connection, and it is free here: the modifier's other meaning (additive select)
3541
+ // belongs to the branch above, which this arm is only ever reached instead of.
3021
3542
  let ref = null; try { ref = pickReferenceAt(cx, cy); } catch { ref = null; }
3022
- if (ref) { resetCycle(); selectReference(ref); return; }
3543
+ if (ref) {
3544
+ resetCycle();
3545
+ // The drill FALLS BACK to selecting the whole reference when the object cannot be addressed
3546
+ // (`objectIndex` -1 from a mesh built before this existed). Refusing outright would make Ctrl+click
3547
+ // do nothing at all on such a reference, which reads as a broken control rather than an older one.
3548
+ if (!(ctrl && selectReferenceObject(ref.referenceId, ref.objectIndex))) selectReference(ref.referenceId);
3549
+ return;
3550
+ }
3023
3551
  resetCycle(); selectReference(null); if (!ctrl) clearConnSel(); return; // empty → deselect (clears any connection too); Ctrl/Shift+empty-click preserves the selection (parity with 2D + the additive intent — a near-miss shouldn't wipe it)
3024
3552
  }
3025
3553
  if (ctrl) { resetCycle(); resetConnState(); if (api && api.onSelect) api.onSelect(hits[0], true); return; } // additive toggles the nearest RAW part (leaves connection mode)
@@ -3066,7 +3594,25 @@ function renderConnEnvelope(conn) {
3066
3594
  connEnvelope.material.depthTest = false; connEnvelope.material.transparent = true; connEnvelope.material.opacity = 0.6; connEnvelope.renderOrder = 996;
3067
3595
  overlayScene.add(connEnvelope);
3068
3596
  }
3069
- function resetConnState() { selConn = null; ctxConn = null; clearConnEnvelope(); } // internal reset, no callbacks
3597
+ // The ONLY writer of ctxConn. hoverGroupOf() reads it (root → the whole connection is the hover group,
3598
+ // drilled → only the part under the cursor), but nothing re-derives that group while the pick under the
3599
+ // cursor is unchanged: a truly still pointer fires no pointermove at all, the hover handler guards on
3600
+ // `top !== hoverId`, and setHover early-returns on the same id. So a drill/ascend under a stationary pointer
3601
+ // would leave the pre-transition group lit until the pick changed (another mesh, empty space, or leaving the
3602
+ // canvas) — and setSelection's re-glow pass would faithfully re-light that stale set. Re-derive the group
3603
+ // here — hoverGroupOf() runs a second time, against the FRESH ctxConn, and setHover re-runs only when the
3604
+ // set actually changed — before the api callbacks the click paths fire, so the setSelection they trigger
3605
+ // sees the right group.
3606
+ // (reconcileConnState also reaches this re-entrantly from INSIDE setSelection — after selIds is assigned,
3607
+ // before the re-glow pass; both orderings are load-bearing.)
3608
+ function setCtxConn(conn) {
3609
+ if (conn === ctxConn) return;
3610
+ ctxConn = conn;
3611
+ const next = hoverGroupOf(hoverId);
3612
+ if (next.length === hoverGlowIds.length && next.every((g, i) => g === hoverGlowIds[i])) return; // only a pointer on the connection being entered or left regroups; a bare member or a different connection groups the same either side — skip the O(meshes) re-sync. Both arrays come from connChildIds over the same meshById order, so this can only ever report a false "changed" (extra work), never a false "unchanged"
3613
+ const id = hoverId; hoverId = null; setHover(id); // clear hoverId to defeat setHover's same-id early-return
3614
+ }
3615
+ function resetConnState() { selConn = null; setCtxConn(null); clearConnEnvelope(); } // internal reset, no callbacks
3070
3616
  // Select the WHOLE connection at root (single-click a part, or a breadcrumb click). Clears any drill context.
3071
3617
  function selectWholeConn(conn) {
3072
3618
  const kids = conn ? connChildIds(conn) : [];
@@ -3075,7 +3621,7 @@ function selectWholeConn(conn) {
3075
3621
  // stay INERT (leave the current selection + draw NO envelope) instead of a phantom envelope with an
3076
3622
  // empty selection. onSelectMany also filters, but the envelope + selConn are installed here first.
3077
3623
  if (api && api.canSelectId && !kids.some(api.canSelectId)) return;
3078
- selConn = conn; ctxConn = null;
3624
+ selConn = conn; setCtxConn(null); // dropping the drill widens the hover GROUP back to the whole connection (masked while those parts stay selected — it pays off when the selection is later cleared and setSelection's re-glow pass re-lights the set)
3079
3625
  renderConnEnvelope(conn);
3080
3626
  if (api && api.onSelectMany) api.onSelectMany(kids);
3081
3627
  }
@@ -3085,7 +3631,7 @@ function selectWholeConnWithGrids(conn, gridIds) {
3085
3631
  const selectableKids = api && api.canSelectId ? kids.filter(api.canSelectId) : kids;
3086
3632
  const selectableGrid = (gridIds || []).length && (!api || !api.canSelectGrid || api.canSelectGrid());
3087
3633
  if (!selectableKids.length && !selectableGrid) return; // a wholly filtered batch is inert, including its existing whole/drilled connection context
3088
- if (selectableKids.length) { selConn = conn; ctxConn = null; renderConnEnvelope(conn); }
3634
+ if (selectableKids.length) { selConn = conn; setCtxConn(null); renderConnEnvelope(conn); }
3089
3635
  else resetConnState(); // a filtered connection may share the box with an allowed grid; never show a phantom envelope
3090
3636
  if (api && api.onSelectBatch) api.onSelectBatch({ memberIds: kids, gridIds: gridIds || [] }, false);
3091
3637
  else selectWholeConn(conn);
@@ -3094,7 +3640,7 @@ function selectWholeConnWithGrids(conn, gridIds) {
3094
3640
  function clearConnSel() { resetConnState(); if (api && api.onSelect) api.onSelect(null, false); }
3095
3641
  // Enter a connection (double-click) and select the part under the cursor — the drill-in step.
3096
3642
  function enterConn(conn, partId) {
3097
- ctxConn = conn; selConn = conn; clearConnEnvelope(); // inside → the part-level highlight carries; no whole envelope
3643
+ setCtxConn(conn); selConn = conn; clearConnEnvelope(); // inside → the part-level highlight carries; no whole envelope (and the hover GROUP narrows to the hovered part, so its siblings stop glowing)
3098
3644
  const grp = boltGroupOf(partId);
3099
3645
  if (grp.length > 1) { if (api && api.onSelectMany) api.onSelectMany(grp); }
3100
3646
  else if (api && api.onSelect) api.onSelect(partId, false);
@@ -4798,8 +5344,9 @@ function dispose() {
4798
5344
  dims3dGroup = dimPreviewLine = overlayDimsGroup = null;
4799
5345
  // The reference layer owns real GPU buffers — a whole tessellated building's worth. Leaving them
4800
5346
  // attached to a torn-down scene is the kind of leak that only shows up after the fifth 2D↔3D switch.
4801
- if (xrefGroup) { xrefGroup.traverse((o) => { o.geometry?.dispose?.(); o.material?.dispose?.(); }); if (scene) scene.remove(xrefGroup); }
5347
+ if (xrefGroup) { disposeReferenceMaterials(); xrefGroup.traverse((o) => { o.geometry?.dispose?.(); }); if (scene) scene.remove(xrefGroup); }
4802
5348
  xrefGroup = null; xrefById.clear(); xrefSelected = null;
5349
+ xrefSubSelected = null; xrefSubMesh = null; xrefSubMats = null;
4803
5350
  clearStructGrid();
4804
5351
  clearWireEdges();
4805
5352
  for (const tex of gridTexCache.values()) tex.dispose();
@@ -4848,7 +5395,7 @@ function debug() {
4848
5395
  hidden: [...groupHidden], solo: [...soloGroups], isolated: isolatedIds ? [...isolatedIds] : null, visible: [...meshById.values()].filter((m) => m.visible).length,
4849
5396
  endpoints: epGroup ? epGroup.children.length : 0,
4850
5397
  endpointColors: epGroup ? epGroup.children.map((c) => '#' + c.material.color.getHexString()) : [],
4851
- hoverId, hoverEp, dragEp, refLine: refLineOn,
5398
+ hoverId, hoverGlowIds: [...hoverGlowIds], hoverEp, dragEp, refLine: refLineOn, // hoverGlowIds = the group the hover glow is computed over (whole connection at root, one part once drilled) — hoverId alone can't show that grouping. Selection still beats hover, so a selected id in this set glows brand blue, not sky
4852
5399
  snapMarker: marker && marker.visible ? { type: lastSnapType3d, at: [marker.position.x, marker.position.y, marker.position.z] } : null, // test-observability for the snap reticle
4853
5400
  gridLevels: [...gridLevelsMm], // the drawn grid elevations a grid snap can land on (one plane per visible datum)
4854
5401
 
@@ -4887,6 +5434,46 @@ function snapCandidatesScreen(type) {
4887
5434
  return allCandidates(null).filter((c) => c.type === type && c.p)
4888
5435
  .map((c) => { const s = toScreen(c.p); return { world: c.p, x: rect.left + s.x, y: rect.top + s.y }; });
4889
5436
  }
5437
+ /**
5438
+ * test helper: client (px) coordinates at which a reference OBJECT is actually frontmost.
5439
+ *
5440
+ * VERIFIED BY RAYCAST, not merely projected. A projected centroid is where an object *is*, which is not
5441
+ * the same as where it can be *clicked*: inside a building most objects sit entirely behind another, and
5442
+ * a test that clicked a projected centroid would select the occluder while believing it had clicked the
5443
+ * object it named — a green run for a feature that does not work. So each candidate point is fed back
5444
+ * through `pickReferenceAt` and kept only if it answers with that same object.
5445
+ *
5446
+ * AND NOTHING OF OURS MAY STAND THERE. `clickSelect` consults the reference layer only when its own
5447
+ * members answered nothing, so a point with one of our beams in front is not a point at which this
5448
+ * object can be drilled into at all — however cleanly the reference raycast resolves it. The first pass
5449
+ * of this helper omitted that check and handed back a coordinate covered by a column; the click selected
5450
+ * the column, which is the CORRECT product behaviour and a useless test coordinate.
5451
+ */
5452
+ function referenceObjectsScreen(refId, opts) {
5453
+ const entry = xrefById.get(refId);
5454
+ if (!entry || !canvasEl) return [];
5455
+ const want = opts && Array.isArray(opts.indices) ? new Set(opts.indices) : null;
5456
+ const limit = opts && Number.isFinite(opts.limit) ? opts.limit : 40;
5457
+ camera.updateMatrixWorld(); entry.group.updateMatrixWorld(true);
5458
+ const rect = canvasEl.getBoundingClientRect(), box = new THREE.Box3(), c = new THREE.Vector3(), out = [];
5459
+ for (const mesh of entry.group.children) {
5460
+ if (!mesh.isMesh) continue;
5461
+ const i = mesh.userData.objectIndex;
5462
+ if (want && !want.has(i)) continue;
5463
+ box.setFromObject(mesh); if (box.isEmpty()) continue;
5464
+ box.getCenter(c);
5465
+ const s = c.clone().project(camera);
5466
+ if (!Number.isFinite(s.x) || s.z > 1 || Math.abs(s.x) > 1 || Math.abs(s.y) > 1) continue;
5467
+ const x = rect.left + (s.x * 0.5 + 0.5) * rect.width, y = rect.top + (-s.y * 0.5 + 0.5) * rect.height;
5468
+ let ours = []; try { ours = meshHitsAt(x, y); } catch { ours = []; }
5469
+ if (ours.length) continue;
5470
+ let hit = null; try { hit = pickReferenceAt(x, y); } catch { hit = null; }
5471
+ if (!hit || hit.referenceId !== refId || hit.objectIndex !== i) continue;
5472
+ out.push({ index: i, objectId: mesh.userData.objectId ?? null, x: Math.round(x), y: Math.round(y) });
5473
+ if (out.length >= limit) break;
5474
+ }
5475
+ return out;
5476
+ }
4890
5477
  // test helper: projected, clip-trimmed structural-grid segments. E2E uses these coordinates to drive a
4891
5478
  // real line click / marquee without guessing where an oblique 3D line landed after camera fitting.
4892
5479
  function gridSegmentsScreen() {
@@ -4905,9 +5492,12 @@ window.Steel3DView = {
4905
5492
  // Reference models (#278) — an editor-only layer. `setReferences` takes the geometry the editor
4906
5493
  // fetched from the reference route; nothing here ever passes through contractToScene, which is what
4907
5494
  // keeps borrowed geometry out of every export by construction rather than by filtering.
4908
- setReferences, setReferenceDisplay: applyReferenceDisplay, setReferencePlacement, selectReference,
5495
+ setReferences, setReferenceDisplay: applyReferenceDisplay, setReferencePlacement, selectReference, referenceProbe,
4909
5496
  selectedReference: () => xrefSelected, frameReference, referenceBounds, referenceInfo,
4910
5497
  pickReferenceAt,
5498
+ // Stage A: drilling into ONE object inside a reference. `selectReferenceObject` is what Ctrl+click and
5499
+ // (later) an object-tree row both call, so the two routes cannot drift into different selections.
5500
+ selectReferenceObject, selectedReferenceObject,
4911
5501
  setLabelsOn, labelsOn: () => labelsOnFlag, // member mark/id label overlay toggle
4912
5502
  syncMemberLabels, // editor calls after a mark/id edit to refresh labels
4913
5503
  setPropLabels, // right-click property labels: editor pushes { labels:[{id,lines}], placement }
@@ -4948,7 +5538,8 @@ window.Steel3DView = {
4948
5538
  addDestAt: (x, y) => { if (!drDraft) return null; const r = drDestPoint({ clientX: x, clientY: y, shiftKey: false, altKey: false }); return r ? { p: r.p, snap: r.snap } : null; }, // test probe: the resolved 2nd draw point at a cursor (respects the axis lock) — read-only, no commit
4949
5539
  selDims3dCount: () => (api && api.selDim3d ? (api.selDim3d() || []).length : 0), // test helper: how many 3D dims are selected
4950
5540
  dim3dLabelOf: (i) => { const el = dimLabelPool[i]; if (!el || el.style.display === 'none') return null; const r = el.getBoundingClientRect(); return { x: r.left + r.width / 2, y: r.top + r.height / 2, text: el.textContent }; },
4951
- debug, probe, screenOf, centerOf, worldOf, snapCandidatesScreen, gridSegmentsScreen, gridBubblesScreen, clipHandlesScreen,
5541
+ wireEdgeColor: (id) => { const ls = wireEdges.get(id); return ls && ls.visible && ls.parent && ls.parent.visible && ls.material ? '#' + ls.material.color.getHexString() : null; }, // test probe: the Wire-mode OUTLINE colour of a member. probe() reads the hidden FILL's emissive, which is set in every mode — so it stays green even when the outline never adopts the cue (exactly the regression this fixes); this is the only read of the line that Wire actually draws. Gated like its sibling probes: ls.visible (leaving Wire only HIDES the outline — wireEdgesFor runs on the wire branch alone — so an ungated read reports a stale Wire colour) and ls.parent.visible (group/legend/isolate/work-area hide the parent MESH, and three skips a hidden parent's children). It still cannot see clip planes, frustum culling or a display:none canvas — a false "on" is possible there, never a false "off"
5542
+ debug, probe, screenOf, centerOf, worldOf, snapCandidatesScreen, referenceObjectsScreen, gridSegmentsScreen, gridBubblesScreen, clipHandlesScreen,
4952
5543
  clipPlanePreviewShown: () => !!clipPlanePreview, // test helper: is the armed-plane hover ghost currently showing?
4953
5544
  clipBoxFloorAt: (x, y) => clipBoxFloorPoint(x, y), // test helper: the snapped footprint point at a cursor ({ xy, snap, world } or null)
4954
5545
  pointClipped: (p) => isPointClipped(p), // test helper: is a world point on the cut-away side of any active clip?