@floless/app 0.104.2 → 0.105.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -20,6 +20,10 @@ header{display:flex;align-items:center;gap:14px;padding:8px 14px;background:var(
20
20
  header b{font-size:14px} header .sp{flex:1}
21
21
  .stat{color:var(--mut);font-size:12px} .stat b{color:var(--text)}
22
22
  .stat.dirty b{color:#f59e0b} .stat.saved b{color:#34d399} .stat.err b{color:#f87171}
23
+ /* Save conflict — the model moved under us. Needs its OWN rule: the other states colour a nested <b>,
24
+ and this text has none, so without this it rendered in muted grey, indistinguishable from idle. Same
25
+ cyan "non-default, click to act" chip the sibling editors use — no new colour. */
26
+ .stat.conflict{color:#22d3ee;border:1px solid #22d3ee;background:rgba(34,211,238,.10);border-radius:4px;padding:1px 6px;cursor:pointer}
23
27
  button{background:#334155;color:var(--text);border:1px solid #475569;border-radius:6px;padding:5px 10px;cursor:pointer;font:13px system-ui}
24
28
  button:hover{background:#475569} button:disabled{opacity:.5;cursor:default}
25
29
  button.primary{background:var(--brand);border-color:var(--brand);color:#fff} button.primary:hover{background:#2f6fe0}
@@ -152,12 +156,52 @@ let mode = 'layer';
152
156
  let nodes = []; // [{ node, el }]
153
157
  let layerColor = {};
154
158
  let dirty = false;
159
+ let serverEtag = null; // the server's tag for the contract we loaded
160
+ let conflicted = false; // latched once a save is refused, so a second click does not re-fire it
155
161
  let sheets = []; // normalizeFilter(F).sheets — per-sheet geometry
156
162
  let active = 0; // index into sheets
157
163
 
158
164
  function setSaved(state){
159
165
  savedEl.className = 'stat ' + (state || '');
160
- savedEl.innerHTML = state === 'dirty' ? 'Unsaved <b>●</b>' : state === 'saved' ? 'Saved <b>✓</b>' : state === 'err' ? 'Save failed <b>✕</b>' : '';
166
+ savedEl.innerHTML = state === 'dirty' ? 'Unsaved <b>●</b>' : state === 'saved' ? 'Saved <b>✓</b>'
167
+ : state === 'err' ? 'Save failed <b>✕</b>'
168
+ // Not an error: the user's selection is fine, the model simply moved under them.
169
+ : state === 'conflict' ? 'Save conflict' : '';
170
+ }
171
+
172
+ /**
173
+ * Someone else wrote to this model after we loaded it, so the save was refused.
174
+ *
175
+ * Same bottom-bar recipe as the steel editor, on purpose — a user who has learned "blue bar at the
176
+ * bottom = something else changed" should not have to relearn it per surface. Reload only: nothing here
177
+ * autosaves and the state at risk is a few facet toggles, so a force-overwrite would be destructive
178
+ * machinery for seconds of redo work.
179
+ */
180
+ // `message` is optional so the 428 (stale-page) case reuses this bar rather than forking a second one —
181
+ // same bar, same tokens, one thing to learn. Defaults to the write-conflict copy.
182
+ function showConflictBanner(message){
183
+ const old = document.getElementById('conflictBanner'); if(old) old.remove();
184
+ const bar = document.createElement('div');
185
+ bar.id = 'conflictBanner';
186
+ bar.style.cssText = 'position:fixed;bottom:0;left:0;right:0;z-index:50;display:flex;align-items:center;gap:10px;'
187
+ + 'padding:10px 16px;background:#1e40af;color:#e0f2fe;font:13px system-ui;border-top:1px solid #3b82f6;'
188
+ + 'box-shadow:0 -4px 18px rgba(0,0,0,.45)';
189
+ const msg = document.createElement('span'); msg.style.cssText = 'flex:1';
190
+ msg.textContent = message
191
+ || 'This model changed somewhere else since you opened it — your save didn’t go through. '
192
+ + 'Reload and reapply your changes.';
193
+ const reload = document.createElement('button');
194
+ reload.style.cssText = 'background:#3b82f6;color:#fff;border:1px solid #60a5fa;border-radius:6px;padding:5px 12px;cursor:pointer;font:13px system-ui';
195
+ reload.textContent = '↻ Reload';
196
+ // No local draft in this surface, so a plain reload is already safe (unlike the steel editor, whose
197
+ // restoreSaved() would re-overlay the conflicting draft).
198
+ reload.onclick = () => location.reload();
199
+ const dismiss = document.createElement('button');
200
+ dismiss.style.cssText = 'background:transparent;color:#93c5fd;border:1px solid #3b82f6;border-radius:6px;padding:5px 10px;cursor:pointer;font:13px system-ui';
201
+ dismiss.textContent = '✕';
202
+ dismiss.onclick = () => bar.remove();
203
+ bar.appendChild(msg); bar.appendChild(reload); bar.appendChild(dismiss);
204
+ document.body.appendChild(bar);
161
205
  }
162
206
  function markDirty(){ dirty = true; saveBtn.disabled = false; setSaved('dirty'); }
163
207
 
@@ -169,6 +213,7 @@ async function boot(){
169
213
  if(res.status === 204){ showEmpty(); return; }
170
214
  if(!res.ok){ showEmpty(); return; }
171
215
  C = await res.json();
216
+ serverEtag = res.headers.get('ETag'); // echoed back on save so a stale write is refused, not silently applied
172
217
  F = C && C.filter;
173
218
  const norm = normalizeFilter(F);
174
219
  sheets = norm.sheets; active = norm.active;
@@ -413,10 +458,30 @@ async function save(){
413
458
  F.sheets = sheets; F.active = active;
414
459
  delete F.page; delete F.elements; delete F.steelBbox; // migrate legacy single-sheet shape forward
415
460
  C.filter = F;
461
+ // A second click while already conflicted must NOT silently re-fire a request we know will fail —
462
+ // just re-surface the explanation.
463
+ if(conflicted){ showConflictBanner(); return; }
416
464
  saveBtn.disabled = true; setSaved('');
417
465
  try {
418
- const res = await fetch('/api/contract/' + encodeURIComponent(APP_ID) + PROJECT_QS, { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify(C) });
466
+ const headers = { 'content-type': 'application/json' };
467
+ // TOTAL, as of P1c: a write with no precondition is refused (428). No tag means we read through the
468
+ // BAKED fallback (the GET tags only store-backed documents) — this app has no draft yet — so the
469
+ // honest precondition is `If-None-Match: *`, "I believe this store is empty".
470
+ if(serverEtag) headers['if-match'] = serverEtag; else headers['if-none-match'] = '*';
471
+ const res = await fetch('/api/contract/' + encodeURIComponent(APP_ID) + PROJECT_QS, { method: 'PUT', headers, body: JSON.stringify(C) });
472
+ if(res.status === 428){ // a writer here sent no precondition — a bug in our code, not a user error.
473
+ // NOT the conflict copy: nothing else wrote, so "changed somewhere else" would be a lie. This bar
474
+ // is Reload-only (no overwrite button), which is already the right shape for a 428.
475
+ console.error('save refused 428 — a first-party writer sent no precondition; this is a FloLess bug');
476
+ setSaved('err'); saveBtn.disabled = false;
477
+ showConflictBanner('FloLess couldn’t save that change. Reload and try again — if it keeps happening, please report it.');
478
+ return;
479
+ }
480
+ if(res.status === 412){
481
+ conflicted = true; setSaved('conflict'); saveBtn.disabled = false; showConflictBanner(); return;
482
+ }
419
483
  if(!res.ok) throw new Error(await res.text());
484
+ const t = res.headers.get('ETag'); if(t) serverEtag = t;
420
485
  dirty = false; setSaved('saved');
421
486
  } catch(e){ console.error('filter save failed', e); setSaved('err'); saveBtn.disabled = false; }
422
487
  }
@@ -0,0 +1,249 @@
1
+ /*
2
+ * steel-materials.js — the Realistic display mode's surface detail.
3
+ *
4
+ * Two pieces, both deliberately asset-free:
5
+ *
6
+ * 1. PROCEDURAL TEXTURES. Concrete aggregate, timber grain, galvanised spangle, brushed metal and
7
+ * so on are generated onto a <canvas> in code — no image files. That is not a size optimisation
8
+ * for its own sake: a shared 3D link is ONE self-contained HTML document capped at 5 MB, and a
9
+ * single 1K albedo+normal pair is 1-2 MB, so ten families of bitmaps could never fit. Generating
10
+ * them also keeps floless's no-runtime-CDN/offline policy intact and keeps AWARE's rendered
11
+ * document byte-identical for an identical scene (the CODE is fixed; the pixels are made at
12
+ * runtime). Every generator draws from a SEEDED prng — never Math.random — so the same family
13
+ * always produces the same surface.
14
+ *
15
+ * 2. TRIPLANAR PROJECTION. Steel members are ExtrudeGeometry, whose UVs are in millimetre scale and
16
+ * differ between the cap faces and the side walls — so a naively mapped texture stretches on the
17
+ * caps and runs the wrong way along the member. Triplanar ignores UVs entirely and projects the
18
+ * texture from world XYZ, blended by the surface normal, so aggregate and grain read correctly on
19
+ * every face of any member at any size. Applied by patching MeshStandardMaterial's shader.
20
+ *
21
+ * ponytail: albedo + roughness are triplanar; NORMAL maps are deliberately not implemented. Triplanar
22
+ * normal mapping needs per-axis tangent-space reconstruction and roughly doubles the shader, while
23
+ * env-lit roughness variation already carries most of the perceived detail. Add it if surfaces still
24
+ * read flat under raking light.
25
+ *
26
+ * Shared by BOTH renderers by copy (floless's editor + AWARE's read-only viewer-3d, which embeds its
27
+ * JS in a Rust string and cannot import this file). That duplication is the established shape of this
28
+ * seam — AWARE's viewer is already a port of the floless engine — but keep the two in step.
29
+ */
30
+
31
+ // A tiny deterministic PRNG (mulberry32). Seeded per family so a surface never changes between runs,
32
+ // which is what lets AWARE promise identical output for identical input.
33
+ function rng(seed) {
34
+ let a = seed >>> 0;
35
+ return () => {
36
+ a = (a + 0x6d2b79f5) >>> 0;
37
+ let t = Math.imul(a ^ (a >>> 15), 1 | a);
38
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
39
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
40
+ };
41
+ }
42
+
43
+ // Value noise on a coarse lattice, smoothed — enough structure for aggregate/mottle without pulling in
44
+ // a noise library. Tiles by wrapping the lattice, so the texture repeats seamlessly under triplanar.
45
+ // Separate X and Y lattice counts. Directional finishes (grain, brushing) come from a COARSER lattice
46
+ // on one axis, never from resampling a square field with a squashed index: doing that reads only the
47
+ // first few rows and then jumps back to row 0 at the tile edge, which — with RepeatWrapping — is a
48
+ // hard seam every tile. Anisotropy in the lattice stays periodic on both axes by construction.
49
+ function noiseField(size, cellsX, cellsY, seed) {
50
+ const r = rng(seed), g = new Float32Array(cellsX * cellsY);
51
+ for (let i = 0; i < g.length; i++) g[i] = r();
52
+ const at = (x, y) => g[(((y % cellsY) + cellsY) % cellsY) * cellsX + (((x % cellsX) + cellsX) % cellsX)];
53
+ const sm = (t) => t * t * (3 - 2 * t); // smoothstep — kills lattice banding
54
+ const out = new Float32Array(size * size);
55
+ const sx = cellsX / size, sy = cellsY / size;
56
+ for (let y = 0; y < size; y++) {
57
+ for (let x = 0; x < size; x++) {
58
+ const fx = x * sx, fy = y * sy, x0 = Math.floor(fx), y0 = Math.floor(fy);
59
+ const tx = sm(fx - x0), ty = sm(fy - y0);
60
+ const a = at(x0, y0), b = at(x0 + 1, y0), c = at(x0, y0 + 1), d = at(x0 + 1, y0 + 1);
61
+ out[y * size + x] = (a + (b - a) * tx) * (1 - ty) + (c + (d - c) * tx) * ty;
62
+ }
63
+ }
64
+ return out;
65
+ }
66
+
67
+ // Sum several noise octaves. Starts at a FINE lattice on purpose: a coarse first octave produces big
68
+ // soft blobs, and a blob stretched over a 3 m column by the triplanar projection reads as a smear or a
69
+ // stain rather than as material. Detail wants to be near the grain scale, not the member scale.
70
+ function fbm(size, seed, aniso = 1, baseCells = 16, octaves = 5) {
71
+ const out = new Float32Array(size * size);
72
+ let amp = 1, cells = baseCells, norm = 0;
73
+ for (let o = 0; o < octaves; o++) {
74
+ // aniso > 1 stretches the pattern along Y by giving that axis proportionally fewer cells.
75
+ const n = noiseField(size, cells, Math.max(1, Math.round(cells / aniso)), seed + o * 977);
76
+ for (let i = 0; i < out.length; i++) out[i] += n[i] * amp;
77
+ norm += amp; amp *= 0.5; cells *= 2;
78
+ }
79
+ for (let i = 0; i < out.length; i++) out[i] /= norm;
80
+ return out;
81
+ }
82
+
83
+ const TEX_SIZE = 256; // plenty under triplanar (the projection scale, not the pixel count, sets apparent detail)
84
+
85
+ // Each family paints its own albedo + roughness pair. `f(x, y, n)` gets the pixel and the fbm value at
86
+ // that pixel and returns [lightness, roughnessDelta] — lightness multiplies the base colour, so the
87
+ // palette in the renderer stays the single source of truth for hue and only DETAIL lives here.
88
+ // Detail lives mostly in ROUGHNESS, not albedo. That split is the whole trick: varying diffuse colour
89
+ // by more than a few percent is exactly what dirt, staining and water marks look like, whereas varying
90
+ // how the surface scatters light is what actually distinguishes cast concrete from brushed stainless.
91
+ // So albedo swings stay small (a few percent) and roughness carries the character.
92
+ const SURFACES = {
93
+ // Aggregate: mostly a scatter difference, with sparse bright specks for exposed stone.
94
+ concrete: (n, r) => [0.955 + n * 0.09 + (n > 0.88 ? 0.04 : 0), 0.16 - n * 0.20 + (r() < 0.003 ? 0.14 : 0)],
95
+ // Grain: the field is squashed along one axis by the caller. Timber tolerates the most albedo
96
+ // variation of any family here, because visible grain genuinely IS a colour difference.
97
+ timber: (n) => [0.90 + n * 0.19, 0.08 - n * 0.14],
98
+ // Spangle: hot-dip crystals differ in how they catch light far more than in tone.
99
+ galvanised: (n) => [0.965 + (n > 0.55 ? 0.05 : 0) + n * 0.03, 0.20 - (n > 0.55 ? 0.16 : 0)],
100
+ // Brushed: fine directional streaks, purely specular — a brushed finish is not a colour change.
101
+ stainless: (n) => [0.978 + n * 0.04, 0.09 - n * 0.11],
102
+ aluminium: (n) => [0.978 + n * 0.04, 0.10 - n * 0.12],
103
+ // Oxidation genuinely does vary in tone, but nothing like as much as the first cut assumed.
104
+ weathering: (n) => [0.88 + n * 0.22, 0.08 - n * 0.13],
105
+ // Orange peel. Kept subtle in ALBEDO — paint is a uniform colour, and mottling it reads as dirt —
106
+ // but given real variation in ROUGHNESS, so the sheen shifts across the face. Without that the
107
+ // surface has nothing to catch the environment and a light paint just blows out to flat white.
108
+ painted: (n) => [0.982 + n * 0.034, 0.12 - n * 0.19],
109
+ steel: (n) => [0.968 + n * 0.055, 0.08 - n * 0.11],
110
+ // Coarse and very rough — asphalt should never catch a highlight.
111
+ asphalt: (n, r) => [0.91 + n * 0.14 + (r() < 0.015 ? 0.06 : 0), 0.07 - n * 0.09],
112
+ glass: null, // no surface detail — smooth by definition
113
+ };
114
+
115
+ // Families whose detail is DIRECTIONAL: the lattice is coarser on one axis so grain/brushing runs one
116
+ // way rather than looking like generic mottle. Keep these MILD. The Y cell count is baseCells/aniso,
117
+ // so a large value drives it toward 1 — a single cell is constant along Y and the surface degenerates
118
+ // into regular vertical ribbing, which reads as corrugated sheet, not as a brushed finish.
119
+ const STRETCH = { timber: 5, stainless: 6, aluminium: 6 };
120
+ // Base lattice per family: how FINE the dominant detail is. The first octave carries full amplitude,
121
+ // so this number, not the octave count, decides what the surface actually looks like. Brushing and
122
+ // aggregate need to be dense — a 16-cell lattice across a 180 mm tile gives ~11 mm stripes, which at
123
+ // member scale reads as ribbing rather than as a finish.
124
+ const BASE_CELLS = { stainless: 56, aluminium: 56, timber: 22, concrete: 26, galvanised: 22, asphalt: 24, painted: 34 };
125
+
126
+ /**
127
+ * Build the albedo + roughness textures for a family. Returns null for families with no surface detail.
128
+ * `THREE` is passed in so this module stays copyable into AWARE's embedded renderer verbatim.
129
+ */
130
+ export function surfaceTextures(THREE, family, baseRoughness) {
131
+ const paint = SURFACES[family];
132
+ if (!paint) return null;
133
+ const size = TEX_SIZE;
134
+ // Seed from the family name so every family differs but each is stable run to run.
135
+ let seed = 0; for (let i = 0; i < family.length; i++) seed = (seed * 31 + family.charCodeAt(i)) >>> 0;
136
+ const field = fbm(size, seed, STRETCH[family] || 1, BASE_CELLS[family] || 16);
137
+ const r = rng(seed ^ 0x9e3779b9);
138
+
139
+ const albedo = document.createElement('canvas'), rough = document.createElement('canvas');
140
+ albedo.width = albedo.height = rough.width = rough.height = size;
141
+ const ai = albedo.getContext('2d').createImageData(size, size);
142
+ const ri = rough.getContext('2d').createImageData(size, size);
143
+ for (let y = 0; y < size; y++) {
144
+ for (let x = 0; x < size; x++) {
145
+ const n = field[y * size + x];
146
+ const [light, dRough] = paint(n, r);
147
+ const i = (y * size + x) * 4;
148
+ const L = Math.max(0, Math.min(255, Math.round(light * 255)));
149
+ ai.data[i] = ai.data[i + 1] = ai.data[i + 2] = L; ai.data[i + 3] = 255;
150
+ // ABSOLUTE roughness, not a delta around 0.5. three MULTIPLIES roughness by this channel, so a
151
+ // map centred on 0.5 silently halves every declared roughness — concrete's 0.92 would render at
152
+ // ~0.46, i.e. twice as glossy as specified. The caller sets material.roughness = 1 so the
153
+ // multiply is an identity and what is written here is exactly the roughness used.
154
+ // (Read from the GREEN channel by three's standard material.)
155
+ const R = Math.max(0, Math.min(255, Math.round((baseRoughness + dRough) * 255)));
156
+ ri.data[i] = ri.data[i + 1] = ri.data[i + 2] = R; ri.data[i + 3] = 255;
157
+ }
158
+ }
159
+ albedo.getContext('2d').putImageData(ai, 0, 0);
160
+ rough.getContext('2d').putImageData(ri, 0, 0);
161
+
162
+ const mk = (canvas, srgb) => {
163
+ const t = new THREE.CanvasTexture(canvas);
164
+ t.wrapS = t.wrapT = THREE.RepeatWrapping;
165
+ if (srgb) t.colorSpace = THREE.SRGBColorSpace;
166
+ t.anisotropy = 4;
167
+ return t;
168
+ };
169
+ // Albedo is colour data (sRGB); roughness is linear data — tagging it sRGB would wash out the detail.
170
+ return { map: mk(albedo, true), roughnessMap: mk(rough, false) };
171
+ }
172
+
173
+ /**
174
+ * Patch a MeshStandardMaterial to sample `map`/`roughnessMap` TRIPLANARLY — projected from world XYZ
175
+ * and blended by the surface normal — instead of through the mesh's UVs.
176
+ *
177
+ * Why not just set texture.repeat: an ExtrudeGeometry beam's UVs are millimetre-scale and inconsistent
178
+ * between its cap faces and its side walls, so any single repeat value stretches somewhere. Projecting
179
+ * from world space sidesteps UVs entirely, which is the only thing that reads correctly on a coped
180
+ * member at architectural scale.
181
+ *
182
+ * `scaleMm` is the world size one texture tile covers (e.g. 400 → the pattern repeats every 400 mm).
183
+ *
184
+ * @param {object} material
185
+ * @param {number} scaleMm
186
+ * @param {'y'|'z'|null} [axis] the geometry's length axis; null projects from world space instead
187
+ */
188
+ export function applyTriplanar(material, scaleMm, axis = null) {
189
+ // `axis === null` → WORLD projection. Isotropic families (concrete, asphalt, painted steel) want
190
+ // this: adjacent members then read as one continuous pour/finish instead of each carrying its own
191
+ // tile origin.
192
+ //
193
+ // Otherwise project from OBJECT space AND permute so the member's length lands on the sampling
194
+ // space's Z. The permutation is the load-bearing part, and object space alone is NOT enough:
195
+ // STRETCH coarsens the texture's Y cell count, so grain runs along texture V — and V maps to `z`
196
+ // on the X/Y-facing side faces (p.yz / p.xz). So object space is only correct where the geometry's
197
+ // length is already local Z, and it isn't consistently: BoxGeometry(w,len,d) and CylinderGeometry
198
+ // are Y-axial, ExtrudeGeometry({depth:len}) is Z-axial. Without the swizzle, timber grain runs
199
+ // along the SHORT axis of every box member. Callers pass the axis from lengthAxisOf().
200
+ const swizzle = axis === 'y' ? '.xzy' : '';
201
+ const posExpr = axis ? `transformed${swizzle}` : '(modelMatrix * vec4(transformed, 1.0)).xyz';
202
+ // The normal must ride the SAME permutation, or the triplanar blend would weigh faces in the
203
+ // unpermuted frame and cross-fade the wrong samples at the corners.
204
+ const nrmExpr = axis ? `objectNormal${swizzle}` : 'mat3(modelMatrix) * objectNormal';
205
+
206
+ material.onBeforeCompile = (shader) => {
207
+ shader.uniforms.uTriScale = { value: 1 / Math.max(1, scaleMm) };
208
+ shader.vertexShader = shader.vertexShader
209
+ .replace('#include <common>', '#include <common>\nvarying vec3 vTriPos;\nvarying vec3 vTriNrm;')
210
+ // worldpos_vertex is where three already computes the world position, so we piggyback rather
211
+ // than recompute the model matrix ourselves. In local mode we take `transformed`/`objectNormal`
212
+ // straight, before the model matrix is applied.
213
+ .replace('#include <worldpos_vertex>', `#include <worldpos_vertex>\n vTriPos = ${posExpr};\n vTriNrm = ${nrmExpr};`);
214
+
215
+ const helper = `
216
+ varying vec3 vTriPos;
217
+ varying vec3 vTriNrm;
218
+ uniform float uTriScale;
219
+ // Sample once per world axis and blend by |normal| — the standard triplanar trick. The 4th power
220
+ // sharpens the blend so faces stay crisp instead of smearing into each other near corners.
221
+ vec4 triplanar(sampler2D tex, vec3 p, vec3 n) {
222
+ vec3 b = pow(abs(normalize(n)), vec3(4.0));
223
+ b /= max(b.x + b.y + b.z, 1e-4);
224
+ return texture2D(tex, p.yz) * b.x + texture2D(tex, p.xz) * b.y + texture2D(tex, p.xy) * b.z;
225
+ }`;
226
+ shader.fragmentShader = shader.fragmentShader
227
+ .replace('#include <common>', '#include <common>' + helper)
228
+ .replace('#include <map_fragment>', `
229
+ #ifdef USE_MAP
230
+ diffuseColor *= triplanar(map, vTriPos * uTriScale, vTriNrm);
231
+ #endif`)
232
+ .replace('#include <roughnessmap_fragment>', `
233
+ float roughnessFactor = roughness;
234
+ #ifdef USE_ROUGHNESSMAP
235
+ roughnessFactor *= triplanar(roughnessMap, vTriPos * uTriScale, vTriNrm).g;
236
+ #endif`);
237
+ };
238
+ // Three caches compiled programs by this key; without a distinct one, a patched and an unpatched
239
+ // material with otherwise identical parameters would silently share the WRONG program.
240
+ material.customProgramCacheKey = () => `triplanar:${scaleMm}:${axis || 'world'}`;
241
+ material.needsUpdate = true;
242
+ }
243
+
244
+ /** World size (mm) one texture tile covers, per family — aggregate is coarse, brushing is fine. */
245
+ export const DIRECTIONAL = new Set(['timber', 'stainless', 'aluminium']);
246
+ export const TILE_MM = {
247
+ concrete: 600, asphalt: 500, timber: 900, weathering: 700,
248
+ galvanised: 260, stainless: 180, aluminium: 180, painted: 420, steel: 400,
249
+ };
@@ -0,0 +1,210 @@
1
+ /*
2
+ * steel-model-adapter.js — the READ side of the steel editor's model boundary (unit 5, P2).
3
+ *
4
+ * PURE and framework-free (no DOM, no Three.js), node-tested from server/steel-model-adapter.test.ts —
5
+ * same shape as grid-core.js / steel-3d-core.js.
6
+ *
7
+ * WHY IT EXISTS
8
+ * `web/steel-editor.html` reads model geometry inline, everywhere, in per-sheet DISPLAY PIXELS. That is
9
+ * what makes `steel.model/v2` (one model in world millimetres) expensive to switch on: activation would
10
+ * mean `if (v2)` branches threaded through a 6,400-line closure. This adapter is the seam. Every method
11
+ * answers in WORLD MILLIMETRES regardless of how the contract underneath stores things, so P5 can add a v2
12
+ * arm behind the same six methods and the editor never learns which one it is talking to.
13
+ *
14
+ * SCOPE — read only, and NOT YET WIRED IN.
15
+ * P2 ships this tested and unconsumed on purpose. Rewiring the editor's read sites is P3's job, and doing
16
+ * it here would invalidate the characterization baseline recorded in the same PR (that baseline is the only
17
+ * evidence P3's refactor changes nothing). Nothing loads this module yet; P3 adds the <script> tag when it
18
+ * consumes it. Writes are P3 as well — there are no mutators here by design.
19
+ *
20
+ * UNITS AND SIGNS — the one thing to get right.
21
+ * Contract geometry is per-sheet display pixels scaled by `plan.pt_per_ft`, with Y growing DOWNWARD, and
22
+ * elevations in INCHES. World mm is X east, Y "up the plan", Z up. So the plan Y axis is NEGATED, exactly
23
+ * as `server/contract-to-scene.ts:dispToMm` does it. That negation is a reflection: it reverses handedness,
24
+ * which is why `sheetFrame` documents what happens to a local frame's sense.
25
+ *
26
+ * This mirrors `contract-to-scene.ts`'s conversion rather than importing it (that file is server TypeScript;
27
+ * this one is a browser module). Two independent world-mm conversions would be a real hazard — a model that
28
+ * renders in one place and exports in another — so the mirror is held in lock-step by a parity test matrix
29
+ * (`server/steel-model-adapter.test.ts`, "parity with contract-to-scene"). Change one, change both.
30
+ *
31
+ * The two agree on every conversion of well-formed data: px scale, the Y negation, inches to mm (including
32
+ * numeric strings), and the plumb-column rule. They diverge, deliberately and by assertion, on MALFORMED or
33
+ * MALFORMED elevations, and on an ABSENT elevation WITH NO SHEET `default_tos` — an absent elevation on a
34
+ * sheet that declares one is in full parity (the matrix asserts both). The renderer coerces whatever it finds and is not always sane about it — `"" -> 0`,
35
+ * `true -> 1"`, `[144] -> 144"`, but `"abc"`, `NaN` and `{}` put a **NaN Z** into the scene — because it
36
+ * must draw something. This reports null instead, because a read boundary must not invent a position.
37
+ * The no-elevation-and-no-default case is in the parity matrix; the malformed shapes are enumerated in
38
+ * `endElevMm: present-but-unreadable is an RFI` (adapter side only — the renderer's NaN behaviour is
39
+ * recorded here rather than asserted, since pinning a NaN as expected output would entrench a bug).
40
+ */
41
+
42
+ import { MODEL_V2_TOL } from './steel-3d-core.js';
43
+
44
+ const FT_MM = 304.8;
45
+ const IN_MM = 25.4; // ← becomes 1 when the contract stores elevations in mm (metric canonicalization)
46
+
47
+ /** Scale for one plan's display pixels → mm. Matches contract-to-scene: a missing/zero pt_per_ft means 1. */
48
+ const scaleOf = (plan) => FT_MM / (plan && plan.pt_per_ft > 0 ? plan.pt_per_ft : 1);
49
+
50
+ /** Display point → world mm. Y is NEGATED (display Y grows down; world Y grows up the plan). */
51
+ const dispToMm = (pt, k) => [pt[0] * k, -pt[1] * k];
52
+
53
+ const finitePt = (p) => Array.isArray(p) && p.length >= 2 && Number.isFinite(p[0]) && Number.isFinite(p[1]);
54
+
55
+ /**
56
+ * A finite number, or null. NUMERIC STRINGS are accepted: hand-edited and older contracts carry `tos: "144"`,
57
+ * and `contract-to-scene` reads them (its `!= null` test lets the string coerce through the arithmetic), so
58
+ * rejecting them here would drop a real elevation that the renderer honours. Blank/whitespace is not zero.
59
+ */
60
+ const num = (v) => {
61
+ if (typeof v === 'number') return Number.isFinite(v) ? v : null;
62
+ if (typeof v === 'string' && v.trim() !== '') { const n = Number(v); return Number.isFinite(n) ? n : null; }
63
+ return null;
64
+ };
65
+
66
+ /**
67
+ * A read-only, world-mm view over a steel contract.
68
+ *
69
+ * `activeSheet` selects which sheet `grid()` answers for; it defaults to the contract's own `active` index,
70
+ * so a caller that does not care gets the sheet the editor has open.
71
+ */
72
+ export function createModelAdapter(contract, { activeSheet } = {}) {
73
+ const plans = (contract && Array.isArray(contract.plans)) ? contract.plans : [];
74
+ const planFor = (m) => plans.find(p => Array.isArray(p.members) && p.members.includes(m)) || null;
75
+
76
+ const activePlan = () => {
77
+ if (activeSheet != null) return plans.find(p => p.sheet === activeSheet) || null;
78
+ const i = Number.isInteger(contract && contract.active) ? contract.active : 0;
79
+ return plans[i] || plans[0] || null;
80
+ };
81
+
82
+ /** Top-of-steel in mm for one member end, or null when neither the member nor its sheet declares one. */
83
+ const endElevMm = (m, plan, i) => {
84
+ const raw = m.role === 'column'
85
+ ? (m.col && (i === 0 ? m.col.bos : m.col.tos))
86
+ : (m.ends && m.ends[i] && m.ends[i].tos);
87
+ const inches = num(raw);
88
+ if (inches != null) return inches * IN_MM;
89
+ // PRESENT BUT UNREADABLE is not the same as UNSET. A `tos` of "", " ", "abc", true, [] or NaN is an
90
+ // authored value this reader cannot interpret; falling through to the sheet default would answer with a
91
+ // confident elevation the contract never stated — the exact fabrication the Z=0 note below refuses.
92
+ // Report null (an RFI) instead. Round-2 review found ten such inputs where the adapter silently
93
+ // substituted default_tos while contract-to-scene coerced the value.
94
+ // `null`/absent IS the editor's own "unset" (ensureMeta writes `tos: null`), so those fall through to
95
+ // the sheet default. Anything else present is malformed, including `''`. An own property explicitly set
96
+ // to `undefined` counts as unset here rather than malformed — JSON.parse cannot produce one, so it
97
+ // cannot reach this from a stored contract, and treating it as unset matches `null`.
98
+ if (raw != null) return null;
99
+ // A column base with no BOS sits at 0 — contract-to-scene:397 does the same.
100
+ if (m.role === 'column' && i === 0) return 0;
101
+ const def = num(plan && plan.default_tos);
102
+ // DELIBERATE DIVERGENCE from contract-to-scene, asserted in the parity test rather than left to be
103
+ // discovered. `contract-to-scene.ts:366` uses `(plan.default_tos ?? 0)`, so a member with no elevation
104
+ // and no sheet default RENDERS at Z=0. That is a renderer's concession — it has to draw something. A
105
+ // read boundary must not repeat it: Z=0 is a fabricated position for what is really an RFI, and v2
106
+ // models elevation as `{known} | {unknown}` precisely so "unknown" survives (see steel-3d-core's
107
+ // knownZ, which likewise returns null and never 0). Callers that need something to draw supply their
108
+ // own fallback; this reports the truth.
109
+ return def == null ? null : def * IN_MM;
110
+ };
111
+
112
+ // Closure-local, so every method below is safe to destructure or pass as a callback. (Using `this`
113
+ // made `const {geometry} = adapter` throw — a boundary API must not carry that trap.)
114
+ const memberById = (id) => {
115
+ for (const p of plans) {
116
+ const hit = (Array.isArray(p.members) ? p.members : []).find(m => m && m.id === id);
117
+ if (hit) return hit;
118
+ }
119
+ return undefined;
120
+ };
121
+
122
+ return {
123
+ /**
124
+ * Every member in the model, across all sheets — selection and edits are model-wide, so reads are too.
125
+ *
126
+ * Returns LIVE contract objects, not copies. That is deliberate and load-bearing: P3's mutation commands
127
+ * operate on these same objects, and cloning here would hand callers a detached graph whose edits go
128
+ * nowhere. It does mean a caller CAN write through a "read" method; enforcing that is the write
129
+ * boundary's job (P3), not a defensive copy here that would cost the whole model on every call.
130
+ */
131
+ members() {
132
+ return plans.flatMap(p => (Array.isArray(p.members) ? p.members : []));
133
+ },
134
+
135
+ /** The member with this id, or undefined. First match wins, mirroring the editor's own `byId`. */
136
+ memberById,
137
+
138
+ /**
139
+ * The member's WORK LINE in world mm — the editable centreline, with no section offset applied.
140
+ * (`contract-to-scene` additionally shifts the rendered box so the work line reads as top-of-steel;
141
+ * that is a rendering concern and deliberately not reflected here.)
142
+ *
143
+ * A column is plumb: both work points share the plan X/Y, and Z runs base → top-of-steel.
144
+ * Returns null for an unknown id, malformed work points, or an end whose elevation is unknown —
145
+ * an unknown elevation is an RFI, not a position, so it is never guessed.
146
+ *
147
+ * `frame` is a SPACE TAG naming the coordinate space, not a local UCS. Do not confuse it with the
148
+ * `frame` of steel-3d-core's worldToLocal/localToWorld, which is a basis object.
149
+ */
150
+ geometry(id) {
151
+ const m = memberById(id);
152
+ if (!m || !Array.isArray(m.wp) || m.wp.length < 2 || !finitePt(m.wp[0]) || !finitePt(m.wp[1])) return null;
153
+ const plan = planFor(m);
154
+ const k = scaleOf(plan);
155
+ const z0 = endElevMm(m, plan, 0), z1 = endElevMm(m, plan, 1);
156
+ if (z0 == null || z1 == null) return null;
157
+ const a = dispToMm(m.wp[0], k);
158
+ const b = m.role === 'column' ? a : dispToMm(m.wp[1], k); // plumb: the top shares the base X/Y
159
+ return { from: [a[0], a[1], z0], to: [b[0], b[1], z1], frame: 'world-mm' };
160
+ },
161
+
162
+ /**
163
+ * The active sheet's structural grid, or null. Returned AS STORED (grid-core owns its vocabulary:
164
+ * relative spacing strings for X/Y, absolute levels for Z, all parsing to mm through grid-core). It is
165
+ * not converted here — re-deriving grid geometry in a second place is exactly the duplication this
166
+ * boundary exists to prevent.
167
+ */
168
+ grid() {
169
+ const p = activePlan();
170
+ return (p && p.grid) || null;
171
+ },
172
+
173
+ /**
174
+ * A sheet's local coordinate frame in world mm, or null when that sheet uses global axes.
175
+ *
176
+ * Stored as `{o,u}` in display pixels — origin plus a unit local-X direction. Converted here to
177
+ * `{origin:[x,y] mm, xAxis:[x,y] unit}`. NOTE the Y negation is a reflection, so a frame that reads
178
+ * counter-clockwise on the sheet reads clockwise in world mm; the axis direction is faithful, its
179
+ * rotational sense is mirrored. Callers comparing angles across the boundary must account for that.
180
+ */
181
+ sheetFrame(sheet) {
182
+ const p = plans.find(x => x.sheet === sheet);
183
+ const f = p && p.frame;
184
+ if (!f || !finitePt(f.o) || !finitePt(f.u)) return null;
185
+ const len = Math.hypot(f.u[0], f.u[1]);
186
+ if (!(len > 0)) return null; // a zero-length axis carries no direction — matches the editor's sanitizeFrame
187
+ const k = scaleOf(p);
188
+ return { origin: dispToMm(f.o, k), xAxis: [f.u[0] / len, -f.u[1] / len] };
189
+ },
190
+
191
+ /**
192
+ * The member's single top-of-steel elevation in mm, or null when it does not have one.
193
+ *
194
+ * Null means "no one elevation", not "zero" — matching steel-3d-core's `knownZ`. A member whose two
195
+ * ends sit at different elevations (a sloping beam, or any column, which spans base to top by
196
+ * definition) genuinely has no single level, so this reports null rather than inventing a
197
+ * representative value; read `geometry(id)` for the two endpoint elevations. Equality is judged at the
198
+ * pinned authoring quantum `MODEL_V2_TOL.CUT_PLANE_MM` (1/16"), not with a fresh magic number.
199
+ */
200
+ elevationOf(id) {
201
+ const m = memberById(id);
202
+ if (!m) return null;
203
+ if (m.role === 'column') return null; // a column spans levels; its top is geometry(id).to[2]
204
+ const plan = planFor(m);
205
+ const z0 = endElevMm(m, plan, 0), z1 = endElevMm(m, plan, 1);
206
+ if (z0 == null || z1 == null) return null;
207
+ return Math.abs(z0 - z1) <= MODEL_V2_TOL.CUT_PLANE_MM ? z0 : null;
208
+ },
209
+ };
210
+ }