Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: give Three.js model PBR materials an environment to reflect, and export the render profile (#4630)

[._.]/ Adam Eivy56a8394917de
diff --git a/client/src/components/threejsModels/ThreejsModelPreview.jsx b/client/src/components/threejsModels/ThreejsModelPreview.jsx
index b1ab8b23bb..6a894fb9ae 100644
--- a/client/src/components/threejsModels/ThreejsModelPreview.jsx
+++ b/client/src/components/threejsModels/ThreejsModelPreview.jsx
@@ -1,9 +1,10 @@
import { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react';
import { useSearchParams } from 'react-router';
-import { Canvas, useFrame } from '@react-three/fiber';
+import { Canvas, useFrame, useThree } from '@react-three/fiber';
import { Bounds, OrbitControls, useBounds } from '@react-three/drei';
import * as THREE from 'three';
import { createSculptBufferGeometry, needsSculptBufferGeometry, sculptMaterialProps } from '../../lib/threejsSculpt';
+import { createSculptEnvironmentTexture, resolveSculptEnvironment, THREEJS_RENDER_PROFILE } from '../../lib/threejsEnvironment';
import {
collectThreejsCues,
evaluateThreejsClipPose,
@@ -129,14 +130,14 @@ function Geometry({ definition }) {
}
}
-function Material({ definition, highlighted = false, auditMode = 'final', partId, opacity }) {
+function Material({ definition, highlighted = false, auditMode = 'final', partId, opacity, envMapIntensity = 1 }) {
if (auditMode === 'normals') return <meshNormalMaterial />;
if (auditMode === 'wireframe') return <meshBasicMaterial color="#cbd5e1" wireframe />;
if (auditMode === 'boundaries') {
return <meshStandardMaterial color={auditPartColor(partId)} metalness={0} roughness={0.62} />;
}
if (auditMode === 'neutral') return <meshStandardMaterial color="#a8b0bd" metalness={0} roughness={0.72} />;
- const authored = sculptMaterialProps(definition);
+ const authored = sculptMaterialProps(definition, envMapIntensity);
// A clip's opacity channel overrides the authored value for as long as the
// clip drives it. `transparent` has to come with it — Three.js ignores an
// opacity below 1 on an opaque material — but the authored flag still wins
@@ -161,7 +162,7 @@ function Material({ definition, highlighted = false, auditMode = 'final', partId
const offsetPosition = (position = [0, 0, 0], offset) =>
(Array.isArray(offset) ? position.map((value, axis) => value + offset[axis]) : position);
-function Part({ part, materials, layout, selection, selectedId, onSelect, auditMode, pose }) {
+function Part({ part, materials, layout, selection, selectedId, onSelect, auditMode, pose, envMapIntensity }) {
// The clip's pose for this part, or nothing — a part no sequence drives keeps
// exactly the transform the spec authored, which is also what every part of a
// model with no clips at all gets.
@@ -191,11 +192,11 @@ function Part({ part, materials, layout, selection, selectedId, onSelect, auditM
{part.geometry && (
<mesh castShadow={part.castShadow} receiveShadow={part.receiveShadow} onClick={select}>
<Geometry definition={part.geometry} />
- <Material definition={materials[part.material]} highlighted={highlighted} auditMode={auditMode} partId={part.id} opacity={posed?.opacity} />
+ <Material definition={materials[part.material]} highlighted={highlighted} auditMode={auditMode} partId={part.id} opacity={posed?.opacity} envMapIntensity={envMapIntensity} />
</mesh>
)}
{part.children.filter(isReliefPart).map((child) => (
- <Part key={child.id} part={child} materials={materials} layout={layout} selection={selection} selectedId={selectedId} onSelect={onSelect} auditMode={auditMode} pose={pose} />
+ <Part key={child.id} part={child} materials={materials} layout={layout} selection={selection} selectedId={selectedId} onSelect={onSelect} auditMode={auditMode} pose={pose} envMapIntensity={envMapIntensity} />
))}
</>
);
@@ -214,6 +215,7 @@ function Part({ part, materials, layout, selection, selectedId, onSelect, auditM
onSelect={onSelect}
auditMode={auditMode}
pose={pose}
+ envMapIntensity={envMapIntensity}
/>
))}
</group>
@@ -289,10 +291,39 @@ function SceneLight({ light }) {
return <directionalLight color={light.color} intensity={light.intensity} position={light.position} castShadow />;
}
+// The image-based lighting `spec.lights` cannot supply. Punctual lights light a
+// surface; only an environment gives it something to REFLECT, so without this a
+// physically plausible conductor renders near-black and transmission, clearcoat
+// and iridescence do nothing — and the next refinement pass "fixes" that by
+// authoring implausible values back in.
+//
+// Assigned imperatively rather than through drei's <Environment preset=…>, which
+// fetches an HDR from a CDN: rendering a local model must make no outbound
+// request. The texture is owned here, so switching presets or unmounting
+// releases the GPU memory the PMREM pass allocated.
+function SceneEnvironment({ preset }) {
+ const gl = useThree((state) => state.gl);
+ const scene = useThree((state) => state.scene);
+ useEffect(() => {
+ if (!scene) return undefined;
+ const texture = preset === 'none' ? null : createSculptEnvironmentTexture(gl, preset);
+ scene.environment = texture;
+ return () => {
+ // Only clear what this effect set — a later effect may already have
+ // installed the next preset's texture.
+ if (scene.environment === texture) scene.environment = null;
+ texture?.dispose();
+ };
+ }, [gl, scene, preset]);
+ return null;
+}
+
function ProceduralScene({ spec, background, layout, selection, selectedId, onSelect, auditMode, pose, clipId }) {
+ const environment = resolveSculptEnvironment(spec);
return (
<>
{background && <color attach="background" args={[background]} />}
+ <SceneEnvironment preset={environment.preset} />
{spec.lights.map((light, index) => <SceneLight key={`${light.type}-${index}`} light={light} />)}
<Bounds fit clip observe margin={1.25}>
<SceneRefit growth={layout.growth} clipId={clipId} />
@@ -311,6 +342,7 @@ function ProceduralScene({ spec, background, layout, selection, selectedId, onSe
onSelect={onSelect}
auditMode={auditMode}
pose={pose}
+ envMapIntensity={environment.intensity}
/>
))}
</group>
@@ -560,7 +592,12 @@ export default function ThreejsModelPreview({ spec, family = null, className = '
shadows={quality.shadows}
camera={{ position: auditCameraPosition, fov: spec.camera.fov, near: 0.01, far: 10_000 }}
dpr={quality.dpr}
- gl={{ alpha: transparent }}
+ // The colour-management half of the render profile the export stamps on
+ // every model. outputColorSpace and toneMapping come from r3f own
+ // defaults for linear={false} flat={false} — so neither flag is passed
+ // here — while exposure is the one r3f leaves to three, stated outright
+ // rather than inherited so the exported claim stays true.
+ gl={{ alpha: transparent, toneMappingExposure: THREEJS_RENDER_PROFILE.toneMappingExposure }}
>
<PreviewAdaptiveQuality
enabled={qualityMode === 'auto'}
diff --git a/client/src/components/threejsModels/ThreejsModelPreview.test.jsx b/client/src/components/threejsModels/ThreejsModelPreview.test.jsx
index a6067f7151..a41fe2a740 100644
--- a/client/src/components/threejsModels/ThreejsModelPreview.test.jsx
+++ b/client/src/components/threejsModels/ThreejsModelPreview.test.jsx
@@ -2,11 +2,35 @@ import { act, fireEvent, render, screen } from '@testing-library/react';
import { MemoryRouter, useLocation } from 'react-router';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+// The preview reads the live renderer and scene off the r3f context to install a
+// PMREM environment. There is no GL context under jsdom, so the stand-ins below
+// are what the environment effect writes to — and `scene.environment` is the one
+// observable that says whether a spec's preset reached the scene at all.
+const threeState = vi.hoisted(() => ({ gl: { isWebGLRenderer: true }, scene: { environment: null } }));
+const environmentBuilds = vi.hoisted(() => []);
+vi.mock('../../lib/threejsEnvironment', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ // PMREM needs a real renderer; what matters here is WHICH preset the preview
+ // asked for and that the texture it got is released again.
+ createSculptEnvironmentTexture: (_renderer, preset) => {
+ const texture = { preset, dispose: vi.fn() };
+ environmentBuilds.push(texture);
+ return texture;
+ },
+ };
+});
+
vi.mock('@react-three/fiber', () => ({
+ useThree: (selector) => selector(threeState),
Canvas: ({ children, ...props }) => (
<div
data-testid="threejs-canvas"
data-alpha={String(props.gl?.alpha)}
+ data-tone-exposure={String(props.gl?.toneMappingExposure)}
+ data-linear={String(props.linear)}
+ data-flat={String(props.flat)}
data-dpr={Array.isArray(props.dpr) ? props.dpr.join(',') : String(props.dpr)}
data-shadows={String(props.shadows)}
data-camera-position={props.camera?.position?.join(',')}
@@ -47,6 +71,7 @@ vi.mock('../../lib/threejsSculpt', async (importOriginal) => {
};
});
+import { THREEJS_RENDER_PROFILE } from '../../lib/threejsEnvironment';
import ThreejsModelPreview from './ThreejsModelPreview';
const SPEC = {
@@ -232,6 +257,74 @@ describe('ThreejsModelPreview', () => {
});
});
+// Punctual lights light a surface; only an environment gives it something to
+// REFLECT. Without one, a physically plausible conductor renders near-black and
+// the next refinement pass "fixes" that by authoring implausible values back in.
+describe('ThreejsModelPreview environment', () => {
+ const metalSpec = (environment) => ({
+ ...SPEC,
+ ...(environment ? { environment } : {}),
+ materials: { chrome: material({ metalness: 1, roughness: 0.1 }) },
+ parts: [part('shell', box, 'chrome')],
+ });
+ const intensityOf = (container) =>
+ container.querySelector('meshStandardMaterial').getAttribute('envMapIntensity');
+
+ beforeEach(() => {
+ environmentBuilds.length = 0;
+ threeState.scene.environment = null;
+ });
+
+ // Every export stamps THREEJS_RENDER_PROFILE onto the model as the settings it
+ // was authored against. r3f installs sRGB + ACESFilmic for `linear={false}
+ // flat={false}`, so passing either flag here would quietly make that claim
+ // false; exposure is the one r3f leaves alone, so the preview states it.
+ it('renders at the render profile the export promises', () => {
+ renderPreview(<ThreejsModelPreview spec={SPEC} />);
+ const canvas = screen.getByTestId('threejs-canvas');
+ expect(canvas).toHaveAttribute('data-tone-exposure', String(THREEJS_RENDER_PROFILE.toneMappingExposure));
+ expect(canvas).toHaveAttribute('data-linear', 'undefined');
+ expect(canvas).toHaveAttribute('data-flat', 'undefined');
+ });
+
+ it('assigns the authored preset to the scene and forwards its intensity to the material', () => {
+ const { container } = renderPreview(<ThreejsModelPreview spec={metalSpec({ preset: 'studio', intensity: 2 })} />);
+
+ expect(environmentBuilds.map((texture) => texture.preset)).toEqual(['studio']);
+ expect(threeState.scene.environment).toBe(environmentBuilds[0]);
+ expect(intensityOf(container)).toBe('2');
+ });
+
+ // A record stored before the environment block shipped has no key and was
+ // rendered with none, so it must keep rendering exactly that way.
+ it('builds nothing for a spec that predates the environment block', () => {
+ const { container } = renderPreview(<ThreejsModelPreview spec={metalSpec(null)} />);
+
+ expect(environmentBuilds).toHaveLength(0);
+ expect(threeState.scene.environment).toBeNull();
+ expect(intensityOf(container)).toBe('1');
+ });
+
+ it('swaps presets without leaking the previous PMREM texture', () => {
+ const { rerender } = renderPreview(<ThreejsModelPreview spec={metalSpec({ preset: 'neutral', intensity: 1 })} />);
+ const [first] = environmentBuilds;
+
+ rerender(<ThreejsModelPreview spec={metalSpec({ preset: 'studio', intensity: 1 })} />);
+ expect(first.dispose).toHaveBeenCalled();
+ expect(threeState.scene.environment).toBe(environmentBuilds[1]);
+ expect(environmentBuilds[1].preset).toBe('studio');
+ });
+
+ it('releases the texture and clears the scene on unmount', () => {
+ const { unmount } = renderPreview(<ThreejsModelPreview spec={metalSpec({ preset: 'studio', intensity: 1 })} />);
+ const [texture] = environmentBuilds;
+
+ unmount();
+ expect(texture.dispose).toHaveBeenCalled();
+ expect(threeState.scene.environment).toBeNull();
+ });
+});
+
// A knife: one blade carrying surface relief that must not fly off on its own,
// plus a separate handle so there is something to separate FROM.
const knifeSpec = () => ({
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 6065fa4ed5..ceb4702e37 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -181,9 +181,10 @@ grep -i "what you want to do" client/src/lib/README.md
| `terminalScroll.js` | Scrolling the Shell terminal by touch, and inside a full-screen TUI. Two gaps, one primitive: xterm 6 binds **no touch handlers at all** (its viewport is VS Code’s `SmoothScrollableElement`, whose scroll extent is virtual — there is no oversized spacer for the browser to scroll natively), and a TUI’s ALTERNATE screen buffer additionally has no scrollback, so `scrollLines()` clamps to a no-op there. `attachTerminalTouchScroll(terminal)` (→ detach fn) makes a one-finger drag scroll in either buffer; `scrollTerminalLines(terminal, lines, geometry?)` / `scrollTerminalPage(terminal, direction)` drive it — via `scrollLines()` in the normal buffer, and in the alternate buffer by synthesizing `DOM_DELTA_LINE` wheel events on `terminal.element`, xterm’s only injection point (`attachCustomWheelEventHandler` intercepts, it cannot inject), so xterm’s own table picks SGR mouse report vs cursor key from the DEC modes the TUI set. `measureTerminalGeometry(terminal)` takes the one layout-forcing read per gesture (row height + screen centre); `planTouchScrollSteps(accumPx, rowHeightPx)` is the pure sub-row-remainder core. Wired in `useShellSession` (`scrollPage`) + the `SCROLL_KEYS` buttons in `components/shell/TerminalHotKeys.jsx`. |
| `terminalTheme.js` | Pure xterm.js palette builder for the Shell terminal. `buildTerminalTheme({ bg, fg, accent, card, error, success, warning }, mode)` assembles the xterm `theme` object — base ANSI colors from the active theme's CSS vars, the rest from mode-tuned literals (`ANSI_NIGHT` bright/pastel for dark backgrounds, `ANSI_DAY` darkened/saturated so colored CLI output stays legible on daytime themes). `parseCssColorToHex(raw, fallback)` normalizes both the `15 15 15` triple form and the `rgb(7 7 7 / 0.86)` function form (used by `--port-terminal-*` tokens) to `#rrggbb`, dropping alpha. No DOM reads — `Shell.jsx` resolves CSS vars and re-applies on theme switch. |
| `threejsAnimation.js` | Pure pose evaluator for the declarative clip contract in `server/lib/threejsModel.js`, used by the Three.js Models preview transport. `evaluateThreejsClipPose(clip, timeSeconds)` → `{ timeSeconds, pose, activeSequenceIds, activePartIds }` where `pose` is a null-prototype partId → `{ position?, rotationDegrees?, scale?, opacity?, visible? }` map: each part+channel resolves from the one sequence that owns the instant (the window containing it, else the most recent behind it, else the next ahead), `visible` steps at the window's end rather than interpolating, and a part no sequence drives is absent so the spec renders as authored. `collectThreejsCues(clip, from, to)` returns the data-only sound cues a play loop crossed in the half-open `[from, to)` interval — a scrub calls it never, which is what makes scrubbing silent. `listThreejsClips` / `listThreejsCues` / `resolveThreejsClip` / `getThreejsClipDuration` read a spec that may have no `animation` key at all. |
+| `threejsEnvironment.js` | Image-based lighting for the procedural sculpt spec, used by the Three.js Models preview. `spec.lights` are punctual — they light a surface but give it nothing to REFLECT, so `metalness`, `transmission`, `clearcoat` and `iridescence` read off an environment or read off nothing, and a plausible conductor renders near-black without one. `createSculptEnvironmentTexture(renderer, preset)` builds a preset locally from three's own primitives and prefilters it through `PMREMGenerator` — `neutral` is three's bundled `RoomEnvironment`, `studio` a dark shell with three emissive softbox panels plus a floor bounce — returning null for `none`; the caller owns the texture. Deliberately NOT drei's `<Environment preset=…>`, which fetches an HDR from a CDN: rendering a local model makes no outbound request. `resolveSculptEnvironment(spec)` is the client mirror of `resolveThreejsEnvironment` in `server/lib/threejsModel.js`, reading a spec with no `environment` key as the `none` it was actually authored against. |
| `threejsExplode.js` | Disassembly + part-picking maths for the procedural sculpt spec, shared by the Three.js Models preview so explode and the picker agree on what "a part" is. `computeExplodeLayout(parts, amount)` → `{ offsets, meshOffsets, unitIds, growth }`: separation is a layout **scale about the model centre** (≈2× at full explode) plus a base clearance for parts sitting at the centre — never a uniform outward push, which slides the arrangement without opening gaps — where `offsets` add to a unit's own `position` and `meshOffsets` apply to a group around a container's own geometry (moving its group instead would drag its child units along), and `growth` measures how much the layout actually grew so the camera re-fits on real change. `buildPartSelectionIndex(parts)` → `{ owners, ancestry, names }` for click resolution, subtree highlight, and the selection label. All maps are null-prototype — part ids are provider-authored and `idSchema` accepts `toString`. `isReliefPart` / `isContainerPart` expose the shared part definition: a part flagged `explodeWithParent` is surface relief that rides its parent and resolves selection up to it (unless it has no parent to ride), every other geometry-bearing part is both a movable unit and a selectable component, a part whose descendants carry geometry is additionally descended through, and a part with no geometry in its subtree moves nothing. |
| `threejsRig.js` | `summarizeThreejsArticulation(spec)` → `{ articulationReady, jointCount, socketCount, attachmentCount, jointsByPartId }` — client mirror of the readiness rule in `server/lib/threejsModelRig.js`, used by the Three.js Models preview, which is handed a bare spec rather than the record's stored report (and gets none at all for a model generated before rig readiness shipped). A spec with no `articulation` key reads as a static assembly; a graph is ready only when it carries more than a lone root and every child joint names a pivot socket. `jointsByPartId` is null-prototype so a provider-authored part id cannot resolve to an inherited function. |
-| `threejsSculpt.js` | Three.js construction helpers for the validated procedural sculpt spec (`server/lib/threejsModel.js`) used by the Three.js Models preview. `createSculptBufferGeometry(definition)` builds the schema forms r3f has no direct element for — `custom` (indexed BufferGeometry), `extrude` (closed 2D outline + holes swept to `depth`, optional bevel) and `tube` (CatmullRom path swept at `radius`) — returning null for primitives, which stay declarative; callers own disposal. `needsSculptBufferGeometry(definition)` is the matching predicate. `sculptMaterialProps(definition)` maps a material definition to its Three.js props, forwarding the physical-only channels (`clearcoat`, `ior`, `transmission`, `thickness`, `sheen`, `iridescence`, `anisotropy`) only for `type: physical`. Mirrors the `createGeometry`/`createMaterial` bodies `buildThreejsFactorySource()` emits, so the preview and the exported standalone factory render the same scene. |
+| `threejsSculpt.js` | Three.js construction helpers for the validated procedural sculpt spec (`server/lib/threejsModel.js`) used by the Three.js Models preview. `createSculptBufferGeometry(definition)` builds the schema forms r3f has no direct element for — `custom` (indexed BufferGeometry), `extrude` (closed 2D outline + holes swept to `depth`, optional bevel) and `tube` (CatmullRom path swept at `radius`) — returning null for primitives, which stay declarative; callers own disposal. `needsSculptBufferGeometry(definition)` is the matching predicate. `sculptMaterialProps(definition, envMapIntensity)` maps a material definition to its Three.js props, forwarding the physical-only channels (`clearcoat`, `ior`, `transmission`, `thickness`, `sheen`, `iridescence`, `anisotropy`) only for `type: physical`, and the spec-level `environment.intensity` as `envMapIntensity` on every lit material (`basic` is unlit and takes none). Mirrors the `createGeometry`/`createMaterial` bodies `buildThreejsFactorySource()` emits, so the preview and the exported standalone factory render the same scene. |
| `universeBuilderShared.js` | Shared constants + pure category/trunk/composite helpers for the Universe Builder page and its extracted tab/editor components (#2374): `TRUNK_TABS`/`TRUNK_BY_ID`/`TRUNK_BY_KIND`, `TAB_*` + `BUCKET_CANON`, `CATEGORY_LABELS`, `DEFAULT_RENDER_OPTS`, `COMPOSITE_BOARD_KINDS`; and helpers `groupBucketsByKind`, `normalizeCategoryKey`, `humanizeCategory`, `ensureDraftCategories`, `getCategoryKeys`, `compositeKindLabel`. No React state — safe to import from the page or any tab component without a cycle. |
| `universeBuilderCounts.js` | Pure prompt-count helpers for the Universe Builder render buttons (#2374), mirroring the server's compile/skip rules so inline counts match what `/render` will enqueue: `totalVariationCount`, `canonEntryHasContent`, `countCanonWithContent`, `renderPromptCount`, `scopedPromptCount`. The server `compilePrompts`/`synthesizeCanonPrompt` copy is authoritative — keep in sync. |
| `wrSceneCursor.js` | Resolve which script scene the editor caret sits in (`sceneAtCursor`, `sceneAnchorIndex`) — inverse of WorkEditor's jump-to-scene text search; drives the live render preview's "scene at cursor" target. |
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index 06971c5eb6..3ef1ffdfde 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -146,6 +146,7 @@ export * from './terminalDictation.js';
export * from './terminalScroll.js';
export * from './terminalTheme.js';
export * from './threejsAnimation.js';
+export * from './threejsEnvironment.js';
export * from './threejsExplode.js';
export * from './threejsRig.js';
export * from './threejsSculpt.js';
diff --git a/client/src/lib/threejsEnvironment.js b/client/src/lib/threejsEnvironment.js
new file mode 100644
index 0000000000..605985ff10
--- /dev/null
+++ b/client/src/lib/threejsEnvironment.js
@@ -0,0 +1,143 @@
+/**
+ * Image-based lighting for the validated procedural sculpt spec
+ * (`server/lib/threejsModel.js`).
+ *
+ * `spec.lights` are punctual: they light a surface but give it nothing to
+ * REFLECT. Every reflective PBR channel the material schema accepts —
+ * `metalness`, `transmission`, `clearcoat`, `iridescence` — reads off an
+ * environment map or reads off nothing at all, so a physically plausible
+ * conductor renders near-black in a scene with none.
+ *
+ * Both presets are built here from three's own primitives and prefiltered
+ * through `PMREMGenerator`. Deliberately NOT drei's `<Environment preset=…>`:
+ * that fetches an HDR from a CDN, and rendering a local model must never make an
+ * outbound request.
+ */
+
+import * as THREE from 'three';
+import { RoomEnvironment } from 'three/examples/jsm/environments/RoomEnvironment.js';
+
+/**
+ * Mirrors `THREEJS_ENVIRONMENT_PRESETS` in `server/lib/threejsModel.js`, which
+ * is the authoring contract. `threejsEnvironment.test.js` asserts the two agree.
+ */
+export const THREEJS_ENVIRONMENT_PRESETS = ['none', 'neutral', 'studio'];
+
+/** Mirrors `DEFAULT_THREEJS_ENVIRONMENT` — what a spec with no key was rendered with. */
+export const DEFAULT_THREEJS_ENVIRONMENT = Object.freeze({ preset: 'none', intensity: 1 });
+
+/**
+ * Mirrors `THREEJS_RENDER_PROFILE`, the colour-management contract
+ * `buildThreejsFactorySource()` stamps onto every export. The preview has to
+ * actually render at these settings or the exported claim is false, and two
+ * renders of the same spec stop being comparable.
+ *
+ * `outputColorSpace` and `toneMapping` are what react-three-fiber's `<Canvas>`
+ * installs for `linear={false} flat={false}` (its defaults), so the preview
+ * simply must not pass either flag; `toneMappingExposure` is the one it does not
+ * touch, so the preview passes it through `gl`.
+ */
+export const THREEJS_RENDER_PROFILE = Object.freeze({
+ outputColorSpace: 'srgb',
+ toneMapping: 'ACESFilmic',
+ toneMappingExposure: 1,
+});
+
+/**
+ * The spec's environment, normalized. Client mirror of
+ * `resolveThreejsEnvironment` — the preview is handed a bare spec, including
+ * records stored before this block shipped, which read as `none` because that is
+ * what they were authored against.
+ */
+export function resolveSculptEnvironment(spec) {
+ const environment = spec?.environment;
+ if (!environment || typeof environment !== 'object') return { ...DEFAULT_THREEJS_ENVIRONMENT };
+ return {
+ preset: THREEJS_ENVIRONMENT_PRESETS.includes(environment.preset)
+ ? environment.preset
+ : DEFAULT_THREEJS_ENVIRONMENT.preset,
+ intensity: typeof environment.intensity === 'number' && Number.isFinite(environment.intensity)
+ ? environment.intensity
+ : DEFAULT_THREEJS_ENVIRONMENT.intensity,
+ };
+}
+
+// A three-panel softbox rig in a dark shell: a bright key, a broad soft fill
+// opposite it, and a rim behind the subject. Emissive panels rather than lights
+// because PMREM prefilters what the scene RENDERS — a punctual light in the
+// source scene contributes almost nothing to the resulting radiance map, while a
+// panel becomes a reflection with a readable shape. The dark shell is the point
+// of the preset: it gives a conductor high-contrast highlights and real dark
+// regions, which is what makes `metalness` and `clearcoat` legible at all.
+const STUDIO_PANELS = [
+ { size: [7, 7], position: [5, 4, 5], intensity: 6 },
+ { size: [9, 6], position: [-6, 2, 3], intensity: 1.8 },
+ { size: [7, 5], position: [0, 3.5, -7], intensity: 3 },
+ // Floor bounce, so the underside is not a void.
+ { size: [12, 12], position: [0, -5, 0], intensity: 0.6 },
+];
+
+const STUDIO_SHELL_COLOR = 0x14171d;
+
+function createStudioEnvironmentScene() {
+ const scene = new THREE.Scene();
+ scene.add(new THREE.Mesh(
+ new THREE.BoxGeometry(32, 24, 32),
+ new THREE.MeshBasicMaterial({ color: STUDIO_SHELL_COLOR, side: THREE.BackSide })
+ ));
+ for (const panel of STUDIO_PANELS) {
+ const mesh = new THREE.Mesh(
+ new THREE.PlaneGeometry(...panel.size),
+ // Above 1 on purpose: the colour is a linear radiance value here, not a
+ // display colour, and a softbox that only ever reaches white reflects as
+ // flat grey on a smooth metal.
+ new THREE.MeshBasicMaterial({ color: 0xffffff, side: THREE.DoubleSide })
+ );
+ mesh.material.color.multiplyScalar(panel.intensity);
+ mesh.position.set(...panel.position);
+ mesh.lookAt(0, 0, 0);
+ scene.add(mesh);
+ }
+ return scene;
+}
+
+/**
+ * The source scene for a preset, or null for `none` (and for an unknown preset,
+ * which a newer peer's spec can carry — an unrecognized name renders as no
+ * environment rather than as a guess at which one was meant).
+ * Caller owns disposal via `disposeSculptEnvironmentScene`.
+ */
+export function createSculptEnvironmentScene(preset) {
+ if (preset === 'neutral') return new RoomEnvironment();
+ if (preset === 'studio') return createStudioEnvironmentScene();
+ return null;
+}
+
+/** Release every geometry and material a preset scene allocated. */
+export function disposeSculptEnvironmentScene(scene) {
+ scene?.traverse?.((node) => {
+ node.geometry?.dispose?.();
+ const material = node.material;
+ if (Array.isArray(material)) material.forEach((entry) => entry?.dispose?.());
+ else material?.dispose?.();
+ });
+}
+
+/**
+ * PMREM-prefilter a preset into the texture `scene.environment` wants, or null
+ * for `none`. The source scene and the generator are both released here; the
+ * CALLER owns the returned texture and must dispose it.
+ *
+ * @param {THREE.WebGLRenderer} renderer the live renderer (PMREM needs a GL context)
+ * @param {string} preset one of `THREEJS_ENVIRONMENT_PRESETS`
+ */
+export function createSculptEnvironmentTexture(renderer, preset) {
+ if (!renderer) return null;
+ const scene = createSculptEnvironmentScene(preset);
+ if (!scene) return null;
+ const pmrem = new THREE.PMREMGenerator(renderer);
+ const texture = pmrem.fromScene(scene, 0.04).texture;
+ pmrem.dispose();
+ disposeSculptEnvironmentScene(scene);
+ return texture;
+}
diff --git a/client/src/lib/threejsEnvironment.test.js b/client/src/lib/threejsEnvironment.test.js
new file mode 100644
index 0000000000..47ee4ce9a8
--- /dev/null
+++ b/client/src/lib/threejsEnvironment.test.js
@@ -0,0 +1,102 @@
+// @vitest-environment node
+import { describe, expect, it, vi } from 'vitest';
+import * as THREE from 'three';
+import {
+ THREEJS_ENVIRONMENT_PRESETS as SERVER_PRESETS,
+ DEFAULT_THREEJS_ENVIRONMENT as SERVER_DEFAULT,
+ THREEJS_RENDER_PROFILE as SERVER_RENDER_PROFILE,
+ resolveThreejsEnvironment,
+} from '../../../server/lib/threejsModel.js';
+import {
+ THREEJS_ENVIRONMENT_PRESETS,
+ DEFAULT_THREEJS_ENVIRONMENT,
+ THREEJS_RENDER_PROFILE,
+ createSculptEnvironmentScene,
+ createSculptEnvironmentTexture,
+ disposeSculptEnvironmentScene,
+ resolveSculptEnvironment,
+} from './threejsEnvironment.js';
+
+describe('preset contract parity with the server schema', () => {
+ // The server schema is the authoring contract. A preset the viewer cannot
+ // build would be accepted from a provider and then render as nothing, which is
+ // exactly the "authored metal has no environment" bug this module exists to
+ // close — so the two lists have to be one list.
+ it('offers exactly the presets the spec schema accepts', () => {
+ expect(THREEJS_ENVIRONMENT_PRESETS).toEqual(SERVER_PRESETS);
+ expect(DEFAULT_THREEJS_ENVIRONMENT).toEqual(SERVER_DEFAULT);
+ });
+
+ // The export stamps the server's copy onto every model; the preview renders at
+ // the client's. Let them drift and the exported render profile is a lie.
+ it('renders at the render profile the export stamps on the model', () => {
+ expect(THREEJS_RENDER_PROFILE).toEqual(SERVER_RENDER_PROFILE);
+ });
+
+ it('resolves a spec the same way the server does', () => {
+ const specs = [
+ null,
+ {},
+ { environment: { preset: 'studio', intensity: 2 } },
+ { environment: { preset: 'neutral' } },
+ { environment: { preset: 'hdri', intensity: 3 } },
+ { environment: { intensity: Number.NaN } },
+ { environment: 'studio' },
+ ];
+ for (const spec of specs) {
+ expect(resolveSculptEnvironment(spec)).toEqual(resolveThreejsEnvironment(spec));
+ }
+ });
+
+ it('reads a spec with no environment key as none — what it was authored against', () => {
+ expect(resolveSculptEnvironment({ lights: [] })).toEqual({ preset: 'none', intensity: 1 });
+ });
+});
+
+describe('createSculptEnvironmentScene', () => {
+ it('builds nothing for none, or for a preset a newer peer authored', () => {
+ expect(createSculptEnvironmentScene('none')).toBeNull();
+ expect(createSculptEnvironmentScene('hdri')).toBeNull();
+ expect(createSculptEnvironmentScene(undefined)).toBeNull();
+ });
+
+ it('builds the neutral room and the studio rig entirely in-process', () => {
+ for (const preset of ['neutral', 'studio']) {
+ const scene = createSculptEnvironmentScene(preset);
+ expect(scene).toBeInstanceOf(THREE.Scene);
+ expect(scene.children.length).toBeGreaterThan(0);
+ disposeSculptEnvironmentScene(scene);
+ }
+ });
+
+ // The reason for hand-building `studio` rather than reaching for drei's
+ // <Environment preset=…>: a conductor needs bright sources against a dark
+ // surround to read as metal, and PortOS must fetch no HDR to render locally.
+ it('gives studio emissive panels brighter than white against a dark shell', () => {
+ const scene = createSculptEnvironmentScene('studio');
+ const brightness = scene.children.map((child) => child.material.color.r);
+ expect(Math.max(...brightness)).toBeGreaterThan(1);
+ expect(Math.min(...brightness)).toBeLessThan(0.2);
+ disposeSculptEnvironmentScene(scene);
+ });
+
+ it('releases every geometry and material the preset allocated', () => {
+ const scene = createSculptEnvironmentScene('studio');
+ const geometries = [];
+ const materials = [];
+ scene.traverse((node) => {
+ if (node.geometry) geometries.push(vi.spyOn(node.geometry, 'dispose'));
+ if (node.material) materials.push(vi.spyOn(node.material, 'dispose'));
+ });
+ disposeSculptEnvironmentScene(scene);
+ expect(geometries.length).toBeGreaterThan(0);
+ for (const spy of [...geometries, ...materials]) expect(spy).toHaveBeenCalled();
+ });
+});
+
+describe('createSculptEnvironmentTexture', () => {
+ it('returns null without building anything for none or a missing renderer', () => {
+ expect(createSculptEnvironmentTexture(null, 'studio')).toBeNull();
+ expect(createSculptEnvironmentTexture({}, 'none')).toBeNull();
+ });
+});
diff --git a/client/src/lib/threejsSculpt.js b/client/src/lib/threejsSculpt.js
index 1b9e8c6722..dea57c5414 100644
--- a/client/src/lib/threejsSculpt.js
+++ b/client/src/lib/threejsSculpt.js
@@ -62,8 +62,15 @@ export function createSculptBufferGeometry(definition) {
* Map a validated material definition to the props for its Three.js material.
* Physical-only channels are dropped for standard/basic so an authored spec that
* carries schema defaults cannot leak unsupported props onto the wrong material.
+ *
+ * `envMapIntensity` is the spec-level `environment.intensity` (see
+ * `threejsEnvironment.js`), forwarded to every lit material so the strength the
+ * spec authored actually reaches the surfaces reflecting it. `basic` is unlit
+ * and takes no environment at all. Mirrors `createMaterial()` in
+ * `buildThreejsFactorySource()`, which reads the same value off the exported
+ * render profile — the two must move together.
*/
-export function sculptMaterialProps(definition) {
+export function sculptMaterialProps(definition, envMapIntensity = 1) {
const unlit = {
color: definition.color,
opacity: definition.opacity,
@@ -77,6 +84,7 @@ export function sculptMaterialProps(definition) {
roughness: definition.roughness,
emissive: definition.emissive,
emissiveIntensity: definition.emissiveIntensity,
+ envMapIntensity,
};
if (definition.type !== 'physical') return lit;
return {
diff --git a/client/src/lib/threejsSculpt.test.js b/client/src/lib/threejsSculpt.test.js
index 3956758f5c..d7797a7c9a 100644
--- a/client/src/lib/threejsSculpt.test.js
+++ b/client/src/lib/threejsSculpt.test.js
@@ -120,5 +120,16 @@ describe('sculptMaterialProps', () => {
const props = sculptMaterialProps({ ...definition, type: 'basic' });
expect(props).toEqual({ color: '#ffffff', opacity: 1, transparent: false, wireframe: false });
});
+
+ // Without this the spec's environment intensity never reaches a surface, and
+ // every model reflects at exactly 1 whatever it authored.
+ it('forwards the environment intensity to lit materials only', () => {
+ expect(sculptMaterialProps(definition, 2.5).envMapIntensity).toBe(2.5);
+ expect(sculptMaterialProps({ ...definition, type: 'standard' }, 2.5).envMapIntensity).toBe(2.5);
+ expect(sculptMaterialProps({ ...definition, type: 'basic' }, 2.5)).not.toHaveProperty('envMapIntensity');
+ // A caller that has no environment to declare still gets the neutral value,
+ // never `undefined` — three reads that as "leave the material's own".
+ expect(sculptMaterialProps(definition).envMapIntensity).toBe(1);
+ });
});
// @vitest-environment node
diff --git a/client/src/pages/ThreejsModelDetail.jsx b/client/src/pages/ThreejsModelDetail.jsx
index 55b785211c..65a764d744 100644
--- a/client/src/pages/ThreejsModelDetail.jsx
+++ b/client/src/pages/ThreejsModelDetail.jsx
@@ -653,7 +653,7 @@ export default function ThreejsModelDetail() {
? 'Recognized materials match their substance'
: 'No material named a substance to check'}
footer={`Every channel here is already inside what Three.js accepts, so this check asks the other question: whether the values suit the substance the material is named for — metallic wood and opaque glass both parse. Only materials whose id names exactly one substance are checked, and nothing is ever adjusted.${
- materialFindings.length > 0
+ countSeverities(materialFindings).warning > 0
? ' Refining without your own feedback will also ask for values that match the substance — keep any deliberate stylization in your own feedback.'
: ''
}`}
diff --git a/server/lib/README.md b/server/lib/README.md
index da207b873f..9846d79c48 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -176,7 +176,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `imageWatermark.js` | `removeCornerWatermark` (erases the visible Gemini/Nano-Banana bottom-right ✦ via dependency-free harmonic/Laplace inpaint) + pure helpers `resolveWatermarkRegion` / `inpaintRegion`. Distinct from SynthID regen — this targets the *visible* corner logo. |
| `localImageFilename.js` | `localImageFilename(urlOrPath)` resolves a stored image reference to the bare gallery-image filename under `data/images/` (or null for empty/external-URL/non-image-path) — the unit the peer-sync asset pipeline hashes + transfers. Single source of truth for the authors/artists/albums/Creative-Director filename resolvers (`headshotImageFilename`/`portraitImageFilename`/`coverImageFilename`/`startingImageFilename` are thin wrappers). Also exports `assetBasename(pathOrName)`, the shared strip-querystring→basename primitive (reused by moodBoard's `imageUrlToAppAsset`). |
| `localMemory.js` | Shared best-effort local-model unload + available-memory report (`prepareLocalMemory`) for GPU-heavy local work; only loopback Ollama / LM Studio backends are evicted. |
-| `threejsModel.js` | Validated declarative procedural-model schema plus deterministic standalone Three.js factory export for the Three.js Models workspace. Also the cross-section gate: `evaluateThreejsFlatness(spec)` counts distinct vertex planes per axis — relative to the mesh's own size, with a rotation-invariant zero-volume check behind it — and treats an `extrude` with no bevel thickness as the two-plane slab it is to report when the majority of identity-priority features are built only from flat parts — a model that reads right head-on and like cardboard when orbited. `buildThreejsFlatnessFeedback(flatness)` turns that into default refinement feedback; `listSpecNames(names)` is the shared capped name-list formatter both gates use in finding messages. Also the material-plausibility gate: `evaluateThreejsMaterialPlausibility(spec)` keys a bounded per-family prior table (metal, wood, plastic, glass, fabric, ceramic, rubber, stone, leather, paper) off tokens in each material's id and reports channels whose values the named substance does not support — metalness 0.9 oak, transmission 1.0 steel — skipping any id that names no family or two, and any channel the material's `type` never forwards to Three.js. Advisory only: it never clamps, because a stylized model may legitimately break every prior. `buildThreejsMaterialFeedback(plausibility)` turns that into default refinement feedback. |
+| `threejsModel.js` | Validated declarative procedural-model schema plus deterministic standalone Three.js factory export for the Three.js Models workspace. Also the cross-section gate: `evaluateThreejsFlatness(spec)` counts distinct vertex planes per axis — relative to the mesh's own size, with a rotation-invariant zero-volume check behind it — and treats an `extrude` with no bevel thickness as the two-plane slab it is to report when the majority of identity-priority features are built only from flat parts — a model that reads right head-on and like cardboard when orbited. `buildThreejsFlatnessFeedback(flatness)` turns that into default refinement feedback; `listSpecNames(names)` is the shared capped name-list formatter both gates use in finding messages. Also the material-plausibility gate: `evaluateThreejsMaterialPlausibility(spec)` keys a bounded per-family prior table (metal, wood, plastic, glass, fabric, ceramic, rubber, stone, leather, paper) off tokens in each material's id and reports channels whose values the named substance does not support — metalness 0.9 oak, transmission 1.0 steel — skipping any id that names no family or two, and any channel the material's `type` never forwards to Three.js. Advisory only: it never clamps, because a stylized model may legitimately break every prior. `buildThreejsMaterialFeedback(plausibility)` turns that into default refinement feedback. The same pass emits a `reflective-material-without-environment` note when a spec authors reflective channels (metalness above 0.6, or any transmission/clearcoat/iridescence) while `environment.preset` is `none` — those channels read off an environment, so in that scene their values cannot be judged at all. `THREEJS_ENVIRONMENT_PRESETS` / `resolveThreejsEnvironment(spec)` are the bounded `{ preset, intensity }` block and its `none`-defaulting reader (a spec stored before it shipped has no key and was rendered with no environment), and `THREEJS_RENDER_PROFILE` is the colour-space/tone-map/exposure contract `buildThreejsFactorySource()` stamps onto `root.userData.sculptRuntime.render` and exports as `renderProfile`, so a consumer wiring their own `WebGLRenderer` reproduces the model instead of a differently tone-mapped approximation. |
| `threejsModelAnimation.js` | `summarizeThreejsAnimation(spec)` — clip inventory *and* playback gate over an already-validated Three.js spec: `{ animated, clipCount, cueCount, sequenceCount, movingPartCount, longestClipSeconds, findings, warningCount, clips }`. The schema proves a declared `animation` block is well *formed* (sequences on real parts, inside their clip, never two on one channel at once, never a cue without motion); this reports what the model *declared* — one entry per clip with its role, duration, sequence and distinct-cue counts — plus the ways a well-formed clip still plays badly: a clip authored against a pose the assembly does not build (`clip-start-pose-mismatch`), a handover between sequences that do not meet (`clip-sequence-jump`), a `loop: true` clip that does not return to where it began, a one-shot `idle`, an unfired cue, a long dead tail, and an articulation graph with no clip at all. Advisory warnings only — a static assembly is a complete answer. `buildThreejsAnimationFeedback(animation)` turns those findings into default refinement feedback. A spec with no `animation` key summarizes as not animated — never as evaluated-and-empty. |
| `threejsModelCoverage.js` | `evaluateThreejsPartCoverage(spec, { family })` — structural assembly gate over an already-validated Three.js spec: flags promised features fused onto the same part set, geometry claimed by no detail, and details nothing was built for (folded minor relief stays a `note`). With a subject family it also warns on a required component the spec never mentions at all — the one check that can fault a spec for what it failed to *promise*. `buildThreejsCoverageFeedback(coverage)` turns the error findings (plus any family gap) into default refinement feedback. |
| `threejsModelFamilies.js` | Curated subject-family checklists for Three.js generation. `THREEJS_MODEL_FAMILY_OPTIONS` / `THREEJS_MODEL_FAMILY_IDS` drive the picker and route validation; `buildThreejsFamilyChecklist(id)` returns the prompt block spliced into generation (`''` for the default `general`, so an un-narrowed subject keeps the unchanged general-purpose prompt); `findMissingFamilyComponents(spec, id)` reports which required components the spec never mentions. |
diff --git a/server/lib/threejsModel.js b/server/lib/threejsModel.js
index 1219692dfc..84ebce51fa 100644
--- a/server/lib/threejsModel.js
+++ b/server/lib/threejsModel.js
@@ -316,6 +316,69 @@ const lightSchema = z.object({
penumbra: z.number().finite().min(0).max(1).default(0.25),
});
+/**
+ * The image-based lighting the spec is authored against.
+ *
+ * `lights` alone are punctual: they light a surface but give it nothing to
+ * REFLECT, and every reflective PBR channel the material schema accepts —
+ * `metalness`, `transmission`, `clearcoat`, `iridescence` — reads off an
+ * environment or reads off nothing at all. A conductor in a scene with no
+ * environment renders near-black however plausible its values are, so a
+ * refinement pass has every incentive to "fix" the look by authoring
+ * implausible values back in.
+ *
+ * Both presets are built locally from three's own primitives (see
+ * `client/src/lib/threejsEnvironment.js`) — PortOS never fetches an HDR to
+ * render a local model.
+ */
+export const THREEJS_ENVIRONMENT_PRESETS = ['none', 'neutral', 'studio'];
+
+const environmentSchema = z.object({
+ preset: z.enum(THREEJS_ENVIRONMENT_PRESETS).default('none'),
+ intensity: z.number().finite().min(0).max(4).default(1),
+});
+
+/**
+ * What a spec with no `environment` key means. A record stored before this block
+ * shipped was authored and rendered with no environment at all, so `none` is the
+ * honest reading of it — not a retroactive claim that it had one.
+ */
+export const DEFAULT_THREEJS_ENVIRONMENT = Object.freeze({ preset: 'none', intensity: 1 });
+
+/**
+ * The spec's environment, normalized for a caller that must not care whether the
+ * key is present. Tolerant of a partially-filled block so a stored record that
+ * predates a field reads as the default for it rather than `undefined`.
+ */
+export const resolveThreejsEnvironment = (spec) => {
+ const environment = spec?.environment;
+ if (!environment || typeof environment !== 'object') return { ...DEFAULT_THREEJS_ENVIRONMENT };
+ return {
+ preset: THREEJS_ENVIRONMENT_PRESETS.includes(environment.preset)
+ ? environment.preset
+ : DEFAULT_THREEJS_ENVIRONMENT.preset,
+ intensity: typeof environment.intensity === 'number' && Number.isFinite(environment.intensity)
+ ? environment.intensity
+ : DEFAULT_THREEJS_ENVIRONMENT.intensity,
+ };
+};
+
+/**
+ * The renderer settings a PortOS-authored spec is composed against, stamped onto
+ * the exported factory so a consumer wiring their own `WebGLRenderer` reproduces
+ * the model instead of a differently tone-mapped approximation of it. These are
+ * the react-three-fiber `<Canvas>` defaults the preview runs on; two renders of
+ * the same spec are only comparable when both sides agree on them.
+ *
+ * Data only. The factory never constructs a renderer, exactly as it never
+ * constructs a scene or a camera.
+ */
+export const THREEJS_RENDER_PROFILE = Object.freeze({
+ outputColorSpace: 'srgb',
+ toneMapping: 'ACESFilmic',
+ toneMappingExposure: 1,
+});
+
const socketSchema = z.object({
name: idSchema,
parentPartId: idSchema,
@@ -538,6 +601,11 @@ const makeSpecSchema = (scaleSchema) => z.object({
.refine((materials) => Object.keys(materials).length > 0, 'at least one material is required')
.refine((materials) => Object.keys(materials).length <= 50, 'at most 50 materials are allowed'),
lights: z.array(lightSchema).min(1).max(8),
+ // Optional and additive, same contract as `articulation` and `animation`: a
+ // spec authored before image-based lighting shipped simply has no key, which
+ // `resolveThreejsEnvironment` reads as the `none` it was actually rendered
+ // with. A newly authored spec is asked for a real preset.
+ environment: environmentSchema.optional(),
parts: z.array(makePartSchema(scaleSchema)).min(1).max(40),
sockets: z.array(socketSchema).max(40).default([]),
// Optional and additive: a spec written before articulation shipped simply has
@@ -989,6 +1057,24 @@ const MATERIAL_CHANNELS_BY_TYPE = {
physical: ['metalness', 'roughness', 'clearcoat', 'ior', 'transmission', 'sheen'],
};
+// The channels that read off an ENVIRONMENT rather than off the punctual lights:
+// with nothing to reflect, a conductor renders near-black and transmission,
+// clearcoat and iridescence do essentially nothing. Same type filter as above —
+// `basic` is unlit and the physical-only channels are forwarded only by
+// `type: 'physical'` — so the note never names a channel that could not have
+// rendered anyway. The metalness threshold is the metal family's own floor: a
+// dielectric with a little metalness has almost nothing to lose here.
+const REFLECTIVE_METALNESS_FLOOR = 0.6;
+const REFLECTIVE_CHANNELS_BY_TYPE = {
+ basic: [],
+ standard: ['metalness'],
+ physical: ['metalness', 'transmission', 'clearcoat', 'iridescence'],
+};
+
+// A channel counts as authored when it is above the floor its own absence would
+// sit at: metalness has a real threshold, the rest are opt-in from zero.
+const reflectiveChannelFloor = (channel) => (channel === 'metalness' ? REFLECTIVE_METALNESS_FLOOR : 0);
+
/**
* Split a material id into lowercase word tokens, breaking on separators AND on
* camelCase boundaries so `oakTrim` and `oak_trim` tokenize the same. A trailing
@@ -1035,9 +1121,19 @@ const matchMaterialFamily = (id) => {
export function evaluateThreejsMaterialPlausibility(spec) {
const materials = (spec?.materials && typeof spec.materials === 'object') ? spec.materials : {};
const findings = [];
+ const unlitReflective = [];
+ const environment = resolveThreejsEnvironment(spec);
let matched = 0;
for (const [id, material] of Object.entries(materials)) {
+ if (environment.preset === 'none') {
+ const reflective = (REFLECTIVE_CHANNELS_BY_TYPE[material?.type] || REFLECTIVE_CHANNELS_BY_TYPE.standard)
+ .filter((channel) => {
+ const value = material?.[channel];
+ return typeof value === 'number' && Number.isFinite(value) && value > reflectiveChannelFloor(channel);
+ });
+ if (reflective.length > 0) unlitReflective.push({ id, channels: reflective });
+ }
const prior = matchMaterialFamily(id);
if (!prior) continue;
matched += 1;
@@ -1066,13 +1162,28 @@ export function evaluateThreejsMaterialPlausibility(spec) {
});
}
+ // One finding per implausible material, so the warning tally is also the count
+ // of materials that failed — no separate tally that could disagree with it.
+ const warningCount = findings.length;
+
+ // One note for the whole spec rather than one per material: the remedy is a
+ // single spec-level choice, and repeating it per material would bury the
+ // substance warnings above it.
+ if (unlitReflective.length > 0) {
+ findings.push({
+ code: 'reflective-material-without-environment',
+ severity: 'note',
+ materialIds: unlitReflective.map((entry) => entry.id),
+ channels: unlitReflective,
+ message: `${listSpecNames(unlitReflective.map((entry) => entry.id))} author reflective channels (${listSpecNames([...new Set(unlitReflective.flatMap((entry) => entry.channels))])}) while "environment.preset" is "none". Those channels read off an environment, so in this scene a conductor renders near-black and transmission, clearcoat and iridescence do essentially nothing — the values cannot be judged as authored. Give the spec an environment ("neutral" or "studio") to see them.`,
+ });
+ }
+
return {
findings,
errorCount: 0,
- warningCount: findings.length,
- noteCount: 0,
- // One finding per implausible material, so `warningCount` is also the count
- // of materials that failed — no separate tally that could disagree with it.
+ warningCount,
+ noteCount: findings.length - warningCount,
materialCount: Object.keys(materials).length,
matchedMaterialCount: matched,
};
@@ -1080,17 +1191,24 @@ export function evaluateThreejsMaterialPlausibility(spec) {
/**
* Default refinement feedback derived from a stored material-plausibility
- * result. Returns '' when every recognized material is plausible, so the caller
- * falls through to whatever other feedback it has.
+ * result: the substance warnings, then the unlit-reflective note if the spec
+ * authored reflective channels with no environment. Returns '' when there is
+ * neither, so the caller falls through to whatever other feedback it has.
*/
export function buildThreejsMaterialFeedback(plausibility) {
- const warnings = (plausibility?.findings || []).filter((finding) => finding.severity === 'warning');
- if (warnings.length === 0) return '';
- return [
+ const findings = plausibility?.findings || [];
+ const warnings = findings.filter((finding) => finding.severity === 'warning');
+ const substance = warnings.length === 0 ? [] : [
'The previous pass gave some materials values that do not match the substance they are named for:',
...warnings.map((finding, index) => `${index + 1}. ${finding.message}`),
'Set each channel from what the surface actually is — bare metal is metallic and fairly smooth, wood and stone are rough dielectrics, glass transmits — and keep any deliberate stylization you still want.',
- ].join('\n');
+ ];
+ // The unlit-reflective note is fed back as well as displayed: choosing an
+ // environment preset is a change the next pass can actually make, and leaving
+ // it out is what lets a refinement "fix" a black conductor by dropping its
+ // metalness instead.
+ const unlit = findings.filter((finding) => finding.code === 'reflective-material-without-environment');
+ return [...substance, ...unlit.map((finding) => finding.message)].join('\n');
}
const toIdentifier = (name) => {
@@ -1114,12 +1232,28 @@ export function buildThreejsFactorySource(input) {
const spec = parsed.data;
const factoryName = `create${toIdentifier(spec.name)}Model`;
const serialized = JSON.stringify(spec, null, 2);
+ // The renderer contract the spec was composed against. Serialized rather than
+ // derived in the emitted source, because the colour-management half of it is
+ // PortOS's viewer contract and is not in the spec at all.
+ const renderProfile = JSON.stringify(
+ { ...THREEJS_RENDER_PROFILE, environment: resolveThreejsEnvironment(spec) },
+ null,
+ 2
+ );
return `// Generated by PortOS Three.js Models.
// Procedural image-to-Three.js workflow inspired by https://github.com/hoainho/img2threejs
import * as THREE from 'three';
const spec = ${serialized};
+
+// The renderer settings this model was authored against. Configure your own
+// WebGLRenderer and scene to match, or it will not reproduce: without the
+// environment its metals have nothing to reflect, and a different tone map or
+// exposure changes every value on screen. Data only — this module builds no
+// renderer, and the environment preset is yours to construct.
+const renderProfile = ${renderProfile};
+
const radians = (degrees) => THREE.MathUtils.degToRad(degrees);
const rotation = (value) => value.map(radians);
@@ -1192,6 +1326,9 @@ function createMaterial(definition) {
roughness: definition.roughness,
emissive: definition.emissive,
emissiveIntensity: definition.emissiveIntensity,
+ // The spec's environment intensity, so the reflective channels below read at
+ // the strength they were authored at once you assign the environment.
+ envMapIntensity: renderProfile.environment.intensity,
};
if (definition.type === 'physical') {
return new THREE.MeshPhysicalMaterial({
@@ -1254,10 +1391,13 @@ export function ${factoryName}() {
animation: spec.animation || null,
detailInventory: spec.detailInventory,
limitations: spec.limitations,
+ // The renderer contract above, carried on the model so a consumer that only
+ // ever sees the Group still knows what it has to match to reproduce it.
+ render: renderProfile,
};
return root;
}
${THREEJS_PLAYER_SOURCE}
-export { spec };
+export { spec, renderProfile };
`;
}
diff --git a/server/lib/threejsModel.test.js b/server/lib/threejsModel.test.js
index 1892cbf394..c08b75efdd 100644
--- a/server/lib/threejsModel.test.js
+++ b/server/lib/threejsModel.test.js
@@ -5,6 +5,7 @@ import {
buildThreejsMaterialFeedback,
evaluateThreejsFlatness,
evaluateThreejsMaterialPlausibility,
+ resolveThreejsEnvironment,
storedThreejsSculptSpecSchema,
threejsGeometrySchema,
threejsSculptSpecSchema,
@@ -745,8 +746,13 @@ describe('buildThreejsFactorySource articulation', () => {
// crate hierarchy and swaps the material map. Every material is parsed through
// the real schema first, so a fixture can never assert on a value the authoring
// contract would have rejected anyway.
-const materialSpec = (materials) => threejsSculptSpecSchema.parse({
+// Every case that is about SUBSTANCE plausibility gets a real environment, so the
+// unlit-reflective note never lands in its findings; the environment cases pass
+// null to omit the key entirely, which is what a record stored before the block
+// shipped looks like.
+const materialSpec = (materials, environment = { preset: 'studio', intensity: 1 }) => threejsSculptSpecSchema.parse({
...validSpec(),
+ ...(environment ? { environment } : {}),
materials,
parts: [{ ...validSpec().parts[0], children: [], material: Object.keys(materials)[0] }],
sockets: [],
@@ -841,6 +847,124 @@ describe('evaluateThreejsMaterialPlausibility', () => {
});
});
+describe('evaluateThreejsMaterialPlausibility environment', () => {
+ const notes = (result) => result.findings.filter((finding) => finding.severity === 'note');
+
+ // The whole point of the note: metalness 0.95 is exactly what the metal prior
+ // ASKS for, so it draws no substance warning — and in a scene with no
+ // environment it renders near-black anyway.
+ it('notes a plausible conductor that has nothing to reflect', () => {
+ const result = evaluateThreejsMaterialPlausibility(materialSpec({
+ steelPlate: { type: 'standard', color: '#8a8f98', metalness: 0.95, roughness: 0.2 },
+ }, null));
+ expect(result.warningCount).toBe(0);
+ expect(result.noteCount).toBe(1);
+ const [note] = notes(result);
+ expect(note.code).toBe('reflective-material-without-environment');
+ expect(note.materialIds).toEqual(['steelPlate']);
+ expect(note.message).toContain('metalness');
+ expect(note.message).toContain('"none"');
+ });
+
+ it('names transmission, clearcoat, and iridescence as reflective too', () => {
+ const result = evaluateThreejsMaterialPlausibility(materialSpec({
+ windowPane: { type: 'physical', color: '#cfe8ff', metalness: 0, roughness: 0.05, transmission: 0.9, ior: 1.5 },
+ lacquerShell: { type: 'physical', color: '#334155', metalness: 0, roughness: 0.3, clearcoat: 0.8 },
+ pearlInlay: { type: 'physical', color: '#f5f5f4', metalness: 0, roughness: 0.2, iridescence: 0.7 },
+ }, null));
+ const [note] = notes(result);
+ expect(note.materialIds).toEqual(['windowPane', 'lacquerShell', 'pearlInlay']);
+ expect(note.message).toContain('transmission');
+ expect(note.message).toContain('clearcoat');
+ expect(note.message).toContain('iridescence');
+ });
+
+ it('stays silent once the spec authors an environment', () => {
+ const materials = {
+ steelPlate: { type: 'standard', color: '#8a8f98', metalness: 0.95, roughness: 0.2 },
+ };
+ expect(notes(evaluateThreejsMaterialPlausibility(materialSpec(materials, { preset: 'neutral', intensity: 1 })))).toEqual([]);
+ expect(notes(evaluateThreejsMaterialPlausibility(materialSpec(materials, { preset: 'studio', intensity: 2 })))).toEqual([]);
+ // An explicit "none" is the same scene as no key at all, so it still notes.
+ expect(notes(evaluateThreejsMaterialPlausibility(materialSpec(materials, { preset: 'none', intensity: 1 })))).toHaveLength(1);
+ });
+
+ // A channel the material's type never forwards cannot render, so it cannot be
+ // the reason anything looks wrong — and a dielectric with a trace of metalness
+ // has essentially nothing to lose.
+ it('ignores channels the type drops, unlit materials, and non-reflective values', () => {
+ const result = evaluateThreejsMaterialPlausibility(materialSpec({
+ plasticShell: { type: 'standard', color: '#334155', metalness: 0.2, roughness: 0.5, transmission: 1, clearcoat: 1 },
+ decalSticker: { type: 'basic', color: '#8a8f98', metalness: 1, roughness: 0 },
+ }, null));
+ expect(notes(result)).toEqual([]);
+ });
+
+ it('feeds the note back so a refinement fixes the scene instead of the metal', () => {
+ const feedback = buildThreejsMaterialFeedback(evaluateThreejsMaterialPlausibility(materialSpec({
+ steelPlate: { type: 'standard', color: '#8a8f98', metalness: 0.95, roughness: 0.2 },
+ }, null)));
+ expect(feedback).toContain('steelPlate');
+ expect(feedback).toContain('environment');
+ // No substance warning fired, so the feedback must not open with one.
+ expect(feedback).not.toContain('do not match the substance');
+ });
+});
+
+describe('threejsSculptSpecSchema environment', () => {
+ it('accepts a bounded preset and intensity', () => {
+ const parsed = threejsSculptSpecSchema.parse({ ...validSpec(), environment: { preset: 'studio', intensity: 2.5 } });
+ expect(parsed.environment).toEqual({ preset: 'studio', intensity: 2.5 });
+ expect(threejsSculptSpecSchema.safeParse({ ...validSpec(), environment: { preset: 'hdri' } }).success).toBe(false);
+ expect(threejsSculptSpecSchema.safeParse({ ...validSpec(), environment: { preset: 'studio', intensity: 9 } }).success).toBe(false);
+ });
+
+ // Additive-optional, the same contract as `articulation` and `animation`: a
+ // record an install stored before this block shipped must parse untouched, and
+ // must not acquire a key claiming an environment it never had.
+ it('leaves a stored spec that predates it alone, and reads it as none', () => {
+ const legacy = validSpec();
+ const parsed = storedThreejsSculptSpecSchema.parse(legacy);
+ expect(parsed.environment).toBeUndefined();
+ expect(resolveThreejsEnvironment(parsed)).toEqual({ preset: 'none', intensity: 1 });
+ });
+
+ it('reads a partial or unrecognized block as the default for the missing half', () => {
+ // A newer peer's preset name resolves to `none` rather than to a guess.
+ expect(resolveThreejsEnvironment({ environment: { preset: 'hdri', intensity: 2 } })).toEqual({ preset: 'none', intensity: 2 });
+ expect(resolveThreejsEnvironment({ environment: { preset: 'studio' } })).toEqual({ preset: 'studio', intensity: 1 });
+ expect(resolveThreejsEnvironment(null)).toEqual({ preset: 'none', intensity: 1 });
+ });
+});
+
+describe('buildThreejsFactorySource render profile', () => {
+ it('stamps the renderer contract the model was authored against', () => {
+ const source = buildThreejsFactorySource({ ...validSpec(), environment: { preset: 'studio', intensity: 1.5 } });
+ expect(source).toContain('const renderProfile = {');
+ expect(source).toContain('export { spec, renderProfile };');
+ expect(source).toContain('render: renderProfile,');
+ const flat = source.replace(/\s+/g, '');
+ expect(flat).toContain('"outputColorSpace":"srgb"');
+ expect(flat).toContain('"toneMapping":"ACESFilmic"');
+ expect(flat).toContain('"toneMappingExposure":1');
+ expect(flat).toContain('"environment":{"preset":"studio","intensity":1.5}');
+ // The intensity has to REACH the material, or the profile is a claim the
+ // export does not honour.
+ expect(source).toContain('envMapIntensity: renderProfile.environment.intensity,');
+ });
+
+ it('stamps the none profile for a stored spec that predates the environment block', () => {
+ const source = buildThreejsFactorySource(validSpec());
+ expect(source.replace(/\s+/g, '')).toContain('"environment":{"preset":"none","intensity":1}');
+ // …without inventing the key on the serialized spec itself: the ONE
+ // occurrence is the render profile's, so the exported spec still round-trips
+ // as the environment-less record the install actually stored.
+ expect(source.match(/"environment"/g)).toHaveLength(1);
+ expect(buildThreejsFactorySource({ ...validSpec(), environment: { preset: 'neutral', intensity: 1 } })
+ .match(/"environment"/g)).toHaveLength(2);
+ });
+});
+
describe('buildThreejsMaterialFeedback', () => {
it('returns empty for a missing or clean plausibility result', () => {
expect(buildThreejsMaterialFeedback(null)).toBe('');
diff --git a/server/services/threejsModels/prompt.js b/server/services/threejsModels/prompt.js
index 3c8200132d..03ccd772fc 100644
--- a/server/services/threejsModels/prompt.js
+++ b/server/services/threejsModels/prompt.js
@@ -66,6 +66,7 @@ Return one raw JSON object and nothing else. It must have exactly this top-level
"color":"#RRGGBB","groundColor":"#RRGGBB","intensity":n,
"position":[x,y,z],"angleDegrees":45,"penumbra":0.25
}],
+ "environment": {"preset":"none" | "neutral" | "studio","intensity":0..4},
"parts": [{
"id":"stablePartId","name":"Readable part name",
"geometry": { ...one allowed geometry... },
@@ -84,6 +85,15 @@ Return one raw JSON object and nothing else. It must have exactly this top-level
}]
}
+"environment" is the image-based lighting the scene is composed against, and it is what the
+reflective channels actually read: "metalness", "transmission", "clearcoat" and "iridescence"
+reflect an environment or they reflect nothing, so a physically correct metal in a scene with
+"preset":"none" renders near-black however right its values are. "lights" alone cannot supply
+it. Choose "studio" for anything with bare metal, chrome, gloss, glass or gems — it is a dark
+room with bright softboxes, which gives a conductor high-contrast highlights. Choose "neutral"
+for an evenly-lit subject in matte materials. Choose "none" only for a deliberately flat,
+unreflective look. "intensity" scales how strongly surfaces pick it up; 1 is the neutral value.
+
Every part "scale" component (sx, sy, sz) must be a strictly positive size multiplier of
at least 0.0001. Zero collapses the part to an invisible plane and a negative component
reflects it; both are rejected. This format has no reflection and no hidden parts — build
@@ -249,7 +259,7 @@ WORKFLOW:
3. Inventory every identity-defining visible detail: silhouette, proportions, bevels/rounding, seams, trim, controls, fasteners, facial landmarks, limbs, wear, gloss, emissive regions, and attachment points.
4. Build from a clear parent/child hierarchy. Put moving or attachable pieces in their own named parts. Add sockets for meaningful pivots/attachments. Set "explodeWithParent":true on surface relief — serrations, stria, ridges, trim, engraving, port floors, panel lines and other detail that belongs TO a part rather than being a part — so the viewer takes the model apart into readable components instead of a comb of loose slivers. Leave it false (the default) on anything a person would call a separate component.
5. Use primitive composition first, then the schema-backed extrude/tube/lathe forms for silhouettes, cutouts, and swept details. Use custom triangles only when no other allowed form can reproduce the shape.
-6. Use physically coherent PBR material channels. Reach for "physical" with ior/transmission/thickness for glass, gems, liquid, and clear plastic, sheen for cloth and velvet, iridescence for oil-slick/soap-film/pearlescent finishes, and anisotropy for brushed metal or spun discs. Do not use textures, external meshes, URLs, downloaded assets, or JavaScript.
+6. Use physically coherent PBR material channels. Reach for "physical" with ior/transmission/thickness for glass, gems, liquid, and clear plastic, sheen for cloth and velvet, iridescence for oil-slick/soap-film/pearlescent finishes, and anisotropy for brushed metal or spun discs. Then choose the "environment" preset those channels need — they read off it, not off "lights". Do not use textures, external meshes, URLs, downloaded assets, or JavaScript.
7. Center the subject near the origin, keep dimensions internally consistent, and choose a camera that frames the whole model.
8. Be honest about unseen sides in limitations. Infer conservatively; never claim exact hidden geometry.
9. Ensure every detailInventory item points to real part ids, every material reference exists, every socket parent exists, all ids are unique, custom indices are in range, extrude rings enclose real area with non-overlapping holes inside the outline, and tube paths never repeat a point.
@@ -262,6 +272,9 @@ QUALITY GATE:
- Do not spend custom triangles on a shape extrude, tube, or lathe already expresses.
- A subject that is not genuinely plate-like must not have every identity part flat along one axis: the model has to hold up when it is orbited, not only from the camera you choose.
- Include useful ambient/hemisphere fill plus at least one directional/key light.
+- Any spec that authors a reflective channel — metalness above 0.6, or any transmission,
+ clearcoat, or iridescence — sets an "environment" preset other than "none". Those values
+ cannot be judged, by you or by anyone reviewing the render, in a scene with nothing to reflect.
- Keep the full hierarchy at 160 parts or fewer.${familyChecklist ? `
- Every required component in the subject-family checklist is either built and inventoried, or
named in limitations with the reason the reference does not support it. Silence on one is a failure.
diff --git a/server/services/threejsModels/prompt.test.js b/server/services/threejsModels/prompt.test.js
index 52557a53d9..92a0d29aef 100644
--- a/server/services/threejsModels/prompt.test.js
+++ b/server/services/threejsModels/prompt.test.js
@@ -23,6 +23,16 @@ describe('buildThreejsGenerationPrompt', () => {
expect(build()).toContain('The model must come apart into readable components');
});
+ // Without this the model authors a physically correct conductor into a scene
+ // with nothing to reflect, sees it render near-black, and "fixes" it next pass
+ // by authoring implausible values back in.
+ it('offers the environment block and gates reflective channels on having one', () => {
+ const prompt = build();
+ expect(prompt).toContain('"environment": {"preset":"none" | "neutral" | "studio","intensity":0..4}');
+ expect(prompt).toContain('reflect an environment or they reflect nothing');
+ expect(prompt).toContain('sets an "environment" preset other than "none"');
+ });
+
it('says when extrude is the WRONG answer and gates on cross-section', () => {
const prompt = build();
// Selling extrude for silhouettes without naming its failure mode is how a