@floless/app 0.104.1 → 0.105.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.
@@ -16,11 +16,15 @@
16
16
  */
17
17
  import * as THREE from 'three';
18
18
  import { OrbitControls } from 'three/addons/OrbitControls.js';
19
+ import { RoomEnvironment } from 'three/addons/RoomEnvironment.js';
20
+ import { surfaceTextures, applyTriplanar, TILE_MM, DIRECTIONAL } from './steel-materials.js';
19
21
  import { Brush, Evaluator, SUBTRACTION } from 'three-bvh-csg';
20
- import { snapCandidates, snapPoint, planPointToWp, memberGeometry, elevationLevels, snapElevation, dim3dGeom, dominantAxis3d, planeBasis, planeFrom3Points, vecToPlane, frameFrom3Points, frameFromAngle, worldToLocal, identityFrame, resolvePointEntry, offsetsFor, candidateOnPlane, snapGridPoint, clipSegmentToPlanes, pointSegmentDistance2d, perspectiveSegmentParameter, gridDepthWins, segmentHitsRect2d, projectedFootprintHitsRect2d, pickGridLevel } from './steel-3d-core.js';
22
+ import { snapCandidates, snapPoint, planPointToWp, memberGeometry, planScaleOf, planScaleIndex, memberGeometryInOwnPlan, elevationLevels, elevationLevelsByPlan, snapElevation, dim3dGeom, dominantAxis3d, planeBasis, planeFrom3Points, vecToPlane, frameFrom3Points, frameFromAngle, worldToLocal, identityFrame, resolvePointEntry, offsetsFor, candidateOnPlane, snapGridPoint, clipSegmentToPlanes, pointSegmentDistance2d, perspectiveSegmentParameter, gridDepthWins, segmentHitsRect2d, projectedFootprintHitsRect2d, pickGridLevel } from './steel-3d-core.js';
21
23
  import { gridGeometry, gridCandidates3d, mmPerPx, visibleGridLevels } from './grid-core.js';
22
24
 
23
25
  let renderer, scene, perspCam, orthoCam, camera, controls, root, api, canvasEl, ro, rafId, grid, raycaster, downXY, lastPick = '(none)';
26
+ let lightAmb, lightKey, lightFill; // dimmed in Realistic, where the environment lights the scene
27
+ let shadowGround = null, shadowsEnabled = false; // the `shadowed` mode's ground catcher + its compiled state
24
28
  let pending = null, dragging = null, marker = null, readout = null; // pending = member gesture; readout = drag dimension overlay
25
29
  let boxSel = null, rubber = null; // LEFT-drag-on-empty rubber-band multi-select
26
30
  let hoverId = null, hoverGlowIds = [], hoverChip = null, hoverRAF = 0, lastHoverXY = null; // hover readout + cursor; hoverGlowIds = every mesh currently wearing the sky glow (the WHOLE connection when hovering one of its parts)
@@ -46,7 +50,22 @@ const selLenLabelPool = []; // reused <div> length chips, one per selecte
46
50
  let selLenLabelSpec = null; // [{id, text}] pushed from the editor when "Show member length" is on (⋯ Display)
47
51
  const EP_PX = 4; // end-dot radius in screen px (screen-constant via pxToWorld)
48
52
  let sceneBox = new THREE.Box3(); // current model bounds (Fit / ViewCube)
49
- let displayMode = 'solid'; // solid | wire | xray
53
+ let displayMode = 'solid';
54
+ // Modes that draw solid fills, and so can hide a grid line behind a member. Wire and X-ray cannot:
55
+ // their fills do not write depth, so a grid behind them is genuinely visible. Realistic and Shadowed
56
+ // are as opaque as Solid — leaving them out made every member sitting on a grid line unclickable,
57
+ // because the grid always won the depth comparison.
58
+ const OPAQUE_MODES = new Set(['solid', 'realistic', 'shadowed']); // solid | wire | xray
59
+ // …but the MODE being opaque doesn't make every mesh in it opaque. Realistic/Shadowed render a glass
60
+ // element at opacity 0.28 with depthWrite:false, and a material that writes no depth cannot occlude
61
+ // anything — the same reason Wire/X-ray fills are excluded wholesale. Without this a grid line plainly
62
+ // visible THROUGH glass still lost the depth comparison and could not be picked.
63
+ function occludesGrid(hit) {
64
+ const mat = hit && hit.object && hit.object.material;
65
+ const m = Array.isArray(mat) ? mat[0] : mat;
66
+ if (!m) return false;
67
+ return m.depthWrite !== false && !(m.transparent && m.opacity < 1);
68
+ }
50
69
  const groupHidden = new Set(); // profile keys hidden via the legend
51
70
  let soloGroups = new Set(); // profile keys isolated via the legend (dbl-click; Ctrl/Shift add to the set)
52
71
  let isolatedIds = null; // Tekla "isolate selected": Set of ids shown exclusively, or null for off
@@ -68,6 +87,10 @@ const EP_END = 0xf472b6; // end endpoint (end 2) — magenta
68
87
 
69
88
  // ---- 3D dimension tool ----
70
89
  let dimMode3d = false; // tool armed
90
+ // The grid panel's "Add single line" pick, armed while the 3D view is showing. Same two-click gesture as the
91
+ // dimension tool (and as the 2D pick it mirrors): null = disarmed, {a:null} = waiting for the first point,
92
+ // {a:[x,y,z]} = waiting for the second. The editor owns the arming — it drives BOTH views off one flag.
93
+ let gridLinePick3d = null;
71
94
  let snapOnly3d = null; // Tekla-style snap override for the dim tool: a snapCandidates type ('vertex'|'intersection'|'midpoint'|'centerline'|'vertical-axis'), 'none' = free, null = all (set from the right-click menu in steel-editor.html)
72
95
  // map a 3D candidate type → the 2D running-snap key (⋯ menu → Snapping). Types with no key (level, vertical-axis) are 3D-only aids, always allowed.
73
96
  const SNAP3D_PREF = { vertex: 'end', intersection: 'int', midpoint: 'mid', centerline: 'line', 'grid-line': 'line', 'grid-int': 'int' };
@@ -99,10 +122,13 @@ function candOnActiveWP(c, dragged, wp) {
99
122
  return candidateOnPlane(c, dragged, wp.origin, wp.normal, WP_SNAP_TOL_MM);
100
123
  }
101
124
  let rightDownXY = null, rightMoved = false; // right button: dragged (= orbit/pan, no menu) vs clicked (= snap menu)
125
+ let teklaDrag = null; // Ctrl+Shift drag-out to Tekla: { ids } from the moment the gesture is armed until dragend
102
126
  const dimLock = new Set(); // locked MEASURE axes (subset of x|y|z); empty = Free/aligned. Toggle+combine like Move/Copy's tfLock (measures along the resolved/dominant axis; the 2nd point still free-snaps).
103
127
  let dims3dVisibleFlag = true; // show/hide placed dims
104
128
  let dimDraft3d = null; // { a:[x,y,z] } once the first point is placed (awaiting the 2nd)
105
129
  let dimLastAlt = false; // last-seen Alt state (the hover rAF rebuilds a synthetic event)
130
+ let hoverTeklaMod = false; // last-seen Ctrl+Shift state — arms the drag-out-to-Tekla cursor hint
131
+ let pointerOverCanvas = false; // is the cursor actually on the 3D canvas right now (lastHoverXY outlives the pointer leaving)
106
132
  let dims3dGroup = null; // THREE.Group of placed-dim lines (+ the live preview line)
107
133
  let dimPreviewLine = null; // reused preview line (point 1 → cursor)
108
134
  let dimLabelHost = null; // fixed-position container for label overlays
