@floless/app 0.104.2 → 0.106.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
@@ -103,10 +122,13 @@ function candOnActiveWP(c, dragged, wp) {
103
122
  return candidateOnPlane(c, dragged, wp.origin, wp.normal, WP_SNAP_TOL_MM);
104
123
  }
105
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
106
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).
107
127
  let dims3dVisibleFlag = true; // show/hide placed dims
108
128
  let dimDraft3d = null; // { a:[x,y,z] } once the first point is placed (awaiting the 2nd)
109
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)
110
132
  let dims3dGroup = null; // THREE.Group of placed-dim lines (+ the live preview line)
111
133
  let dimPreviewLine = null; // reused preview line (point 1 → cursor)
112
134
  let dimLabelHost = null; // fixed-position container for label overlays
@@ -122,6 +144,10 @@ function init(canvas, theApi) {
122
144
  if (renderer) return; // once
123
145
  canvasEl = canvas; api = theApi;
124
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;
125
151
  renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
126
152
  renderer.localClippingEnabled = true; // enable clip planes/boxes + the work area (Tekla-style sectioning) — driven via renderer.clippingPlanes (applyClips)
127
153
  scene = new THREE.Scene();
@@ -147,9 +173,11 @@ function init(canvas, theApi) {
147
173
  // always keeps the pivot screen-centred — that would need a custom control); add that only if this isn't enough.
148
174
  controls.addEventListener('start', repivotToCursor);
149
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)
150
- scene.add(new THREE.AmbientLight(0xffffff, 0.65));
151
- const key = new THREE.DirectionalLight(0xffffff, 0.85); key.position.set(0.4, -1, 1.2); scene.add(key);
152
- 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);
153
181
  root = new THREE.Group(); scene.add(root);
154
182
  overlayScene = new THREE.Scene(); // clip/work-area gizmos render here in a 2nd unclipped pass (see loop)
155
183
  epGroup = new THREE.Group(); scene.add(epGroup);
@@ -219,9 +247,19 @@ function init(canvas, theApi) {
219
247
  window.addEventListener('pointermove', onMove); // window so a drag keeps tracking off-canvas
220
248
  window.addEventListener('pointerup', onUp);
221
249
  canvas.addEventListener('pointermove', onHoverMove); // canvas-only: cursor + hover readout when idle
222
- 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
223
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
+ });
224
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);
225
263
  ro = new ResizeObserver(resize); ro.observe(canvas.parentElement || canvas);
226
264
  initCube();
227
265
  initTriad();
@@ -267,6 +305,20 @@ const V = (x, y, z) => new THREE.Vector3(x, y, z);
267
305
 
268
306
  // ---- structural cross-section shapes (ported from AWARE viewer-3d for parity) ----
269
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
+ }
270
322
  function shapeOf(el) {
271
323
  const explicit = (el.section && el.section.shape || '').toString().toUpperCase().trim();
272
324
  if (/^(I|C|L|TUBE|BOX)$/.test(explicit)) return explicit; // explicit section.shape override wins
@@ -512,8 +564,74 @@ function placeElement(mesh, el) {
512
564
  }
513
565
  }
514
566
 
515
- function materialFor(groupKey) {
516
- 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)) {
517
635
  const col = groupColor.get(groupKey) || new THREE.Color(0x94a3b8);
518
636
  // Fasteners (anchor rods / bolts / nuts / washers) read more metallic (zinc-plated); plates/welds/members stay matte.
519
637
  const metallic = groupKey === 'anchor' || groupKey === 'bolt' || groupKey === 'nut' || groupKey === 'washer';
@@ -521,9 +639,22 @@ function materialFor(groupKey) {
521
639
  // Imported (custom) connection meshes are tessellated with untrusted winding order → render both
522
640
  // faces so no triangle drops out; matte steel like a plate.
523
641
  const dbl = groupKey === 'custom';
524
- 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);
525
656
  }
526
- return baseMat.get(groupKey);
657
+ return baseMat.get(key);
527
658
  }
528
659
 
