@floless/app 0.132.1 → 0.133.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.
@@ -15,6 +15,134 @@ import { mmPerPx } from './grid-core.js';
15
15
  export const FT_TO_MM = 304.8;
16
16
  export const IN_TO_MM = 25.4;
17
17
 
18
+ /** Atomic capability marker: storage, readers, authoring and shipped guidance advance together. */
19
+ export const POSITION_BASIS_CAPABILITY_VERSION = 1;
20
+ /** Storage integrity is deliberately much stricter than the geometric near-plumb threshold. */
21
+ export const BASIS_ORTHONORMAL_TOL = 1e-10;
22
+
23
+ const finiteVec3 = (v) => Array.isArray(v) && v.length === 3 && v.every((n) => typeof n === 'number' && Number.isFinite(n));
24
+ const dot3 = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
25
+ const len3 = (v) => Math.sqrt(dot3(v, v));
26
+
27
+ /** Return the stable semantic diagnostic for a stored position basis, or null when it is valid. */
28
+ export function positionBasisIssue(x, y) {
29
+ if (!finiteVec3(x) || !finiteVec3(y)) return 'position-basis-not-unit';
30
+ if (Math.abs(len3(x) - 1) > BASIS_ORTHONORMAL_TOL || Math.abs(len3(y) - 1) > BASIS_ORTHONORMAL_TOL) {
31
+ return 'position-basis-not-unit';
32
+ }
33
+ if (Math.abs(dot3(x, y)) > BASIS_ORTHONORMAL_TOL) return 'position-basis-not-orthogonal';
34
+ return null;
35
+ }
36
+
37
+ /** Strict reader: derive the right-handed normal without normalising or repairing stored axes. */
38
+ export function basisFromAxes(x, y) {
39
+ if (positionBasisIssue(x, y)) return null;
40
+ return { x: [...x], y: [...y], z: cross3(x, y) };
41
+ }
42
+
43
+ /** Writer-only canonicalisation for authoritative view axes. Stored readers never call this helper. */
44
+ export function canonicalPositionBasis(x, y) {
45
+ if (!finiteVec3(x) || !finiteVec3(y)) return null;
46
+ const lx = len3(x);
47
+ if (!(lx > 0)) return null;
48
+ const nx = x.map((n) => n / lx);
49
+ const xy = dot3(y, nx);
50
+ const py = y.map((n, i) => n - xy * nx[i]);
51
+ const ly = len3(py);
52
+ if (!(ly > 0)) return null;
53
+ const ny = py.map((n) => n / ly);
54
+ return Object.freeze({ x: Object.freeze(nx), y: Object.freeze(ny) });
55
+ }
56
+
57
+ /** One production folding rule shared by scene reading, editor display and basis re-expression. */
58
+ export function effectiveDepthPosition(explicit, role, dzMm, horizMm, isVerticalBrace = false) {
59
+ if (explicit === 'top' || explicit === 'middle' || explicit === 'bottom') return explicit;
60
+ if (role === 'column' || isVerticalBrace) return 'middle';
61
+ return dzMm > horizMm * 0.5774 ? 'middle' : 'top';
62
+ }
63
+
64
+ export function effectiveWidthPosition(explicit) {
65
+ return explicit === 'left' || explicit === 'right' ? explicit : 'middle';
66
+ }
67
+
68
+ const addScaled3 = (a, sa, b, sb) => [a[0] * sa + b[0] * sb, a[1] * sa + b[1] * sb, a[2] * sa + b[2] * sb];
69
+ const sub3 = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
70
+ const dist3 = (a, b) => len3(sub3(a, b));
71
+ const finiteNumber = (v, fallback = 0) => typeof v === 'number' && Number.isFinite(v) ? v : fallback;
72
+
73
+ /**
74
+ * Re-express one stored Profile Position against a captured authoring basis without moving any steel.
75
+ * The returned patch deliberately preserves named faces and numeric offsets byte-for-byte: right-handed
76
+ * transverse rebasing changes only the roll spelling and stored basis. A caller applies the user's edit
77
+ * after this preflight succeeds.
78
+ */
79
+ export function reexpressMemberPlacement(member, refFrom, refTo, target, extents = /** @type {{lo:number[],hi:number[]}|null} */ (null)) {
80
+ if (!member || !finiteVec3(refFrom) || !finiteVec3(refTo) || !target) {
81
+ return { ok: false, code: 'position-rebase-invalid', message: 'Profile Position could not be decoded.' };
82
+ }
83
+ const oldBasis = member.positionBasis
84
+ ? basisFromAxes(member.positionBasis.x, member.positionBasis.y)
85
+ : { x: [1, 0, 0], y: [0, 1, 0], z: [0, 0, 1] };
86
+ if (!oldBasis) return { ok: false, code: positionBasisIssue(member.positionBasis?.x, member.positionBasis?.y) || 'position-rebase-invalid' };
87
+ let targetBasis;
88
+ let storedTarget;
89
+ if (target.kind === 'global') {
90
+ targetBasis = { x: [1, 0, 0], y: [0, 1, 0], z: [0, 0, 1] };
91
+ storedTarget = undefined;
92
+ } else {
93
+ storedTarget = canonicalPositionBasis(target.x, target.y);
94
+ targetBasis = storedTarget && basisFromAxes(storedTarget.x, storedTarget.y);
95
+ if (!targetBasis) return { ok: false, code: 'position-authoring-basis-unavailable', message: 'The active edit frame is not a valid orthonormal basis.' };
96
+ }
97
+ const a0 = partFrame(refFrom, refTo, oldBasis.z, oldBasis.x);
98
+ const a1 = partFrame(refFrom, refTo, targetBasis.z, targetBasis.x);
99
+ if (!a0 || !a1) return { ok: false, code: 'position-rebase-degenerate', message: 'A zero-length member has no Profile Position frame.' };
100
+ const dz = Math.abs(refTo[2] - refFrom[2]), horiz = Math.hypot(refTo[0] - refFrom[0], refTo[1] - refFrom[1]);
101
+ const depthFace = effectiveDepthPosition(member.position, member.role === 'column' ? 'column' : 'beam', dz, horiz,
102
+ member.memberType === 'brace' && member.brace?.type === 'vertical');
103
+ const widthFace = effectiveWidthPosition(member.positionH);
104
+ let oy0, oz0;
105
+ if (extents && extents.lo && extents.hi) {
106
+ oy0 = faceOffset(widthFace, extents.lo[0], extents.hi[0]) + finiteNumber(member.positionHOffset);
107
+ oz0 = faceOffset(depthFace, extents.lo[1], extents.hi[1]) + finiteNumber(member.positionOffset);
108
+ } else {
109
+ if (depthFace !== 'middle' || widthFace !== 'middle') {
110
+ return { ok: false, code: 'position-rebase-section-unresolved', message: 'A named section face cannot be re-expressed until the section resolves.' };
111
+ }
112
+ oy0 = finiteNumber(member.positionHOffset);
113
+ oz0 = finiteNumber(member.positionOffset);
114
+ }
115
+ const theta0 = finiteNumber(member.rot) * Math.PI / 180;
116
+ const c0 = Math.cos(theta0), s0 = Math.sin(theta0);
117
+ const width = addScaled3(a0.y, c0, a0.z, s0);
118
+ const depth = addScaled3(a0.y, -s0, a0.z, c0);
119
+ const offset = addScaled3(width, oy0, depth, oz0);
120
+ const theta1 = Math.atan2(dot3(width, a1.z), dot3(width, a1.y));
121
+ const c1 = Math.cos(theta1), s1 = Math.sin(theta1);
122
+ const qY = dot3(offset, a1.y), qZ = dot3(offset, a1.z);
123
+ const oy1 = qY * c1 + qZ * s1, oz1 = -qY * s1 + qZ * c1;
124
+ const width1 = addScaled3(a1.y, c1, a1.z, s1);
125
+ const depth1 = addScaled3(a1.y, -s1, a1.z, c1);
126
+ const offset1 = addScaled3(width1, oy1, depth1, oz1);
127
+ const axial = Math.abs(dot3(offset, a1.x));
128
+ const orth = Math.abs(dot3(width, depth));
129
+ const axisError = Math.max(Math.abs(len3(width) - 1), Math.abs(len3(depth) - 1));
130
+ const offsetError = dist3(offset, offset1);
131
+ const physicalTol = extents ? 0.001 : 1e-9;
132
+ const radius = extents ? Math.max(Math.abs(extents.lo[0]), Math.abs(extents.hi[0]), Math.abs(extents.lo[1]), Math.abs(extents.hi[1])) : 1;
133
+ if (axial > 0.001 || axisError > BASIS_ORTHONORMAL_TOL || orth * radius > physicalTol || offsetError > physicalTol) {
134
+ return { ok: false, code: 'position-rebase-residual', message: 'Re-expression would move the member beyond the 0.001 mm placement tolerance.' };
135
+ }
136
+ let degrees = (theta1 * 180 / Math.PI) % 360;
137
+ if (degrees < 0) degrees += 360;
138
+ if (Object.is(degrees, -0) || Math.abs(degrees) < 1e-12 || Math.abs(degrees - 360) < 1e-12) degrees = 0;
139
+ return {
140
+ ok: true,
141
+ patch: { positionBasis: storedTarget ? { x: [...storedTarget.x], y: [...storedTarget.y] } : undefined, rot: degrees },
142
+ residual: { axial, orthogonal: orth, offset: offsetError },
143
+ };
144
+ }
145
+
18
146
  /** @typedef {'I'|'C'|'L'|'TUBE'|'BOX'} SectionKind */
