diff --git a/package.json b/package.json index 5b8527e..015893e 100644 --- a/package.json +++ b/package.json @@ -58,7 +58,7 @@ "predecoder": "npm run bundle:standalone", "preverify:exports": "npm run bundle:standalone", "prelint": "npm run bundle:standalone", - "build:package": "npm run bundle:standalone && node scripts/build-package.mjs", + "build:package": "node scripts/build-standalone.mjs --force && node scripts/build-package.mjs", "prepack": "npm run build:package", "prepublishOnly": "npm run check" }, diff --git a/scripts/build-standalone.mjs b/scripts/build-standalone.mjs index 358527c..5e8e69f 100644 --- a/scripts/build-standalone.mjs +++ b/scripts/build-standalone.mjs @@ -1,26 +1,66 @@ // Bundles the browser viewer (renderer + runtime) into a string module that // exporters embed into standalone HTML exhibits. +// +// npm pre-scripts call this before almost every command, so it skips the build +// when nothing the bundle reads has changed since the last run. The stamp lists +// every local source file esbuild read, plus the lockfile and this script. +// Pass --force to rebuild regardless. import { build } from 'esbuild'; +import { createHash } from 'node:crypto'; +import { existsSync, readFileSync } from 'node:fs'; import { mkdir, writeFile } from 'node:fs/promises'; -const result = await build({ - entryPoints: ['src/engine/standalone.ts'], - bundle: true, - platform: 'browser', - format: 'iife', - target: 'es2022', - write: false, - minify: true, - legalComments: 'inline', - define: { 'process.env.NODE_ENV': '"production"' }, -}); +const OUT = 'src/generated/standalone.ts'; +const STAMP = 'src/generated/standalone.stamp.json'; +const ALWAYS = ['package-lock.json', 'scripts/build-standalone.mjs']; -const js = result.outputFiles[0].text; -if (!js.length) throw new Error('Empty standalone bundle'); +const hashFile = (file) => { + try { + return createHash('sha256').update(readFileSync(file)).digest('hex'); + } catch { + return null; + } +}; -await mkdir('src/generated', { recursive: true }); -await writeFile( - 'src/generated/standalone.ts', - `// Generated by scripts/build-standalone.mjs. Do not edit.\nexport const standaloneBundle = ${JSON.stringify(js)};\n`, -); -console.log(`Standalone bundle: ${js.length} characters`); +function upToDate() { + if (process.argv.includes('--force') || !existsSync(OUT) || !existsSync(STAMP)) return false; + try { + const stamp = JSON.parse(readFileSync(STAMP, 'utf8')); + const files = Object.entries(stamp.inputs ?? {}); + return files.length > 0 && files.every(([file, hash]) => hashFile(file) === hash); + } catch { + return false; + } +} + +if (upToDate()) { + console.log('Standalone bundle: up to date'); +} else { + const result = await build({ + entryPoints: ['src/engine/standalone.ts'], + bundle: true, + platform: 'browser', + format: 'iife', + target: 'es2022', + write: false, + minify: true, + metafile: true, + legalComments: 'inline', + define: { 'process.env.NODE_ENV': '"production"' }, + }); + + const js = result.outputFiles[0].text; + if (!js.length) throw new Error('Empty standalone bundle'); + + await mkdir('src/generated', { recursive: true }); + await writeFile( + OUT, + `// Generated by scripts/build-standalone.mjs. Do not edit.\nexport const standaloneBundle = ${JSON.stringify(js)};\n`, + ); + + // node_modules inputs are covered by the lockfile hash. + const local = Object.keys(result.metafile.inputs).filter((file) => !file.includes('node_modules/')); + const inputs = Object.fromEntries([...local, ...ALWAYS].map((file) => [file, hashFile(file)])); + await writeFile(STAMP, `${JSON.stringify({ inputs }, null, 2)}\n`); + console.log(`Standalone bundle: ${js.length} characters`); +} diff --git a/skills/decoder/GEOMETRY.md b/skills/decoder/GEOMETRY.md new file mode 100644 index 0000000..fdee0bd --- /dev/null +++ b/skills/decoder/GEOMETRY.md @@ -0,0 +1,90 @@ +# Geometry vocabulary + +Every component's `geometry` is `{ "type": ..., "params": { ... } }`, optionally with `modifiers` and `booleans`. Sizes are in scene units, the same units as `transform.position`. Each shape is centred on its own origin; round shapes stand along the Y axis, so rotate the component to lay them along X or Z. + +Any param you leave out takes the default shown. Unknown params are ignored silently, so spell them exactly. Source of truth: `buildPrimitive` in `src/engine/geometry.ts`. + +## Basic solids + +| type | params (default) | +| ----------------------------- | ------------------------------------------------------------------------------------------------------- | +| `box` | `width` 0.5, `height` 0.5, `depth` 0.5. Edges get a small automatic round unless a side is under 0.014. | +| `rounded_box` | `width` 0.5, `height` 0.5, `depth` 0.5, `radius` 0.05 (corner radius) | +| `cylinder` | `radius` 0.25, `height` 0.6, `segments` 44 (min 24) | +| `tapered_cylinder` | `radiusTop` 0.18, `radiusBottom` 0.3, `height` 0.6, `segments` 44 | +| `sphere` | `radius` 0.3, `widthSegments` 40, `heightSegments` 28 | +| `ellipsoid` | `rx` 0.3, `ry` 0.4, `rz` 0.25 (semi-axes) | +| `cone` | `radius` 0.3, `height` 0.6 | +| `dome` | `radius` 0.35 (upper hemisphere) | +| `torus` | `radius` 0.35 (ring), `tube` 0.08 (thickness), `segments` 64 | +| `hollow_vessel`, `thin_shell` | `outerRadius` 0.35, `innerRadius` 0.28, `height` 0.7, `openTop` true | + +## Profiles and paths + +| type | params (default) | +| --------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `extrude` | `points` [[x,y], ...] closed 2D outline (default 0.6 × 0.4 rectangle), `depth` 0.2, `bevel` true, `bevelThickness` 0.016, `bevelSize` 0.016. Centred after extrusion. | +| `revolve` | `points` [[r,y], ...] half-profile turned about Y (r is distance from the axis), `segments` 48, `smooth` false (true splines the profile) | +| `loft` | `sections` [{ `y`, `points` [[x,z], ...] }, ...]: at least 2, each with the same point count | +| `sweep` | `path` [[x,y,z], ...] (smooth curve through the points), `radius` 0.05 | +| `tube`, `pipe_network`, `flexible_hose` | `points` [[x,y,z], ...], `radius` 0.04, `closed` false. Adds collars at the joints. | +| `rib` | `width` 0.4, `height` 0.25, `thickness` 0.04 (right-triangle gusset) | +| `custom_mesh` | `vertices` flat [x,y,z, ...], `indices` flat triangle list. Use sparingly; normals are computed. | + +## Mechanical parts + +| type | params (default) | +| -------------------- | ------------------------------------------------------------------------------------------------------- | +| `gear` | `teeth` 18 (min 6), `module` 0.04 (pitch diameter = teeth × module), `thickness` 0.1, `boreRadius` 0.08 | +| `gear_train` | `count` 3 (min 2), `module` 0.035. Meshed gears of 12 and 20 teeth alternating along X. | +| `spring` | `radius` 0.18 (coil), `wireRadius` 0.022, `height` 0.5, `coils` 6 | +| `thread` | `radius` 0.14, `pitch` 0.018 (ridge thickness, not the lead), `height` 0.4, `turns` 8 | +| `bearing` | `outerRadius` 0.32, `innerRadius` 0.16, `width` 0.12, `balls` 10 (min 6) | +| `fastener` | `radius` 0.025 (shank), `headHeight` 0.024, `length` 0.06 | +| `flange` | `outerRadius` 0.28, `innerRadius` 0.1, `thickness` 0.055, `bolts` 6 (min 3) | +| `gasket_ring` | `radius` 0.24, `tube` 0.016, `segments` 44 (lies flat in XZ) | +| `piston_cylinder` | `radius` 0.32, `height` 0.36. A piston with ring lands, rings, pin and bosses. | +| `pump_unit` | `radius` 0.22, `length` 0.6 (lies along X) | +| `electric_motor` | `radius` 0.35, `length` 0.85 (lies along X, finned, shaft out both ends) | +| `hydraulic_manifold` | `width` 0.65, `height` 0.28, `depth` 0.35 | +| `heat_exchanger` | `width` 0.7, `height` 0.5, `depth` 0.35, `fins` 11 (min 4) | + +## Electronic, layered and organic + +| type | params (default) | +| ---------------------------------------- | ------------------------------------------------------------------------------- | +| `circuit_board` | `width` 1.0, `height` 0.04 (board thickness), `depth` 0.7, `chips` 5 (min 2) | +| `processor_die` | `width` 1.4, `height` 0.08, `depth` 1.4, `cores` 4 (min 2) | +| `layered_surface` | `layers` 4 (min 2), `width` 1.0, `depth` 1.0, `layerThickness` 0.04, `gap` 0.02 | +| `branching_structure`, `vascular_branch` | `length` 0.9, `radius` 0.09, `branches` 3 (min 2) | +| `molecular_lattice` | `atoms` 8 (min 4), `radius` 0.35 (ring radius) | + +## `instanced` + +A small repeated part; the shape depends on which params you give: + +- `coils` set: spring (`radius` 0.1, `wireRadius` 0.015, `height` 0.25, `coils`). +- else `tube` set: torus (`radius` 0.14, `tube`, `segments` 40). +- else `width` or `depth` set: rounded box (`width` 0.12, `height` 0.06, `depth` 0.08). +- otherwise: cylinder (`radius` 0.05, `height` 0.05). + +An unknown `type` renders a 0.4 placeholder cube; `validate` reports it. + +## Modifiers + +`modifiers` is a list of `{ "kind": ..., ... }` applied in order. Shared fields: `axis` (`x`, `y` or `z`; default `y`) and `offset` [x,y,z]. + +| kind | fields (default) | +| ------------------ | ------------------------------------------------------------------------------------------------------------------------------ | +| `perforation` | `count` 4 (1 to 20), `radius` 0.04, `depth` 1.2, `width` 0.25 (hole spacing) | +| `slot`, `groove` | `width` 0.1, `depth` 0.08, `length` 0.6 | +| `seam` | with `radius`: a ring seam (`depth` 0.008). Without: a flat seam (`width` 0.65, `depth` 0.012, `length` 0.65). | +| `fasteners` | `count` 4 (1 to 16), `boltRadius` 0.02. With `radius`: a bolt circle. Without: corner bolts across `width` 0.4 × `length` 0.4. | +| `gasket`, `o_ring` | `radius` 0.24, `width` 0.015 (cord thickness) | +| `ribs` | `count` 6 (2 to 16), `radius` 0.26, `width` 0.06, `depth` 0.14, `length` 0.022 (rib thickness) | +| `knurling` | `radius` 0.17, `count` 10 (4 to 24), `length` 0.4, `depth` 0.006 | +| `chamfer`, `bevel` | `radius` 0.2, `depth` 0.024 (adds a chamfered collar) | + +## Booleans + +`booleans` is a list of `{ "op": "union" | "subtract" | "intersect", "target": , "transform": }`, applied after modifiers. Use `subtract` for real bores and cut-outs (a cutaway, a hollow handle). Booleans are slower than modifiers, so prefer a modifier when one fits. diff --git a/skills/decoder/SKILL.md b/skills/decoder/SKILL.md index 576b4f4..d46721b 100644 --- a/skills/decoder/SKILL.md +++ b/skills/decoder/SKILL.md @@ -27,13 +27,14 @@ Never edit renderer, Studio or runtime code to represent a subject. Everything a Study a built-in exhibit in `src/projects/` that is close to the subject before writing your own. 2. **Describe three synchronised layers.** - - `components`: nested parts, each with `geometry`, `materialId`, `transform`, `disassembly` and `evidence`. + - `components`: nested parts, each with `geometry`, `materialId`, `transform`, `disassembly` and `evidence`. Every geometry type, its params and defaults, plus modifiers and booleans, are listed in [GEOMETRY.md](GEOMETRY.md). Unknown params are ignored silently, so check spelling there. - `relationships`: typed edges between parts: `force`, `torque`, `rotation`, `translation`, `electrical_power`, `information`, `signal`, `liquid_flow`, `gas_flow`, `heat`, `chemical_exchange`, `optical_transmission`, `control`, `feedback`, `logical_dependency`. + - `effects`: illustrative particles, glows and rays. `radius` is particle size, not coverage; keep it small (a few hundredths of the model's size) and use `path` and `density` to cover an area. - `simulation` and `behaviours`: safe declarative expressions (`sin`, `cos`, `clamp`, `lerp`, `if`, `mod`, `sliderCrank`, `conrodAngle`, lookup tables, ODEs and state machines). No code is ever evaluated. 3. **Validate until clean.** `npm run decoder -- validate .decoder.json` - Fix every error on the component it names (`MISSING_MATERIAL`, `INVALID_GEOMETRY_DIMENSION`, `INVALID_EXPRESSION`, `BROKEN_PARENT_REFERENCE` and so on). Treat warnings as work to do, not noise. + Fix every error on the component it names (`MISSING_MATERIAL`, `UNKNOWN_GEOMETRY_TYPE`, `INVALID_GEOMETRY_DIMENSION`, `INVALID_EXPRESSION`, `BROKEN_PARENT_REFERENCE` and so on). Treat warnings as work to do, not noise. 4. **Inspect and simulate.** `npm run decoder -- inspect .decoder.json` prints diagnostics, bounds and the disassembly plan. diff --git a/src/components/ui/labels.ts b/src/components/ui/labels.ts index 14cd9c8..9485d20 100644 --- a/src/components/ui/labels.ts +++ b/src/components/ui/labels.ts @@ -65,7 +65,7 @@ export function formatNumber(value: number, step?: number): string { /** Splits a runtime readout ("9.0 bar") into its number and unit. */ export function splitReadout(formatted: string, unit: MeasurementUnit): { value: string; unit: string } { const [value] = formatted.split(' '); - return { value, unit: unitText(unit) }; + return { value: unit === '%' ? value.replace(/%$/, '') : value, unit: unitText(unit) }; } export const LIGHTING_LABELS: Record = { diff --git a/src/engine/engine.test.ts b/src/engine/engine.test.ts index cfa30cf..8a484f9 100644 --- a/src/engine/engine.test.ts +++ b/src/engine/engine.test.ts @@ -266,3 +266,38 @@ test('technical illustrations are well-formed SVG markup for every aesthetic', ( ); } }); + +test('validation warns when an effect radius swamps the model, and not at normal sizes', () => { + const sdk = new DecoderSDK(); + const p = structuredClone(BUILTIN_EXHIBITS[0]); + assert.ok(p.effects.length > 0); + assert.ok(!sdk.validate(p).issues.some((i) => i.code === 'EFFECT_RADIUS_TOO_LARGE')); + p.effects[0].radius = 1.5; + const issue = sdk.validate(p).issues.find((i) => i.code === 'EFFECT_RADIUS_TOO_LARGE'); + assert.equal(issue?.severity, 'warning'); + assert.equal(issue?.path, `/effects/${p.effects[0].id}/radius`); + sdk.dispose(); +}); + +test('percent outputs read as 42.5% and split into number and unit', async () => { + const { splitReadout, unitText } = await import('../components/ui/labels'); + const p = structuredClone(BUILTIN_EXHIBITS[0]); + p.simulation.outputs = [{ id: 'duty', label: 'Duty', expression: '42.5', unit: '%', precision: 1 }]; + const sdk = new DecoderSDK(); + const out = sdk.simulateStep(p, 0).outputs[0]; + assert.equal(out.formatted, '42.5%'); + assert.deepEqual(splitReadout(out.formatted, '%'), { value: '42.5', unit: '%' }); + assert.equal(unitText('%'), '%'); + sdk.dispose(); +}); + +test('validation rejects an unknown geometry type instead of drawing a placeholder', () => { + const sdk = new DecoderSDK(); + const p = structuredClone(BUILTIN_EXHIBITS[0]); + const comp = p.components.find((c) => c.geometry)!; + (comp.geometry as { type: string }).type = 'blob'; + const issue = sdk.validate(p).issues.find((i) => i.code === 'UNKNOWN_GEOMETRY_TYPE'); + assert.equal(issue?.severity, 'error'); + assert.equal(issue?.componentId, comp.id); + sdk.dispose(); +}); diff --git a/src/engine/geometry.ts b/src/engine/geometry.ts index 02c9181..0b6b72d 100644 --- a/src/engine/geometry.ts +++ b/src/engine/geometry.ts @@ -1,5 +1,5 @@ import * as THREE from 'three'; -import { ADDITION, Brush, Evaluator, INTERSECTION, SUBTRACTION } from 'three-bvh-csg'; +import { ADDITION, Brush, Evaluator, INTERSECTION, SUBTRACTION } from 'three-bvh-csg/src/index.js'; import { mergeGeometries } from 'three/examples/jsm/utils/BufferGeometryUtils.js'; import type { ComponentNode, diff --git a/src/engine/runtime.ts b/src/engine/runtime.ts index 40a55e7..67193a6 100644 --- a/src/engine/runtime.ts +++ b/src/engine/runtime.ts @@ -166,7 +166,10 @@ export class DecoderRuntime { label: out.label, value: val, unit: out.unit as MeasurementUnit, - formatted: `${val.toFixed(prec)} ${out.unit === 'unitless' ? '' : out.unit}`.trim(), + formatted: + out.unit === '%' + ? `${val.toFixed(prec)}%` + : `${val.toFixed(prec)} ${out.unit === 'unitless' ? '' : out.unit}`.trim(), }; }); diff --git a/src/engine/types.ts b/src/engine/types.ts index 7417b23..ea8898e 100644 --- a/src/engine/types.ts +++ b/src/engine/types.ts @@ -28,6 +28,7 @@ export type MeasurementUnit = | 'N' | 'Nm' | 'ratio' + | '%' | 'unitless'; export type EvidenceClassification = 'observed' | 'documented' | 'inferred' | 'illustrative' | 'unknown'; diff --git a/src/engine/validator.ts b/src/engine/validator.ts index 262b6e7..fcf9ad5 100644 --- a/src/engine/validator.ts +++ b/src/engine/validator.ts @@ -1,7 +1,53 @@ import { validateExpressionSyntax, validateExpressionReferences } from './expressions'; import { validateSchema } from './schema'; -import { computeWorldPositionMap, estimateGeometryLocalBounds } from './spatial'; -import type { DecoderProject, ValidationIssue, ValidationReport } from './types'; +import { computeModelBounds, computeWorldPositionMap, estimateGeometryLocalBounds } from './spatial'; +import type { DecoderProject, PrimitiveType, ValidationIssue, ValidationReport } from './types'; + +const EFFECT_REACH = 3.5; + +// Every geometry type buildPrimitive knows. Record makes the compiler flag a missing one. +const GEOMETRY_TYPES: Record = { + box: true, + rounded_box: true, + cylinder: true, + tapered_cylinder: true, + sphere: true, + ellipsoid: true, + cone: true, + torus: true, + tube: true, + hollow_vessel: true, + dome: true, + extrude: true, + revolve: true, + loft: true, + sweep: true, + thin_shell: true, + rib: true, + gear: true, + thread: true, + spring: true, + bearing: true, + fastener: true, + flange: true, + gasket_ring: true, + pipe_network: true, + flexible_hose: true, + layered_surface: true, + branching_structure: true, + custom_mesh: true, + instanced: true, + piston_cylinder: true, + gear_train: true, + pump_unit: true, + electric_motor: true, + circuit_board: true, + heat_exchanger: true, + hydraulic_manifold: true, + vascular_branch: true, + molecular_lattice: true, + processor_die: true, +}; function isFiniteVec3(v: unknown): v is [number, number, number] { return Array.isArray(v) && v.length === 3 && v.every((n) => typeof n === 'number' && Number.isFinite(n)); @@ -131,6 +177,16 @@ export function validateProject(project: DecoderProject): ValidationReport { // Validate geometry numeric parameters if (comp.geometry) { + if (!Object.hasOwn(GEOMETRY_TYPES, comp.geometry.type)) { + issues.push({ + code: 'UNKNOWN_GEOMETRY_TYPE', + severity: 'error', + path: `/components/${comp.id}/geometry/type`, + componentId: comp.id, + message: `Unknown geometry type "${comp.geometry.type}" on "${comp.name}"; it would render as a placeholder cube.`, + repairHint: `Use one of: ${Object.keys(GEOMETRY_TYPES).join(', ')}.`, + }); + } for (const [pk, pv] of Object.entries(comp.geometry.params)) { if (typeof pv === 'number') { if (!Number.isFinite(pv)) { @@ -443,6 +499,27 @@ export function validateProject(project: DecoderProject): ValidationReport { } } + // Effect radius is the particle size; glows reach about 3x it and vapour spreads 3.5x it. + // Past a quarter of the model's largest dimension the effect swamps the parts it explains. + if (project.effects.length && project.components.some((c) => c.geometry)) { + const modelSize = Math.max(...computeModelBounds(project).size); + for (const eff of project.effects) { + if (typeof eff.radius !== 'number' || !Number.isFinite(eff.radius)) continue; + const reach = eff.radius * EFFECT_REACH; + if (reach > modelSize * 0.25) { + const suggested = Number(((modelSize * 0.25) / EFFECT_REACH).toPrecision(2)); + issues.push({ + code: 'EFFECT_RADIUS_TOO_LARGE', + severity: 'warning', + path: `/effects/${eff.id}/radius`, + componentId: eff.targetComponentId, + message: `Effect "${eff.label}" has radius ${eff.radius}, so its particles reach about ${Number(reach.toPrecision(2))} across a model ${Number(modelSize.toPrecision(2))} wide.`, + repairHint: `Effect radius is particle size, not coverage. Try ${suggested} or less; use path or density for coverage.`, + }); + } + } + } + const errorCount = issues.filter((i) => i.severity === 'error').length; const warningCount = issues.filter((i) => i.severity === 'warning').length; const infoCount = issues.filter((i) => i.severity === 'info').length;