529
660
  function clearRoot() {
@@ -605,7 +736,7 @@ function applyCopes(mesh, cuts) {
605
736
 
606
737
  function buildFromScene(sc) {
607
738
  clearRoot();
608
- 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
609
740
  resetConnState(); // a fresh scene rebuilds selection from scratch — drop any stale connection envelope/context
610
741
  for (const mat of baseMat.values()) mat.dispose(); // shared per-profile materials from the prior build
611
742
  groupColor.clear(); baseMat.clear();
@@ -622,17 +753,52 @@ function buildFromScene(sc) {
622
753
  }
623
754
  }
624
755
  for (const el of sc.elements || []) {
625
- const mesh = new THREE.Mesh(undefined, materialFor(el.group));
756
+ const mesh = new THREE.Mesh(undefined, materialFor(el.group, familyOf(el), lengthAxisOf(el)));
626
757
  if (!placeElement(mesh, el)) continue; // unknown kind → skip (a `cut` is one of these: applied below, never a standalone mesh)
627
758
  const memberCuts = cutsByMember.get(el.id);
628
759
  if (memberCuts && memberCuts.length) applyCopes(mesh, memberCuts); // notch a coped member end
629
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
630
763
  mesh.userData.derived = !!(el.kind && el.kind !== 'box'); // connection parts: rendered, not member-editable
631
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
632
766
  root.add(mesh); meshById.set(el.id, mesh);
633
767
  box.expandByObject(mesh);
634
768
  }
635
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
+ }
636
802
  renderWorkPlane(); // re-draw the gizmo + reference plane sized to the (possibly new) model bounds
637
803
  // Retain the dim-relevant parts (plates + copes) so the legend's DIMENSIONS overlays can be derived
638
804
  // from the resolved geometry — fin-plate holes give bolt pitch/edge clearance, cuts give cope size.
@@ -668,7 +834,7 @@ function buildRefLines() {
668
834
  const pts = [];
669
835
  for (const m of members()) {
670
836
  if (!m || !Array.isArray(m.wp) || m.wp.length < 2) continue;
671
- const g = memberGeometry(m, api.ptPerFt(), api.defaultTosMm());
837
+ const g = geoOf(m);
672
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]));
673
839
  }
674
840
  if (!pts.length) return;
@@ -771,11 +937,10 @@ function syncMemberLabels() {
771
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)';
772
938
  memberLabelHost.appendChild(el); memberLabelPool.push(el);
773
939
  }
774
- const ppf = api.ptPerFt(), dtos = api.defaultTosMm();
775
940
  for (let i = 0; i < memberLabelPool.length; i++) {
776
941
  const el = memberLabelPool[i], m = ms[i];
777
942
  if (!m || !Array.isArray(m.wp) || m.wp.length < 2) { el.style.display = 'none'; el._mid = null; continue; }
778
- const g = memberGeometry(m, ppf, dtos);
943
+ const g = geoOf(m);
779
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];
780
945
  el.textContent = m.mark || m.id || '';
781
946
  el.style.display = 'block';
@@ -816,11 +981,10 @@ function syncPropLabels() {
816
981
  propLabelHost.appendChild(el); propLabelPool.push(el);
817
982
  }
818
983
  const byId = new Map(members().map((m) => [m.id, m]));
819
- const ppf = api.ptPerFt(), dtos = api.defaultTosMm();
820
984
  for (let i = 0; i < propLabelPool.length; i++) {
821
985
  const el = propLabelPool[i], L = labels[i], m = L ? byId.get(L.id) : null;
822
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; }
823
- 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];
824
988
  el._mid = place === 'start' ? a : place === 'end' ? b : [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2, (a[2] + b[2]) / 2];
825
989
  el._memberId = m.id;
826
990
  el.textContent = L.lines.join('\n');
@@ -862,11 +1026,10 @@ function syncSelLenLabels() {
862
1026
  selLenLabelHost.appendChild(el); selLenLabelPool.push(el);
863
1027
  }
864
1028
  const byId = new Map(members().map((m) => [m.id, m]));
865
- const ppf = api.ptPerFt(), dtos = api.defaultTosMm();
866
1029
  for (let i = 0; i < selLenLabelPool.length; i++) {
867
1030
  const el = selLenLabelPool[i], L = labels[i], m = L ? byId.get(L.id) : null;
868
1031
  if (!m || !Array.isArray(m.wp) || m.wp.length < 2 || !L.text) { el.style.display = 'none'; el._mid = null; el._memberId = null; continue; }
869
- 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];
870
1033
  el._mid = [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2, (a[2] + b[2]) / 2];
871
1034
  el._memberId = m.id;
872
1035
  el.textContent = L.text;
