@floless/app 0.143.0 → 0.145.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.
Files changed (52) hide show
  1. package/dist/floless-server.cjs +177602 -161132
  2. package/dist/schemas/steel.model.v2.schema.json +50 -2
  3. package/dist/schemas/tekla.model.v1.schema.json +66 -0
  4. package/dist/schemas/tekla.model.v2.schema.json +69 -0
  5. package/dist/schemas/tekla.source-package.v1.schema.json +37 -0
  6. package/dist/skills/floless-app-steel-takeoff/SKILL.md +24 -1
  7. package/dist/skills/floless-app-workflows/SKILL.md +8 -2
  8. package/dist/skills/floless-app-workflows/references/workspace-data.md +25 -4
  9. package/dist/templates/floless-workspace-model-report.flo +27 -23
  10. package/dist/templates/revit-model.flo +6 -2
  11. package/dist/templates/tekla-model-report.flo +60 -0
  12. package/dist/templates/tekla-parser.flo +61 -0
  13. package/dist/web/app.css +89 -2
  14. package/dist/web/aware.js +423 -46
  15. package/dist/web/chat.css +17 -2
  16. package/dist/web/chat.js +2 -1
  17. package/dist/web/commands-revit.js +4 -0
  18. package/dist/web/commands-shell.js +136 -3
  19. package/dist/web/commands-steel.js +6 -0
  20. package/dist/web/commands-tekla-parser.js +48 -0
  21. package/dist/web/commands.js +1 -1
  22. package/dist/web/grid-core.js +15 -0
  23. package/dist/web/index.html +43 -5
  24. package/dist/web/instructor.js +13 -3
  25. package/dist/web/left-pane.js +160 -10
  26. package/dist/web/model-artifact-loader.js +15 -0
  27. package/dist/web/model-display-units.js +89 -0
  28. package/dist/web/model-editor-revit-adapter.js +21 -4
  29. package/dist/web/model-editor.css +4 -2
  30. package/dist/web/model-measure.js +83 -22
  31. package/dist/web/model-panel-bridge.js +46 -3
  32. package/dist/web/model-pointer-dock.js +26 -1
  33. package/dist/web/model-property-display.js +91 -0
  34. package/dist/web/model-revit-module.js +9 -0
  35. package/dist/web/model-selection-tools.js +11 -0
  36. package/dist/web/model-snap-contract.js +14 -0
  37. package/dist/web/model-snapping.js +564 -139
  38. package/dist/web/model-spatial-panel.js +52 -21
  39. package/dist/web/model-structural-grid-view.js +334 -0
  40. package/dist/web/model-tekla-selection.js +32 -0
  41. package/dist/web/model-viewport-revit-adapter.js +179 -32
  42. package/dist/web/revit-editor.css +11 -1
  43. package/dist/web/revit-editor.html +4 -3
  44. package/dist/web/revit-editor.js +589 -111
  45. package/dist/web/steel-3d-view.js +58 -372
  46. package/dist/web/steel-editor.html +231 -8
  47. package/dist/web/tekla-editor.html +71 -0
  48. package/dist/web/tekla-structural-grid-adapter.js +56 -0
  49. package/dist/web/workspaces.js +872 -97
  50. package/distribution-profile-production.mjs +4 -0
  51. package/distribution-resource-inventory.mjs +4 -2
  52. package/package.json +5 -2
@@ -42,15 +42,18 @@ function button(doc, label, { action, tip, pressed = null, disabled = false } =
42
42
  return control;
43
43
  }
44
44
 