19
147
 
20
148
  /**
@@ -315,6 +443,62 @@ export function sectionOutlinePts(kind, w, d, thk) {
315
443
  /** How many segments approximate a circle for the consumers that need a polygon. */
316
444
  export const ROUND_SEGMENTS = 48;
317
445
 
446
+ /**
447
+ * Editor display topology. A component owns one outer path and zero or more holes; multiple components
448
+ * still belong to one logical member (2L), so the Three adapter can extrude them into one mesh.
449
+ */
450
+ export function sectionTopology(displaySection, w, d, fallbackKind = 'BOX') {
451
+ const polygon = (points) => ({ kind: 'polygon', points });
452
+ const circle = (radius) => ({ kind: 'circle', cx: 0, cy: 0, radius });
453
+ const component = (outer, holes = []) => ({ outer, holes });
454
+ const xs = displaySection || null;
455
+
456
+ if (xs?.shape === 'chs') {
457
+ const od = Number(xs.od) > 0 ? Number(xs.od) : Math.min(w, d);
458
+ const t = Number(xs.t);
459
+ const radius = od / 2;
460
+ return [component(circle(radius), t > 0 && t < radius ? [circle(radius - t)] : [])];
461
+ }
462
+ if (xs?.shape === 'solid-circle') {
463
+ const diameter = Number(xs.diameter) > 0 ? Number(xs.diameter) : Math.min(w, d);
464
+ return [component(circle(diameter / 2))];
465
+ }
466
+ if (xs?.shape === 'tee') {
467
+ const hw = w / 2, hd = d / 2;
468
+ const tf = Math.min(Math.max(Number(xs.tf) || d * 0.1, 0.1), d);
469
+ const tw = Math.min(Math.max(Number(xs.tw) || w * 0.1, 0.1), w);
470
+ return [component(polygon([[-hw, hd], [hw, hd], [hw, hd - tf], [tw / 2, hd - tf], [tw / 2, -hd], [-tw / 2, -hd], [-tw / 2, hd - tf], [-hw, hd - tf]]))];
471
+ }
472
+ if (xs?.shape === 'double-angle') {
473
+ const longBack = String(xs.orientation).toLowerCase() !== 'slbb';
474
+ const legDepth = Number(xs.d);
475
+ const legWidth = Number(xs.b);
476
+ const t = Math.min(Number(xs.t), legDepth, legWidth);
477
+ const gap = Math.max(Number(xs.gap) || 0, 0);
478
+ if (!(legDepth > 0 && legWidth > 0 && t > 0)) return [];
479
+ const hd = d / 2, hg = gap / 2;
480
+ if (longBack) {
481
+ const left = [[-hg - legWidth, hd - t], [-hg - t, hd - t], [-hg - t, -hd], [-hg, -hd], [-hg, hd], [-hg - legWidth, hd]];
482
+ const right = [[hg, -hd], [hg + t, -hd], [hg + t, hd - t], [hg + legWidth, hd - t], [hg + legWidth, hd], [hg, hd]];
483
+ return [component(polygon(left)), component(polygon(right))];
484
+ }
485
+ const hw = w / 2;
486
+ const lower = [[-hw, -hd], [-hw + t, -hd], [-hw + t, -hg - t], [hw, -hg - t], [hw, -hg], [-hw, -hg]];
487
+ const upper = [[hw, hd], [hw - t, hd], [hw - t, hg + t], [-hw, hg + t], [-hw, hg], [hw, hg]];
488
+ return [component(polygon(lower)), component(polygon(upper))];
489
+ }
490
+
491
+ const shapeKind = xs?.shape === 'i' ? 'I'
492
+ : xs?.shape === 'channel' ? 'C'
493
+ : xs?.shape === 'angle' ? 'L'
494
+ : xs?.shape === 'rhs' ? 'TUBE'
495
+ : fallbackKind;
496
+ const outlined = sectionOutlinePts(shapeKind, w, d, {
497
+ tw: xs?.tw, tf: xs?.tf, t: xs?.t,
498
+ });
499
+ return [component(polygon(outlined.outer), outlined.hole ? [polygon(outlined.hole)] : [])];
500
+ }
501
+
318
502
  /**
319
503
  * Place a section outline (local px, centred on the origin, section x = width / y = depth) into a plan
320
504
  * sheet's display px, for a member rolled `rotDeg`.
@@ -1167,9 +1351,10 @@ export function dim3dGeom(a, b, axis, axisDir) {
1167
1351
  // above already ended the CLASSIFIER's copies, and these end the OUTLINE's.
1168
1352
 
1169
1353
  /**
1170
- * AWARE's inclusive squared near-vertical predicate, `1 − dot(axis, up)² ≤ 1e−6`. Keeping the squared
1171
- * form—not an independently rounded `sin θ` comparison—makes the branch and its floating boundary match
1172
- * the released scene contract. Its visible `sin θ` boundary is 1e−3.
1354
+ * AWARE's inclusive raw cross-multiplied near-vertical predicate,
1355
+ * `|d − dot(d, up) up|² ≤ 1e−6 |d|²`. The literal operation shape is part of the floating-point contract:
1356
+ * normalizing `d`, subtracting from one, or dividing the sides moves the seam. Its visible `sin θ`
1357
+ * boundary is 1e−3.
1173
1358
  */