@@ -956,7 +1119,7 @@ function clearStructGrid() {
956
1119
  }
957
1120
  function buildStructGrid() {
958
1121
  clearStructGrid();
959
- 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.
960
1123
  if (!api || !api.getGrid || !scene) return;
961
1124
  let g = null, geo = null;
962
1125
  try { g = api.getGrid(); if (!g || g.on === false) return; geo = gridGeometry(g, api.ptPerFt()); }
@@ -1081,7 +1244,7 @@ let rebuildSeq = 0;
1081
1244
  async function rebuild(fit = false) {
1082
1245
  if (!api) return;
1083
1246
  invalidatePointEntry('rebuild'); // synchronous, BEFORE the first await — the scene is changing; drop any open typed entry + stale base (never on stale async completion)
1084
- 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
1085
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)
1086
1249
  if (fit) fitPending = true; // entering 3D re-fits; an edit-triggered rebuild keeps the camera put
1087
1250
  const seq = ++rebuildSeq;
@@ -1108,6 +1271,70 @@ function setProjection(mode) {
1108
1271
  }
1109
1272
  function projection() { return camera === orthoCam ? 'ortho' : 'persp'; }
1110
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
+ }
1111
1338
  // Wireframe mode uses per-mesh THREE.EdgesGeometry outlines instead of mat.wireframe: the latter draws
1112
1339
  // every triangulation edge, so each beam face shows a spurious diagonal "internal line" (F2). An
1113
1340
  // EdgesGeometry with a threshold angle keeps only edges where adjacent faces diverge past the threshold —
@@ -1139,18 +1366,53 @@ function clearWireEdges() {
1139
1366
  // whatever material each mesh currently carries (shared profile material OR its selection clone).
1140
1367
  function applyDisplayMode() {
1141
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');
1142
1373
  for (const [id, mesh] of meshById) {
1143
1374
  const mat = mesh.material; if (!mat) continue;
1144
1375
  if (String(id).startsWith('det:')) continue; // placed details (Slice 4) own their transparency + opacity — display mode must not override them
1145
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);
1146
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
1147
1401
  else {
1148
1402
  mat.visible = true; const ls = wireEdges.get(id); if (ls) ls.visible = false;
1149
1403
  if (displayMode === 'xray') { mat.wireframe = false; mat.transparent = true; mat.opacity = 0.25; mat.depthWrite = false; }
1150
- 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
+ }
1151
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;
1152
1413
  mat.needsUpdate = true;
1153
1414
  }
1415
+ syncClipMirror(); // shadows just turned on or off — the mirror follows
1154
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)
1155
1417
  }
1156
1418
  // A work area in "show whole parts" mode acts as a spatial filter: a part whose world AABB touches the box shows
@@ -1237,6 +1499,7 @@ function applyClips() {
1237
1499
  const active = clips.filter((c) => c.enabled).flatMap((c) => c.planes);
1238
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)
1239
1501
  renderer.clippingPlanes = active.length ? active : EMPTY_CLIPS;
1502
+ syncClipMirror(); // materials hold their own reference for the shadow pass — re-point it
1240
1503
  }
1241
1504
  // 6 inward planes (keep INSIDE) for an axis-aligned Box3 → a section/clip box.