45
- function numberField(doc, label, value, name, step = '1') {
45
+ function numberField(doc, label, value, name, step = '1', presentation = null) {
46
46
  const field = doc.createElement('label'); field.className = 'model-spatial-number-field';
47
47
  const caption = doc.createElement('span'); caption.textContent = label;
48
- const input = doc.createElement('input'); input.type = 'number'; input.step = step; input.value = rounded(value); input.dataset.field = name;
48
+ const input = doc.createElement('input'); input.type = presentation ? 'text' : 'number';
49
+ if (!presentation) input.step = step;
50
+ input.value = presentation ? presentation.format(value) : rounded(value); input.dataset.field = name;
51
+ if (presentation) { input.dataset.displayText = input.value; input.dataset.originalMm = String(value); }
49
52
  input.setAttribute('aria-label', label); field.append(caption, input); return field;
50
53
  }
51
54
 
52
- function vectorFields(doc, host, prefix, values, names = ['X', 'Y', 'Z']) {
53
- values.forEach((value, index) => host.append(numberField(doc, names[index], value, `${prefix}-${index}`)));
55
+ function vectorFields(doc, host, prefix, values, names = ['X', 'Y', 'Z'], presentation = null) {
56
+ values.forEach((value, index) => host.append(numberField(doc, names[index], value, `${prefix}-${index}`, '1', presentation)));
54
57
  }
55
58
 
56
59
  function valuesFrom(host, prefix, label) {
@@ -68,16 +71,35 @@ function actionRow(doc) { const row = doc.createElement('div'); row.className =
68
71
 
69
72
  /**
70
73
  * @param {{tools:any, trigger:HTMLElement, ports?:Record<string,Function>, documentRef?:Document,
71
- * windowRef?:Window, onBeforeOpen?:()=>void, onError?:(error:Error)=>void}} options
74
+ * windowRef?:Window, onBeforeOpen?:()=>void, onError?:(error:Error)=>void,
75
+ * lengthDisplay?:{format:(mm:number)=>string,parse:(text:string)=>number|null,unitLabel:()=>string}} options
72
76
  */
73
77
  export function mountModelSpatialPanel({
74
78
  tools, trigger, ports = {}, documentRef = document, windowRef = window, onError = () => {},
75
- onBeforeOpen = () => {},
79
+ onBeforeOpen = () => {}, lengthDisplay = null,
76
80
  }) {
77
81
  if (!tools?.state || !tools?.subscribe || !tools?.activeFrame) throw new TypeError('Spatial panel requires createModelSpatialTools APIs.');
78
82
  if (!trigger?.addEventListener) throw new TypeError('Spatial panel requires a trigger element.');
83
+ if (lengthDisplay && (typeof lengthDisplay.format !== 'function' || typeof lengthDisplay.parse !== 'function' || typeof lengthDisplay.unitLabel !== 'function')) {
84
+ throw new TypeError('Spatial panel length display requires format, parse, and unitLabel functions.');
85
+ }
79
86
  const panelId = `modelSpatialPanel-${++panelSequence}`;
80
87
  let dialog = null, body = null, status = null, destroyed = false;
88
+ const units = () => lengthDisplay ? String(lengthDisplay.unitLabel()) : 'mm';
89
+ const formattedLength = (mm) => lengthDisplay ? String(lengthDisplay.format(mm)) : rounded(mm);
90
+ const lengthPresentation = lengthDisplay ? { format: formattedLength } : null;
91
+ const readLength = (source, label) => {
92
+ const text = typeof source === 'string' ? source : source?.value;
93
+ if (!lengthDisplay) return finite(text, label);
94
+ // Architectural strings round to sixteenths. An untouched field is the original canonical
95
+ // quantity, so clicking Apply to change another field must not move this one by the rounding gap.
96
+ if (typeof source !== 'string' && source?.dataset?.displayText === text) return Number(source.dataset.originalMm);
97
+ const mm = lengthDisplay.parse(text);
98
+ if (typeof mm !== 'number' || !Number.isFinite(mm)) throw new TypeError(`${label} must be a finite length.`);
99
+ return mm;
100
+ };
101
+ const lengthValuesFrom = (host, prefix, label) => [0, 1, 2].map((index) =>
102
+ readLength(host.querySelector(`[data-field="${prefix}-${index}"]`), `${label} ${'XYZ'[index]}`));
81
103
 
82
104
  trigger.setAttribute('aria-haspopup', 'dialog'); trigger.setAttribute('aria-controls', panelId); trigger.setAttribute('aria-expanded', 'false');
83
105
 
@@ -98,7 +120,7 @@ export function mountModelSpatialPanel({
98
120
  const frameSection = section(documentRef, 'Coordinate frame');
99
121
  const summary = documentRef.createElement('div'); summary.className = 'model-spatial-panel-summary';
100
122
  const active = tools.activeFrame(); const label = documentRef.createElement('strong'); label.textContent = active.label;
101
- const origin = documentRef.createElement('span'); origin.textContent = `Origin ${active.origin.map((value) => rounded(value)).join(', ')} mm`;
123
+ const origin = documentRef.createElement('span'); origin.textContent = `Origin ${active.origin.map(formattedLength).join(', ')} ${units()}`;
102
124
  summary.append(label, origin); frameSection.append(summary);
103
125
 
104
126
  const frameActions = actionRow(documentRef);
@@ -122,15 +144,15 @@ export function mountModelSpatialPanel({
122
144
  const local = state.frames.find((item) => item.id === 'local') || state.frames.find((item) => item.id === 'global');
123
145
  const rotation = eulerDegreesFromFrame(local);
124
146
  const localGrid = documentRef.createElement('div'); localGrid.className = 'model-spatial-panel-grid';
125
- const originLabel = documentRef.createElement('div'); originLabel.className = 'model-spatial-panel-grid-label'; originLabel.textContent = 'Local origin · mm';
126
- localGrid.append(originLabel); vectorFields(documentRef, localGrid, 'local-origin', local.origin);
147
+ const originLabel = documentRef.createElement('div'); originLabel.className = 'model-spatial-panel-grid-label'; originLabel.textContent = `Local origin · ${units()}`;
148
+ localGrid.append(originLabel); vectorFields(documentRef, localGrid, 'local-origin', local.origin, ['X', 'Y', 'Z'], lengthPresentation);
127
149
  const rotationLabel = documentRef.createElement('div'); rotationLabel.className = 'model-spatial-panel-grid-label'; rotationLabel.textContent = 'Rotation · degrees';
128
150
  localGrid.append(rotationLabel); vectorFields(documentRef, localGrid, 'local-rotation', rotation, ['X°', 'Y°', 'Z°']);
129
151
  frameSection.append(localGrid);
130
152
  const localActions = actionRow(documentRef);
131
153
  const apply = button(documentRef, 'Apply local frame', { action: 'frame-local-apply', tip: 'Create or update the local frame from these numeric values' });
132
154
  apply.addEventListener('click', () => run(() => {
133
- const nextOrigin = valuesFrom(frameSection, 'local-origin', 'Local origin');
155
+ const nextOrigin = lengthValuesFrom(frameSection, 'local-origin', 'Local origin');
134
156
  const nextRotation = valuesFrom(frameSection, 'local-rotation', 'Local rotation');
135
157
  tools.setLocalTransform({ origin: nextOrigin, ...axesFromEulerDegrees(...nextRotation) });
136
158
  }, 'Local frame active.'));
@@ -139,11 +161,18 @@ export function mountModelSpatialPanel({
139
161
  if (typeof ports.acceptCoordinates === 'function') {
140
162
  const coordinateSection = section(documentRef, 'Typed coordinates');
141
163
  const coordinateRow = documentRef.createElement('div'); coordinateRow.className = 'model-spatial-coordinate-row';
142
- const input = documentRef.createElement('input'); input.type = 'text'; input.dataset.field = 'typed-coordinates'; input.placeholder = 'X, Y, Z or @dX, dY, dZ'; input.setAttribute('aria-label', 'Absolute or relative coordinates in the active frame');
164
+ const input = documentRef.createElement('input'); input.type = 'text'; input.dataset.field = 'typed-coordinates'; input.placeholder = 'X, Y, Z or @dX, dY, dZ'; input.setAttribute('aria-label', `Absolute or relative coordinates in the active frame (${units()})`);
143
165
  const accept = button(documentRef, 'Accept point', { action: 'coordinate-accept', tip: 'Accept absolute coordinates, or prefix with @ for a relative offset' });
144
166
  accept.addEventListener('click', () => run(() => {
145
167
  const basePoint = typeof ports.coordinateBasePoint === 'function' ? ports.coordinateBasePoint() : undefined;
146
- const point = tools.parseCoordinates(input.value, basePoint);
168
+ let text = input.value;
169
+ if (lengthDisplay) {
170
+ const raw = text.trim(), relative = raw.startsWith('@');
171
+ const parts = (relative ? raw.slice(1) : raw).split(',').map((part) => part.trim());
172
+ if (parts.length !== 3) throw new TypeError('Enter X, Y, Z as three finite lengths.');
173
+ text = `${relative ? '@' : ''}${parts.map((part, axis) => readLength(part, `Coordinate ${'XYZ'[axis]}`)).join(',')}`;
174
+ }
175
+ const point = tools.parseCoordinates(text, basePoint);
147
176
  return ports.acceptCoordinates(point, { relative: input.value.trim().startsWith('@'), frame: tools.activeFrame() });
148
177
  }, 'Coordinate accepted.'));
149
178
  input.addEventListener('keydown', (event) => { if (event.key === 'Enter') { event.preventDefault(); accept.click(); } });
@@ -154,10 +183,10 @@ export function mountModelSpatialPanel({
154
183
  function renderWorkPlane(root, state) {
155
184
  const planeSection = section(documentRef, 'Working plane');
156
185
  const controls = documentRef.createElement('div'); controls.className = 'model-spatial-panel-inline';
157
- const offset = numberField(documentRef, 'Offset · mm', state.workPlane?.offsetMm ?? 0, 'plane-offset'); controls.append(offset);
186
+ const offset = numberField(documentRef, `Offset · ${units()}`, state.workPlane?.offsetMm ?? 0, 'plane-offset', '1', lengthPresentation); controls.append(offset);
158
187
  for (const plane of ['xy', 'xz', 'yz']) {
159
188
  const control = button(documentRef, plane.toUpperCase(), { action: `plane-${plane}`, tip: `Set the principal ${plane.toUpperCase()} working plane`, pressed: state.workPlane?.principal === plane });
160
- control.addEventListener('click', () => run(() => tools.setPrincipalWorkPlane({ plane, offsetMm: finite(offset.querySelector('input').value, 'Working-plane offset') }), `${plane.toUpperCase()} working plane active.`));
189
+ control.addEventListener('click', () => run(() => tools.setPrincipalWorkPlane({ plane, offsetMm: readLength(offset.querySelector('input'), 'Working-plane offset') }), `${plane.toUpperCase()} working plane active.`));
161
190
  controls.append(control);
162
191
  }
163
192
  planeSection.append(controls);
@@ -190,17 +219,17 @@ export function mountModelSpatialPanel({
190
219
  const identity = documentRef.createElement('code'); identity.textContent = clip.id; heading.append(name, identity); card.append(heading);
191
220
  const grid = documentRef.createElement('div'); grid.className = 'model-spatial-panel-grid';
192
221
  if (clip.kind === 'plane') {
193
- const a = documentRef.createElement('div'); a.className = 'model-spatial-panel-grid-label'; a.textContent = 'Origin · mm'; grid.append(a); vectorFields(documentRef, grid, 'clip-origin', clip.origin);
222
+ const a = documentRef.createElement('div'); a.className = 'model-spatial-panel-grid-label'; a.textContent = `Origin · ${units()}`; grid.append(a); vectorFields(documentRef, grid, 'clip-origin', clip.origin, ['X', 'Y', 'Z'], lengthPresentation);
194
223
  const b = documentRef.createElement('div'); b.className = 'model-spatial-panel-grid-label'; b.textContent = 'Normal'; grid.append(b); vectorFields(documentRef, grid, 'clip-normal', clip.normal);
195
224
  } else {
196
- const a = documentRef.createElement('div'); a.className = 'model-spatial-panel-grid-label'; a.textContent = 'Minimum · mm'; grid.append(a); vectorFields(documentRef, grid, 'clip-min', clip.min);
197
- const b = documentRef.createElement('div'); b.className = 'model-spatial-panel-grid-label'; b.textContent = 'Maximum · mm'; grid.append(b); vectorFields(documentRef, grid, 'clip-max', clip.max);
225
+ const a = documentRef.createElement('div'); a.className = 'model-spatial-panel-grid-label'; a.textContent = `Minimum · ${units()}`; grid.append(a); vectorFields(documentRef, grid, 'clip-min', clip.min, ['X', 'Y', 'Z'], lengthPresentation);
226
+ const b = documentRef.createElement('div'); b.className = 'model-spatial-panel-grid-label'; b.textContent = `Maximum · ${units()}`; grid.append(b); vectorFields(documentRef, grid, 'clip-max', clip.max, ['X', 'Y', 'Z'], lengthPresentation);
198
227
  }
199
228
  card.append(grid); const actions = actionRow(documentRef);
200
229
  const update = button(documentRef, 'Update', { action: 'clip-update', tip: `Apply edited values to ${name.textContent}` });
201
230
  update.addEventListener('click', () => run(() => tools.updateClip(clip.id, clip.kind === 'plane'
202
- ? { origin: valuesFrom(card, 'clip-origin', 'Clip origin'), normal: valuesFrom(card, 'clip-normal', 'Clip normal') }
203
- : { min: valuesFrom(card, 'clip-min', 'Clip minimum'), max: valuesFrom(card, 'clip-max', 'Clip maximum') }), 'Clip updated.'));
231
+ ? { origin: lengthValuesFrom(card, 'clip-origin', 'Clip origin'), normal: valuesFrom(card, 'clip-normal', 'Clip normal') }
232
+ : { min: lengthValuesFrom(card, 'clip-min', 'Clip minimum'), max: lengthValuesFrom(card, 'clip-max', 'Clip maximum') }), 'Clip updated.'));
204
233
  const remove = button(documentRef, 'Remove', { action: 'clip-remove', tip: `Remove ${name.textContent}` });
205
234
  remove.addEventListener('click', () => run(() => tools.removeClip(clip.id), 'Clip removed.'));
206
235
  const enabled = button(documentRef, clip.enabled === false ? 'Disabled' : 'Enabled', { action: 'clip-enabled', tip: `Enable or disable ${name.textContent}`, pressed: clip.enabled !== false });
@@ -219,7 +248,7 @@ export function mountModelSpatialPanel({
219
248
  if (!area) { areaSection.append(note(documentRef, 'No work area. Create one from the model or current selection in the toolbar.')); root.append(areaSection); return; }
220
249
  const bounds = documentRef.createElement('div'); bounds.className = 'model-spatial-panel-summary';
221
250
  const label = documentRef.createElement('strong'); label.textContent = area.wholeParts ? 'Whole intersecting parts' : 'Physical section cut';
222
- const value = documentRef.createElement('span'); value.textContent = `${area.min.map(rounded).join(', ')} → ${area.max.map(rounded).join(', ')} mm`; bounds.append(label, value); areaSection.append(bounds);
251
+ const value = documentRef.createElement('span'); value.textContent = `${area.min.map(formattedLength).join(', ')} → ${area.max.map(formattedLength).join(', ')} ${units()}`; bounds.append(label, value); areaSection.append(bounds);
223
252
  const actions = actionRow(documentRef);
224
253
  const whole = button(documentRef, 'Whole parts', { action: 'area-whole', tip: 'Show complete parts intersecting the work area', pressed: area.wholeParts });
225
254
  whole.addEventListener('click', () => run(() => tools.setWorkAreaWhole(true)));
@@ -234,7 +263,9 @@ export function mountModelSpatialPanel({
234
263
  function paint(state = tools.state()) {
235
264
  const active = tools.activeFrame(); trigger.textContent = active.label; trigger.setAttribute('aria-label', `Spatial controls. Active frame: ${active.label}`);
236
265
  if (!body) return;
266
+ const scrollTop = body.scrollTop;
237
267
  body.replaceChildren(); renderFrame(body, state); renderWorkPlane(body, state); renderClips(body, state); renderWorkArea(body, state);
268
+ body.scrollTop = scrollTop;
238
269
  }
239
270
 
240
271
  function position() {
@@ -284,7 +315,7 @@ export function mountModelSpatialPanel({
284
315
  const unsubscribe = tools.subscribe((state) => paint(state));
285
316
 
286
317
  return Object.freeze({
287
- open, close, toggle, isOpen: () => !!dialog,
318
+ open, close, toggle, isOpen: () => !!dialog, refreshDisplay: () => { if (!destroyed) paint(); },
288
319
  destroy() {
289
320
  if (destroyed) return; destroyed = true; close({ restoreFocus: false }); unsubscribe();
290
321
  trigger.removeEventListener('click', triggerClick); documentRef.removeEventListener('pointerdown', outside); windowRef.removeEventListener?.('resize', resize);
@@ -0,0 +1,334 @@
1
+ import * as THREE from 'three';
2
+ import {
3
+ clipSegmentToPlanes, gridDepthWins, perspectiveSegmentParameter,
4
+ projectPointOnSegment2d, SEG_DEGENERACY, segmentHitsRect2d,
5
+ } from './steel-3d-core.js';
6
+ import { gridGeometry, gridLevelKey, normalizeHiddenLevels } from './grid-core.js';
7
+
8
+ const LABEL_MIN_GAP = 1.05;
9
+ const LABEL_MAX_STANDOFF = 60;
10
+ const DEFAULT_LABEL_PX = 26;
11
+
12
+ const planeSpecs = (planes = []) => planes.map((plane) => ({
13
+ normal: [plane.normal.x, plane.normal.y, plane.normal.z], constant: plane.constant,
14
+ }));
15
+
16
+ const finiteBox = (box) => box && !box.isEmpty() ? box : null;
17
+
18
+ /**
19
+ * The one structural-grid presentation used by every model viewport.
20
+ *
21
+ * Hosts provide camera/scene mechanics and mesh candidates. This object alone owns grid Three.js
22
+ * objects, labels, clipping, point/marquee hits, grid/mesh arbitration, paint, bounds and disposal.
23
+ */
24
+ export function createModelStructuralGridView(options) {
25
+ if (!options?.scene || !options?.labelScene || typeof options.getCamera !== 'function'
26
+ || typeof options.getCanvas !== 'function') throw new TypeError('Structural grid view needs scenes, camera and canvas.');
27
+ const scene = options.scene; const labelScene = options.labelScene;
28
+ const getCamera = options.getCamera; const getCanvas = options.getCanvas;
29
+ const getClipPlanes = options.getClipPlanes ?? (() => []);
30
+ const lines = new Map(); const textures = new Map();
31
+ let lineGroup = null; let labelGroup = null; let levels = []; let allLevels = []; let hiddenLevels = [];
32
+ let renderPoint = null;
33
+ let selected = new Set(); let hidden = new Set(); let isolated = null;
34
+ let labelPx = Number.isFinite(options.labelPx) ? options.labelPx : DEFAULT_LABEL_PX;
35
+ let anchorWarning = false; let badScaleWarning = false;
36
+ const aScratch = new THREE.Vector3(); const bScratch = new THREE.Vector3(); const depthScratch = new THREE.Vector3();
37
+
38
+ const camera = () => getCamera();
39
+ const canvas = () => getCanvas();
40
+ const vector = (p) => p instanceof THREE.Vector3 ? p.clone() : new THREE.Vector3(...p);
41
+ const disposeObject = (object) => { object.geometry?.dispose?.(); object.material?.dispose?.(); };
42
+
43
+ function clear() {
44
+ if (lineGroup) { for (const child of [...lineGroup.children]) { lineGroup.remove(child); disposeObject(child); } scene.remove(lineGroup); }
45
+ if (labelGroup) { for (const child of [...labelGroup.children]) { labelGroup.remove(child); disposeObject(child); } labelScene.remove(labelGroup); }
46
+ lineGroup = null; labelGroup = null; levels = []; allLevels = []; hiddenLevels = []; renderPoint = null; lines.clear();
47
+ }
48
+
49
+ function bubbleTexture(label) {
50
+ const key = `b:${label}`; if (textures.has(key)) return textures.get(key);
51
+ const size = 256; const cv = document.createElement('canvas'); cv.width = cv.height = size;
52
+ const g = cv.getContext('2d'); const radius = size / 2 - 10;
53
+ g.beginPath(); g.arc(size / 2, size / 2, radius, 0, Math.PI * 2); g.fillStyle = '#0f172a'; g.fill();
54
+ g.lineWidth = 10; g.strokeStyle = '#64748b'; g.stroke(); g.fillStyle = '#e2e8f0';
55
+ g.font = 'bold 100px system-ui'; const em = g.measureText(label).width / 100; const inner = radius - 10;
56
+ const fontSize = Math.min(120, .95 * inner / Math.sqrt(em * em / 4 + .1296));
57
+ g.font = `bold ${fontSize}px system-ui`; g.textAlign = 'center'; g.textBaseline = 'middle';
58
+ g.fillText(label, size / 2, size / 2 + 4);
59
+ const texture = new THREE.CanvasTexture(cv); textures.set(key, texture); return texture;
60
+ }
61
+
62
+ function tagTexture(label) {
63
+ const key = `t:${label}`; if (textures.has(key)) return textures.get(key);
64
+ const width = 512; const height = 80; const cv = document.createElement('canvas'); cv.width = width; cv.height = height;
65
+ const g = cv.getContext('2d'); g.beginPath(); g.roundRect(4, 4, width - 8, height - 8, 14);
66
+ g.fillStyle = '#0f172a'; g.fill(); g.lineWidth = 4; g.strokeStyle = '#64748b'; g.stroke(); g.fillStyle = '#94a3b8';
67
+ let fontSize = 40; g.font = `bold ${fontSize}px system-ui`;
68
+ while (fontSize > 12 && g.measureText(label).width > width - 28) { fontSize -= 2; g.font = `bold ${fontSize}px system-ui`; }
69
+ g.textAlign = 'center'; g.textBaseline = 'middle'; g.fillText(label, width / 2, height / 2 + 2, width - 28);
70
+ const texture = new THREE.CanvasTexture(cv); textures.set(key, texture); return texture;
71
+ }
72
+
73
+ function build({ grid, geometry = null, mmPerPx = 1, geometryOptions = { yUp: true }, scale = 1, flipY = false,
74
+ canonicalToRenderPoint = null, selectedIds = selected } = {}) {
75
+ clear(); selected = new Set(selectedIds ?? []);
76
+ if (!grid) return false;
77
+ geometry ??= gridGeometry(grid, mmPerPx, geometryOptions);
78
+ const drawable = geometry.v?.length || geometry.h?.length || geometry.lines?.length;
79
+ if (!drawable) return false;
80
+ const mx = (value) => value * scale; const my = (value) => (flipY ? -value : value) * scale;
81
+ allLevels = (geometry.zs?.length ? geometry.zs.map((level) => ({ ...level }))
82
+ : [{ mm: 0, label: '0', authored: '', sourceIndex: 0, fallback: true }])
83
+ .sort((left, right) => left.mm - right.mm);
84
+ lineGroup = new THREE.Group(); lineGroup.userData.structuralGrid = true;
85
+ renderPoint = (x, y, z) => vector(canonicalToRenderPoint
86
+ ? canonicalToRenderPoint([x, y, z])
87
+ : [mx(x), my(y), z]);
88
+ const addLine = (id, ends) => {
89
+ const focused = selected.has(id);
90
+ const line = new THREE.LineSegments(new THREE.BufferGeometry(), new THREE.LineDashedMaterial({
91
+ color: focused ? 0x3b82f6 : 0x64748b, dashSize: 450, gapSize: 220, transparent: true, opacity: focused ? 1 : .85,
92
+ }));
93
+ line.userData.gridId = id; line.userData.canonicalEnds = ends;
94
+ lines.set(id, line); lineGroup.add(line);
95
+ };
96
+ for (const [index, line] of (geometry.v ?? []).entries()) addLine(line.id ?? `gv:${index}`, [[line.x, line.lo], [line.x, line.hi]]);
97
+ for (const [index, line] of (geometry.h ?? []).entries()) addLine(line.id ?? `gh:${index}`, [[line.lo, line.y], [line.hi, line.y]]);
98
+ for (const [index, line] of (geometry.lines ?? []).entries()) addLine(line.id ?? `gl:${index}`, [line.a, line.b]);
99
+ scene.add(lineGroup);
100
+
101
+ labelGroup = new THREE.Group(); labelGroup.userData.structuralGridLabels = true;
102
+ const sprite = (texture, label, id) => {
103
+ const value = new THREE.Sprite(new THREE.SpriteMaterial({ map: texture, depthTest: true, depthWrite: false, transparent: true }));
104
+ value.userData.label = String(label ?? ''); value.userData.gridId = id ?? null; value.renderOrder = 994; labelGroup.add(value); return value;
105
+ };
106
+ const bubble = (label, id, ax, ay, ox, oy) => {
107
+ const value = sprite(bubbleTexture(label), label, id);
108
+ value.userData.anchorXY = [ax, ay]; value.userData.otherXY = [ox, oy]; value.userData.levelAllowed = false;
109
+ };
110
+ for (const [index, line] of (geometry.v ?? []).entries()) { const id = line.id ?? `gv:${index}`; bubble(line.label, id, line.x, line.lo, line.x, line.hi); bubble(line.label, id, line.x, line.hi, line.x, line.lo); }
111
+ for (const [index, line] of (geometry.h ?? []).entries()) { const id = line.id ?? `gh:${index}`; bubble(line.label, id, line.lo, line.y, line.hi, line.y); bubble(line.label, id, line.hi, line.y, line.lo, line.y); }
112
+ for (const [index, line] of (geometry.lines ?? []).entries()) { const id = line.id ?? `gl:${index}`; bubble(line.label, id, line.a[0], line.a[1], line.b[0], line.b[1]); bubble(line.label, id, line.b[0], line.b[1], line.a[0], line.a[1]); }
113
+ for (const level of allLevels) {
114
+ const value = sprite(tagTexture(level.label), level.label, null); value.userData.anchor = renderPoint(geometry.x0, geometry.y1, level.mm);
115
+ value.userData.tagAspect = 4.8; value.userData.levelKey = gridLevelKey(level.mm); value.position.copy(value.userData.anchor);
116
+ }
117
+ labelScene.add(labelGroup); setHiddenLevels(grid.hidden_z ?? []); return true;
118
+ }
119
+
120
+ function levelInfo() {
121
+ const hiddenKeys = new Set(hiddenLevels.map(gridLevelKey));
122
+ return allLevels.map((level) => ({ key: gridLevelKey(level.mm), mm: level.mm, label: level.label,
123
+ authored: level.authored ?? '', fallback: level.fallback === true, visible: !hiddenKeys.has(gridLevelKey(level.mm)) }));
124
+ }
125
+
126
+ function setHiddenLevels(values = []) {
127
+ hiddenLevels = normalizeHiddenLevels(values, allLevels);
128
+ const hiddenKeys = new Set(hiddenLevels.map(gridLevelKey));
129
+ const visibleLevels = allLevels.filter((level) => !hiddenKeys.has(gridLevelKey(level.mm)));
130
+ levels = visibleLevels.map((level) => level.mm);
131
+ for (const line of lines.values()) {
132
+ const visiblePoints = []; const completePoints = []; const ends = line.userData.canonicalEnds ?? [];
133
+ if (ends.length === 2) {
134
+ for (const level of allLevels) {
135
+ completePoints.push(renderPoint(ends[0][0], ends[0][1], level.mm), renderPoint(ends[1][0], ends[1][1], level.mm));
136
+ }
137
+ for (const level of visibleLevels) {
138
+ visiblePoints.push(renderPoint(ends[0][0], ends[0][1], level.mm), renderPoint(ends[1][0], ends[1][1], level.mm));
139
+ }
140
+ }
141
+ line.geometry.dispose(); line.geometry = new THREE.BufferGeometry().setFromPoints(visiblePoints);
142
+ line.computeLineDistances(); line.userData.segments = visiblePoints.map((point) => point.toArray());
143
+ line.userData.completeSegments = completePoints.map((point) => point.toArray());
144
+ line.userData.levelVisible = visibleLevels.length > 0;
145
+ }
146
+ const bubbleLevel = visibleLevels[0] ?? null;
147
+ if (labelGroup) for (const label of labelGroup.children) {
148
+ if (label.userData.gridId) {
149
+ label.userData.levelAllowed = bubbleLevel !== null;
150
+ if (bubbleLevel) {
151
+ const [ax, ay] = label.userData.anchorXY; const [ox, oy] = label.userData.otherXY;
152
+ label.userData.anchor = renderPoint(ax, ay, bubbleLevel.mm); const other = renderPoint(ox, oy, bubbleLevel.mm);
153
+ label.userData.outward = label.userData.anchor.clone().sub(other).normalize();
154
+ if (!Number.isFinite(label.userData.outward.x) || label.userData.outward.lengthSq() < 1e-12) label.userData.outward.set(1, 0, 0);
155
+ label.position.copy(label.userData.anchor);
156
+ }
157
+ } else label.userData.levelAllowed = !hiddenKeys.has(label.userData.levelKey);
158
+ }
159
+ setVisibility({ hiddenIds: hidden, isolatedIds: isolated });
160
+ }
161
+
162
+ function pxToWorld(px, position) {
163
+ const cam = camera(); const el = canvas();
164
+ if (cam?.isOrthographicCamera) return px * ((cam.top - cam.bottom) / Math.max(1, el?.clientHeight ?? 1)) / (cam.zoom || 1);
165
+ const depth = -depthScratch.copy(position).applyMatrix4(cam.matrixWorldInverse).z;
166
+ if (!(depth > 0) || !Number.isFinite(depth)) return 0;
167
+ return px * (2 * Math.tan(THREE.MathUtils.degToRad(cam.fov) / 2) * depth) / Math.max(1, el?.clientHeight ?? 1);
168
+ }
169
+ function screenPxPerWorld(from, direction, length, width, height) {
170
+ if (!(length > 0)) return null;
171
+ aScratch.copy(from).project(camera()); bScratch.copy(from).addScaledVector(direction, length).project(camera());
172
+ if (![aScratch.x, aScratch.y, bScratch.x, bScratch.y].every(Number.isFinite)) return null;
173
+ return Math.hypot((bScratch.x - aScratch.x) * .5 * width, (bScratch.y - aScratch.y) * .5 * height) / length;
174
+ }
175
+
176
+ function resizeLabels() {
177
+ const activePlanes = getClipPlanes();
178
+ for (const line of lines.values()) if (line.material.clippingPlanes !== activePlanes) line.material.clippingPlanes = activePlanes;
179
+ const cam = camera(); const el = canvas(); if (!labelGroup?.children.length || !cam || !el) return;
180
+ const width = el.clientWidth || 1; const height = el.clientHeight || 1; cam.updateMatrixWorld(); const placed = [];
181
+ for (const sprite of labelGroup.children) {
182
+ const data = sprite.userData;
183
+ if (!data?.anchor) { if (!anchorWarning) { anchorWarning = true; console.warn('[structural-grid] label has no anchor'); } continue; }
184
+ sprite.visible = data.allowed !== false; if (!sprite.visible) continue;
185
+ const diameter = pxToWorld(labelPx, data.anchor);
186
+ // A label can briefly sit behind the camera while the model is fitting. That is a normal
187
+ // render transition, not a broken grid; leave it hidden until the next resize pass.
188
+ if (!(diameter > 0) || !Number.isFinite(diameter)) {
189
+ if (!badScaleWarning) {
190
+ badScaleWarning = true;
191
+ console.warn('[structural-grid] label size is invalid — keeping the last good size (check the camera frustum)');
192
+ }
193
+ continue;
194
+ }
195
+ if (data.tagAspect) { const w = diameter * data.tagAspect; const h = diameter * .75; const gap = diameter * .4; sprite.scale.set(w, h, 1); sprite.position.set(data.anchor.x - w / 2 - gap, data.anchor.y + h / 2 + gap, data.anchor.z); continue; }
196
+ const ratio = screenPxPerWorld(data.anchor, data.outward, diameter, width, height);
197
+ const wanted = ratio !== null && ratio > 1e-9 ? Math.max((labelPx / 2) / ratio, diameter / 2) : diameter / 2;
198
+ const standoff = Math.min(wanted, diameter / 2 * LABEL_MAX_STANDOFF);
199
+ sprite.position.copy(data.anchor).addScaledVector(data.outward, standoff);
200
+ if (standoff < wanted * .999) { sprite.visible = false; continue; }
201
+ const finalDiameter = pxToWorld(labelPx, sprite.position); sprite.scale.setScalar(finalDiameter > 0 ? finalDiameter : diameter); sprite.scale.z = 1; placed.push(sprite);
202
+ }
203
+ // One logical grid line is drawn at every visible level while its bubbles sit at the base level.
204
+ // Hide a bubble when another level of its own line crosses inside the rim; a crossed-out label is
205
+ // less useful than an intentionally omitted one and cannot be fixed by moving the one base bubble.
206
+ const projectedSegments = new Map();
207
+ for (const [id, line] of lines) {
208
+ if (!line.visible) continue; const values = []; const points = line.userData.segments ?? [];
209
+ for (let index = 0; index + 1 < points.length; index += 2) {
210
+ const segment = trimmed(points[index], points[index + 1]); if (!segment) continue;
211
+ const a = vector(segment[0]).project(cam); const b = vector(segment[1]).project(cam);
212
+ if (![a.x, a.y, b.x, b.y].every(Number.isFinite) || a.z < -1 || a.z > 1 || b.z < -1 || b.z > 1) continue;
213
+ values.push([(a.x * .5 + .5) * width, (-a.y * .5 + .5) * height,
214
+ (b.x * .5 + .5) * width, (-b.y * .5 + .5) * height]);
215
+ }
216
+ if (values.length) projectedSegments.set(id, values);
217
+ }
218
+ const survivors = [];
219
+ for (const sprite of placed) {
220
+ const p = aScratch.copy(sprite.position).project(cam);
221
+ if (![p.x, p.y, p.z].every(Number.isFinite) || p.z < -1 || p.z > 1) { survivors.push(sprite); continue; }
222
+ const x = (p.x * .5 + .5) * width; const y = (-p.y * .5 + .5) * height;
223
+ const crossed = (projectedSegments.get(sprite.userData.gridId) ?? []).some((segment) =>
224
+ projectPointOnSegment2d([x, y], segment.slice(0, 2), segment.slice(2), SEG_DEGENERACY.atMost(0)).distance < labelPx / 2 - 1.5);
225
+ if (crossed) sprite.visible = false; else survivors.push(sprite);
226
+ }
227
+ placed.length = 0; placed.push(...survivors);
228
+ if (selected.size) placed.sort((left, right) => Number(selected.has(right.userData.gridId)) - Number(selected.has(left.userData.gridId)));
229
+ const kept = []; const min = labelPx * LABEL_MIN_GAP;
230
+ for (const sprite of placed) {
231
+ const p = aScratch.copy(sprite.position).project(cam); if (![p.x, p.y, p.z].every(Number.isFinite) || p.z < -1 || p.z > 1) continue;
232
+ const x = (p.x * .5 + .5) * width; const y = (-p.y * .5 + .5) * height;
233
+ if (kept.some((prior) => Math.hypot(prior.x - x, prior.y - y) < min)) { sprite.visible = false; continue; }
234
+ kept.push({ x, y });
235
+ }
236
+ labelGroup.updateMatrixWorld(true);
237
+ }
238
+
239
+ function setVisibility({ hiddenIds = hidden, isolatedIds = isolated } = {}) {
240
+ hidden = new Set(hiddenIds ?? []); isolated = isolatedIds == null ? null : new Set(isolatedIds); let any = false;
241
+ for (const [id, line] of lines) { line.visible = line.userData.levelVisible !== false && (isolated === null || isolated.has(id)) && !hidden.has(id); any ||= line.visible; }
242
+ if (labelGroup) for (const label of labelGroup.children) { const id = label.userData.gridId; const allowed = label.userData.levelAllowed !== false
243
+ && (id ? (isolated === null || isolated.has(id)) && !hidden.has(id) : any); label.userData.allowed = allowed; label.visible = allowed; }
244
+ resizeLabels();
245
+ }
246
+
247
+ function applyPaint({ selectedIds = selected, ghost = null } = {}) {
248
+ selected = new Set(selectedIds ?? []); const active = ghost?.active === true; const focus = new Set(ghost?.focusIds ?? []); const opacity = ghost?.opacity ?? .18;
249
+ for (const [id, line] of lines) { const focused = active ? focus.has(id) : selected.has(id); const faded = active && !focused; line.material.color.setHex(focused ? 0x3b82f6 : 0x64748b); line.material.transparent = faded || !focused; line.material.opacity = faded ? opacity : focused ? 1 : .85; line.material.depthWrite = !faded; }
250
+ if (labelGroup) for (const label of labelGroup.children) { const id = label.userData.gridId; const faded = active && (id ? !focus.has(id) : !focus.size); label.material.transparent = true; label.material.opacity = faded ? opacity : 1; label.material.depthWrite = false; }
251
+ resizeLabels();
252
+ }
253
+
254
+ function frustum() { const cam = camera(); cam.updateMatrixWorld(); return new THREE.Frustum().setFromProjectionMatrix(new THREE.Matrix4().multiplyMatrices(cam.projectionMatrix, cam.matrixWorldInverse)); }
255
+ function trimmed(a, b, includeFrustum = true) {
256
+ const section = clipSegmentToPlanes(a, b, planeSpecs(getClipPlanes())); if (!section) return null;
257
+ return includeFrustum ? clipSegmentToPlanes(section[0], section[1], planeSpecs(frustum().planes)) : section;
258
+ }
259
+ function screen(point) { const rect = canvas().getBoundingClientRect(); const p = vector(point).project(camera()); return Number.isFinite(p.x) && Number.isFinite(p.y) ? [rect.left + (p.x * .5 + .5) * rect.width, rect.top + (-p.y * .5 + .5) * rect.height] : null; }
260
+
261
+ function gridHitAt(clientX, clientY, raycaster = new THREE.Raycaster()) {
262
+ if (!lines.size) return null; const cam = camera(); const rect = canvas().getBoundingClientRect(); cam.updateMatrixWorld();
263
+ const ndc = new THREE.Vector2(((clientX - rect.left) / rect.width) * 2 - 1, -((clientY - rect.top) / rect.height) * 2 + 1); raycaster.setFromCamera(ndc, cam);
264
+ const bubbles = labelGroup ? labelGroup.children.filter((item) => item.visible && item.userData.gridId) : [];
265
+ const bubble = raycaster.intersectObjects(bubbles, false)[0];
266
+ if (bubble) return { id: bubble.object.userData.gridId, bubble: true, distance: bubble.distance, depth: bubble.point.clone().project(cam).z };
267
+ let best = null;
268
+ for (const [id, line] of lines) { if (!line.visible) continue; const points = line.userData.segments ?? [];
269
+ for (let i = 0; i + 1 < points.length; i += 2) { const segment = trimmed(points[i], points[i + 1]); if (!segment) continue; const sa = screen(segment[0]); const sb = screen(segment[1]); if (!sa || !sb) continue;
270
+ const hit = projectPointOnSegment2d([clientX, clientY], sa, sb, SEG_DEGENERACY.atMost(0)); if (hit.distance > 8) continue;
271
+ const clipA = new THREE.Vector4(...segment[0], 1).applyMatrix4(cam.matrixWorldInverse).applyMatrix4(cam.projectionMatrix);
272
+ const clipB = new THREE.Vector4(...segment[1], 1).applyMatrix4(cam.matrixWorldInverse).applyMatrix4(cam.projectionMatrix);
273
+ const t = perspectiveSegmentParameter(hit.t, clipA.w, clipB.w); const world = vector(segment[0]).lerp(vector(segment[1]), t);
274
+ const candidate = { id, bubble: false, distance: cam.position.distanceTo(world), depth: world.clone().project(cam).z, pixelDistance: hit.distance };
275
+ if (!best || candidate.pixelDistance < best.pixelDistance - .01 || Math.abs(candidate.pixelDistance - best.pixelDistance) <= .01 && candidate.distance < best.distance) best = candidate;
276
+ }
277
+ }
278
+ return best;
279
+ }
280
+
281
+ function pick({ clientX, clientY, meshHits = [], isOpaqueOccluder = () => true, raycaster } = {}) {
282
+ const gridHit = gridHitAt(clientX, clientY, raycaster); const cam = camera();
283
+ const ordered = [...meshHits].filter((hit) => hit?.point).sort((left, right) => {
284
+ const dl = vector(left.point).clone().project(cam).z; const dr = vector(right.point).clone().project(cam).z; return dl - dr || (left.distance ?? Infinity) - (right.distance ?? Infinity);
285
+ });
286
+ const occluder = ordered.find(isOpaqueOccluder); const meshDepth = occluder ? vector(occluder.point).project(cam).z : Infinity;
287
+ return gridHit && gridDepthWins(gridHit.depth, meshDepth) ? { kind: 'grid', ...gridHit } : ordered.length ? { kind: 'mesh', hit: ordered[0] } : gridHit ? { kind: 'grid', ...gridHit } : null;
288
+ }
289
+
290
+ function rectangleHits(x0, y0, x1, y1, windowMode) {
291
+ const area = [Math.min(x0, x1), Math.min(y0, y1), Math.max(x0, x1), Math.max(y0, y1)]; const out = [];
292
+ for (const [id, line] of lines) { if (!line.visible) continue; const points = line.userData.segments ?? []; let hit = false;
293
+ for (let i = 0; i + 1 < points.length; i += 2) { const segment = trimmed(points[i], points[i + 1]); if (!segment) continue; const sa = screen(segment[0]); const sb = screen(segment[1]); if (sa && sb && segmentHitsRect2d(sa, sb, area, windowMode)) { hit = true; break; } }
294
+ if (hit) out.push(id);
295
+ }
296
+ return out;
297
+ }
298
+
299
+ function hasVisibleFragment(id) {
300
+ const line = lines.get(id); if (!line?.visible) return false;
301
+ const points = line.userData.segments ?? [];
302
+ for (let index = 0; index + 1 < points.length; index += 2) if (trimmed(points[index], points[index + 1], false)) return true;
303
+ return false;
304
+ }
305
+
306
+ function bounds(mode = 'visible') {
307
+ const box = new THREE.Box3();
308
+ for (const line of lines.values()) { if (mode === 'visible' && !line.visible) continue;
309
+ const points = mode === 'visible' ? line.userData.segments ?? [] : line.userData.completeSegments ?? line.userData.segments ?? [];
310
+ for (let i = 0; i + 1 < points.length; i += 2) { const segment = mode === 'visible' ? trimmed(points[i], points[i + 1], false) : [points[i], points[i + 1]]; if (!segment) continue; box.expandByPoint(vector(segment[0])); box.expandByPoint(vector(segment[1])); }
311
+ }
312
+ return finiteBox(box);
313
+ }
314
+ function composeBounds({ meshBounds = null, purpose = 'camera-all', gridOwnerSelected = false } = {}) {
315
+ const gridBounds = purpose === 'camera-selection' && gridOwnerSelected ? bounds('complete') : purpose === 'camera-all' ? bounds('visible') : null;
316
+ if (!meshBounds) return gridBounds?.clone() ?? null; if (!gridBounds) return meshBounds.clone?.() ?? meshBounds;
317
+ return (meshBounds.clone?.() ?? new THREE.Box3(vector(meshBounds.min), vector(meshBounds.max))).union(gridBounds);
318
+ }
319
+
320
+ function segmentsScreen() { const rect = canvas().getBoundingClientRect(); const out = [];
321
+ for (const [id, line] of lines) { if (!line.visible) continue; const points = line.userData.segments ?? []; for (let i = 0; i + 1 < points.length; i += 2) { const segment = trimmed(points[i], points[i + 1]); if (!segment) continue; const sa = screen(segment[0]); const sb = screen(segment[1]); if (sa && sb) out.push({ id, a: { x: sa[0], y: sa[1] }, b: { x: sb[0], y: sb[1] } }); } }
322
+ return out;
323
+ }
324
+ function bubblesScreen() { const rect = canvas().getBoundingClientRect(); return labelGroup ? labelGroup.children.filter((item) => item.visible && item.userData.gridId).map((item) => { const p = item.getWorldPosition(new THREE.Vector3()).project(camera()); return { id: item.userData.gridId, x: rect.left + (p.x * .5 + .5) * rect.width, y: rect.top + (-p.y * .5 + .5) * rect.height }; }) : []; }
325
+ function info() { return { lines: lines.size, labels: labelGroup?.children.length ?? 0, labelTexts: labelGroup ? [...new Set(labelGroup.children.map((item) => item.userData.label).filter(Boolean))] : [], lineOpacities: [...lines.values()].filter((line) => line.visible).map((line) => line.material.opacity), labelOpacities: labelGroup ? labelGroup.children.filter((item) => item.visible).map((item) => item.material.opacity) : [], selected: [...selected], ids: [...lines.keys()], visible: [...lines].filter(([, line]) => line.visible).map(([id]) => id), hidden: [...hidden], isolated: isolated === null ? null : [...isolated], levels: levelInfo() }; }
326
+
327
+ return Object.freeze({
328
+ build, clear, resizeLabels, setVisibility, setHiddenLevels, levelInfo, applyPaint, gridHitAt, pick, rectangleHits, hasVisibleFragment, bounds, composeBounds,
329
+ segmentsScreen, bubblesScreen, info,
330
+ setLabelPx(value) { labelPx = value; resizeLabels(); }, labelPx: () => labelPx,
331
+ get lines() { return lines; }, get lineGroup() { return lineGroup; }, get labelGroup() { return labelGroup; }, get levels() { return [...levels]; },
332
+ dispose() { clear(); for (const texture of textures.values()) texture.dispose(); textures.clear(); },
333
+ });
334
+ }
@@ -0,0 +1,32 @@
1
+ export const TEKLA_GEOMETRY_SELECTION_CAP = 5000;
2
+
3
+ /**
4
+ * Resolve only supplied geometry and authenticated membership; labels never imply membership.
5
+ * @param {string[]} ids
6
+ * @param {Map<string, any>} entityById
7
+ * @param {Map<string, string[]>} membersByAssembly
8
+ * @param {Set<string> | null} visibleIds
9
+ */
10
+ export function teklaGeometrySelection(ids, entityById, membersByAssembly = new Map(), visibleIds = null) {
11
+ const selected = new Set(), visited = new Set();
12
+ const visit = (id) => {
13
+ if (visited.has(id)) return; visited.add(id);
14
+ const entity = entityById.get(id); if (!entity) return;
15
+ if (Array.isArray(entity.geometry) && entity.geometry.length && (!visibleIds || visibleIds.has(id))) selected.add(id);
16
+ if (selected.size > TEKLA_GEOMETRY_SELECTION_CAP) return;
17
+ for (const member of membersByAssembly.get(id) || []) { visit(member); if (selected.size > TEKLA_GEOMETRY_SELECTION_CAP) return; }
18
+ };
19
+ for (const id of ids || []) { visit(id); if (selected.size > TEKLA_GEOMETRY_SELECTION_CAP) return null; }
20
+ return [...selected];
21
+ }
22
+
23
+ /** The verifier admits `contains` only for a native assembly → native part membership. */
24
+ export function teklaAssemblyMembership(relationships) {
25
+ const members = new Map();
26
+ for (const relationship of relationships || []) {
27
+ if (relationship.kind !== 'contains') continue;
28
+ const ids = members.get(relationship.from) || [];
29
+ ids.push(relationship.to); members.set(relationship.from, ids);
30
+ }
31
+ return members;
32
+ }