@@ -118,6 +144,10 @@ function init(canvas, theApi) {
118
144
  if (renderer) return; // once
119
145
  canvasEl = canvas; api = theApi;
120
146
  renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
147
+ // Off by default and switched on only by the `shadowed` mode: leaving shadow mapping enabled
148
+ // compiles shadow code into every material even when nothing casts, so the cheap modes would still
149
+ // pay for it. The one-time recompile on the switch is the price of that.
150
+ renderer.shadowMap.enabled = false; renderer.shadowMap.type = THREE.PCFSoftShadowMap;
121
151
  renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
122
152
  renderer.localClippingEnabled = true; // enable clip planes/boxes + the work area (Tekla-style sectioning) — driven via renderer.clippingPlanes (applyClips)
123
153
  scene = new THREE.Scene();
@@ -143,9 +173,11 @@ function init(canvas, theApi) {
143
173
  // always keeps the pivot screen-centred — that would need a custom control); add that only if this isn't enough.
144
174
  controls.addEventListener('start', repivotToCursor);
145
175
  canvas.addEventListener('wheel', onWheelHover, { capture: true, passive: true }); // keep the cursor pos fresh for the wheel-triggered re-pivot (capture → runs before OrbitControls' wheel handler)
146
- scene.add(new THREE.AmbientLight(0xffffff, 0.65));
147
- const key = new THREE.DirectionalLight(0xffffff, 0.85); key.position.set(0.4, -1, 1.2); scene.add(key);
148
- const fill = new THREE.DirectionalLight(0xffffff, 0.25); fill.position.set(-1, 0.6, 0.4); scene.add(fill);
176
+ // Kept on module scope so Realistic can dim them: an environment map is itself a light source, and
177
+ // leaving this rig at full strength on top of it lights the scene roughly twice over.
178
+ lightAmb = new THREE.AmbientLight(0xffffff, 0.65); scene.add(lightAmb);
179
+ lightKey = new THREE.DirectionalLight(0xffffff, 0.85); lightKey.position.set(0.4, -1, 1.2); scene.add(lightKey);
180
+ lightFill = new THREE.DirectionalLight(0xffffff, 0.25); lightFill.position.set(-1, 0.6, 0.4); scene.add(lightFill);
149
181
  root = new THREE.Group(); scene.add(root);
150
182
  overlayScene = new THREE.Scene(); // clip/work-area gizmos render here in a 2nd unclipped pass (see loop)
151
183
  epGroup = new THREE.Group(); scene.add(epGroup);
@@ -215,9 +247,19 @@ function init(canvas, theApi) {
215
247
  window.addEventListener('pointermove', onMove); // window so a drag keeps tracking off-canvas
216
248
  window.addEventListener('pointerup', onUp);
217
249
  canvas.addEventListener('pointermove', onHoverMove); // canvas-only: cursor + hover readout when idle
218
- canvas.addEventListener('pointerleave', () => { hoverEp = null; if (hoverRAF) { cancelAnimationFrame(hoverRAF); hoverRAF = 0; } setHover(null); setClipPlanePreview(null); if (clipMode && marker) marker.visible = false; updateStatusChip(); }); // leaving the canvas clears the hover glow + chip + clip-plane ghost + a clip snap reticle; cancel any queued hover frame so it can't re-glow the last member after the cursor left
250
+ canvas.addEventListener('pointerenter', () => { pointerOverCanvas = true; });
251
+ canvas.addEventListener('pointerleave', () => { pointerOverCanvas = false; hoverEp = null; if (hoverRAF) { cancelAnimationFrame(hoverRAF); hoverRAF = 0; } setHover(null); setClipPlanePreview(null); if (clipMode && marker) marker.visible = false; updateStatusChip(); }); // leaving the canvas clears the hover glow + chip + clip-plane ghost + a clip snap reticle; cancel any queued hover frame so it can't re-glow the last member after the cursor left
219
252
  canvas.addEventListener('dblclick', onDblClick); // "zoom to detail": dbl-click a part zooms to it (empty = no-op)
253
+ // The OS took the pointer away mid-gesture: no pointerup will follow, so onUp's cleanup never runs.
254
+ // Clear the half-built press too, or orbit stays disabled until some later interaction repairs it.
255
+ canvas.addEventListener('pointercancel', () => {
256
+ if (!teklaDrag) return;
257
+ endTeklaDrag();
258
+ pending = dragging = null; downXY = null; if (controls) controls.enabled = true;
259
+ });
220
260
  window.addEventListener('keydown', onKey); // Tekla keyboard nav: arrows pan, Ctrl/Shift+arrows rotate
261
+ window.addEventListener('keydown', onModifierChange); // the drag-out cursor hint tracks the keys, not just the mouse
262
+ window.addEventListener('keyup', onModifierChange);
221
263
  ro = new ResizeObserver(resize); ro.observe(canvas.parentElement || canvas);
222
264
  initCube();
223
265
  initTriad();
@@ -263,6 +305,20 @@ const V = (x, y, z) => new THREE.Vector3(x, y, z);
263
305
 
264
306
  // ---- structural cross-section shapes (ported from AWARE viewer-3d for parity) ----
265
307
  // section.w = flange/overall width, section.d = section depth; shape derived from the profile name.
308
+ // Which LOCAL axis this element's geometry runs its length along — what directional grain must
309
+ // follow. The constructors disagree, which is the whole reason this exists: BoxGeometry(w,len,d)
310
+ // and CylinderGeometry are Y-axial, while ExtrudeGeometry({depth:len}) is Z-axial. Imported custom
311
+ // meshes have no canonical length axis, so they keep world projection (null).
312
+ function lengthAxisOf(el) {
313
+ const kind = (el && el.kind) || 'box';
314
+ if (kind === 'custom' || kind === 'mesh') return null;
315
+ // `nut` belongs here, not with the plates: placeNut delegates to placeBar, so a nut is a 6-sided
316
+ // CylinderGeometry swept along local +Y like a rod — classifying it 'z' brushed a directional
317
+ // finish across the nut's short axis instead of along its sweep.
318
+ if (kind === 'rod' || kind === 'bolt-shank' || kind === 'anchor' || kind === 'nut') return 'y'; // CylinderGeometry
319
+ if (kind === 'plate' || kind === 'washer' || kind === 'bolt-head') return 'z';
320
+ return shapeOf(el) === 'BOX' ? 'y' : 'z'; // Box vs Extrude
321
+ }
266
322
  function shapeOf(el) {
267
323
  const explicit = (el.section && el.section.shape || '').toString().toUpperCase().trim();
268
324
  if (/^(I|C|L|TUBE|BOX)$/.test(explicit)) return explicit; // explicit section.shape override wins
@@ -508,8 +564,74 @@ function placeElement(mesh, el) {
508
564
  }
509
565
  }
510
566
 
511
- function materialFor(groupKey) {
512
- if (!baseMat.has(groupKey)) {
567
+ // ---- Realistic display mode: real construction materials ----------------------------------
568
+ // Parity with AWARE's viewer-3d (cli/src/render/viewer_3d.rs) — the SAME table and grade map, so a
569
+ // model looks the same in the editor as in a shared read-only link. `painted` deliberately has no
570
+ // colour of its own: it keeps the element's profile colour, so switching to Realistic does not
571
+ // flatten every member to one grey and destroy the legend.
572
+ const MATERIALS = {
573
+ // Painted steel gets a REAL paint colour — shop-primer grey — not the member's profile colour.
574
+ // Keeping the legend hue here was the original design and it was wrong: it put hot-pink beams in a
575
+ // view whose entire purpose is to look real, giving neither a usable legend nor a believable model.
576
+ // Colour-by-profile is what Solid is for; Realistic is for showing someone the building.
577
+ painted: { metalness: 0.0, roughness: 0.62, color: 0x8f949b },
578
+ steel: { metalness: 1.0, roughness: 0.45, color: 0x8a8f98 }, // bare / mill finish
579
+ galvanised: { metalness: 0.85, roughness: 0.62, color: 0xb8bfc6 }, // spangled zinc — rougher on purpose
580
+ stainless: { metalness: 1.0, roughness: 0.18, color: 0xc7ccd1 },
581
+ weathering: { metalness: 0.55, roughness: 0.75, color: 0x7a4a32 }, // COR-TEN
582
+ aluminium: { metalness: 1.0, roughness: 0.30, color: 0xd6d9dc },
583
+ concrete: { metalness: 0.0, roughness: 0.92, color: 0xa8a49c },
584
+ timber: { metalness: 0.0, roughness: 0.70, color: 0xb0854a },
585
+ asphalt: { metalness: 0.0, roughness: 0.95, color: 0x2e3033 },
586
+ glass: { metalness: 0.0, roughness: 0.05, color: 0xcfe3ee, opacity: 0.28 },
587
+ };
588
+ // A grade names the ALLOY, not the finish, so it only decides the look where the alloy IS the look.
589
+ // Plain carbon (A36/A992/A572/A709/A500/A501) matches nothing and falls through to `painted`.
590
+ const GRADE_FAMILIES = [
591
+ ['stainless', /STAINLESS|INOX|A240|\b(304|316|321|410)\b/],
592
+ ['weathering', /WEATHERING|COR-?TEN|A588|A847/],
593
+ ['aluminium', /ALUMINI?UM|\bALUM\b|\b(6061|6063|5052)\b/],
594
+ ['galvanised', /GALVANI[SZ]ED|\bHDG\b|A123|A153|\bG90\b/],
595
+ ['concrete', /CONCRETE/],
596
+ ['timber', /TIMBER|WOOD|GLULAM|\bLVL\b/],
597
+ ['asphalt', /ASPHALT|BITUMEN|TARMAC/],
598
+ ['glass', /GLASS|GLAZING/],
599
+ ];
600
+ // `material` is the ELEMENT-level field (the one contractToScene emits and the IFC writer reads);
601
+ // `meta.material` is a fallback only. Each candidate is trimmed BEFORE the choice — a whitespace-only
602
+ // value is truthy, so a bare `||` would pick it, trim it to nothing, and skip a good fallback.
603
+ function familyOf(el) {
604
+ const pick = (v) => (v == null ? '' : String(v)).trim();
605
+ const raw = pick(el && el.material) || pick(el && el.meta && el.meta.material);
606
+ if (!raw) return 'painted';
607
+ if (MATERIALS[raw.toLowerCase()]) return raw.toLowerCase(); // an explicit family name wins outright
608
+ const up = raw.toUpperCase();
609
+ for (const [fam, re] of GRADE_FAMILIES) if (re.test(up)) return fam;
610
+ return 'painted';
611
+ }
612
+
613
+ // Generated surfaces are shared per FAMILY across every profile and every rebuild (they depend only
614
+ // on the family), so the canvas work happens once per family per session, not once per member.
615
+ const texByFamily = new Map();
616
+ function surfaceFor(family) {
617
+ if (!family) return null;
618
+ if (!texByFamily.has(family)) {
619
+ const spec = MATERIALS[family];
620
+ // The map encodes ABSOLUTE roughness around this family's declared value, so it needs it here.
621
+ texByFamily.set(family, surfaceTextures(THREE, family, spec ? spec.roughness : 0.5));
622
+ }
623
+ return texByFamily.get(family);
624
+ }
625
+
626
+ // Materials are shared per (profile, family) pair rather than per profile alone: two members of the
627
+ // same profile can carry different materials, and applyDisplayMode MUTATES the shared material — so
628
+ // keying on the profile alone would repaint a whole profile group from one member's material.
629
+ function materialFor(groupKey, family, axis = null) {
630
+ const fam = family || 'painted';
631
+ // The axis belongs in the KEY: one group can hold both Y-axial boxes and Z-axial extrusions, and
632
+ // they need different shaders — sharing a single material would give half of them the wrong grain.
633
+ const key = `${groupKey}|${fam}|${axis || 'world'}`;
634
+ if (!baseMat.has(key)) {
513
635
  const col = groupColor.get(groupKey) || new THREE.Color(0x94a3b8);
514
636
  // Fasteners (anchor rods / bolts / nuts / washers) read more metallic (zinc-plated); plates/welds/members stay matte.
515
637
  const metallic = groupKey === 'anchor' || groupKey === 'bolt' || groupKey === 'nut' || groupKey === 'washer';
@@ -517,9 +639,22 @@ function materialFor(groupKey) {
517
639
  // Imported (custom) connection meshes are tessellated with untrusted winding order → render both
518
640
  // faces so no triangle drops out; matte steel like a plate.
519
641
  const dbl = groupKey === 'custom';
520
- baseMat.set(groupKey, new THREE.MeshStandardMaterial({ color: col, metalness: metal, roughness: rough, side: dbl ? THREE.DoubleSide : THREE.FrontSide }));
642
+ const mat = new THREE.MeshStandardMaterial({ color: col, metalness: metal, roughness: rough, side: dbl ? THREE.DoubleSide : THREE.FrontSide });
643
+ // The shadow pass uses a depth material that ignores renderer.clippingPlanes unless the material
644
+ // opts in — without this, a clip plane, clip box or work area hides geometry that keeps casting.
645
+ mat.clipShadows = true;
646
+ // Patch for triplanar sampling ONCE, at creation, rather than toggling it with the mode: both
647
+ // replaced chunks are guarded by USE_MAP/USE_ROUGHNESSMAP, so with no maps bound the patched
648
+ // shader is equivalent to the stock one — and Solid never pays a program recompile on switch.
649
+ if (TILE_MM[fam]) applyTriplanar(mat, TILE_MM[fam], DIRECTIONAL.has(fam) ? axis : null);
650
+ // Remember the flat look so leaving Realistic restores it EXACTLY — including the per-group
651
+ // metal/rough split above, which a constant would flatten. Stored as a plain hex NUMBER, not a
652
+ // THREE.Color: Material.clone() round-trips userData through JSON (the selection/hover clones
653
+ // below rely on it), which would reduce a Color instance to a bare {r,g,b} object.
654
+ mat.userData = { family: fam, baseHex: col.getHex(), baseMetal: metal, baseRough: rough, axis };
655
+ baseMat.set(key, mat);
521
656
  }
522
- return baseMat.get(groupKey);
657
+ return baseMat.get(key);
523
658
  }
524
659
 
525
660
  function clearRoot() {
@@ -601,7 +736,7 @@ function applyCopes(mesh, cuts) {
601
736
 
602
737
  function buildFromScene(sc) {
603
738
  clearRoot();
604
- clipCandidates = null; clipLevels = null; // the model changed (edit/undo/redo) — drop the clip-draw snap cache so a draw in progress re-snaps against the CURRENT members/grid/levels, never stale ones
739
+ clipCandidates = null; clipLevels = null; scaleIdx = null; // the model changed (edit/undo/redo) — drop the clip-draw snap cache so a draw in progress re-snaps against the CURRENT members/grid/levels, never stale ones
605
740
  resetConnState(); // a fresh scene rebuilds selection from scratch — drop any stale connection envelope/context
606
741
  for (const mat of baseMat.values()) mat.dispose(); // shared per-profile materials from the prior build
607
742
  groupColor.clear(); baseMat.clear();
@@ -618,17 +753,52 @@ function buildFromScene(sc) {
618
753
  }
619
754
  }
620
755
  for (const el of sc.elements || []) {
621
- const mesh = new THREE.Mesh(undefined, materialFor(el.group));
756
+ const mesh = new THREE.Mesh(undefined, materialFor(el.group, familyOf(el), lengthAxisOf(el)));
622
757
  if (!placeElement(mesh, el)) continue; // unknown kind → skip (a `cut` is one of these: applied below, never a standalone mesh)
623
758
  const memberCuts = cutsByMember.get(el.id);
624
759
  if (memberCuts && memberCuts.length) applyCopes(mesh, memberCuts); // notch a coped member end
625
760
  mesh.userData.id = el.id; mesh.userData.group = el.group; mesh.userData.profile = el.meta && el.meta.profile;
761
+ mesh.userData.family = familyOf(el); // the selection/hover clones and the restore path need it too
762
+ mesh.userData.axis = lengthAxisOf(el); // …and so does the axis, or a clone rebuilds a world-projected shader
626
763
  mesh.userData.derived = !!(el.kind && el.kind !== 'box'); // connection parts: rendered, not member-editable
627
764
  mesh.userData.conn = el.conn || null; mesh.userData.connKind = el.connKind || null; // Connection Component membership (Slice A) — the whole-select/drill handle
765
+ mesh.receiveShadow = true; // steel catches shadow from steel; casting is decided per-pass in applyDisplayMode
628
766
  root.add(mesh); meshById.set(el.id, mesh);
629
767
  box.expandByObject(mesh);
630
768
  }
631
769
  sceneBox = box.clone();
770
+ // A single-material model reads flat without shadows: nothing marks where a column lands or a beam
771
+ // meets a column. Sized from the model bounds — a fixed frustum either clips a large model or
772
+ // wastes resolution on a small one. The scene is Z-UP here (contractToScene emits meta.up='z'), so
773
+ // the catcher plane needs no rotation and sits at the model's minimum Z.
774
+ if (lightKey && !box.isEmpty()) {
775
+ const size = box.getSize(new THREE.Vector3()), centre = box.getCenter(new THREE.Vector3()); // expandByObject: real mesh extents, not centrelines
776
+ const span = Math.max(size.x, size.y, size.z) || 1;
777
+ lightKey.castShadow = shadowsEnabled; // syncShadows owns this; a rebuild must not force it on
778
+ // Position the light AND its target around the model before sizing the camera. The key light sits
779
+ // at a fixed unit offset and targets the origin by default, so on a millimetre-scale model it
780
+ // stayed ~1.6 mm from the origin while the near plane moved out to hundreds of millimetres —
781
+ // putting the geometry behind the near plane, and any model not centred on the origin outside the
782
+ // frustum entirely. Either way Shadowed produced little or no shadow.
783
+ lightKey.position.copy(centre).add(new THREE.Vector3(span * 0.6, -span, span * 1.2));
784
+ lightKey.target.position.copy(centre);
785
+ if (lightKey.target.parent !== scene) scene.add(lightKey.target);
786
+ lightKey.target.updateMatrixWorld();
787
+ lightKey.shadow.mapSize.set(2048, 2048);
788
+ const sc = lightKey.shadow.camera, r = span * 1.2;
789
+ sc.left = -r; sc.right = r; sc.top = r; sc.bottom = -r; sc.near = span * 0.02; sc.far = span * 10;
790
+ sc.updateProjectionMatrix();
791
+ // Steel webs are thin, so acne and peter-panning are both easy to hit; a model-scaled normalBias
792
+ // handles the thin-web case a constant one cannot.
793
+ lightKey.shadow.bias = -0.0004; lightKey.shadow.normalBias = Math.max(span * 0.0015, 1);
794
+ if (shadowGround) { scene.remove(shadowGround); shadowGround.geometry.dispose(); shadowGround.material.dispose(); }
795
+ // ShadowMaterial catches the shadow while staying invisible itself, so the background shows
796
+ // through everywhere the shadow is not.
797
+ shadowGround = new THREE.Mesh(new THREE.PlaneGeometry(span * 4, span * 4), new THREE.ShadowMaterial({ opacity: 0.42 }));
798
+ shadowGround.position.set(centre.x, centre.y, box.min.z);
799
+ shadowGround.receiveShadow = true; shadowGround.visible = false;
800
+ scene.add(shadowGround);
801
+ }
632
802
  renderWorkPlane(); // re-draw the gizmo + reference plane sized to the (possibly new) model bounds
633
803
  // Retain the dim-relevant parts (plates + copes) so the legend's DIMENSIONS overlays can be derived
634
804
  // from the resolved geometry — fin-plate holes give bolt pitch/edge clearance, cuts give cope size.
@@ -664,7 +834,7 @@ function buildRefLines() {
664
834
  const pts = [];
665
835
  for (const m of members()) {
666
836
  if (!m || !Array.isArray(m.wp) || m.wp.length < 2) continue;
667
- const g = memberGeometry(m, api.ptPerFt(), api.defaultTosMm());
837
+ const g = geoOf(m);
668
838
  pts.push(new THREE.Vector3(g.line[0][0], g.line[0][1], g.line[0][2]), new THREE.Vector3(g.line[1][0], g.line[1][1], g.line[1][2]));
669
839
  }
670
840
  if (!pts.length) return;
@@ -678,6 +848,7 @@ function setRefLine(on) { refLineOn = !!on; buildRefLines(); }
678
848
  // placement click raycasts a member face (anchor) or the ground plane and hands the point + basis +
679
849
  // anchor id back to the editor, which creates + selects the detail and records the create request.
680
850
  function setInsertMode(on, pending) {
851
+ if (on) dropGridLinePick3d();
681
852
  insertMode = !!on;
682
853
  insertPending = insertMode ? (pending || insertPending) : null;
683
854
  if (insertMode) { if (api && api.disarmTransform) api.disarmTransform(); if (api && api.disarmAdd) api.disarmAdd(); setClipMode(null); disarmFrame3d(); }
@@ -691,6 +862,7 @@ function insertModeOn() { return insertMode; }
691
862
  // snaps the base to a real framing level. A one-shot left-click hands the picked base elevation to the editor
692
863
  // via api.onBasePick. Mirrors setInsertMode.
693
864
  function setBasePickMode(colId) {
865
+ if (colId) dropGridLinePick3d();
694
866
  basePickCol = colId || null;
695
867
  basePickLevels = null;
696
868
  if (basePickCol) {
@@ -765,11 +937,10 @@ function syncMemberLabels() {
765
937
  el.style.cssText = 'position:absolute;transform:translate(-50%,-50%);pointer-events:none;background:var(--panel,#0f172a);color:var(--mut,#94a3b8);border:1px solid var(--line,#1e293b);border-radius:4px;padding:1px 5px;font:11px system-ui;white-space:nowrap;box-shadow:0 1px 4px rgba(0,0,0,.4)';
766
938
  memberLabelHost.appendChild(el); memberLabelPool.push(el);
767
939
  }
768
- const ppf = api.ptPerFt(), dtos = api.defaultTosMm();
769
940
  for (let i = 0; i < memberLabelPool.length; i++) {
770
941
  const el = memberLabelPool[i], m = ms[i];
771
942
  if (!m || !Array.isArray(m.wp) || m.wp.length < 2) { el.style.display = 'none'; el._mid = null; continue; }
772
- const g = memberGeometry(m, ppf, dtos);
943
+ const g = geoOf(m);
773
944
  el._mid = [(g.line[0][0] + g.line[1][0]) / 2, (g.line[0][1] + g.line[1][1]) / 2, (g.line[0][2] + g.line[1][2]) / 2];
774
945
  el.textContent = m.mark || m.id || '';
775
946
  el.style.display = 'block';
@@ -810,11 +981,10 @@ function syncPropLabels() {
810
981
  propLabelHost.appendChild(el); propLabelPool.push(el);
811
982
  }
812
983
  const byId = new Map(members().map((m) => [m.id, m]));
813
- const ppf = api.ptPerFt(), dtos = api.defaultTosMm();
814
984
  for (let i = 0; i < propLabelPool.length; i++) {
815
985
  const el = propLabelPool[i], L = labels[i], m = L ? byId.get(L.id) : null;
816
986
  if (!m || !Array.isArray(m.wp) || m.wp.length < 2 || !L.lines || !L.lines.length) { el.style.display = 'none'; el._mid = null; el._memberId = null; continue; }
817
- const g = memberGeometry(m, ppf, dtos), a = g.line[0], b = g.line[1];
987
+ const g = geoOf(m), a = g.line[0], b = g.line[1];
818
988
  el._mid = place === 'start' ? a : place === 'end' ? b : [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2, (a[2] + b[2]) / 2];
819
989
  el._memberId = m.id;
820
990
  el.textContent = L.lines.join('\n');
@@ -856,11 +1026,10 @@ function syncSelLenLabels() {
856
1026
  selLenLabelHost.appendChild(el); selLenLabelPool.push(el);
857
1027
  }
858
1028
  const byId = new Map(members().map((m) => [m.id, m]));
859
- const ppf = api.ptPerFt(), dtos = api.defaultTosMm();
860
1029
  for (let i = 0; i < selLenLabelPool.length; i++) {
861
1030
  const el = selLenLabelPool[i], L = labels[i], m = L ? byId.get(L.id) : null;
862
1031
  if (!m || !Array.isArray(m.wp) || m.wp.length < 2 || !L.text) { el.style.display = 'none'; el._mid = null; el._memberId = null; continue; }
863
- const g = memberGeometry(m, ppf, dtos), a = g.line[0], b = g.line[1];
1032
+ const g = geoOf(m), a = g.line[0], b = g.line[1];
864
1033
  el._mid = [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2, (a[2] + b[2]) / 2];
865
1034
  el._memberId = m.id;
866
1035
  el.textContent = L.text;
@@ -950,7 +1119,7 @@ function clearStructGrid() {
950
1119
  }
951
1120
  function buildStructGrid() {
952
1121
  clearStructGrid();
953
- dimCandidates3d = null; tfCandidates = null; clipCandidates = null; clipLevels = null; // the grid just changed → EVERY cached snap set built from the OLD one is stale (dim, Move/Copy + Add, clip-box draw). rebuild() already nulls these, but refresh3DGrid() (grid panel edits, and the plan switch setPlan now fires) reaches us without it, which would pair one sheet's grid X/Y with another's elevations.
1122
+ dimCandidates3d = null; tfCandidates = null; clipCandidates = null; clipLevels = null; scaleIdx = null; // the grid just changed → EVERY cached snap set built from the OLD one is stale (dim, Move/Copy + Add, clip-box draw). rebuild() already nulls these, but refresh3DGrid() (grid panel edits, and the plan switch setPlan now fires) reaches us without it, which would pair one sheet's grid X/Y with another's elevations.
954
1123
  if (!api || !api.getGrid || !scene) return;
955
1124
  let g = null, geo = null;
956
1125
  try { g = api.getGrid(); if (!g || g.on === false) return; geo = gridGeometry(g, api.ptPerFt()); }
@@ -1075,7 +1244,7 @@ let rebuildSeq = 0;
1075
1244
  async function rebuild(fit = false) {
1076
1245
  if (!api) return;
1077
1246
  invalidatePointEntry('rebuild'); // synchronous, BEFORE the first await — the scene is changing; drop any open typed entry + stale base (never on stale async completion)
1078
- clipCandidates = null; clipLevels = null; // …and the clip-draw snap cache, synchronously here too (not only in buildFromScene): every edit/undo/redo funnels through rebuild(), so a draw in progress can't snap against pre-edit candidates during the async fetchScene window
1247
+ clipCandidates = null; clipLevels = null; scaleIdx = null; // …and the clip-draw snap cache, synchronously here too (not only in buildFromScene): every edit/undo/redo funnels through rebuild(), so a draw in progress can't snap against pre-edit candidates during the async fetchScene window
1079
1248
  if (marker && clipMode === 'box') marker.visible = false; // a model change under an armed box draw invalidates the reticle position — drop it (the next hover re-snaps)
1080
1249
  if (fit) fitPending = true; // entering 3D re-fits; an edit-triggered rebuild keeps the camera put
1081
1250
  const seq = ++rebuildSeq;
@@ -1102,6 +1271,70 @@ function setProjection(mode) {
1102
1271
  }
1103
1272
  function projection() { return camera === orthoCam ? 'ortho' : 'persp'; }
1104
1273
  function setDisplayMode(m) { displayMode = m; applyDisplayMode(); }
1274
+ // Realistic metal is nothing but reflections: against the editor's two-directional rig, with nothing
1275
+ // to reflect, metalness=1 renders BLACK. So Realistic generates an image-based light in the browser
1276
+ // (RoomEnvironment → PMREM, both from the vendored three — no CDN, still offline) and switches on
1277
+ // filmic tone mapping. Generated once and cached; cleared with the mode so Solid/Wire/X-ray look
1278
+ // exactly as they always did.
1279
+ //
1280
+ // Returns whether the environment is LIVE. If PMREM fails we must NOT go on to apply metalness=1 —
1281
+ // with nothing to reflect that renders every metal element black, far worse than not switching.
1282
+ let envRT = null, envFailed = false;
1283
+ // Shadows are a VARIANT of Realistic, not an orthogonal toggle: they need its environment and solid
1284
+ // surfaces to mean anything, and they cost real frame time — so `shadowed` is its own mode and plain
1285
+ // `realistic` stays the cheap default. Tracked so shadowMap.enabled flips only when the value really
1286
+ // changes: it alters the shader defines, so every material recompiles on each flip.
1287
+ // Materials keep their OWN reference to the clip planes for the shadow pass, since renderer-global
1288
+ // ones are cleared there. The clip code REPLACES that array rather than mutating it, so the reference
1289
+ // must be re-pointed on every clip change — a stale one leaves the model visibly clipped after the
1290
+ // clip was cleared, and the shadow pass cutting against the previous set after a new one.
1291
+ function syncClipMirror() {
1292
+ const gp = renderer.clippingPlanes;
1293
+ const use = (shadowsEnabled && gp && gp.length) ? gp : null;
1294
+ for (const m of meshById.values()) if (m.material) m.material.clippingPlanes = use;
1295
+ }
1296
+ function syncShadows(want) {
1297
+ // Applied every pass, not just on change: a rebuild makes fresh lights, which would otherwise keep
1298
+ // the default castShadow=false while the flag still said true — so the first switch into `shadowed`
1299
+ // after any edit would report shadows on and render none.
1300
+ if (lightKey) lightKey.castShadow = want;
1301
+ if (shadowGround) shadowGround.visible = want;
1302
+ if (shadowsEnabled === want) return;
1303
+ // Only the recompile is gated: changing shadowMap.enabled alters the shader defines.
1304
+ shadowsEnabled = want;
1305
+ renderer.shadowMap.enabled = want;
1306
+ for (const m of meshById.values()) if (m.material) m.material.needsUpdate = true;
1307
+ }
1308
+ function setEnvironment(on) {
1309
+ if (on && !envRT && !envFailed) {
1310
+ try {
1311
+ const pmrem = new THREE.PMREMGenerator(renderer);
1312
+ const room = new RoomEnvironment();
1313
+ // RoomEnvironment is authored Y-up (ceiling and key light along +Y) but this scene is Z-up, so
1314
+ // baking it unrotated lights the model from the side and gives reflections that disagree with
1315
+ // the geometry. Rotate it into the scene's frame before the PMREM bake.
1316
+ room.rotation.x = Math.PI / 2;
1317
+ envRT = pmrem.fromScene(room, 0.04);
1318
+ pmrem.dispose();
1319
+ } catch (err) { envFailed = true; console.warn('Realistic materials unavailable:', err); }
1320
+ }
1321
+ const live = on && !!envRT;
1322
+ scene.environment = live ? envRT.texture : null;
1323
+ // An environment map IS a light source. The analytic rig above was tuned for a scene with NO
1324
+ // environment, so leaving it at full strength while the env is on lights everything about twice
1325
+ // over — which is why mid-grey paint was clipping to white and concrete looked washed out. The
1326
+ // ambient goes nearly to zero (the env supplies omnidirectional light, and far better, since it
1327
+ // has direction and therefore shows form) and the directionals drop to a shaping role.
1328
+ if (lightAmb) lightAmb.intensity = live ? 0.06 : 0.65;
1329
+ if (lightKey) lightKey.intensity = live ? 0.40 : 0.85;
1330
+ if (lightFill) lightFill.intensity = live ? 0.10 : 0.25;
1331
+ // Brightness of the reflection is lifted PER MATERIAL via envMapIntensity (see applyDisplayMode),
1332
+ // not via scene.environmentIntensity: that property only exists in three r163+, and AWARE's viewer
1333
+ // pins r160, so scene-level lifting could not be ported to the shared read-only viewer.
1334
+ renderer.toneMapping = live ? THREE.ACESFilmicToneMapping : THREE.NoToneMapping;
1335
+ renderer.toneMappingExposure = live ? 1.15 : 1;
1336
+ return live;
1337
+ }
1105
1338
  // Wireframe mode uses per-mesh THREE.EdgesGeometry outlines instead of mat.wireframe: the latter draws
1106
1339
  // every triangulation edge, so each beam face shows a spurious diagonal "internal line" (F2). An
1107
1340
  // EdgesGeometry with a threshold angle keeps only edges where adjacent faces diverge past the threshold —
@@ -1133,18 +1366,53 @@ function clearWireEdges() {
1133
1366
  // whatever material each mesh currently carries (shared profile material OR its selection clone).
1134
1367
  function applyDisplayMode() {
1135
1368
  const wire = displayMode === 'wire', live = new Set();
1369
+ // Gate the PBR pass on the environment being LIVE, not merely on the mode being selected.
1370
+ // Both realistic modes get the environment and the material table; only `shadowed` also casts.
1371
+ const realistic = setEnvironment(displayMode === 'realistic' || displayMode === 'shadowed');
1372
+ syncShadows(realistic && displayMode === 'shadowed');
1136
1373
  for (const [id, mesh] of meshById) {
1137
1374
  const mat = mesh.material; if (!mat) continue;
1138
1375
  if (String(id).startsWith('det:')) continue; // placed details (Slice 4) own their transparency + opacity — display mode must not override them
1139
1376
  live.add(id);
1377
+ // Reset the surface on EVERY pass so a mode switch is symmetric — leaving Realistic must restore
1378
+ // the flat shading exactly, not strand the last family's metalness on a shared material.
1379
+ const u = mat.userData || {};
1380
+ const real = realistic ? (MATERIALS[u.family] || MATERIALS.painted) : null;
1381
+ if (u.baseMetal != null) mat.metalness = real ? real.metalness : u.baseMetal;
1382
+ // A metal has NO diffuse term — the environment is its entire brightness — and RoomEnvironment is
1383
+ // a dim little box, so an unlifted metalness=1 surface reads darker than the matte paint beside
1384
+ // it. Lift the metals; leave the dielectrics (concrete, timber, paint) alone or they blow out.
1385
+ mat.envMapIntensity = real ? (1 + real.metalness * 1.6) : 1;
1386
+ // Surface detail (aggregate, grain, spangle) only in Realistic — Solid/Wire/X-ray stay flat, which
1387
+ // is what makes them readable as working views. Binding/clearing a map changes the shader's
1388
+ // defines, so needsUpdate below is load-bearing, not decorative.
1389
+ const tex = real ? surfaceFor(u.family) : null;
1390
+ // With a map bound the roughness is ENTIRELY in the texture (absolute values), so the scalar must
1391
+ // be 1 or three multiplies it in twice. Without one, fall back to the declared/base scalar.
1392
+ if (u.baseRough != null) mat.roughness = tex ? 1 : (real ? real.roughness : u.baseRough);
1393
+ const wantMap = tex ? tex.map : null;
1394
+ if (mat.map !== wantMap) { mat.map = wantMap; mat.roughnessMap = tex ? tex.roughnessMap : null; mat.needsUpdate = true; }
1395
+ // Safe on the selection/hover CLONES too: they glow via `emissive`, never `.color`, and carry the
1396
+ // same userData — so the family colour applies to a selected member exactly as to a shared one.
1397
+ // `.set` NOT `.setHex`: `.set` is the one form that is also correct if a colour ever arrives as a
1398
+ // CSS string, which is how scene group colours come in.
1399
+ if (u.baseHex != null) mat.color.set(real && real.color != null ? real.color : u.baseHex);
1140
1400
  if (wire) { mat.wireframe = false; mat.transparent = false; mat.opacity = 1; mat.depthWrite = true; mat.visible = false; wireEdgesFor(id, mesh).visible = true; } // hide the solid fill; the outline carries the shape
1141
1401
  else {
1142
1402
  mat.visible = true; const ls = wireEdges.get(id); if (ls) ls.visible = false;
1143
1403
  if (displayMode === 'xray') { mat.wireframe = false; mat.transparent = true; mat.opacity = 0.25; mat.depthWrite = false; }
1144
- else { mat.wireframe = false; mat.transparent = false; mat.opacity = 1; mat.depthWrite = true; }
1404
+ else {
1405
+ const op = real && real.opacity != null ? real.opacity : 1;
1406
+ mat.wireframe = false; mat.opacity = op; mat.transparent = op < 1; mat.depthWrite = op >= 1;
1407
+ }
1145
1408
  }
1409
+ // Decided HERE rather than at build time: it depends on the opacity this pass just set, and
1410
+ // three's shadow depth material has no notion of ordinary transparency, so a translucent element
1411
+ // would otherwise cast as solidly as steel.
1412
+ mesh.castShadow = shadowsEnabled && mat.opacity >= 0.95;
1146
1413
  mat.needsUpdate = true;
1147
1414
  }
1415
+ syncClipMirror(); // shadows just turned on or off — the mirror follows
1148
1416
  for (const [id, ls] of wireEdges) if (!live.has(id) || ls.parent !== meshById.get(id)) { if (ls.parent) ls.parent.remove(ls); if (ls.geometry) ls.geometry.dispose(); wireEdges.delete(id); } // prune outlines whose mesh is gone OR was rebuilt under the same id (wireEdgesFor rebuilds on next Wire entry)
1149
1417
  }
1150
1418
  // A work area in "show whole parts" mode acts as a spatial filter: a part whose world AABB touches the box shows
@@ -1231,6 +1499,7 @@ function applyClips() {
1231
1499
  const active = clips.filter((c) => c.enabled).flatMap((c) => c.planes);
1232
1500
  if (workArea && workArea.enabled && !workArea.whole) active.push(...workArea.planes); // the work area sections the view too — unless it's in "show whole parts" mode (parts are hidden/shown whole via applyGroupVisibility, never sliced)
1233
1501
  renderer.clippingPlanes = active.length ? active : EMPTY_CLIPS;
1502
+ syncClipMirror(); // materials hold their own reference for the shadow pass — re-point it
1234
1503
  }
1235
1504
  // 6 inward planes (keep INSIDE) for an axis-aligned Box3 → a section/clip box.
1236
1505
  function boxToPlanes(b) {
@@ -1244,6 +1513,7 @@ function rebuildClipPlanes(c) { // recompute a clip's .planes from its ed
1244
1513
  c.planes = c.kind === 'box' ? boxToPlanes(c.box) : [new THREE.Plane().setFromNormalAndCoplanarPoint(c.n, c.point)];
1245
1514
  }
1246
1515
  function setClipMode(m) { // arm/disarm a clip pick: 'plane' (click a face) | 'box' (draw 2 corners) | null
1516
+ if (m) dropGridLinePick3d();
1247
1517
  if (m && dimMode3d) toggleDimTool();
1248
1518
  if (m) { if (api && api.disarmTransform) api.disarmTransform(); if (api && api.disarmAdd) api.disarmAdd(); cmClear3d(); drClear3d(); disarmFrame3d(); } // clip shares the left-click — disarm Move/Copy + Add + the local frame so their picks don't steal it (onDown routes them first)
1249
1519
  clipMode = (m === 'plane' || m === 'box') ? m : null;
@@ -1490,7 +1760,7 @@ function clipBoxFrom(a, b, zlo, ztop) {
1490
1760
  // the cache on every arm/disarm. A malformed member/grid degrades to no snap (raw floor), never a broken tool.
1491
1761
  let clipCandidates = null, clipLevels = null;
1492
1762
  function clipBoxSnapCands() { if (!clipCandidates) { try { clipCandidates = allCandidates(null); } catch { clipCandidates = []; } } return clipCandidates; }
1493
- function clipBoxLevels() { if (!clipLevels) { try { clipLevels = elevationLevels(members(), api.ptPerFt(), api.defaultTosMm(), null); } catch { clipLevels = []; } } return clipLevels; }
1763
+ function clipBoxLevels() { if (!clipLevels) { try { clipLevels = elevationLevelsByPlan(planList(), activeScale(), null); } catch { clipLevels = []; } } return clipLevels; } // model-wide: the clip box spans every sheet, so it must be able to snap to an off-sheet endpoint
1494
1764
  // A footprint corner from the cursor: the floor point under it, PULLED to a member/grid/UCS snap when one is
1495
1765
  // screen-near — same candidates + running-snaps filter as the Dimension / Move tools. Returns { xy:[x,y], snap,
1496
1766
  // world } or null (ray parallel to the floor). We keep only the snap's X/Y (the corner rides the floor plane).
@@ -1688,6 +1958,13 @@ const VIEW_KEYS = { t: 'top', f: 'front', r: 'right', b: 'back', l: 'left' };
1688
1958
  function onKey(e) {
1689
1959
  if (!renderer || !canvasEl || canvasEl.style.display === 'none') return; // only when 3D is active
1690
1960
  const ae = document.activeElement; if (ae && /^(INPUT|SELECT|TEXTAREA)$/.test(ae.tagName)) return;
1961
+ // Esc mid-drag-out → nothing is sent, even if the pointer is then released over Tekla: ending the
1962
+ // gesture here leaves the release with no drag to complete. (A native HTML5 drag never delivered
1963
+ // this key to the page at all, so Esc could only ever cancel by accident of where you let go.)
1964
+ // Any ARMED drag-out, not just a travelling one: before the movement threshold the gesture is still
1965
+ // loaded, and cancelling only the active case left it armed to fire on the next few pixels of a
1966
+ // press the user had already abandoned.
1967
+ if (teklaDrag && e.key === 'Escape') { e.preventDefault(); endTeklaDrag(); pending = dragging = null; if (controls) controls.enabled = true; return; }
1691
1968
  if (pending && pending.clipDrag && e.key === 'Escape') { e.preventDefault(); const p = pending; if (p.plane) p.clip.point = p.prePoint; else p.clip.box.copy(p.preBox); rebuildClipPlanes(p.clip); applyClips(); renderClipGizmo(); pending = dragging = null; if (controls) controls.enabled = true; if (readout) readout.style.display = 'none'; return; } // Esc mid-drag → undo the handle move
1692
1969
  if (framePicking() && e.key === 'Escape') { e.preventDefault(); if (frame3d) { cancelFramePick(); fireFrameChange(); } else armFrame3d(false); return; } // Esc cancels the whole 3-click pick (discards partial clicks); no prior frame → also exit the tool
1693
1970
  if (pending && pending.frameDrag && e.key === 'Escape') { e.preventDefault(); if (frame3d && pending.preFrame) frame3d = cloneFrame(pending.preFrame); pending = dragging = null; if (controls) controls.enabled = true; if (readout) readout.style.display = 'none'; fireFrameChange(); return; } // Esc mid-drag → revert the frame to its pre-drag basis
@@ -1702,6 +1979,10 @@ function onKey(e) {
1702
1979
  if (wasEp) rebuildEndpoints(); // restore the dragged endpoint dot to its original spot
1703
1980
  return;
1704
1981
  }
1982
+ // No Escape branch for gridLinePick3d on purpose: the EDITOR owns Esc for this tool. Its window keydown is bound at
1983
+ // parse time, ours inside init(), so the editor's always runs first and cancels the pick while leaving grid mode open.
1984
+ // Cancelling here first would make its handler fall through to setGridMode(false) and close the panel too — one Esc
1985
+ // doing two things.
1705
1986
  if (wpMode && e.key === 'Escape') { e.preventDefault(); if (wpMode === '3pt' && wpDraft && wpDraft.length) { wpDraft.pop(); updateStatusChip(); } else { wpMode = null; wpDraft = null; marker.visible = false; canvasEl.style.cursor = 'default'; reflectWpBar(); updateStatusChip(); } return; } // Esc steps a 3pt pick back, else disarms the set-plane mode
1706
1987
  if (insertMode && e.key === 'Escape') { e.preventDefault(); setInsertMode(false); if (api && api.toast) api.toast('Insert cancelled'); return; } // Esc disarms the detail-placement pick
1707
1988
  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
@@ -1728,12 +2009,34 @@ function onKey(e) {
1728
2009
  }
1729
2010
  // ---- 3D dimension tool controls (driven from the toolbar + the keyboard) ----
1730
2011
  function toggleDimTool() {
2012
+ if (!dimMode3d) dropGridLinePick3d(); // arming the dim tool takes the left-click — cancel an armed grid-line pick through the editor first
1731
2013
  dimMode3d = !dimMode3d;
1732
2014
  if (!dimMode3d) { dimDraft3d = null; dimCandidates3d = null; dimPreviewLine.visible = false; marker.visible = false; readout.style.display = 'none'; canvasEl.style.cursor = 'default'; setSnapOnly3d(null); } // disarming ends the operation → the snap override reverts to all snaps
1733
2015
  else { if (clipMode) setClipMode(null); if (wpMode) armWorkPlanePick(wpMode); if (api && api.disarmTransform) api.disarmTransform(); if (api && api.disarmAdd) api.disarmAdd(); drClear3d(); disarmFrame3d(); controls.enabled = true; canvasEl.style.cursor = 'crosshair'; } // arming the dim tool disarms the clip pick, a set-plane pick, Move/Copy, Add-member AND the local frame (all share the left-click + Esc)
1734
2016
  reflectDimBar();
1735
2017
  return dimMode3d;
1736
2018
  }
2019
+ // Arm/disarm the grid panel's "Add single line" pick for the 3D view. The early-out keeps re-arming a no-op:
2020
+ // every path that arms this pick starts from a fresh {a:null}, so a redundant arm can never wipe a half-finished one.
2021
+ function armGridLinePick3d(on) {
2022
+ on = !!on;
2023
+ if (on === !!gridLinePick3d) return on;
2024
+ // Disarm the conflicting tools BEFORE raising our own flag — each call below takes the DISARM direction, where their
2025
+ // own dropGridLinePick3d() guard is skipped, so this cannot cancel the very pick being armed.
2026
+ // basePickCol and insertMode matter as much as the rest: onDown routes both AHEAD of this pick, so leaving either
2027
+ // armed would make every click place a detail / do the base pick while the hint still reads "Pick the first point"
2028
+ // — the exact dead-control failure this change exists to fix.
2029
+ if (on) { if (dimMode3d) toggleDimTool(); if (clipMode) setClipMode(null); setInsertMode(false); setBasePickMode(null); if (wpMode) armWorkPlanePick(wpMode); if (api && api.disarmTransform) api.disarmTransform(); if (api && api.disarmAdd) api.disarmAdd(); drClear3d(); disarmFrame3d(); }
2030
+ gridLinePick3d = on ? { a: null } : null;
2031
+ if (!gridLinePick3d) { if (dimPreviewLine) dimPreviewLine.visible = false; if (marker) marker.visible = false; if (readout) readout.style.display = 'none'; if (canvasEl) canvasEl.style.cursor = 'default'; }
2032
+ else { if (controls) controls.enabled = true; if (canvasEl) canvasEl.style.cursor = 'crosshair'; }
2033
+ updateStatusChip();
2034
+ return on;
2035
+ }
2036
+ // The reverse of the exclusivity above: another 3D tool taking the left-click must cancel an armed grid-line pick
2037
+ // THROUGH the editor, so the panel hint and the button's armed state can't be left claiming a pick that no longer owns
2038
+ // the canvas. Falls back to a local disarm if the host wired no callback, so the pick can never survive the handover.
2039
+ function dropGridLinePick3d() { if (!gridLinePick3d) return; if (api && api.onGridLinePickCancel) api.onGridLinePickCancel(); else armGridLinePick3d(false); }
1737
2040
  // snap override setter — notifies the host page so its header chip stays in sync with every clear path
1738
2041
  function setSnapOnly3d(k) { snapOnly3d = k || null; if (api && api.onSnapOnlyChanged) api.onSnapOnlyChanged(); }
1739
2042
  // X/Y/Z each TOGGLE the measure axis in the lock set (press again to release; combine 2–3 → the dim measures along
@@ -1826,7 +2129,7 @@ function setSelection(ids) {
1826
2129
  if (String(id).startsWith('det:')) { if (mesh.material && mesh.material.color) mesh.material.color.setHex(on ? 0x93c5fd : 0xffffff); continue; }
1827
2130
  // Selected → a per-mesh clone that glows (so one selected member doesn't tint its whole profile
1828
2131
  // group). Deselected → back to the SHARED profile material (its real colour).
1829
- mesh.material = on ? selectedMaterial(mesh) : materialFor(mesh.userData.group);
2132
+ mesh.material = on ? selectedMaterial(mesh) : materialFor(mesh.userData.group, mesh.userData.family, mesh.userData.axis);
1830
2133
  mesh.material.emissive = new THREE.Color(on ? SELECT_EMISSIVE : 0x000000);
1831
2134
  mesh.material.emissiveIntensity = on ? 0.6 : 0;
1832
2135
  }
@@ -1839,15 +2142,24 @@ function setSelection(ids) {
1839
2142
  updateStatusChip();
1840
2143
  }
1841
2144
  let selIds = new Set();
2145
+ // Material.clone() copies parameters but NOT instance-assigned callbacks, so a cloned highlight
2146
+ // material loses the triplanar patch and falls back to three's stock UV sampling — the highlighted
2147
+ // member's texture stretches and smears for as long as it stays selected or hovered.
2148
+ function highlightClone(mesh) {
2149
+ const c = materialFor(mesh.userData.group, mesh.userData.family, mesh.userData.axis).clone();
2150
+ const tile = TILE_MM[mesh.userData.family];
2151
+ if (tile) applyTriplanar(c, tile, DIRECTIONAL.has(mesh.userData.family) ? mesh.userData.axis : null);
2152
+ return c;
2153
+ }
1842
2154
  function selectedMaterial(mesh) {
1843
- if (!mesh.userData._selMat) mesh.userData._selMat = materialFor(mesh.userData.group).clone();
2155
+ if (!mesh.userData._selMat) mesh.userData._selMat = highlightClone(mesh);
1844
2156
  return mesh.userData._selMat;
1845
2157
  }
1846
2158
  // ---- sky hover glow (replaces the on-hover endpoint dots) ----
1847
2159
  // A per-mesh clone so glowing one member doesn't tint its whole profile group (same trick as
1848
2160
  // selection). Selection always wins: a selected member keeps its blue glow and is left untouched.
1849
2161
  function hoverMaterial(mesh) {
1850
- if (!mesh.userData._hovMat) mesh.userData._hovMat = materialFor(mesh.userData.group).clone();
2162
+ if (!mesh.userData._hovMat) mesh.userData._hovMat = highlightClone(mesh);
1851
2163
  return mesh.userData._hovMat;
1852
2164
  }
1853
2165
  function setHoverGlow(id, on, sync = true) {
@@ -1855,7 +2167,7 @@ function setHoverGlow(id, on, sync = true) {
1855
2167
  const mesh = meshById.get(id);
1856
2168
  if (!mesh || String(id).startsWith('det:')) return; // placed details use a texture, no emissive to glow
1857
2169
  if (selIds.has(id)) return; // selected beats hovered — don't disturb its blue glow
1858
- mesh.material = on ? hoverMaterial(mesh) : materialFor(mesh.userData.group);
2170
+ mesh.material = on ? hoverMaterial(mesh) : materialFor(mesh.userData.group, mesh.userData.family, mesh.userData.axis);
1859
2171
  mesh.material.emissive = new THREE.Color(on ? HOVER_EMISSIVE : 0x000000);
1860
2172
  mesh.material.emissiveIntensity = on ? HOVER_INTENSITY : 0;
1861
2173
  if (sync) applyDisplayMode(); // ALWAYS re-sync after a material swap (mirrors setSelection): the swapped-in clone may have been cloned in another mode, and on clear the restored shared material can itself be stale — for a sole-profile member it stays detached while its mesh wears _hovMat, so applyDisplayMode never updated it. emissive is preserved (applyDisplayMode never touches it). sync=false lets a whole-connection glow batch ONE applyDisplayMode() after the loop instead of an O(meshes) sweep per part.
@@ -1893,7 +2205,7 @@ function rebuildEndpoints() {
1893
2205
  for (const id of show) {
1894
2206
  const mesh = meshById.get(id); if (mesh && !mesh.visible) continue; // a legend-hidden member shows no dots
1895
2207
  const m = memberById(id); if (!m) continue;
1896
- const g = memberGeometry(m, api.ptPerFt(), api.defaultTosMm());
2208
+ const g = geoOf(m);
1897
2209
  addEndpoint(g.line[0], epMatStart, id, 0); addEndpoint(g.line[1], epMatEnd, id, 1);
1898
2210
  }
1899
2211
  }
@@ -2475,13 +2787,27 @@ const members = () => (api && api.getMembers && api.getMembers()) || [];
2475
2787
  // Resolve a member by id MODEL-WIDE (every sheet), not just the active plane: the 3D shows all sheets,
2476
2788
  // so a pick / drag / hover / endpoint-handle can target a member on any plane. Falls back to the active
2477
2789
  // list if the host doesn't expose allMembers.
2478
- // ponytail: geometry + drag/endpoint commits here still use the ACTIVE plane's ppf/dtos (api.ptPerFt/
2479
- // defaultTosMm) — the whole 3D interaction layer (snap, grid, geometry) is built on one active scale.
2480
- // That is EXACT when the set has a uniform ppf, which real reads guarantee (same assumption membersInRect
2481
- // documents). Editing an off-active-sheet member whose sheet has a DIFFERENT ppf would mis-scale the
2482
- // commit. Upgrade path if sheets ever differ: expose api.ptPerFtFor(id)/defaultTosMmFor(id) and thread the
2483
- // per-member scale through the drag-start capture + memberGeometry/planPointToWp commit sites.
2484
2790
  const memberById = (id) => { const all = (api && api.allMembers && api.allMembers()) || members(); return all.find((x) => x.id === id); };
2791
+ // Drag/endpoint grabs resolve the scale of the sheet that OWNS the grabbed member, from the same
2792
+ // per-plan list that builds the snap candidates (allCandidates → membersByPlan). Previously both used
2793
+ // the ACTIVE plane's ppf/dtos, so editing an off-active-sheet member whose sheet has a different
2794
+ // pt_per_ft inverted the commit through the wrong scale and wrote a mis-scaled wp — while the target it
2795
+ // snapped to had been computed in the target sheet's own scale. One source ⇒ they cannot disagree.
2796
+ const activeScale = () => ({ ptPerFt: api.ptPerFt(), defaultTosMm: api.defaultTosMm() });
2797
+ const planList = () => { try { return (api.membersByPlan && api.membersByPlan()) || []; } catch { return []; } };
2798
+ // id → owning plan's scale, built ONCE per scene rebuild. Resolving per call scanned every plan's
2799
+ // members (and re-allocated the membersByPlan wrapper array), turning the model-wide per-member loops
2800
+ // — labels, endpoints, reference lines, membersInRect — quadratic. Invalidated in buildFromScene
2801
+ // alongside the other scene caches; a member added since the last rebuild misses the index and falls
2802
+ // back to the active scale, which is where a newly-added member lives anyway.
2803
+ let scaleIdx = null;
2804
+ const scaleIndex = () => { if (!scaleIdx) { try { scaleIdx = planScaleIndex(planList(), activeScale()); } catch { return new Map(); } } return scaleIdx; }; // a transient failure returns an empty index WITHOUT caching it — caching one would silently downgrade every member to the active scale until the next rebuild
2805
+ const scaleFor = (m) => planScaleOf(scaleIndex(), m, activeScale()); // keyed by the member OBJECT — ids are only sheet-unique
2806
+ // A member's geometry in ITS OWN sheet's scale + default T.O.S — matching the server bake, which
2807
+ // resolves per-plan (contract-to-scene: per-plan pt_per_ft + `default_tos ?? 0`). Using the ACTIVE
2808
+ // sheet's default T.O.S here put every overlay (handles, labels, reference lines) for an off-sheet
2809
+ // member whose T.O.S is unset at the WRONG elevation, while its server-built mesh sat at the right one.
2810
+ const geoOf = (m) => memberGeometryInOwnPlan(m, scaleIndex(), activeScale());
2485
2811
  const geoMode = () => (api && api.geoMode && api.geoMode()) || null;
2486
2812
 
2487
2813
  // ---- working plane (spec §6): session view-state grounding ALL 3D picks. null = the active plan's
@@ -2589,6 +2915,7 @@ function setFrameOrigin(originMm) {
2589
2915
  function clearFrame3d() { const had = !!frame3d || frameMode; cancelFramePick(); frame3d = null; frameMode = false; if (had) fireFrameChange(); }
2590
2916
  function armFrame3d(on) { // arm/disarm the tool; arming disarms conflicting tools
2591
2917
  frameMode = on == null ? !frameMode : !!on;
2918
+ if (frameMode) dropGridLinePick3d();
2592
2919
  if (frameMode) {
2593
2920
  if (dimMode3d) toggleDimTool(); if (api && api.disarmTransform) api.disarmTransform(); if (api && api.disarmAdd) api.disarmAdd(); cmClear3d(); drClear3d(); if (wpMode) { wpMode = null; wpDraft = null; reflectWpBar(); } setClipMode(null); setInsertMode(false); // arming the frame disarms EVERY other left-click 3D tool (incl. clip + insert)
2594
2921
  framePickPts = frame3d ? null : []; // no frame yet → start the 3-click pick; an existing frame → straight to drag-refine (re-pick from the panel)
@@ -2821,7 +3148,7 @@ function renderWorkPlane() {
2821
3148
  function reflectWpBar() { const b = document.getElementById('m3dWp'); if (b) { b.classList.toggle('on', !!wpMode || !!workPlane);
2822
3149
  const kind = workPlane && workPlane.kind ? { face: 'Face', p3: '3pt', xy: 'XY', xz: 'XZ', yz: 'YZ' }[workPlane.kind] || '' : '';
2823
3150
  b.textContent = wpMode ? '◇ Plane ✕' : (kind ? '◇ Plane: ' + kind + ' ▾' : '◇ Plane ▾'); } reflectDimAxisBar(); } // the label reads the active plane without opening the menu (ux review); relabel the dim-axis bar (a set/cleared plane flips X/Y between World and local)
2824
- function armWorkPlanePick(mode) { if (wpMode === mode) { wpMode = null; wpDraft = null; } else { wpMode = mode; wpDraft = null; if (dimMode3d) toggleDimTool(); if (api && api.disarmTransform) api.disarmTransform(); if (api && api.disarmAdd) api.disarmAdd(); cmClear3d(); drClear3d(); disarmFrame3d(); } marker.visible = false; canvasEl.style.cursor = wpMode ? 'crosshair' : 'default'; reflectWpBar(); } // a set-plane pick shares the left-click — disarm Move/Copy + Add + the local frame (their onDown routes run first)
3151
+ function armWorkPlanePick(mode) { if (wpMode === mode) { wpMode = null; wpDraft = null; } else { wpMode = mode; wpDraft = null; dropGridLinePick3d(); if (dimMode3d) toggleDimTool(); if (api && api.disarmTransform) api.disarmTransform(); if (api && api.disarmAdd) api.disarmAdd(); cmClear3d(); drClear3d(); disarmFrame3d(); } marker.visible = false; canvasEl.style.cursor = wpMode ? 'crosshair' : 'default'; reflectWpBar(); } // a set-plane pick shares the left-click — disarm Move/Copy + Add + the local frame (their onDown routes run first)
2825
3152
  function setWorkPlanePrincipal(kind, offsetMm) {
2826
3153
  const off = offsetMm || 0;
2827
3154
  const def = { xy: { normal: [0, 0, 1], xAxis: [1, 0, 0] }, xz: { normal: [0, 1, 0], xAxis: [1, 0, 0] }, yz: { normal: [1, 0, 0], xAxis: [0, 1, 0] } }[kind];
@@ -3206,7 +3533,7 @@ function dimPointAt(e, anchor) {
3206
3533
  }
3207
3534
  let id = null; try { id = pickAt(e.clientX, e.clientY); } catch { id = null; }
3208
3535
  let planeZ = sceneBox.isEmpty() ? 0 : sceneBox.min.z;
3209
- if (id) { const m = memberById(id); if (m) { const g = memberGeometry(m, api.ptPerFt(), api.defaultTosMm()); planeZ = (g.line[0][2] + g.line[1][2]) / 2; } }
3536
+ if (id) { const m = memberById(id); if (m) { const g = geoOf(m); planeZ = (g.line[0][2] + g.line[1][2]) / 2; } }
3210
3537
  const hit = rayToPlane(e.clientX, e.clientY, planeZ); if (!hit) return null;
3211
3538
  if (!dimCandidates3d) dimCandidates3d = allCandidates(null); // member + grid candidates (allCandidates folds in the grid)
3212
3539
  const cands = dimCandidates3d.filter((c) => candAllowed3d(c.type)); // right-click override (one type / free) + the persistent running-snaps from the ⋯ menu
@@ -3238,6 +3565,26 @@ function dimPointAt(e, anchor) {
3238
3565
  const win = rGrid && (!rMem || rGrid.d <= rMem.d) ? rGrid : rMem;
3239
3566
  return { p: win ? win.r.snapped : hit, type: win ? win.r.candidate.type : null };
3240
3567
  }
3568
+ // The point under the cursor for the grid-line pick. Reuses the dimension tool's snapped pick (member + grid
3569
+ // candidates, running-snaps applied) with NO anchor, so Alt never forces the dim tool's vertical branch — a grid
3570
+ // line is a plan entity and only its X/Y survive the commit.
3571
+ function gridLinePickPoint3d(e) { return dimPointAt({ clientX: e.clientX, clientY: e.clientY, altKey: false }, null); }
3572
+ // Rubber-band + readout while placing a grid line: plan length and bearing, matching what the 2D pick shows.
3573
+ function gridLineHoverPreview3d() {
3574
+ if (!lastHoverXY || !canvasEl || !dimPreviewLine) return;
3575
+ const r = gridLinePickPoint3d({ clientX: lastHoverXY[0], clientY: lastHoverXY[1] });
3576
+ const snapped = !!(r && r.type);
3577
+ if (snapped) showMarker(r.p, r.type); else marker.visible = false; // reticle only on a real snap — same rule as the dim tool
3578
+ canvasEl.style.cursor = snapped ? 'none' : 'crosshair';
3579
+ if (gridLinePick3d.a && r) {
3580
+ dimPreviewLine.geometry.setFromPoints([new THREE.Vector3(...gridLinePick3d.a), new THREE.Vector3(...r.p)]);
3581
+ dimPreviewLine.visible = true;
3582
+ const dx = r.p[0] - gridLinePick3d.a[0], dy = r.p[1] - gridLinePick3d.a[1], len = Math.hypot(dx, dy); // PLAN length (X/Y only) — the Z the pick landed on is discarded on commit
3583
+ readout._dist.textContent = api.fmtLen ? api.fmtLen(len) : (len / 304.8).toFixed(2) + ' ft';
3584
+ readout._type.textContent = ' · angle ' + Math.round(Math.atan2(-dy, dx) * 180 / Math.PI) + '°' + (r.type ? ' · ' + r.type : ''); // NEGATE dy: scene Y runs opposite plan-display Y (buildStructGrid: mmY = -px*k), so a raw atan2 would report the bearing mirrored against the 2D tool for the very same line. The k>0 scale cancels out of the ratio.
3585
+ readout.style.left = (lastHoverXY[0] + 14) + 'px'; readout.style.top = (lastHoverXY[1] + 14) + 'px'; readout.style.display = 'block';
3586
+ } else { dimPreviewLine.visible = false; if (r) roShowCoordOnly(r.p, lastHoverXY[0], lastHoverXY[1]); else readout.style.display = 'none'; }
3587
+ }
3241
3588
  // The axis to measure on: Alt held during the 2nd pick forces a pure-vertical (Z) measurement,
3242
3589
  // overriding the sticky axis (else a sticky X/Y would collapse the Alt-locked point to zero length).
3243
3590
  // The ONE axis a dimension measures along, resolving the lock set: Alt (held on the 2nd pick) forces vertical Z;
@@ -3284,11 +3631,20 @@ function onDown(e) {
3284
3631
  if (clipMode === 'box') { e.stopPropagation(); onClipBoxClick(e); return; } // armed: 2-corner clip-box draw on the floor plane
3285
3632
  if (framePicking()) { e.stopPropagation(); controls.enabled = true; framePickClick(e); return; } // 3-click UCS set: this click collects the origin / X point / Y point
3286
3633
  if (frameMode) { let fh = null; try { fh = pickFrameHandle(e.clientX, e.clientY); } catch { fh = null; } if (fh) { e.stopPropagation(); controls.enabled = false; startFrameDrag(fh, e); return; } } // grab the local-frame origin/ring (armed) → drag it; an empty click falls through (orbit)
3287
- if (frame3d && !frameMode && !geoMode() && !cmActive() && !addActive() && !dimMode3d && !clipMode && !wpMode && !basePickCol && !insertMode && !selectedClipIds.size) { // passive gizmo, no tool armed → clicking its origin/ring re-selects the local frame for editing (NOT reached by box-select or select-all, which only touch members)
3634
+ if (frame3d && !frameMode && !geoMode() && !cmActive() && !addActive() && !dimMode3d && !clipMode && !wpMode && !basePickCol && !insertMode && !gridLinePick3d && !selectedClipIds.size) { // passive gizmo, no tool armed → clicking its origin/ring re-selects the local frame for editing (NOT reached by box-select or select-all, which only touch members). gridLinePick3d belongs in this list like every other armed tool: the handle captures within ~16 px, so without it the frame ORIGIN — a snap target the grid pick advertises — could never be used as a grid endpoint; the click would re-arm the frame and cancel the pick instead.
3288
3635
  let fh = null; try { fh = pickFrameHandle(e.clientX, e.clientY, true); } catch { fh = null; }
3289
3636
  if (fh) { e.stopPropagation(); controls.enabled = false; armFrame3d(true); startFrameDrag(fh, e); return; } // re-arm the tool + grab the clicked handle so a click-drag manipulates immediately
3290
3637
  }
3291
- if (selectedClipIds.size) { let ch = null; try { ch = pickClipHandle(e.clientX, e.clientY); } catch { ch = null; } if (ch) { e.stopPropagation(); controls.enabled = false; downXY = [e.clientX, e.clientY]; startClipDrag(ch, e); return; } } // grab a clip handle (plane dot / box face) → drag it
3638
+ if (selectedClipIds.size && !gridLinePick3d) { let ch = null; try { ch = pickClipHandle(e.clientX, e.clientY); } catch { ch = null; } if (ch) { e.stopPropagation(); controls.enabled = false; downXY = [e.clientX, e.clientY]; startClipDrag(ch, e); return; } } // grab a clip handle (plane dot / box face) → drag it. Not while the grid pick is armed: a handle drag would start under an armed two-click tool, leaving the button + hint claiming a pick and the shared preview line stranded (onUp clears the marker/readout but not dimPreviewLine).
3639
+ if (gridLinePick3d) { // grid panel "Add single line": pick A, then B → the editor commits it (mirrors the 2D pick)
3640
+ e.stopPropagation(); controls.enabled = true;
3641
+ const r = gridLinePickPoint3d(e); if (!r) return;
3642
+ if (!gridLinePick3d.a) { gridLinePick3d.a = r.p; updateStatusChip(); if (api && api.onGridLinePickStep) api.onGridLinePickStep(); return; } // step BOTH readouts to "second point" — the canvas chip and the panel hint
3643
+ const a = gridLinePick3d.a;
3644
+ if (dimPreviewLine) dimPreviewLine.visible = false; if (marker) marker.visible = false; if (readout) readout.style.display = 'none';
3645
+ if (api && api.onAddGridLine3d) api.onAddGridLine3d(a, r.p); // the editor converts world mm → plan display px, commits + disarms; a rejected (too-short) line leaves the pick armed so the 2nd point can be retried, exactly as in 2D
3646
+ return;
3647
+ }
3292
3648
  if (dimMode3d) { // 2-click dimension placement (not a drag): pick A, then B → place
3293
3649
  e.stopPropagation(); controls.enabled = true;
3294
3650
  const r = dimPointAt(e, dimDraft3d && dimDraft3d.a); if (!r) return;
@@ -3309,27 +3665,124 @@ function onDown(e) {
3309
3665
  // An end node (the yellow/magenta dot) under the cursor → grab just that endpoint to stretch the member.
3310
3666
  let ep = null; try { ep = pickEndpoint(e.clientX, e.clientY); } catch { ep = null; }
3311
3667
  if (ep) { e.stopPropagation(); controls.enabled = false; startEndpointGrab(ep, e); return; }
3312
- let gridHit=null,allMeshHits=[];try{gridHit=pickGridAt(e.clientX,e.clientY);}catch(err){console.error('steel-3d: grid hit-test failed',err);}try{allMeshHits=meshHitsAt(e.clientX,e.clientY);}catch(err){console.error('steel-3d: mesh hit-test failed',err);}const gridAllowed=!api||!api.canSelectGrid||api.canSelectGrid(),gridOccluders=displayMode==='solid'?allMeshHits:[],meshDepth=gridOccluders.length?gridOccluders[0].point.clone().project(camera).z:Infinity,gridInFront=gridHit&&gridDepthWins(gridHit.depth,meshDepth);if(gridHit&&!gridAllowed&&gridInFront){e.stopPropagation();controls.enabled=false;pending={filteredGrid:true};return;} // Deliberately consume the LEFT select gesture like 2D when the visible grid is frontmost: a filtered grid stays inert and preserves selection. RIGHT-drag orbit is a separate handler.
3668
+ let gridHit=null,allMeshHits=[];try{gridHit=pickGridAt(e.clientX,e.clientY);}catch(err){console.error('steel-3d: grid hit-test failed',err);}try{allMeshHits=meshHitsAt(e.clientX,e.clientY);}catch(err){console.error('steel-3d: mesh hit-test failed',err);}const gridAllowed=!api||!api.canSelectGrid||api.canSelectGrid(),gridOccluders=OPAQUE_MODES.has(displayMode)?allMeshHits.filter(occludesGrid):[],meshDepth=gridOccluders.length?gridOccluders[0].point.clone().project(camera).z:Infinity,gridInFront=gridHit&&gridDepthWins(gridHit.depth,meshDepth);if(gridHit&&!gridAllowed&&gridInFront){e.stopPropagation();controls.enabled=false;pending={filteredGrid:true};return;} // Deliberately consume the LEFT select gesture like 2D when the visible grid is frontmost: a filtered grid stays inert and preserves selection. RIGHT-drag orbit is a separate handler.
3313
3669
  const gridWins=gridAllowed&&gridHit&&gridInFront;if(gridWins){e.stopPropagation();controls.enabled=false;pending={gridId:gridHit.id,add:e.ctrlKey||e.metaKey||e.shiftKey};return;} // Compare projected depth in Solid; Wire/X-ray fills do not write depth and therefore cannot phantom-occlude a visible grid.
3314
3670
  if (!id) { pending = null; boxSel = { x: e.clientX, y: e.clientY }; return; } // empty space → box-select on drag
3315
3671
  e.stopPropagation(); controls.enabled = false; // grabbed a member → suppress orbit (enabled=false is the reliable guard)
3316
3672
  try {
3317
3673
  const m = memberById(id);
3318
- const ppf = api.ptPerFt(), dtos = api.defaultTosMm();
3674
+ const { ptPerFt: ppf, defaultTosMm: dtos } = scaleFor(m); // the GRABBED member's sheet, not the active one
3319
3675
  const geo = m ? memberGeometry(m, ppf, dtos) : null;
3320
3676
  const mesh = meshById.get(id);
3321
3677
  const planeZ = geo ? (geo.line[0][2] + geo.line[1][2]) / 2 : 0;
3322
3678
  const ctrl = e.ctrlKey || e.metaKey, add = ctrl || e.shiftKey; // ctrl gates the copy gesture; ctrl OR shift toggles selection on a click (Tekla)
3679
+ // Ctrl+Shift on a member that is already selected arms the drag-out to Tekla. Claimed ahead of
3680
+ // the copy/ortho state below, because Ctrl+Shift+DRAG would otherwise mean copy-with-ortho-lock
3681
+ // (the one gesture this feature costs). Arming is not yet dragging: the gesture only becomes a
3682
+ // drag-out once the pointer travels (onMove), so a stationary Ctrl+Shift click still falls
3683
+ // through to the toggle-select it has always been, and `pending` is still built below so an
3684
+ // un-armed press behaves identically.
3685
+ if (ctrl && e.shiftKey && selIds.has(id) && api && api.teklaSelectionIds) {
3686
+ const ids = api.teklaSelectionIds();
3687
+ // `blocked` while a send is in flight: the gesture is still CLAIMED (so it cannot fall through
3688
+ // to the Ctrl-copy this modifier combination would otherwise mean, quietly duplicating members
3689
+ // in the draft), it simply never becomes a drag-out.
3690
+ if (ids.length) {
3691
+ teklaDrag = { ids, active: false, blocked: !!(api.teklaSendBusy && api.teklaSendBusy()) };
3692
+ // Capture the pointer so move/up keep arriving once the cursor is over Tekla — that stream is
3693
+ // the whole gesture. (A native HTML5 drag would carry an image over other windows, but the OS
3694
+ // then paints its own "no drop here" cursor the entire way, because Tekla never accepts the
3695
+ // data — it looks like a refusal while the send actually works.)
3696
+ try { canvasEl.setPointerCapture(e.pointerId); teklaDrag.pointerId = e.pointerId; } catch { /* capture is an optimisation; window-level listeners still fire */ }
3697
+ }
3698
+ }
3323
3699
  pending = {
3324
3700
  id, ctrl, add, ppf, planeZ,
3325
3701
  copy: ctrl, copyIds: ctrl ? (selIds.has(id) ? [...selIds] : [id]) : null, // Ctrl+drag copies: the selection if this member is in it, else just it
3326
3702
  grab: geo ? rayToPlane(e.clientX, e.clientY, planeZ) : null,
3327
3703
  origMm: geo ? geo.line.map((p) => [p[0], p[1], p[2]]) : null,
3328
3704
  candidates: allCandidates(ctrl ? undefined : id).filter((c) => candAllowed3d(c.type)), // member + grid snap targets (a ctrl-copy snaps to the ORIGINAL too; a move excludes itself), filtered by the running-snaps (⋯ menu → Snapping)
3329
- levels: elevationLevels(members(), ppf, dtos, id), // Alt-drag (vertical) snaps to these T.O.S levels
3705
+ levels: elevationLevelsByPlan(planList(), activeScale(), m), // Alt-drag snaps to T.O.S levels across EVERY sheet, each in its own default elevation (pairing the active sheet's members with the grabbed sheet's default reported unset-T.O.S members at an elevation they are not drawn at)
3330
3706
  mesh, meshPos0: mesh ? mesh.position.clone() : null, delta: null, mode: null,
3331
3707
  };
3332
- } catch (err) { controls.enabled = true; pending = null; } // a failure must never strand orbit disabled
3708
+ } catch (err) { controls.enabled = true; pending = null; endTeklaDrag(); } // a failure must never strand orbit disabled — nor an armed drag-out holding the pointer capture, which the next movement would fire
3709
+ }
3710
+
3711
+ // ── Ctrl+Shift drag-out: carry the selection to the Tekla window ───────────────────────────────
3712
+ // A web page cannot hand a payload to a native window, so "drop into Tekla" is the gesture, not the
3713
+ // transport: releasing outside our own window sends the selection, and the server bakes those members
3714
+ // into the open model at their REAL model coordinates (where the cursor was is not a place).
3715
+ //
3716
+ // This tracks the pointer itself rather than using a native HTML5 drag. A native drag can carry an
3717
+ // image over other windows, but the drop effect belongs to whatever is under the cursor — and Tekla
3718
+ // never accepts our data, so Windows paints the "no drop here" circle across the entire gesture and
3719
+ // over the release point. That reads as a refusal of an action that actually works. Pointer capture
3720
+ // keeps move/up flowing while the cursor is over Tekla, leaves the cursor alone, and makes Esc a real
3721
+ // cancel (during a native drag the page never sees the key).
3722
+
3723
+ /** The badge that follows the cursor while a drag-out is live (same recipe as the legend's drag ghost). */
3724
+ function teklaBadge(n) {
3725
+ const el = document.createElement('div');
3726
+ el.className = 'tekla-drag-ghost';
3727
+ el.innerHTML = '<svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true" focusable="false">'
3728
+ + '<path d="M9.5 2.5H13.5V6.5M13.5 2.5 8 8M11 9.5V12a1.5 1.5 0 0 1-1.5 1.5h-6A1.5 1.5 0 0 1 2 12V6a1.5 1.5 0 0 1 1.5-1.5H6"'
3729
+ + ' fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>';
3730
+ el.append(document.createTextNode(`${n} ${n === 1 ? 'member' : 'members'} → Tekla`));
3731
+ document.body.appendChild(el);
3732
+ return el;
3733
+ }
3734
+
3735
+ /**
3736
+ * Has the pointer left the BROWSER — i.e. is it over another application rather than over FloLess?
3737
+ *
3738
+ * Measured against the top-level browser window on screen, deliberately NOT against our own viewport:
3739
+ * this editor is loaded in the Workspaces shell's iframe, so its viewport ends where the shell's own
3740
+ * chrome begins. Releasing over that chrome is still inside FloLess, but an iframe-relative test would
3741
+ * call it "outside" and insert into the user's live model on a gesture they meant to abandon.
3742
+ *
3743
+ * What sits under the pointer out there is unknowable to a web page — releasing over the desktop sends
3744
+ * just as releasing over Tekla does. The status chip says "release over the Tekla window" for that
3745
+ * reason; leaving the browser IS the commit.
3746
+ */
3747
+ function pointerOutsideWindow(e) {
3748
+ try {
3749
+ const shell = window.top; // same-origin: the shell embeds us itself
3750
+ return e.screenX < shell.screenX || e.screenY < shell.screenY
3751
+ || e.screenX > shell.screenX + shell.outerWidth
3752
+ || e.screenY > shell.screenY + shell.outerHeight;
3753
+ } catch {
3754
+ return e.clientX < 0 || e.clientY < 0 || e.clientX > window.innerWidth || e.clientY > window.innerHeight;
3755
+ }
3756
+ }
3757
+
3758
+ /** Tear down a live drag-out: badge, capture, cursor. Shared by the release, Esc, and pointercancel. */
3759
+ function endTeklaDrag() {
3760
+ if (!teklaDrag) return;
3761
+ if (teklaDrag.badge) teklaDrag.badge.remove();
3762
+ if (teklaDrag.pointerId != null && canvasEl) {
3763
+ try { canvasEl.releasePointerCapture(teklaDrag.pointerId); } catch { /* already released with the pointer */ }
3764
+ }
3765
+ teklaDrag = null;
3766
+ if (canvasEl) canvasEl.style.cursor = 'default';
3767
+ updateStatusChip();
3768
+ }
3769
+
3770
+ /** The pointer moved far enough with the gesture armed: this is a drag-out, not a click. */
3771
+ function onTeklaDragMove(e) {
3772
+ if (teklaDrag.blocked) return; // a send is already running: hold the gesture inert rather than start a second
3773
+ if (!teklaDrag.active) {
3774
+ // Committing to the drag-out abandons the half-built move/copy, so the release can never also
3775
+ // land as a member move.
3776
+ teklaDrag.active = true;
3777
+ pending = dragging = null; boxSel = null; if (controls) controls.enabled = true;
3778
+ teklaDrag.badge = teklaBadge(teklaDrag.ids.length);
3779
+ updateStatusChip();
3780
+ }
3781
+ // The badge is ours to place; outside the window it simply clips away, and the status chip carries
3782
+ // the message from there.
3783
+ teklaDrag.badge.style.left = (e.clientX + 16) + 'px';
3784
+ teklaDrag.badge.style.top = (e.clientY + 14) + 'px';
3785
+ if (canvasEl) canvasEl.style.cursor = pointerOutsideWindow(e) ? 'default' : 'alias';
3333
3786
  }
3334
3787
 
3335
3788
  // Vertical (Alt) drag: raise/lower the member's elevation, snapping to other members' T.O.S levels.
@@ -3351,7 +3804,7 @@ function onMoveVertical(e) {
3351
3804
  function startEndpointGrab(ep, e) {
3352
3805
  try {
3353
3806
  const m = memberById(ep.id); if (!m) { controls.enabled = true; return; }
3354
- const ppf = api.ptPerFt(), dtos = api.defaultTosMm();
3807
+ const { ptPerFt: ppf, defaultTosMm: dtos } = scaleFor(m); // the GRABBED member's sheet, not the active one
3355
3808
  const g = memberGeometry(m, ppf, dtos);
3356
3809
  pending = {
3357
3810
  epDrag: true, id: ep.id, end: ep.end, ppf,
@@ -3390,6 +3843,12 @@ function onMoveEndpoint(e) {
3390
3843
  function onMove(e) {
3391
3844
  if (rightDownXY && Math.hypot(e.clientX - rightDownXY[0], e.clientY - rightDownXY[1]) > 5) rightMoved = true; // right-DRAG = orbit/pan, so no snap menu on the release
3392
3845
  if (!renderer || !canvasEl || canvasEl.style.display === 'none') return; // 3D inactive — ignore window pointer events
3846
+ // Ctrl+Shift drag-out armed: this pointer stream is the gesture, so the move/copy path stands down.
3847
+ // Below the drag tolerance nothing has happened yet — the press can still turn out to be a click.
3848
+ if (teklaDrag) {
3849
+ if (teklaDrag.active || (downXY && Math.hypot(e.clientX - downXY[0], e.clientY - downXY[1]) > DRAG_TOL_PX)) onTeklaDragMove(e);
3850
+ return;
3851
+ }
3393
3852
  if (boxSel) { onBoxMove(e); return; }
3394
3853
  if (pending && pending.clipDrag) { onMoveClip(e); return; } // dragging a clip handle (plane offset / box face)
3395
3854
  if (pending && pending.frameDrag) { onMoveFrame(e); return; } // dragging the local-frame origin / rotation ring
@@ -3476,19 +3935,18 @@ function memberFootprintHit(mesh, r, windowMode, rect) {
3476
3935
  function membersInRect(x0, y0, x1, y1, windowMode) {
3477
3936
  const rect = canvasEl.getBoundingClientRect();
3478
3937
  const r = [Math.min(x0, x1), Math.min(y0, y1), Math.max(x0, x1), Math.max(y0, y1)];
3479
- const ppf = api.ptPerFt(), dtos = api.defaultTosMm();
3480
3938
  // ALL sheets' members, not just the active one — the 3D shows every plan, so a box must be able to grab a
3481
3939
  // member on any floor (the meshes are server-positioned, so the primary footprint hit is correct across
3482
- // sheets; the client-recomputed a/b fallback uses the active ppf and may be off for a far sheet, but the
3483
- // footprint test catches those). Without this, an area-select only picks the active sheet — "selection
3484
- // depth doesn't match what I see."
3940
+ // sheets; the client-recomputed a/b fallback now resolves each member in its OWN sheet's scale via geoOf,
3941
+ // so it is no longer off for a far sheet). Without this, an area-select only picks the active sheet —
3942
+ // "selection depth doesn't match what I see."
3485
3943
  const memById = new Map(((api && api.allMembers && api.allMembers()) || members()).map((m) => [m.id, m]));
3486
3944
  const toScreen = (p) => { const w = new THREE.Vector3(p[0], p[1], p[2]).project(camera); return { s: [rect.left + (w.x * 0.5 + 0.5) * rect.width, rect.top + (-w.y * 0.5 + 0.5) * rect.height], behind: w.z > 1 }; };
3487
3945
  const out = [];
3488
3946
  for (const [id, m] of meshById) {
3489
3947
  if (!m.visible || m.userData.derived) continue; // derived connection parts aren't member-selectable (mirrors pickAt; dbl-click-zoom deliberately includes them)
3490
3948
  const mem = memById.get(id); if (!mem) continue;
3491
- let a, b; try { const g = memberGeometry(mem, ppf, dtos); a = toScreen(g.line[0]); b = toScreen(g.line[1]); } catch { continue; }
3949
+ let a, b; try { const g = geoOf(mem); a = toScreen(g.line[0]); b = toScreen(g.line[1]); } catch { continue; }
3492
3950
  if (memberFootprintHit(m, r, windowMode, rect)) { out.push(id); continue; } // select what the user boxed: the rendered solid, including high-level members and columns
3493
3951
  if (a.behind || b.behind) { // an endpoint is behind the camera → the projected segment is unreliable; fall back to the member-centre test (old behaviour, no regression for members straddling the camera plane)
3494
3952
  const w = m.getWorldPosition(new THREE.Vector3()).project(camera); if (w.z > 1) continue;
@@ -3530,7 +3988,23 @@ function connsInRect(x0, y0, x1, y1, windowMode) {
3530
3988
 
3531
3989
  function onUp(e) {
3532
3990
  if (e.button === 2) rightDownXY = null; // end the click-vs-drag test (rightMoved keeps the verdict for the contextmenu that follows)
3991
+ // A live drag-out ends here: released outside our window → send; anywhere inside → silently
3992
+ // nothing, which is the escape hatch. A press that never travelled was a click, so it falls
3993
+ // through and still toggles the member in the selection, exactly as it always has.
3994
+ let teklaSend = null;
3995
+ if (teklaDrag) {
3996
+ const drag = teklaDrag;
3997
+ endTeklaDrag();
3998
+ if (drag.active) {
3999
+ // Fall THROUGH to the shared overlay cleanup below rather than returning here — a snap marker
4000
+ // or readout left over from before the gesture would otherwise sit on the canvas until the next
4001
+ // hover. The send is deferred to just past that line for the same reason.
4002
+ pending = dragging = null; downXY = null; if (controls) controls.enabled = true;
4003
+ if (pointerOutsideWindow(e) && api && api.onSendToTekla) teklaSend = drag.ids;
4004
+ }
4005
+ }
3533
4006
  if (marker) marker.visible = false; if (readout) readout.style.display = 'none'; if (rubber) rubber.style.display = 'none'; if (epPreview) epPreview.visible = false; if (epMovedLine) epMovedLine.visible = false; clearCopyGhost(); dragEp = null; // always clear overlays
4007
+ if (teklaSend) { api.onSendToTekla(teklaSend); return; }
3534
4008
  if (!renderer || !canvasEl || canvasEl.style.display === 'none') { downXY = null; boxSel = pending = dragging = null; if (controls) controls.enabled = true; return; } // 3D hidden mid-gesture → drop stale gesture state (no resume on re-show)
3535
4009
  const bs = boxSel; boxSel = null;
3536
4010
  if (bs) { // empty-space gesture: drag = box-select, click = clear selection
@@ -3566,8 +4040,8 @@ function onUp(e) {
3566
4040
  if (p.geo === 'el') { if (p.targetId && !selIds.has(p.targetId) && api && api.onTrimExtend) api.onTrimExtend(p.targetId); return; } // target line ≠ a selected member; trims ALL selected
3567
4041
  if (p.geo === 'split') { // cut the selected member at the clicked point on its centreline
3568
4042
  const m = memberById(p.selId); if (!m) return;
3569
- const ppf = api.ptPerFt();
3570
- const g = memberGeometry(m, ppf, api.defaultTosMm());
4043
+ const { ptPerFt: ppf, defaultTosMm: dtos } = scaleFor(m); // the SPLIT member's sheet, not the active one
4044
+ const g = memberGeometry(m, ppf, dtos);
3571
4045
  const planeZ = (g.line[0][2] + g.line[1][2]) / 2;
3572
4046
  const hit = rayToPlane(e.clientX, e.clientY, planeZ); if (!hit) return;
3573
4047
  if (p.targetId !== p.selId) return; // the cut click must land on the selected member's body
@@ -3652,14 +4126,36 @@ function dimHoverPreview(alt) {
3652
4126
  if (r && !dimDraft3d) roShowCoordOnly(r.p, lastHoverXY[0], lastHoverXY[1]); // first dim point: coords-only chip
3653
4127
  else if (readout) readout.style.display = 'none'; } // no point (or a draft with the cursor off-plane) → clear the chip
3654
4128
  }
4129
+ /**
4130
+ * Ctrl/Shift went down or up — repaint the hover state from the KEYS.
4131
+ *
4132
+ * The drag-out's `alias` cursor is derived from the modifiers seen on the last pointer MOVE, so
4133
+ * letting go of Ctrl+Shift without moving the mouse left it on screen advertising a gesture that was
4134
+ * no longer armed. Replay the last hover position with the modifier state the key event carries.
4135
+ * (Independent QA caught this; the author's own pass always moved the mouse afterwards.)
4136
+ */
4137
+ function onModifierChange(e) {
4138
+ if (e.key !== 'Control' && e.key !== 'Shift' && e.key !== 'Meta') return;
4139
+ if (!lastHoverXY || pending || dragging || boxSel || teklaDrag) return; // mid-gesture the cursor belongs to that gesture
4140
+ // `lastHoverXY` outlives the pointer leaving the canvas, so without this a modifier pressed while
4141
+ // typing in the inspector would replay a stale canvas position and re-glow the member the cursor
4142
+ // left behind. Insert is the one armed tool with no hover-priority branch, so a replay would repaint
4143
+ // over its crosshair — leave it alone rather than widen a cursor bug that predates this handler.
4144
+ if (!pointerOverCanvas || insertMode) return;
4145
+ onHoverMove({ clientX: lastHoverXY[0], clientY: lastHoverXY[1], altKey: dimLastAlt, shiftKey: e.shiftKey, ctrlKey: e.ctrlKey, metaKey: e.metaKey });
4146
+ }
4147
+
3655
4148
  function onHoverMove(e) {
3656
4149
  lastHoverXY = [e.clientX, e.clientY];
3657
4150
  dimLastAlt = e.altKey; // remembered so the rAF body can rebuild a synthetic event
3658
4151
  tfLastShift = e.shiftKey; // same for the Move/Copy ortho lock
4152
+ hoverTeklaMod = (e.ctrlKey || e.metaKey) && e.shiftKey; // and for the drag-out-to-Tekla cursor hint below
3659
4153
  if (hoverRAF || pending || dragging || boxSel) return;
4154
+ if (teklaDrag && teklaDrag.active) return; // a live drag-out owns the cursor; hover would repaint it from what's under the pointer
3660
4155
  hoverRAF = requestAnimationFrame(() => {
3661
4156
  hoverRAF = 0;
3662
4157
  if (!lastHoverXY || pending || dragging || boxSel) return;
4158
+ if (gridLinePick3d) { gridLineHoverPreview3d(); return; } // armed grid-line pick owns the hover (rubber-band + snap reticle)
3663
4159
  if (basePickCol) { // Mode B armed: reticle on the column axis + a live elevation readout
3664
4160
  const p = basePickPoint(lastHoverXY[0], lastHoverXY[1]);
3665
4161
  if (p) {
@@ -3716,6 +4212,10 @@ function onHoverMove(e) {
3716
4212
  let top = null; try { top = pickAllAt(lastHoverXY[0], lastHoverXY[1])[0] || null; } catch { top = null; }
3717
4213
  const topMesh = top ? meshById.get(top) : null, isPart = !!(topMesh && topMesh.userData.derived);
3718
4214
  const canDrag = api && api.dragMoveEnabled && api.dragMoveEnabled();
4215
+ // Ctrl+Shift over a member already in the selection: 'alias' ("this creates something elsewhere")
4216
+ // is the only hint that the drag-out to Tekla exists — distinct from the grab/pointer this same
4217
+ // member shows unmodified, and it costs no chrome on an already-busy canvas.
4218
+ if (hoverTeklaMod && top && selIds.has(top) && !geoMode()) { canvasEl.style.cursor = 'alias'; if (top !== hoverId) { setHover(top); updateStatusChip(); } return; }
3719
4219
  canvasEl.style.cursor = geoMode() ? 'crosshair' : (top ? ((isPart || !canDrag) ? 'pointer' : 'grab') : 'default'); // derived part → pointer (select-only); member → grab only when drag-move is ON, else pointer (a click just selects — the cursor tells the truth, like 2D)
3720
4220
  if (top !== hoverId) { setHover(top); updateStatusChip(); }
3721
4221
  });
@@ -3727,12 +4227,16 @@ function updateStatusChip() {
3727
4227
  const rect = canvasEl.getBoundingClientRect();
3728
4228
  let txt = '';
3729
4229
  const showId = hoverId || (selIds.size === 1 ? [...selIds][0] : null);
3730
- if (wpMode === 'face') txt = 'Click a member face — the working plane lands on it · Esc to cancel';
4230
+ // The badge follows the cursor and so clips away at the window edge — from there this chip is the
4231
+ // only thing still telling the user what releasing will do.
4232
+ if (teklaDrag && teklaDrag.active) txt = `Release over the Tekla window to insert ${teklaDrag.ids.length} member${teklaDrag.ids.length === 1 ? '' : 's'} · release here or Esc to cancel`;
4233
+ else if (wpMode === 'face') txt = 'Click a member face — the working plane lands on it · Esc to cancel';
3731
4234
  else if (wpMode === '3pt') txt = ['Click the plane origin (snapped) · Esc to cancel', 'Click the local-X direction point · Esc to cancel', 'Click a point on the plane’s Y side · Esc to cancel'][(wpDraft || []).length] || '';
3732
4235
  else if (addActive()) txt = drDraft ? 'Click the member end · X/Y/Z lock to the local axes, Shift straight · Esc drops the start' + lockChipTxt() : 'Draw a member on the working plane — click the start point · Esc exits';
3733
4236
  else if (cmActive()) { const st = cmActive(), lock = lockChipTxt();
3734
4237
  txt = (!tfDraft ? ((st.tool === 'move' ? 'Move' : (st.array ? 'Copy array' : 'Copy')) + ' — click the base point on the working plane · type after the pick for an exact value')
3735
4238
  : (st.array && !tfDraft.vA ? 'Click the direction-A point — or type its spacing' : st.array ? 'Click the direction-B point — the grid previews live' : 'Click the destination — X/Y lock to the plane axes · Esc cancels')) + lock; }
4239
+ else if (gridLinePick3d) txt = gridLinePick3d.a ? 'Click the second point of the grid line · Esc to cancel' : 'Click the first point of the grid line · Esc to cancel'; // must sit above the showId/default branches, else an armed two-click tool shows the hovered member or the drag-move hint the user can't act on
3736
4240
  else if (clipMode === 'plane') txt = 'Click a face to set a clip plane · Esc to cancel';
3737
4241
  else if (clipMode === 'box') txt = !clipBoxDraft ? 'Click the first floor corner of the clip box · Esc to cancel' : !clipBoxDraft.b ? 'Click the opposite floor corner · Esc to cancel' : 'Move up/down to set the height, then click · Esc to step back';
3738
4242
  else if (showId) { const m = memberById(showId); txt = m ? `${m.id} · ${m.profile || '—'}` : ''; }
@@ -3763,11 +4267,13 @@ function hide() {
3763
4267
  if (memberLabelHost) memberLabelHost.style.display = 'none'; // member labels ride the same about-to-stop loop — hide them too, or they strand over the 2D UI
3764
4268
  if (propLabelHost) propLabelHost.style.display = 'none'; // property labels ride the same loop — hide synchronously so none strand over the 2D UI
3765
4269
  clearCopyGhost(); // drop a stale Ctrl+drag copy ghost on the way out
4270
+ endTeklaDrag(); // and a live drag-out to Tekla — a stranded one would leave its badge on screen and swallow every later pointer move
3766
4271
  if (canvasEl) canvasEl.style.display = 'none'; if (hoverChip) hoverChip.style.display = 'none'; if (rafId) { cancelAnimationFrame(rafId); rafId = null; }
3767
4272
  }
3768
4273
  function isReady() { return built; }
3769
4274
 
3770
4275
  function dispose() {
4276
+ endTeklaDrag(); // release the pointer capture and take the badge with us
3771
4277
  if (rafId) cancelAnimationFrame(rafId);
3772
4278
  if (hoverRAF) cancelAnimationFrame(hoverRAF);
3773
4279
  if (ro) ro.disconnect();
@@ -3776,6 +4282,8 @@ function dispose() {
3776
4282
  window.removeEventListener('pointermove', onMove);
3777
4283
  window.removeEventListener('pointerup', onUp);
3778
4284
  window.removeEventListener('keydown', onKey);
4285
+ window.removeEventListener('keydown', onModifierChange);
4286
+ window.removeEventListener('keyup', onModifierChange);
3779
4287
  for (const ovl of [readout, hoverChip, rubber, dimLabelHost]) if (ovl && ovl.parentNode) ovl.parentNode.removeChild(ovl);
3780
4288
  dimLabelHost = null; dimLabelPool.length = 0;
3781
4289
  if (memberLabelHost && memberLabelHost.parentNode) memberLabelHost.parentNode.removeChild(memberLabelHost);
@@ -3822,6 +4330,27 @@ function debug() {
3822
4330
  ids: [...meshById.keys()].slice(0, 12),
3823
4331
  geomTypes: [...meshById.values()].reduce((h, m) => { const t = m.geometry.type; h[t] = (h[t] || 0) + 1; return h; }, {}),
3824
4332
  lastPick, projection: projection(), mode: displayMode,
4333
+ // Realistic-mode state. `envOn` is the load-bearing one: metal with no environment renders black,
4334
+ // so "the mode switched" is not evidence on its own — the environment has to be live.
4335
+ envOn: scene ? scene.environment !== null && renderer.toneMapping === THREE.ACESFilmicToneMapping : false,
4336
+ materials: Object.fromEntries([...meshById].map(([id, m]) => [id, m.material ? {
4337
+ family: (m.material.userData || {}).family,
4338
+ metalness: m.material.metalness, roughness: m.material.roughness,
4339
+ color: '#' + m.material.color.getHexString(),
4340
+ // Surface detail: whether the generated maps are bound, and whether the material is running the
4341
+ // triplanar program rather than stock UV sampling (the cache key is the only externally visible
4342
+ // marker that onBeforeCompile actually took effect).
4343
+ map: !!m.material.map, roughMap: !!m.material.roughnessMap,
4344
+ triplanar: typeof m.material.customProgramCacheKey === 'function' ? m.material.customProgramCacheKey() : null,
4345
+ } : null])),
4346
+ // Compiled program count — a shader that failed to compile never reaches this list.
4347
+ programs: renderer && renderer.info && renderer.info.programs ? renderer.info.programs.length : null,
4348
+ // Read the rendered frame back as a data URL. The context is created without
4349
+ // preserveDrawingBuffer (the right default — it costs memory and bandwidth), so the buffer is
4350
+ // undefined after compositing; rendering synchronously immediately before the read is what makes
4351
+ // the pixels valid. Exists so a MATERIAL change can be checked by looking at it, not only by
4352
+ // asserting on state — the whole point of Realistic is how it looks.
4353
+ snapshot: (quality = 0.82) => { renderer.render(scene, camera); return canvasEl.toDataURL('image/jpeg', quality); },
3825
4354
  hidden: [...groupHidden], solo: [...soloGroups], isolated: isolatedIds ? [...isolatedIds] : null, visible: [...meshById.values()].filter((m) => m.visible).length,
3826
4355
  endpoints: epGroup ? epGroup.children.length : 0,
3827
4356
  endpointColors: epGroup ? epGroup.children.map((c) => '#' + c.material.color.getHexString()) : [],
@@ -3846,7 +4375,7 @@ function probe(id) {
3846
4375
  // test helper: client (px) coords of a member's endpoint (end 0|1) — lets an E2E drive a precise drag
3847
4376
  function screenOf(id, end) {
3848
4377
  const m = memberById(id); if (!m) return null;
3849
- const g = memberGeometry(m, api.ptPerFt(), api.defaultTosMm());
4378
+ const g = geoOf(m);
3850
4379
  const s = toScreen(g.line[end]); const rect = canvasEl.getBoundingClientRect();
3851
4380
  return { x: rect.left + s.x, y: rect.top + s.y };
3852
4381
  }
@@ -3885,8 +4414,9 @@ window.Steel3DView = {
3885
4414
  setSelLenLabels, // on-select member-length labels: editor pushes [{id,text}] (⋯ Display "Show member length")
3886
4415
  propLabelTexts: () => propLabelPool.filter((el) => el.style.display !== 'none' && el.style.visibility !== 'hidden').map((el) => el.textContent), // visible property-label chips — for tests
3887
4416
  selLenLabelTexts: () => selLenLabelPool.filter((el) => el.style.display !== 'none' && el.style.visibility !== 'hidden').map((el) => el.textContent), // visible on-select length chips — for tests
3888
- epScreen: (id) => { const m = memberById(id); if (!m || !canvasEl) return null; const g = memberGeometry(m, api.ptPerFt(), api.defaultTosMm()); 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
4417
+ 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
3889
4418
  refreshGrid: buildStructGrid, // grid edited in the panel → re-render without a full rebuild
4419
+ 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)
3890
4420
  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()] }), // test helper
3891
4421
  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.
3892
4422
  if (!wpGroup) return { group: false, extent: wpExtent };
@@ -3905,6 +4435,7 @@ window.Steel3DView = {
3905
4435
  drClear3d, drEscape: () => { if (drDraft) { drDraft = null; if (drRubber) drRubber.visible = false; if (marker) marker.visible = false; if (readout) readout.style.display = 'none'; return true; } return false; }, // Esc drops the START only — KEEP the axis lock (tfLock) so the next member reuses it (matches the chip + Move/Copy step-back); full disarm (drClear3d) clears the lock
3906
4436
  toggleDimTool, setDimAxis, dimAxis, setDims3dVisible, dims3dVisible, refreshDims,
3907
4437
  setSnapOnly: setSnapOnly3d, snapOnly: () => snapOnly3d, dimToolOn: () => dimMode3d, rightDragged: () => rightMoved, // Tekla-style snap override (right-click menu lives in steel-editor.html)
4438
+ teklaDragging: () => !!(teklaDrag && teklaDrag.active), // a drag-out to Tekla is in flight — the editor's global Escape must leave it (and the selection) alone
3908
4439
  refreshOverlayDims,
3909
4440
  overlayDimsInfo: () => computeOverlayDims().map((s) => ({ label: s.label, cat: s.cat })), // the dims currently emitted (toggle + visibility applied) — for tests
3910
4441
  overlayLabelTexts: () => overlayLabelPool.filter((el) => el.style.display !== 'none' && el.style.visibility !== 'hidden').map((el) => el.textContent),