1242
1505
  function boxToPlanes(b) {
@@ -1497,7 +1760,7 @@ function clipBoxFrom(a, b, zlo, ztop) {
1497
1760
  // the cache on every arm/disarm. A malformed member/grid degrades to no snap (raw floor), never a broken tool.
1498
1761
  let clipCandidates = null, clipLevels = null;
1499
1762
  function clipBoxSnapCands() { if (!clipCandidates) { try { clipCandidates = allCandidates(null); } catch { clipCandidates = []; } } return clipCandidates; }
1500
- 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
1501
1764
  // A footprint corner from the cursor: the floor point under it, PULLED to a member/grid/UCS snap when one is
1502
1765
  // screen-near — same candidates + running-snaps filter as the Dimension / Move tools. Returns { xy:[x,y], snap,
1503
1766
  // world } or null (ray parallel to the floor). We keep only the snap's X/Y (the corner rides the floor plane).
@@ -1695,6 +1958,13 @@ const VIEW_KEYS = { t: 'top', f: 'front', r: 'right', b: 'back', l: 'left' };
1695
1958
  function onKey(e) {
1696
1959
  if (!renderer || !canvasEl || canvasEl.style.display === 'none') return; // only when 3D is active
1697
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; }
1698
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
1699
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
1700
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
@@ -1859,7 +2129,7 @@ function setSelection(ids) {
1859
2129
  if (String(id).startsWith('det:')) { if (mesh.material && mesh.material.color) mesh.material.color.setHex(on ? 0x93c5fd : 0xffffff); continue; }
1860
2130
  // Selected → a per-mesh clone that glows (so one selected member doesn't tint its whole profile
1861
2131
  // group). Deselected → back to the SHARED profile material (its real colour).
1862
- 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);
1863
2133
  mesh.material.emissive = new THREE.Color(on ? SELECT_EMISSIVE : 0x000000);
1864
2134
  mesh.material.emissiveIntensity = on ? 0.6 : 0;
1865
2135
  }
@@ -1872,15 +2142,24 @@ function setSelection(ids) {
1872
2142
  updateStatusChip();
1873
2143
  }
1874
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
+ }
1875
2154
  function selectedMaterial(mesh) {
1876
- if (!mesh.userData._selMat) mesh.userData._selMat = materialFor(mesh.userData.group).clone();
2155
+ if (!mesh.userData._selMat) mesh.userData._selMat = highlightClone(mesh);
1877
2156
  return mesh.userData._selMat;
1878
2157
  }
1879
2158
  // ---- sky hover glow (replaces the on-hover endpoint dots) ----
1880
2159
  // A per-mesh clone so glowing one member doesn't tint its whole profile group (same trick as
1881
2160
  // selection). Selection always wins: a selected member keeps its blue glow and is left untouched.
1882
2161
  function hoverMaterial(mesh) {
1883
- if (!mesh.userData._hovMat) mesh.userData._hovMat = materialFor(mesh.userData.group).clone();
2162
+ if (!mesh.userData._hovMat) mesh.userData._hovMat = highlightClone(mesh);
1884
2163
  return mesh.userData._hovMat;
1885
2164
  }
1886
2165
  function setHoverGlow(id, on, sync = true) {
@@ -1888,7 +2167,7 @@ function setHoverGlow(id, on, sync = true) {
1888
2167
  const mesh = meshById.get(id);
1889
2168
  if (!mesh || String(id).startsWith('det:')) return; // placed details use a texture, no emissive to glow
1890
2169
  if (selIds.has(id)) return; // selected beats hovered — don't disturb its blue glow
1891
- 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);
1892
2171
  mesh.material.emissive = new THREE.Color(on ? HOVER_EMISSIVE : 0x000000);
1893
2172
  mesh.material.emissiveIntensity = on ? HOVER_INTENSITY : 0;
1894
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.
@@ -1926,7 +2205,7 @@ function rebuildEndpoints() {
1926
2205
  for (const id of show) {
1927
2206
  const mesh = meshById.get(id); if (mesh && !mesh.visible) continue; // a legend-hidden member shows no dots
1928
2207
  const m = memberById(id); if (!m) continue;
1929
- const g = memberGeometry(m, api.ptPerFt(), api.defaultTosMm());
2208
+ const g = geoOf(m);
1930
2209
  addEndpoint(g.line[0], epMatStart, id, 0); addEndpoint(g.line[1], epMatEnd, id, 1);
1931
2210
  }
1932
2211
  }
@@ -2508,13 +2787,27 @@ const members = () => (api && api.getMembers && api.getMembers()) || [];
2508
2787
  // Resolve a member by id MODEL-WIDE (every sheet), not just the active plane: the 3D shows all sheets,
2509
2788
  // so a pick / drag / hover / endpoint-handle can target a member on any plane. Falls back to the active
2510
2789
  // list if the host doesn't expose allMembers.
2511
- // ponytail: geometry + drag/endpoint commits here still use the ACTIVE plane's ppf/dtos (api.ptPerFt/
2512
- // defaultTosMm) — the whole 3D interaction layer (snap, grid, geometry) is built on one active scale.
2513
- // That is EXACT when the set has a uniform ppf, which real reads guarantee (same assumption membersInRect
2514
- // documents). Editing an off-active-sheet member whose sheet has a DIFFERENT ppf would mis-scale the
2515
- // commit. Upgrade path if sheets ever differ: expose api.ptPerFtFor(id)/defaultTosMmFor(id) and thread the
2516
- // per-member scale through the drag-start capture + memberGeometry/planPointToWp commit sites.
2517
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());
2518
2811
  const geoMode = () => (api && api.geoMode && api.geoMode()) || null;