1174
1359
  export const FRAME_DEGENERATE_SQ = 1e-6;
1175
1360
  export const FRAME_DEGENERATE = Math.sqrt(FRAME_DEGENERATE_SQ);
@@ -1307,8 +1492,8 @@ export function faceOffset(named, lo, hi) {
1307
1492
  * `memberMeshAxes` below, which is this frame with the axes reordered into the geometry's local order. It
1308
1493
  * agreed with this rule for every ordinary member — which is why the divergence shipped unnoticed — and
1309
1494
  * differed by a full 180° for a member stored top→base, where three.js's arbitrary antiparallel tie-break
1310
- * yielded (−x̂, +ŷ) against this rule's (+x̂, −ŷ). (A second band, at the near-plumb cut, closed earlier
1311
- * when #786 gave both the same `1 − dot² ≤ 1e−6` predicate.)
1495
+ * yielded (−x̂, +ŷ) against this rule's (+x̂, −ŷ). A second band at the near-plumb cut is kept closed by
1496
+ * the shared literal raw cross-multiplied predicate.
1312
1497
  *
1313
1498
  * WHAT THAT COST WHILE IT LASTED, since it bounds what the fix can change. The renderer centres the mesh
1314
1499
  * on the line the BAKE already offset (`placeMember`: `mesh.position` is the midpoint of `el.from`/
@@ -1326,9 +1511,8 @@ export function faceOffset(named, lo, hi) {
1326
1511
  */
1327
1512
  export function partFrame(from, to, up = [0, 0, 1], upX = [1, 0, 0]) {
1328
1513
  const d = [to[0] - from[0], to[1] - from[1], to[2] - from[2]];
1329
- // Match AWARE `normalized3`: `sqrt(dot(v, v))`, deliberately not `Math.hypot`. They round an exact
1330
- // 1e-3 near-vertical boundary differently, which would otherwise defeat the inclusive predicate below.
1331
- const len = Math.sqrt(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]);
1514
+ const dSq = (d[0] * d[0] + d[1] * d[1]) + d[2] * d[2];
1515
+ const len = Math.sqrt(dSq);
1332
1516
  if (!(len > 0) || !isFinite(len)) return null;
1333
1517
  const x = [d[0] / len, d[1] / len, d[2] / len];
1334
1518
  const unit = (v, label, min = 0) => {
@@ -1337,9 +1521,12 @@ export function partFrame(from, to, up = [0, 0, 1], upX = [1, 0, 0]) {
1337
1521
  return [v[0] / l, v[1] / l, v[2] / l];
1338
1522
  };
1339
1523
  const u = unit(up, 'up');
1340
- const upDot = u[0] * x[0] + u[1] * x[1] + u[2] * x[2];
1341
- const perpendicularSq = Math.max(0, 1 - upDot * upDot);
1342
- const degenerate = perpendicularSq <= FRAME_DEGENERATE_SQ;
1524
+ // Match AWARE #435 literally. These raw operands and the cross-multiplied comparison are deliberate:
1525
+ // algebraically equivalent normalized/cancelling/quotient forms disagree in the IEEE-754 seam.
1526
+ const rawUpDot = (u[0] * d[0] + u[1] * d[1]) + u[2] * d[2];
1527
+ const q = [d[0] - rawUpDot * u[0], d[1] - rawUpDot * u[1], d[2] - rawUpDot * u[2]];
1528
+ const qSq = (q[0] * q[0] + q[1] * q[1]) + q[2] * q[2];
1529
+ const degenerate = qSq <= FRAME_DEGENERATE_SQ * dSq;
1343
1530
  if (degenerate) {
1344
1531
  // Same projected +X seed rule as AWARE's scene_roll::member_frame. `upX` is intentionally validated
1345
1532
  // only here: an ordinary +X beam legitimately has an unused +X seed with a zero member-plane projection.
@@ -1348,6 +1535,7 @@ export function partFrame(from, to, up = [0, 0, 1], upX = [1, 0, 0]) {
1348
1535
  return { x, y, z: cross3(x, y), degenerate };
1349
1536
  }
1350
1537
  // Canonical ordinary branch: depth is projected up; width is depth × member axis (not its sign reverse).
1538
+ const upDot = u[0] * x[0] + u[1] * x[1] + u[2] * x[2];
1351
1539
  const z = unit([u[0] - upDot * x[0], u[1] - upDot * x[1], u[2] - upDot * x[2]], 'up projection');
1352
1540
  return { x, y: cross3(z, x), z, degenerate };
1353
1541
  }
@@ -20,7 +20,7 @@ import { RoomEnvironment } from 'three/addons/RoomEnvironment.js';
20
20
  import { surfaceTextures, applyTriplanar, TILE_MM, DIRECTIONAL } from './steel-materials.js';
21
21
  import { canvasToolGuidanceState } from './steel-canvas-guidance.js';
22
22
  import { Brush, Evaluator, SUBTRACTION } from 'three-bvh-csg';
23
- import { snapPoint, planPointToWp, memberGeometry, snapElevation, dim3dGeom, dominantAxis3d, planeBasis, planeFrom3Points, frameFrom3Points, frameFromAngle, worldToLocal, identityFrame, resolvePointEntry, offsetsFor, candidateOnPlane, snapGridPoint, clipSegmentToPlanes, pointSegmentDistance2d, perspectiveSegmentParameter, gridDepthWins, segmentHitsRect2d, projectedFootprintHitsRect2d, pickGridLevel, selectedLengthLabelAnchors, sectionKindOf, sectionOutlinePts, memberMeshAxes } from './steel-3d-core.js';
23
+ import { snapPoint, planPointToWp, memberGeometry, snapElevation, dim3dGeom, dominantAxis3d, planeBasis, planeFrom3Points, frameFrom3Points, frameFromAngle, worldToLocal, identityFrame, resolvePointEntry, offsetsFor, candidateOnPlane, snapGridPoint, clipSegmentToPlanes, pointSegmentDistance2d, perspectiveSegmentParameter, gridDepthWins, segmentHitsRect2d, projectedFootprintHitsRect2d, pickGridLevel, selectedLengthLabelAnchors, sectionKindOf, sectionTopology, memberMeshAxes, POSITION_BASIS_CAPABILITY_VERSION } from './steel-3d-core.js';
24
24
  // `gridGeometry`, `gridCandidates3d` and `mmPerPx` live behind the host's model read boundary because
25
25
  // their display-scale argument is meaningless on a world-mm model grid.
26
26
  import { visibleGridLevels, gridTransientScopeSignature, reconcileGridTransientState, objectSelectionStatus } from './grid-core.js';
@@ -460,7 +460,9 @@ function lengthAxisOf(el) {
460
460
  // finish across the nut's short axis instead of along its sweep.
461
461
  if (kind === 'rod' || kind === 'bolt-shank' || kind === 'anchor' || kind === 'nut') return 'y'; // CylinderGeometry
462
462
  if (kind === 'plate' || kind === 'washer' || kind === 'bolt-head') return 'z';
463
- return shapeOf(el) === 'BOX' ? 'y' : 'z'; // Box vs Extrude
463
+ const display = el?.meta?.displaySection;
464
+ const displayExtrudes = display && !/^(rect|joist|unsupported-custom)$/.test(String(display.shape));
465
+ return !displayExtrudes && shapeOf(el) === 'BOX' ? 'y' : 'z'; // Box vs Extrude
464
466
  }
465
467
  function shapeOf(el) {
466
468
  const explicit = (el.section && el.section.shape || '').toString().toUpperCase().trim();
@@ -485,25 +487,32 @@ function realThk(xs, key, half) {
485
487
  // an L4X4 leg came out 18.3mm against a real 9.5, so a connection bearing on the real face rendered buried
486
488
  // in a member that was drawn nearly twice too thick. The estimates remain as the fallback for sections we
487
489
  // have no data for; they are the reason a member can still be drawn at all.
488
- function profileShape(kind, w, d, xs) {
489
- // The outline itself comes from steel-3d-core.js, which the 2D plan draws from too — one set of points,
490
- // so a section whose real thickness is known cannot be extruded as one shape and drawn as another (see
491
- // sectionOutlinePts). Two differences survive on purpose: 3D punches a tube's bore below where the plan
492
- // draws a tube solid, and a section with NO thickness source falls back to estimates whose floors are
493
- // absolute in each caller's own unit. All that is left here is turning the points into a THREE.Shape.
494
- const { outer, hole } = sectionOutlinePts(kind, w, d, {
495
- tw: realThk(xs, 'tw', w / 2), tf: realThk(xs, 'tf', d / 2), t: realThk(xs, 't', Math.min(w, d) / 2),
490
+ function profileShape(kind, w, d, xs, displaySection) {
491
+ const fallback = xs ? {
492
+ ...(xs.shape === 'i' ? { shape: 'i', d: xs.d, bf: xs.bf, tw: realThk(xs, 'tw', w / 2), tf: realThk(xs, 'tf', d / 2) } : {}),
493
+ ...(xs.shape === 'channel' ? { shape: 'channel', d: xs.d, bf: xs.bf, tw: realThk(xs, 'tw', w / 2), tf: realThk(xs, 'tf', d / 2) } : {}),
494
+ ...(xs.shape === 'angle' ? { shape: 'angle', d: xs.d, b: xs.b, t: realThk(xs, 't', Math.min(w, d) / 2) } : {}),
495
+ ...(xs.shape === 'rhs' ? { shape: 'rhs', d: xs.d, b: xs.b, t: realThk(xs, 't', Math.min(w, d) / 2) } : {}),
496
+ ...(xs.shape === 'chs' ? { shape: 'chs', od: xs.od, t: realThk(xs, 't', Math.min(w, d) / 2) } : {}),
497
+ } : null;
498
+ const topology = sectionTopology(displaySection || fallback, w, d, kind);
499
+ const trace = (path, descriptor) => {
500
+ if (descriptor.kind === 'circle') { path.absarc(descriptor.cx, descriptor.cy, descriptor.radius, 0, Math.PI * 2, false); return; }
501
+ descriptor.points.forEach(([x, y], i) => (i ? path.lineTo(x, y) : path.moveTo(x, y))); path.closePath();
502
+ };
503
+ return topology.map(({ outer, holes }) => {
504
+ const shape = new THREE.Shape(); trace(shape, outer);
505
+ for (const hole of holes) { const path = new THREE.Path(); trace(path, hole); shape.holes.push(path); }
506
+ return shape;
496
507
  });
497
- const s = new THREE.Shape();
498
- const trace = (path, pts) => { pts.forEach(([x, y], i) => (i ? path.lineTo(x, y) : path.moveTo(x, y))); path.closePath(); };
499
- trace(s, outer);
500
- if (hole) { const h = new THREE.Path(); trace(h, hole); s.holes.push(h); }
501
- return s;
502
508
  }
503
509
  function memberGeom(el, w, d, len) {
504
510
  const kind = shapeOf(el);
505
- if (kind === 'BOX') return new THREE.BoxGeometry(w, len, d); // length on local Y
506
- const g = new THREE.ExtrudeGeometry(profileShape(kind, w, d, el && el.xsection), { depth: len, bevelEnabled: false });
511
+ const display = el?.meta?.displaySection;
512
+ const displayExtrudes = display && !/^(rect|joist|unsupported-custom)$/.test(String(display.shape));
513
+ if (kind === 'BOX' && !displayExtrudes) return new THREE.BoxGeometry(w, len, d); // length on local Y
514
+ const shapes = profileShape(kind, w, d, el && el.xsection, display);
515
+ const g = new THREE.ExtrudeGeometry(shapes, { depth: len, bevelEnabled: false, curveSegments: 32 });
507
516
  g.translate(0, 0, -len / 2); return g; // extruded +Z, centred
508
517
  }
509
518
  const _ZA = new THREE.Vector3(0, 0, 1), _YA = new THREE.Vector3(0, 1, 0);
@@ -513,7 +522,7 @@ const _ZA = new THREE.Vector3(0, 0, 1), _YA = new THREE.Vector3(0, 1, 0);
513
522
  // spelled out here: it is `partFrame`'s `up` parameter, which defaults to world Z (see `memberMeshAxes`).
514
523
  /**
515
524
  * Orient a member from its two raw world endpoints. `from` and `to` are endpoint triples, never a
516
- * pre-normalized direction; normalizing before `partFrame` can select the other inclusive boundary branch.
525
+ * pre-normalized direction: AWARE #435 makes the raw subtraction operands part of the branch contract.
517
526
  * @param {THREE.Object3D & {geometry: THREE.BufferGeometry}} mesh
518
527
  * @param {[number, number, number]} from raw world start endpoint
519
528
  * @param {[number, number, number]} to raw world end endpoint
@@ -528,15 +537,14 @@ function orientMember(mesh, from, to, el) {
528
537
  // had it right (#770). One frame, so the tie-break and the near-plumb cut cannot drift apart again.
529
538
  //
530
539
  // THE AUTHORED REFERENCE LINE selects the frame, and the operands must be the bake's own — not a
531
- // direction recovered from anywhere else. `partFrame`'s near-plumb predicate (`1 − dot² ≤ 1e−6`) is
532
- // INCLUSIVE, so for a member on the cut a single last-bit difference decides the branch and swings the
533
- // depth axis 90°. Two roundings had to go (both found by Codex on #801):
540
+ // direction recovered from anywhere else. `partFrame`'s raw cross-multiplied near-plumb predicate is
541
+ // INCLUSIVE, so for a member on the cut a single last-bit operand difference decides the branch and can
542
+ // swing an asymmetric section sharply. Two operand changes had to go (both found by Codex on #801):
534
543
  //
535
- // - normalizing here first, then letting `partFrame` normalize again. `[5, 0, √(5000²−5²)]` is
536
- // `sin θ = 1e−3` dead on and flips from the ordinary branch to the degenerate one.
544
+ // - normalizing here first, which is forbidden by AWARE #435: classification reads raw `to − from`.
537
545
  // - subtracting the PLACED endpoints. `el.from`/`el.to` are `refFrom + o` / `refTo + o` for the same
538
546
  // section-position offset, so `to − from` is not bit-identical to `refTo − refFrom`. Swept on that
539
- // same member, 98,755 of 400,000 legal offsets flipped the branch.
547
+ // same member, 99,261 of 400,000 legal offsets flipped the branch under the raw predicate.
540
548
  //
541
549
  // So `contract-to-scene` ships `refFrom`/`refTo` alongside the placed line and they are what comes in
542
550
  // here; `from`/`to` remain the fallback for a scene that predates them or an element with no authored
@@ -942,6 +950,7 @@ function buildFromScene(sc) {
942
950
  const memberCuts = cutsByMember.get(el.id);
943
951
  if (memberCuts && memberCuts.length) applyCopes(mesh, memberCuts); // notch a coped member end
944
952
  mesh.userData.id = el.id; mesh.userData.group = el.group; mesh.userData.profile = el.meta && el.meta.profile;
953
+ mesh.userData.sectionShape = el.meta?.displaySection?.shape || el.xsection?.shape || shapeOf(el).toLowerCase();
945
954
  mesh.userData.family = familyOf(el); // the selection/hover clones and the restore path need it too
946
955
  mesh.userData.axis = lengthAxisOf(el); // …and so does the axis, or a clone rebuilds a world-projected shader
947
956
  mesh.userData.derived = !!(el.kind && el.kind !== 'box'); // connection parts: rendered, not member-editable
@@ -5482,9 +5491,27 @@ function pointEntryFrame() {
5482
5491
  if (frame3d) return { kind: 'local', frame: frame3d }; // full basis already; token deep-clones it
5483
5492
  return { kind: 'global', frame: RO_IDENT }; // identity([0,0,0]) — reused, no per-call alloc
5484
5493
  }
5494
+ function positionAuthoringBasisSnapshot() {
5495
+ const p = pointEntryFrame(), f = p.frame;
5496
+ return Object.freeze({
5497
+ ok: true, kind: p.kind,
5498
+ x: Object.freeze([...f.xAxis]), y: Object.freeze([...f.yAxis]),
5499
+ generation: pointEntryGen, capabilityVersion: POSITION_BASIS_CAPABILITY_VERSION,
5500
+ });
5501
+ }
5485
5502
  // A monotonic generation: any mutation that could change the entry frame, anchor, or scene bumps it, so a
5486
5503
  // token whose gen still matches at commit is proven un-drifted (frame/anchor snapshot stays valid).
5487
5504
  let pointEntryGen = 0;
5505
+ const positionBasisListeners = new Set();
5506
+ function bumpPointEntryGen() {
5507
+ pointEntryGen++;
5508
+ for (const listener of positionBasisListeners) { try { listener(positionAuthoringBasisSnapshot()); } catch (_) {} }
5509
+ }
5510
+ function onPositionAuthoringBasisChange(listener) {
5511
+ if (typeof listener !== 'function') return () => {};
5512
+ positionBasisListeners.add(listener);
5513
+ return () => positionBasisListeners.delete(listener);
5514
+ }
5488
5515
  let pointEntryTok = null; // { consumer:'movecopy'|'add', gen, frame, kind, anchorWorld, aimWorld|null, addPhase } | null
5489
5516
  // Open: capture the frame/anchor/aim snapshot for one operation. Returns the initial HUD UI state, or null-ok.
5490
5517
  function pointEntryBegin(consumer) {
@@ -5503,12 +5530,12 @@ function pointEntryBegin(consumer) {
5503
5530
  return { ok: true, mode, locked, kind: pef.kind, primed: pef.kind !== 'global' };
5504
5531
  }
5505
5532
  function pointEntryEnd() { pointEntryTok = null; } // editor closed the HUD (not a commit) → drop the token, no gen bump
5506
- function pointEntryCommit() { pointEntryTok = null; pointEntryGen++; } // a successful commit: clear token + bump gen BEFORE the geometry callback (silent — no drift toast on the reentrant rebuild)
5533
+ function pointEntryCommit() { pointEntryTok = null; bumpPointEntryGen(); } // a successful commit: clear token + bump gen BEFORE the geometry callback (silent — no drift toast on the reentrant rebuild)
5507
5534
  // Any mutation that could change the entry frame/anchor/scene. hard = the scene/tool changed → also drop the
5508
5535
  // base/start so a stale anchor can't revalidate; soft (frame/workplane drift) keeps the world base.
5509
5536
  function invalidatePointEntry(reason) {
5510
5537
  const hadLive = !!pointEntryTok, hadStaged = !!(tfDraft && tfDraft.vA);
5511
- pointEntryGen++; pointEntryTok = null;
5538
+ bumpPointEntryGen(); pointEntryTok = null;
5512
5539
  tfLast = null; tfLastClient = null; // drop the captured aim so a reopened {dist} demands a fresh hover under the new frame (Codex R5 #1)
5513
5540
  const hard = reason === 'rebuild' || reason === 'undo' || reason === 'view' || reason === 'hide';
5514
5541
  if (hard) { cmClear3d(); drClear3d(); }
@@ -5518,7 +5545,7 @@ function invalidatePointEntry(reason) {
5518
5545
  }
5519
5546
  // A pointer base/start pick invalidates any open typed-entry token (silent — no toast): the anchor changed,
5520
5547
  // so a stale HUD from a prior phase/operation must not commit against the new draft.
5521
- function notePointerPick() { if (pointEntryTok && api && api.closeCmHud) api.closeCmHud(); pointEntryTok = null; pointEntryGen++; }
5548
+ function notePointerPick() { if (pointEntryTok && api && api.closeCmHud) api.closeCmHud(); pointEntryTok = null; bumpPointEntryGen(); }
5522
5549
  // What the tools ACTUALLY follow — a set ◇ Plane shadows the local frame, so the chip never claims Local
5523
5550
  // while a plane overrides it. Editor's Axes chip reads this in 3D. A horizontal frame reports its in-plane
5524
5551
  // angle; a tilted frame reports its tilt (normal off-vertical) — a single angle can't describe a 3D orientation.
@@ -6082,12 +6109,11 @@ function drHudApply(pv, abs) {
6082
6109
  if (r.error) return { err: r.error === 'empty' ? 'Type a coordinate (X, Y)' : 'Enter a valid value' };
6083
6110
  const p = r.point;
6084
6111
  if (t.addPhase === 'start') { // set the start; the tool stays armed for the 2nd point
6085
- pointEntryCommit(); drDraft = p; tfCandidates = null;
6112
+ pointEntryCommit(); drDraft = p; drBasisTok = positionAuthoringBasisSnapshot(); tfCandidates = null;
6086
6113
  if (readout) readout.style.display = 'none';
6087
6114
  return { ok: true };
6088
6115
  }
6089
6116
  if (!drDraft || Math.hypot(p[0] - drDraft[0], p[1] - drDraft[1], p[2] - drDraft[2]) < 0.5) return { err: 'Zero length — type a non-zero value' }; // sub-mm epsilon (typed; NOT the 50 mm pointer double-click guard)
6090
- pointEntryCommit();
6091
6117
  commitDrawPoint(p);
6092
6118
  return { ok: true };
6093
6119
  }
@@ -6095,19 +6121,26 @@ function drHudApply(pv, abs) {
6095
6121
  // ---- draw a new member on the working plane (spec §7): two plane picks → api.onAddMember3d (scene
6096
6122
  // mm); the editor maps them to wp + per-end TOS and materializes a beam or (near-vertical) column. ----
6097
6123
  let drDraft = null; // first pick, scene mm
6124
+ let drBasisTok = null; // immutable authoring-basis snapshot captured with the first point
6098
6125
  let drRubber = null;
6099
6126
  const addActive = () => !!(api && api.addModeActive && api.addModeActive());
6100
- function drClear3d() { drDraft = null; tfLock.clear(); if (drRubber) drRubber.visible = false; if (marker) marker.visible = false; if (readout) readout.style.display = 'none'; } // callable pre-init (all handles guarded); clears the shared axis lock on Add disarm (mirrors cmClear3d)
6127
+ function drClear3d() { drDraft = null; drBasisTok = null; tfLock.clear(); if (drRubber) drRubber.visible = false; if (marker) marker.visible = false; if (readout) readout.style.display = 'none'; } // callable pre-init (all handles guarded); clears the shared axis lock on Add disarm (mirrors cmClear3d)
6101
6128
  // The shared "commit the 2nd draw point" transition — used by both the pointer (drClick) and typed entry
6102
6129
  // (drHudApply). Clears local draw state BEFORE the geometry callback so the reentrant rebuild is safe.
6103
6130
  function commitDrawPoint(p2) {
6104
- const start = drDraft;
6105
- drDraft = null; tfCandidates = null; // the new member is a snap target for the NEXT one — invalidate the shared snap cache
6131
+ const start = drDraft, basis = drBasisTok;
6132
+ if (!basis || basis.generation !== pointEntryGen) {
6133
+ drDraft = null; drBasisTok = null; if (api && api.toast) api.toast('Frame changed — pick both member points again');
6134
+ return false;
6135
+ }
6136
+ drDraft = null; drBasisTok = null; tfCandidates = null; // the new member is a snap target for the NEXT one — invalidate the shared snap cache
6106
6137
  if (drRubber) drRubber.visible = false; if (readout) readout.style.display = 'none'; // stays armed for the next member
6107
- if (start && api && api.onAddMember3d) api.onAddMember3d(start, p2);
6138
+ pointEntryCommit(); // invalidate the captured generation before the re-entrant model rebuild
6139
+ if (start && api && api.onAddMember3d) api.onAddMember3d(start, p2, basis);
6140
+ return true;
6108
6141
  }
6109
6142
  function drClick(e) {
6110
- if (!drDraft) { const r0 = wpPointAt(e); if (!r0) return; notePointerPick(); drDraft = r0.p; return; } // start pick = free (bumps the gen so an open first-point typed token can't survive)
6143
+ if (!drDraft) { const r0 = wpPointAt(e); if (!r0) return; notePointerPick(); drDraft = r0.p; drBasisTok = positionAuthoringBasisSnapshot(); return; } // start pick = free (bumps the gen so an open first-point typed token can't survive)
6111
6144
  const r = drDestPoint(e); if (!r) return; // 2nd pick: X/Y/Z line-lock (or Alt normal) if locked, else free snap
6112
6145
  const p = r.p;
6113
6146
  if (Math.hypot(p[0] - drDraft[0], p[1] - drDraft[1], p[2] - drDraft[2]) < 50) return; // ~<2in — ignore a doubled click (pointer only; typed uses a sub-mm epsilon)
@@ -7178,6 +7211,7 @@ function setInputActive(on) { inputActive = on !== false; }
7178
7211
  function isReady() { return built; }
7179
7212
 
7180
7213
  function dispose() {
7214
+ positionBasisListeners.clear();
7181
7215
  // Stage D, torn down like every sibling overlay above. Without it a re-init() mints a fresh line and
7182
7216
  // label while refMeasure3d still reports armed:true against a reference id from the previous
7183
7217
  // session — a chip asking for a first point over a scene where every click is a no-op.
@@ -7280,6 +7314,13 @@ function debug() {
7280
7314
  firstId: meshById.keys().next().value ?? null,
7281
7315
  ids: [...meshById.keys()].slice(0, 12),
7282
7316
  geomTypes: [...meshById.values()].reduce((h, m) => { const t = m.geometry.type; h[t] = (h[t] || 0) + 1; return h; }, {}),
7317
+ sectionGeometry: Object.fromEntries([...meshById].map(([id, m]) => {
7318
+ if (!m.geometry.boundingBox) m.geometry.computeBoundingBox();
7319
+ const size = m.geometry.boundingBox?.getSize(new THREE.Vector3());
7320
+ return [id, { profile: m.userData.profile, shape: m.userData.sectionShape, type: m.geometry.type,
7321
+ vertices: m.geometry.attributes?.position?.count ?? 0, groups: m.geometry.groups?.length ?? 0,
7322
+ localSize: size ? [size.x, size.y, size.z] : null }];
7323
+ })),
7283
7324
  lastPick, projection: projection(), mode: displayMode,
7284
7325
  // Realistic-mode state. `envOn` is the load-bearing one: metal with no environment renders black,
7285
7326
  // so "the mode switched" is not evidence on its own — the environment has to be live.
@@ -7339,6 +7380,21 @@ function centerOf(id) {
7339
7380
  return { x: rect.left + (w.x * 0.5 + 0.5) * rect.width, y: rect.top + (-w.y * 0.5 + 0.5) * rect.height };
7340
7381
  }
7341
7382
  function worldOf(id) { const m = meshById.get(id); if (!m) return null; const w = m.getWorldPosition(new THREE.Vector3()); return [w.x, w.y, w.z]; } // test helper: a rendered part's world position
7383
+ // Test helper: the ACTUAL rendered member basis after its mesh quaternion and parent transforms. Unlike a
7384
+ // fresh `partFrame` call, this observes the object the canvas draws. BoxGeometry's width is local -X; an
7385
+ // extruded asymmetric profile uses local +X width, +Y depth, +Z member axis.
7386
+ function memberBasis(id) {
7387
+ const m = meshById.get(id); if (!m || !m.geometry) return null;
7388
+ const q = m.getWorldQuaternion(new THREE.Quaternion());
7389
+ const box = m.geometry.type === 'BoxGeometry';
7390
+ const xyz = (v) => { v.applyQuaternion(q); return [v.x, v.y, v.z]; };
7391
+ return {
7392
+ geometry: m.geometry.type,
7393
+ width: xyz(new THREE.Vector3(box ? -1 : 1, 0, 0)),
7394
+ depth: xyz(new THREE.Vector3(0, box ? 0 : 1, box ? 1 : 0)),
7395
+ axis: xyz(new THREE.Vector3(0, box ? 1 : 0, box ? 0 : 1)),
7396
+ };
7397
+ }
7342
7398
  // test helper: client (px) coords of every POINT snap candidate of `type` currently in view (members + grid, via
7343
7399
  // allCandidates) — drives precise E2E snap hovers, including grid nodes/intersections (grid-int).
7344
7400
  function snapCandidatesScreen(type) {
@@ -7471,11 +7527,11 @@ window.Steel3DView = {
7471
7527
  cameraState, setCameraState, sectionViewState, sceneBounds, objectsPaneState, applyObjectsPaneState, // saved-view snapshot surface (Views Organizer + F11 generated cuts)
7472
7528
  workAreaSetAll, workAreaFromSelection, workAreaToggle, workAreaSetWhole, clearWorkArea, workAreaState,
7473
7529
  armWorkPlanePick, setWorkPlanePrincipal, clearWorkPlane, toggleWorkPlaneVisible, workPlaneInfo,
7474
- armFrame3d, disarmFrame3d, repickFrame3d, setFrame3d, setFrameBasis, setFrameAngle, setFrameOrigin, clearFrame3d, frameInfo, frameArmed: () => frameMode, framePicking, framePickStep, frameHandlesScreen, // 3D local drawing frame (UCS stage 1)
7530
+ armFrame3d, disarmFrame3d, repickFrame3d, setFrame3d, setFrameBasis, setFrameAngle, setFrameOrigin, clearFrame3d, frameInfo, positionAuthoringBasis: positionAuthoringBasisSnapshot, onPositionAuthoringBasisChange, frameArmed: () => frameMode, framePicking, framePickStep, frameHandlesScreen, // 3D local drawing frame (UCS stage 1)
7475
7531
  coordReadout: () => { if (!readout || !readout._coord || readout.style.display === 'none' || readout._coord.style.display === 'none') return null; return { local: readout._coord.classList.contains('ro-local'), values: readout._coordV.map((v) => v.textContent), labels: readout._coordL.map((l) => l.textContent.trim()), text: readout._coord.textContent }; }, // UCS stage 2 test probe: the live local-coordinate row (null when hidden)
7476
7532
  cmEscape, cmHasBase, cmClear3d, setCmAxis, cmLastClient, cmHudApply,
7477
7533
  drHudApply, pointEntryBegin, pointEntryEnd, drHasStart: () => !!drDraft, // UCS stage 3: shared typed point-entry HUD (Move/Copy + Add)
7478
- 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
7534
+ drClear3d, drEscape: () => { if (drDraft) { drDraft = null; drBasisTok = 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
7479
7535
  toggleDimTool, setDimAxis, dimAxis, setDims3dVisible, dims3dVisible, refreshDims,
7480
7536
  setSnapOnly: setSnapOnly3d, snapOnly: () => snapOnly3d, dimToolOn: () => dimMode3d, rightDragged: () => rightMoved, // Tekla-style snap override (right-click menu lives in steel-editor.html)
7481
7537
  teklaDragging: () => !!(teklaDrag && teklaDrag.active), // a drag-out to Tekla is in flight — the editor's global Escape must leave it (and the selection) alone
@@ -7492,7 +7548,7 @@ window.Steel3DView = {
7492
7548
  selDims3dCount: () => (api && api.selDim3d ? (api.selDim3d() || []).length : 0), // test helper: how many 3D dims are selected
7493
7549
  dim3dLabelOf: (i) => { const el = dimLabelPool[i]; if (!el || el.style.display === 'none') return null; const r = el.getBoundingClientRect(); return { x: r.left + r.width / 2, y: r.top + r.height / 2, text: el.textContent }; },
7494
7550
  wireEdgeColor: (id) => { const ls = wireEdges.get(id); return ls && ls.visible && ls.parent && ls.parent.visible && ls.material ? '#' + ls.material.color.getHexString() : null; }, // test probe: the Wire-mode OUTLINE colour of a member. probe() reads the hidden FILL's emissive, which is set in every mode — so it stays green even when the outline never adopts the cue (exactly the regression this fixes); this is the only read of the line that Wire actually draws. Gated like its sibling probes: ls.visible (leaving Wire only HIDES the outline — wireEdgesFor runs on the wire branch alone — so an ungated read reports a stale Wire colour) and ls.parent.visible (group/legend/isolate/work-area hide the parent MESH, and three skips a hidden parent's children). It still cannot see clip planes, frustum culling or a display:none canvas — a false "on" is possible there, never a false "off"
7495
- debug, probe, screenOf, centerOf, worldOf, snapCandidatesScreen, referenceObjectsScreen, gridSegmentsScreen, gridBubblesScreen, clipHandlesScreen,
7551
+ debug, probe, screenOf, centerOf, worldOf, memberBasis, snapCandidatesScreen, referenceObjectsScreen, gridSegmentsScreen, gridBubblesScreen, clipHandlesScreen,
7496
7552
  clipPlanePreviewShown: () => !!clipPlanePreview, // test helper: is the armed-plane hover ghost currently showing?
7497
7553
  clipBoxFloorAt: (x, y) => clipBoxFloorPoint(x, y), // test helper: the snapped footprint point at a cursor ({ xy, snap, world } or null)
7498
7554
  pointClipped: (p) => isPointClipped(p), // test helper: is a world point on the cut-away side of any active clip?