2519
2812
 
2520
2813
  // ---- working plane (spec §6): session view-state grounding ALL 3D picks. null = the active plan's
@@ -3240,7 +3533,7 @@ function dimPointAt(e, anchor) {
3240
3533
  }
3241
3534
  let id = null; try { id = pickAt(e.clientX, e.clientY); } catch { id = null; }
3242
3535
  let planeZ = sceneBox.isEmpty() ? 0 : sceneBox.min.z;
3243
- 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; } }
3244
3537
  const hit = rayToPlane(e.clientX, e.clientY, planeZ); if (!hit) return null;
3245
3538
  if (!dimCandidates3d) dimCandidates3d = allCandidates(null); // member + grid candidates (allCandidates folds in the grid)
3246
3539
  const cands = dimCandidates3d.filter((c) => candAllowed3d(c.type)); // right-click override (one type / free) + the persistent running-snaps from the ⋯ menu
@@ -3372,27 +3665,124 @@ function onDown(e) {
3372
3665
  // An end node (the yellow/magenta dot) under the cursor → grab just that endpoint to stretch the member.
3373
3666
  let ep = null; try { ep = pickEndpoint(e.clientX, e.clientY); } catch { ep = null; }
3374
3667
  if (ep) { e.stopPropagation(); controls.enabled = false; startEndpointGrab(ep, e); return; }
3375
- 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.
3376
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.
3377
3670
  if (!id) { pending = null; boxSel = { x: e.clientX, y: e.clientY }; return; } // empty space → box-select on drag
3378
3671
  e.stopPropagation(); controls.enabled = false; // grabbed a member → suppress orbit (enabled=false is the reliable guard)
3379
3672
  try {
3380
3673
  const m = memberById(id);
3381
- const ppf = api.ptPerFt(), dtos = api.defaultTosMm();
3674
+ const { ptPerFt: ppf, defaultTosMm: dtos } = scaleFor(m); // the GRABBED member's sheet, not the active one
3382
3675
  const geo = m ? memberGeometry(m, ppf, dtos) : null;
3383
3676
  const mesh = meshById.get(id);
3384
3677
  const planeZ = geo ? (geo.line[0][2] + geo.line[1][2]) / 2 : 0;
3385
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
+ }
3386
3699
  pending = {
3387
3700
  id, ctrl, add, ppf, planeZ,
3388
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
3389
3702
  grab: geo ? rayToPlane(e.clientX, e.clientY, planeZ) : null,
3390
3703
  origMm: geo ? geo.line.map((p) => [p[0], p[1], p[2]]) : null,
3391
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)
3392
- 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)
3393
3706
  mesh, meshPos0: mesh ? mesh.position.clone() : null, delta: null, mode: null,
3394
3707
  };
3395
- } 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';
3396
3786
  }
3397
3787
 
3398
3788
  // Vertical (Alt) drag: raise/lower the member's elevation, snapping to other members' T.O.S levels.
@@ -3414,7 +3804,7 @@ function onMoveVertical(e) {
3414
3804
  function startEndpointGrab(ep, e) {
3415
3805
  try {
3416
3806
  const m = memberById(ep.id); if (!m) { controls.enabled = true; return; }
3417
- const ppf = api.ptPerFt(), dtos = api.defaultTosMm();
3807
+ const { ptPerFt: ppf, defaultTosMm: dtos } = scaleFor(m); // the GRABBED member's sheet, not the active one
3418
3808
  const g = memberGeometry(m, ppf, dtos);
3419
3809
  pending = {
3420
3810
  epDrag: true, id: ep.id, end: ep.end, ppf,
@@ -3453,6 +3843,12 @@ function onMoveEndpoint(e) {
3453
3843
  function onMove(e) {
3454
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
3455
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
+ }
3456
3852
  if (boxSel) { onBoxMove(e); return; }
3457
3853
  if (pending && pending.clipDrag) { onMoveClip(e); return; } // dragging a clip handle (plane offset / box face)
3458
3854
  if (pending && pending.frameDrag) { onMoveFrame(e); return; } // dragging the local-frame origin / rotation ring
@@ -3539,19 +3935,18 @@ function memberFootprintHit(mesh, r, windowMode, rect) {
3539
3935
  function membersInRect(x0, y0, x1, y1, windowMode) {
3540
3936
  const rect = canvasEl.getBoundingClientRect();
3541
3937
  const r = [Math.min(x0, x1), Math.min(y0, y1), Math.max(x0, x1), Math.max(y0, y1)];
3542
- const ppf = api.ptPerFt(), dtos = api.defaultTosMm();
3543
3938
  // ALL sheets' members, not just the active one — the 3D shows every plan, so a box must be able to grab a
3544
3939
  // member on any floor (the meshes are server-positioned, so the primary footprint hit is correct across
3545
- // sheets; the client-recomputed a/b fallback uses the active ppf and may be off for a far sheet, but the
3546
- // footprint test catches those). Without this, an area-select only picks the active sheet — "selection
3547
- // 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."
3548
3943
  const memById = new Map(((api && api.allMembers && api.allMembers()) || members()).map((m) => [m.id, m]));
3549
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 }; };
3550
3945
  const out = [];
3551
3946
  for (const [id, m] of meshById) {
3552
3947
  if (!m.visible || m.userData.derived) continue; // derived connection parts aren't member-selectable (mirrors pickAt; dbl-click-zoom deliberately includes them)
3553
3948
  const mem = memById.get(id); if (!mem) continue;
3554
- 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; }
3555
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
3556
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)
3557
3952
  const w = m.getWorldPosition(new THREE.Vector3()).project(camera); if (w.z > 1) continue;
@@ -3593,7 +3988,23 @@ function connsInRect(x0, y0, x1, y1, windowMode) {
3593
3988
 
3594
3989
  function onUp(e) {
3595
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
+ }
3596
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; }
3597
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)
3598
4009
  const bs = boxSel; boxSel = null;
3599
4010
  if (bs) { // empty-space gesture: drag = box-select, click = clear selection
@@ -3629,8 +4040,8 @@ function onUp(e) {
3629
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
3630
4041
  if (p.geo === 'split') { // cut the selected member at the clicked point on its centreline
3631
4042
  const m = memberById(p.selId); if (!m) return;
3632
- const ppf = api.ptPerFt();
3633
- 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);
3634
4045
  const planeZ = (g.line[0][2] + g.line[1][2]) / 2;
3635
4046
  const hit = rayToPlane(e.clientX, e.clientY, planeZ); if (!hit) return;
3636
4047
  if (p.targetId !== p.selId) return; // the cut click must land on the selected member's body
@@ -3715,11 +4126,32 @@ function dimHoverPreview(alt) {
3715
4126
  if (r && !dimDraft3d) roShowCoordOnly(r.p, lastHoverXY[0], lastHoverXY[1]); // first dim point: coords-only chip
3716
4127
  else if (readout) readout.style.display = 'none'; } // no point (or a draft with the cursor off-plane) → clear the chip
3717
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
+
3718
4148
  function onHoverMove(e) {
3719
4149
  lastHoverXY = [e.clientX, e.clientY];
3720
4150
  dimLastAlt = e.altKey; // remembered so the rAF body can rebuild a synthetic event
3721
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
3722
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
3723
4155
  hoverRAF = requestAnimationFrame(() => {
3724
4156
  hoverRAF = 0;
3725
4157
  if (!lastHoverXY || pending || dragging || boxSel) return;
@@ -3780,6 +4212,10 @@ function onHoverMove(e) {
3780
4212
  let top = null; try { top = pickAllAt(lastHoverXY[0], lastHoverXY[1])[0] || null; } catch { top = null; }
3781
4213
  const topMesh = top ? meshById.get(top) : null, isPart = !!(topMesh && topMesh.userData.derived);
3782
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; }
3783
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)
3784
4220
  if (top !== hoverId) { setHover(top); updateStatusChip(); }
3785
4221
  });
@@ -3791,7 +4227,10 @@ function updateStatusChip() {
3791
4227
  const rect = canvasEl.getBoundingClientRect();
3792
4228
  let txt = '';
3793
4229
  const showId = hoverId || (selIds.size === 1 ? [...selIds][0] : null);
3794
- 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';
3795
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] || '';
3796
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';
3797
4236
  else if (cmActive()) { const st = cmActive(), lock = lockChipTxt();
@@ -3828,11 +4267,13 @@ function hide() {
3828
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
3829
4268
  if (propLabelHost) propLabelHost.style.display = 'none'; // property labels ride the same loop — hide synchronously so none strand over the 2D UI
3830
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
3831
4271
  if (canvasEl) canvasEl.style.display = 'none'; if (hoverChip) hoverChip.style.display = 'none'; if (rafId) { cancelAnimationFrame(rafId); rafId = null; }
3832
4272
  }
3833
4273
  function isReady() { return built; }
3834
4274
 
3835
4275
  function dispose() {
4276
+ endTeklaDrag(); // release the pointer capture and take the badge with us
3836
4277
  if (rafId) cancelAnimationFrame(rafId);
3837
4278
  if (hoverRAF) cancelAnimationFrame(hoverRAF);
3838
4279
  if (ro) ro.disconnect();
@@ -3841,6 +4282,8 @@ function dispose() {
3841
4282
  window.removeEventListener('pointermove', onMove);
3842
4283
  window.removeEventListener('pointerup', onUp);
3843
4284
  window.removeEventListener('keydown', onKey);
4285
+ window.removeEventListener('keydown', onModifierChange);
4286
+ window.removeEventListener('keyup', onModifierChange);
3844
4287
  for (const ovl of [readout, hoverChip, rubber, dimLabelHost]) if (ovl && ovl.parentNode) ovl.parentNode.removeChild(ovl);
3845
4288
  dimLabelHost = null; dimLabelPool.length = 0;
3846
4289
  if (memberLabelHost && memberLabelHost.parentNode) memberLabelHost.parentNode.removeChild(memberLabelHost);
@@ -3887,6 +4330,27 @@ function debug() {
3887
4330
  ids: [...meshById.keys()].slice(0, 12),
3888
4331
  geomTypes: [...meshById.values()].reduce((h, m) => { const t = m.geometry.type; h[t] = (h[t] || 0) + 1; return h; }, {}),
3889
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); },
3890
4354
  hidden: [...groupHidden], solo: [...soloGroups], isolated: isolatedIds ? [...isolatedIds] : null, visible: [...meshById.values()].filter((m) => m.visible).length,
3891
4355
  endpoints: epGroup ? epGroup.children.length : 0,
3892
4356
  endpointColors: epGroup ? epGroup.children.map((c) => '#' + c.material.color.getHexString()) : [],
@@ -3911,7 +4375,7 @@ function probe(id) {
3911
4375
  // test helper: client (px) coords of a member's endpoint (end 0|1) — lets an E2E drive a precise drag
3912
4376
  function screenOf(id, end) {
3913
4377
  const m = memberById(id); if (!m) return null;
3914
- const g = memberGeometry(m, api.ptPerFt(), api.defaultTosMm());
4378
+ const g = geoOf(m);
3915
4379
  const s = toScreen(g.line[end]); const rect = canvasEl.getBoundingClientRect();
3916
4380
  return { x: rect.left + s.x, y: rect.top + s.y };
3917
4381
  }
@@ -3950,7 +4414,7 @@ window.Steel3DView = {
3950
4414
  setSelLenLabels, // on-select member-length labels: editor pushes [{id,text}] (⋯ Display "Show member length")
3951
4415
  propLabelTexts: () => propLabelPool.filter((el) => el.style.display !== 'none' && el.style.visibility !== 'hidden').map((el) => el.textContent), // visible property-label chips — for tests
3952
4416
  selLenLabelTexts: () => selLenLabelPool.filter((el) => el.style.display !== 'none' && el.style.visibility !== 'hidden').map((el) => el.textContent), // visible on-select length chips — for tests
3953
- 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
3954
4418
  refreshGrid: buildStructGrid, // grid edited in the panel → re-render without a full rebuild
3955
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)
3956
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
@@ -3971,6 +4435,7 @@ window.Steel3DView = {
3971
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
3972
4436
  toggleDimTool, setDimAxis, dimAxis, setDims3dVisible, dims3dVisible, refreshDims,
3973
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
3974
4439
  refreshOverlayDims,
3975
4440
  overlayDimsInfo: () => computeOverlayDims().map((s) => ({ label: s.label, cat: s.cat })), // the dims currently emitted (toggle + visibility applied) — for tests
3976
4441
  overlayLabelTexts: () => overlayLabelPool.filter((el) => el.style.display !== 'none' && el.style.visibility !== 'hidden').map((el) => el.textContent),