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

fix([issue-3483]): make a geometry-bearing container a movable unit, and move part selection into the URL

[._.]/ Adam Eivy9524675c43e6
diff --git a/client/src/components/threejsModels/ThreejsModelPreview.jsx b/client/src/components/threejsModels/ThreejsModelPreview.jsx
index d4a3c96681..a74d9260ff 100644
--- a/client/src/components/threejsModels/ThreejsModelPreview.jsx
+++ b/client/src/components/threejsModels/ThreejsModelPreview.jsx
@@ -1,9 +1,10 @@
import { useCallback, useEffect, useId, useMemo, useState } from 'react';
+import { useSearchParams } from 'react-router';
import { Canvas } 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 { buildPartSelectionIndex, computeExplodeLayout } from '../../lib/threejsExplode';
+import { buildPartSelectionIndex, computeExplodeLayout, isReliefPart } from '../../lib/threejsExplode';
const radians = (degrees = 0) => THREE.MathUtils.degToRad(degrees);
const rotation = (degrees = [0, 0, 0]) => degrees.map(radians);
@@ -73,13 +74,15 @@ function Material({ definition, highlighted = false }) {
return <meshStandardMaterial {...lit} />;
}
+// Part ids are provider-authored and the schema accepts `toString`, so a bare
+// lookup can hand back an inherited function; only a real triple is an offset.
const offsetPosition = (position = [0, 0, 0], offset) =>
- (offset ? position.map((value, axis) => value + offset[axis]) : position);
+ (Array.isArray(offset) ? position.map((value, axis) => value + offset[axis]) : position);
-function Part({ part, materials, offsets, selection, selectedId, onSelect }) {
+function Part({ part, materials, layout, selection, selectedId, onSelect }) {
const transform = {
name: part.name,
- position: offsetPosition(part.position, offsets[part.id]),
+ position: offsetPosition(part.position, layout.offsets[part.id]),
rotation: rotation(part.rotationDegrees),
scale: part.scale,
};
@@ -91,20 +94,32 @@ function Part({ part, materials, offsets, selection, selectedId, onSelect }) {
event.stopPropagation();
onSelect(selection.owners[part.id] || part.id);
};
- return (
- <group {...transform}>
+ // Relief rides this part's own geometry, so both sit inside the mesh offset
+ // when this part is a container that moves its shell independently of its
+ // children. Everything else is a part in its own right and stays outside it.
+ const own = (
+ <>
{part.geometry && (
- <mesh castShadow={part.castShadow} receiveShadow={part.receiveShadow} onPointerDown={select}>
+ <mesh castShadow={part.castShadow} receiveShadow={part.receiveShadow} onClick={select}>
<Geometry definition={part.geometry} />
<Material definition={materials[part.material]} highlighted={highlighted} />
</mesh>
)}
- {part.children.map((child) => (
+ {part.children.filter(isReliefPart).map((child) => (
+ <Part key={child.id} part={child} materials={materials} layout={layout} selection={selection} selectedId={selectedId} onSelect={onSelect} />
+ ))}
+ </>
+ );
+ const meshOffset = layout.meshOffsets[part.id];
+ return (
+ <group {...transform}>
+ {Array.isArray(meshOffset) ? <group position={meshOffset}>{own}</group> : own}
+ {part.children.filter((child) => !isReliefPart(child)).map((child) => (
<Part
key={child.id}
part={child}
materials={materials}
- offsets={offsets}
+ layout={layout}
selection={selection}
selectedId={selectedId}
onSelect={onSelect}
@@ -165,7 +180,7 @@ function ProceduralScene({ spec, background, layout, selection, selectedId, onSe
key={part.id}
part={part}
materials={spec.materials}
- offsets={layout.offsets}
+ layout={layout}
selection={selection}
selectedId={selectedId}
onSelect={onSelect}
@@ -189,21 +204,41 @@ function ProceduralScene({ spec, background, layout, selection, selectedId, onSe
export default function ThreejsModelPreview({ spec, className = '' }) {
const [background, setBackground] = useState(() => spec?.background || '#000000');
const [explode, setExplode] = useState(0);
- const [selectedId, setSelectedId] = useState(null);
+ const [searchParams, setSearchParams] = useSearchParams();
const explodeSliderId = useId();
+ // Keyed on the authored background, not on `spec` — the detail page re-fetches
+ // the record every 2s while a generation runs, and a fresh object with the
+ // same content would throw away the background the user just picked.
+ const authoredBackground = spec?.background;
useEffect(() => {
- setBackground(spec?.background || '#000000');
- // A new model has different parts — a carried-over selection or explode
- // amount would point at geometry that no longer exists.
- setExplode(0);
- setSelectedId(null);
- }, [spec]);
+ setBackground(authoredBackground || '#000000');
+ }, [authoredBackground]);
const parts = spec?.parts;
const selection = useMemo(() => buildPartSelectionIndex(parts || []), [parts]);
const layout = useMemo(() => computeExplodeLayout(parts || [], explode), [parts, explode]);
- const handleSelect = useCallback((partId) => setSelectedId(partId || null), []);
+
+ // Same reason: reset the disassembly only when the part set actually changes,
+ // not on every poll that hands back an equivalent spec.
+ const partSignature = useMemo(() => Object.keys(selection.names).join('|'), [selection]);
+ useEffect(() => {
+ setExplode(0);
+ }, [partSignature]);
+
+ // The URL is the source of truth for what is selected, so a picked part is
+ // shareable and reload-safe; an id the current model doesn't have degrades to
+ // no selection instead of an empty label.
+ const requestedPartId = searchParams.get('part');
+ const selectedId = requestedPartId && selection.names[requestedPartId] ? requestedPartId : null;
+ const handleSelect = useCallback((partId) => {
+ setSearchParams((previous) => {
+ const next = new URLSearchParams(previous);
+ if (partId) next.set('part', partId);
+ else next.delete('part');
+ return next;
+ }, { replace: true });
+ }, [setSearchParams]);
if (!spec) {
return (
@@ -294,7 +329,7 @@ export default function ThreejsModelPreview({ spec, className = '' }) {
<button
type="button"
aria-label="Clear part selection"
- onClick={() => setSelectedId(null)}
+ onClick={() => handleSelect(null)}
className="rounded px-1.5 py-0.5 hover:bg-white/15"
>
Clear
diff --git a/client/src/components/threejsModels/ThreejsModelPreview.test.jsx b/client/src/components/threejsModels/ThreejsModelPreview.test.jsx
index 0c2802cd13..c880a93584 100644
--- a/client/src/components/threejsModels/ThreejsModelPreview.test.jsx
+++ b/client/src/components/threejsModels/ThreejsModelPreview.test.jsx
@@ -1,4 +1,5 @@
import { fireEvent, render, screen } from '@testing-library/react';
+import { MemoryRouter } from 'react-router';
import { beforeEach, describe, expect, it, vi } from 'vitest';
vi.mock('@react-three/fiber', () => ({
@@ -82,6 +83,10 @@ const part = (id, geometry, materialId, overrides = {}) => ({
...overrides,
});
+// The preview keeps the picked part in the URL, so every render needs a router.
+const renderPreview = (ui, entry = '/') =>
+ render(ui, { wrapper: ({ children }) => <MemoryRouter initialEntries={[entry]}>{children}</MemoryRouter> });
+
const box = { type: 'box', width: 1, height: 1, depth: 1 };
const positionOf = (container, name) =>
container.querySelector(`group[name="${name}"]`).getAttribute('position').split(',').map(Number);
@@ -89,7 +94,7 @@ const setExplode = (value) => fireEvent.change(screen.getByLabelText('Explode'),
describe('ThreejsModelPreview', () => {
it('offers preset and custom preview backgrounds without changing the scene spec', () => {
- render(<ThreejsModelPreview spec={SPEC} />);
+ renderPreview(<ThreejsModelPreview spec={SPEC} />);
expect(screen.getByRole('button', { name: 'Black' })).toHaveAttribute('aria-pressed', 'false');
expect(screen.getByRole('button', { name: 'Green screen' })).toHaveAttribute('aria-pressed', 'false');
@@ -105,7 +110,7 @@ describe('ThreejsModelPreview', () => {
});
it('renders extrude and tube parts as built buffer geometries', () => {
- const { container } = render(<ThreejsModelPreview spec={{
+ const { container } = renderPreview(<ThreejsModelPreview spec={{
...SPEC,
materials: { body: material() },
parts: [
@@ -140,7 +145,7 @@ describe('ThreejsModelPreview', () => {
});
it('forwards physical material channels only to physical materials', () => {
- const { container } = render(<ThreejsModelPreview spec={{
+ const { container } = renderPreview(<ThreejsModelPreview spec={{
...SPEC,
materials: {
glass: material({ type: 'physical', ior: 1.45, transmission: 0.8, thickness: 0.6, sheen: 0.3, iridescence: 0.7, anisotropy: 0.9 }),
@@ -187,7 +192,7 @@ describe('ThreejsModelPreview disassembly', () => {
});
it('separates the parts by scaling the layout about the centre, keeping relief on its part', () => {
- const { container } = render(<ThreejsModelPreview spec={knifeSpec()} />);
+ const { container } = renderPreview(<ThreejsModelPreview spec={knifeSpec()} />);
expect(positionOf(container, 'Blade')).toEqual([-1, 0, 0]);
expect(positionOf(container, 'Handle')).toEqual([1, 0, 0]);
@@ -206,7 +211,7 @@ describe('ThreejsModelPreview disassembly', () => {
});
it('re-fits the camera when the layout actually grows', () => {
- render(<ThreejsModelPreview spec={knifeSpec()} />);
+ renderPreview(<ThreejsModelPreview spec={knifeSpec()} />);
boundsApi.fit.mockClear();
setExplode(0.5);
@@ -219,16 +224,16 @@ describe('ThreejsModelPreview disassembly', () => {
});
it('disables the explode control when there is only one part to move', () => {
- render(<ThreejsModelPreview spec={{ ...SPEC, materials: { steel: material() }, parts: [part('solo', box, 'steel')] }} />);
+ renderPreview(<ThreejsModelPreview spec={{ ...SPEC, materials: { steel: material() }, parts: [part('solo', box, 'steel')] }} />);
expect(screen.getByLabelText('Explode')).toBeDisabled();
});
it('resolves a click on surface relief up to the part it belongs to and highlights that subtree', () => {
- const { container } = render(<ThreejsModelPreview spec={knifeSpec()} />);
+ const { container } = renderPreview(<ThreejsModelPreview spec={knifeSpec()} />);
expect(screen.queryByRole('button', { name: 'Clear part selection' })).not.toBeInTheDocument();
- fireEvent.pointerDown(container.querySelector('group[name="Serrations"] mesh'));
+ fireEvent.click(container.querySelector('group[name="Serrations"] mesh'));
// The sliver is not the answer — the blade it rides is.
expect(screen.getByText('Blade')).toBeInTheDocument();
@@ -240,10 +245,46 @@ describe('ThreejsModelPreview disassembly', () => {
expect(container.querySelector('group[name="Handle"] meshStandardMaterial').getAttribute('emissive')).toBe('#000000');
});
+ it('moves a container-with-geometry\'s own shell without dragging its child part', () => {
+ const { container } = renderPreview(<ThreejsModelPreview spec={{
+ ...SPEC,
+ materials: { steel: material() },
+ parts: [part('body', box, 'steel', {
+ name: 'Body',
+ children: [part('trim', box, 'steel', { name: 'Trim', position: [0, 0, 1] })],
+ })],
+ }} />);
+
+ // Assembled: the body's group sits at the origin and its shell is not offset.
+ expect(container.querySelector('group[name="Body"] > group:not([name])')).toBeNull();
+
+ setExplode(1);
+
+ // The body's GROUP must not move — that would carry the trim with it and
+ // separate nothing. Its shell moves inside an offset group instead.
+ expect(positionOf(container, 'Body')).toEqual([0, 0, 0]);
+ const shell = container.querySelector('group[name="Body"] > group:not([name])');
+ expect(shell.getAttribute('position').split(',').map(Number).some((value) => value !== 0)).toBe(true);
+ expect(shell.querySelector('mesh')).not.toBeNull();
+ // And the trim moves on its own.
+ expect(positionOf(container, 'Trim')).not.toEqual([0, 0, 1]);
+ });
+
+ it('keeps the picked part in the URL so it survives a reload and a stale id degrades', () => {
+ const { container, unmount } = renderPreview(<ThreejsModelPreview spec={knifeSpec()} />, '/?part=handle');
+ expect(screen.getByText('Handle')).toBeInTheDocument();
+ expect(container.querySelectorAll('meshStandardMaterial[emissive="#38bdf8"]')).toHaveLength(1);
+ unmount();
+
+ // A link to a part this model no longer has must not render an empty label.
+ renderPreview(<ThreejsModelPreview spec={knifeSpec()} />, '/?part=noSuchPart');
+ expect(screen.queryByRole('button', { name: 'Clear part selection' })).not.toBeInTheDocument();
+ });
+
it('selects a plain part on its own and clears the selection', () => {
- const { container } = render(<ThreejsModelPreview spec={knifeSpec()} />);
+ const { container } = renderPreview(<ThreejsModelPreview spec={knifeSpec()} />);
- fireEvent.pointerDown(container.querySelector('group[name="Handle"] mesh'));
+ fireEvent.click(container.querySelector('group[name="Handle"] mesh'));
expect(screen.getByText('Handle')).toBeInTheDocument();
expect(container.querySelectorAll('meshStandardMaterial[emissive="#38bdf8"]')).toHaveLength(1);
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 2e453560b6..699a85cae9 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -163,7 +163,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `syncCounts.js` | Directional pending-sync counts for the Instances federation cards. `directionalCounts({ localMax, peerMax, ourCursor, peerCursorForUs })` → `{ toPull, toPush }` (each a non-negative Number, or `null` when unknown) from monotonic change-log seqs; `diffSeq(ahead, behind)` is the BigInt-safe clamp-at-zero subtraction (handles numeric strings past `MAX_SAFE_INTEGER`); `describeDirectional({ toPull, toPush })` renders the plain-language `{ state, text }` ("in sync" / "N to pull · M to push" / "checking…"). No React — `SyncStatusBadge` drives it. |
| `tabNotation.js` | Guitar-tab / chord-sheet / ChordPro text parser for SongBook (`/songbook`). `parseTabSheet(text)` → `{ lines, meta, errors }` classifying each line (`section`/`chords`/`lyric`/`tabstaff`/`chordlyric`/`blank`/`text`) with chord names + column offsets, plus ChordPro meta (`{title:}`/`{artist:}`/`{key:}`/`{capo:}`); `detectFormat(text)` → `'chordpro' \| 'tab' \| 'plain'`; `normalizePastedTab(text)` cleans HTML remnants/entities, CRLF, tabs→spaces, blank-line runs; `transposeChordName(name, n)` / `transposeText(text, n)` transpose chord symbols (slash chords, sensible sharp/flat spelling, column-preserving on chord lines); `TAB_ARTICULATIONS` documents tab-staff technique characters for the viewer legend; `CHORD_TOKEN_RE` exported for reuse, plus `NOTE_TO_PC` / `spellPitchClass` exported minimally so `chordShapes.js` derives voicings from the same pitch-class tables. Forgiving — never throws, unknown lines classify as `text`. NOT the lead-sheet parser (`scoreNotation.js`). |
| `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. |
-| `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, 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 — with offsets returned in each part's own parent space and `growth` measuring 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. `isReliefPart` / `isContainerPart` expose the shared part definition: a part flagged `explodeWithParent` is surface relief that rides its parent and resolves selection up to it, a part whose descendants carry the geometry is a container that is descended through, everything else is a leaf that moves and selects on its own. |
+| `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. |
| `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. |
| `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. |
diff --git a/client/src/lib/threejsExplode.js b/client/src/lib/threejsExplode.js
index 82f3810ce3..d25141803c 100644
--- a/client/src/lib/threejsExplode.js
+++ b/client/src/lib/threejsExplode.js
@@ -9,11 +9,21 @@
* - A part flagged `explodeWithParent` is **surface relief** (serrations, stria,
* trim, port floors). It rides its parent: it never moves on its own, and a
* click on it resolves up to the part it belongs to. Without this, a
- * disassembly shatters into a comb of loose slivers.
- * - A part whose (non-relief) descendants carry the geometry is a **container**:
- * it is descended through, and its children are the things that move.
- * - Anything else that is not relief is a **leaf**: it moves as one rigid unit
- * (with its relief) and selects on its own.
+ * disassembly shatters into a comb of loose slivers. (Relief with no parent to
+ * ride is a contradiction the schema allows — a root-level flagged part is
+ * treated as an ordinary part, exactly as the picker self-owns it.)
+ * - Every other part that carries its own geometry is a **movable unit**, which
+ * is also precisely what the picker selects. That equivalence is the whole
+ * point: the things you can take apart and the things you can click are the
+ * same set.
+ * - A part whose (non-relief) descendants carry geometry is additionally a
+ * **container** — it is descended through, so those descendants are units of
+ * their own. A container that also has its own geometry moves that geometry
+ * (and its relief) as a unit while its children move independently; the
+ * offset for it therefore applies to the mesh inside the part, not to the
+ * part's group, which would drag every child along with it.
+ * - A part with no geometry anywhere in its subtree moves nothing and is not a
+ * unit — an empty organizational group must not drag the model centre.
*
* Separation is a layout **scale about the model centre**, not a uniform outward
* push: pushing every part the same distance slides the arrangement without ever
@@ -60,27 +70,35 @@ const localMatrix = (part) => {
/**
* Walk the tree to the parts that actually move, carrying each one's model-space
- * position and the parent basis its offset has to be expressed in (offsets are
- * applied to the part's own `position`, which lives in parent space).
+ * position and the basis its offset has to be expressed in.
+ *
+ * `onMesh` distinguishes the two places an offset can land: a plain unit moves
+ * its whole group (offset in the PARENT's space, added to `position`), while a
+ * container that has geometry of its own moves only that geometry (offset in
+ * its OWN space, applied to a group around the mesh) so its child units stay
+ * free to move independently.
*/
const collectExplodeUnits = (parts) => {
const units = [];
- const walk = (list, parentMatrix) => {
+ const walk = (list, parentMatrix, hasOwner) => {
for (const part of list || []) {
- if (isReliefPart(part)) continue;
+ // Relief rides its parent — unless there is no parent to ride, which the
+ // picker also treats as an ordinary part.
+ if (isReliefPart(part) && hasOwner) continue;
const matrix = parentMatrix.clone().multiply(localMatrix(part));
- if (isContainerPart(part)) {
- walk(childrenOf(part), matrix);
- continue;
+ const container = isContainerPart(part);
+ if (part?.geometry) {
+ units.push({
+ id: part.id,
+ position: new THREE.Vector3().setFromMatrixPosition(matrix),
+ basis: container ? matrix : parentMatrix,
+ onMesh: container,
+ });
}
- units.push({
- id: part.id,
- position: new THREE.Vector3().setFromMatrixPosition(matrix),
- parentMatrix,
- });
+ if (container) walk(childrenOf(part), matrix, true);
}
};
- walk(parts, new THREE.Matrix4());
+ walk(parts, new THREE.Matrix4(), false);
return units;
};
@@ -95,11 +113,11 @@ const fallbackDirection = (index, count) => {
return direction.lengthSq() > EPSILON ? direction.normalize() : new THREE.Vector3(0, 1, 0);
};
-// A world-space delta becomes a parent-space delta through the inverse of the
-// parent's basis. A degenerate (zero-scaled) parent has no inverse — fall back
-// to the world delta rather than emitting NaN positions.
-const toParentSpace = (delta, parentMatrix) => {
- const basis = new THREE.Matrix3().setFromMatrix4(parentMatrix);
+// A world-space delta becomes a local delta through the inverse of the frame it
+// will be applied in. A degenerate (zero-scaled) frame has no inverse — fall
+// back to the world delta rather than emitting NaN positions.
+const toLocalDelta = (delta, frame) => {
+ const basis = new THREE.Matrix3().setFromMatrix4(frame);
if (Math.abs(basis.determinant()) < EPSILON) return delta.clone();
return delta.clone().applyMatrix3(basis.clone().invert());
};
@@ -107,10 +125,15 @@ const toParentSpace = (delta, parentMatrix) => {
/**
* Explode layout for a spec's parts at `amount` (0 assembled → 1 fully apart).
*
- * Returns the per-part offsets to add to each unit's `position`, the ids of the
- * units that moved, and `growth` — how much the layout actually grew, measured
- * from the moved parts rather than guessed, so the camera can re-fit on real
- * change instead of on every slider tick.
+ * Returns `offsets` (added to a unit's own `position`), `meshOffsets` (applied
+ * to a group around a container's own geometry, so moving it does not drag the
+ * container's child units), the ids of the units that moved, and `growth` — how
+ * much the layout actually grew, measured from the moved parts rather than
+ * guessed, so the camera re-fits on real change instead of every slider tick.
+ *
+ * Both maps are null-prototype: part ids are provider-authored and the schema
+ * happily accepts `toString` or `constructor`, which on a plain object would
+ * read back an inherited function and produce NaN positions.
*/
export function computeExplodeLayout(parts, amount = 0) {
const units = collectExplodeUnits(parts);
@@ -118,14 +141,17 @@ export function computeExplodeLayout(parts, amount = 0) {
const progress = clamp01(amount);
// One unit has nothing to separate from, and any offset would just translate
// the whole model out of frame.
- if (progress <= 0 || units.length < 2) return { offsets: {}, unitIds, growth: 1 };
+ if (progress <= 0 || units.length < 2) {
+ return { offsets: Object.create(null), meshOffsets: Object.create(null), unitIds, growth: 1 };
+ }
const box = new THREE.Box3();
for (const unit of units) box.expandByPoint(unit.position);
const centre = box.getCenter(new THREE.Vector3());
const assembledRadius = units.reduce((max, unit) => Math.max(max, unit.position.distanceTo(centre)), 0);
- const offsets = {};
+ const offsets = Object.create(null);
+ const meshOffsets = Object.create(null);
let explodedRadius = 0;
units.forEach((unit, index) => {
const delta = unit.position.clone().sub(centre);
@@ -137,11 +163,14 @@ export function computeExplodeLayout(parts, amount = 0) {
const clearance = (assembledRadius || 1) * EXPLODE_BASE_CLEARANCE * progress;
const worldOffset = direction.multiplyScalar(scaled + clearance);
explodedRadius = Math.max(explodedRadius, unit.position.clone().add(worldOffset).distanceTo(centre));
- offsets[unit.id] = toParentSpace(worldOffset, unit.parentMatrix).toArray();
+ const local = toLocalDelta(worldOffset, unit.basis).toArray();
+ if (unit.onMesh) meshOffsets[unit.id] = local;
+ else offsets[unit.id] = local;
});
return {
offsets,
+ meshOffsets,
unitIds,
// Units stacked on one point have no assembled radius to grow FROM, but the
// clearance still moved them — report absolute growth there so the camera
@@ -158,11 +187,14 @@ export function computeExplodeLayout(parts, amount = 0) {
* - `ancestry[id]` — root-to-self id chain, so "is this part inside the
* selection?" (subtree highlight) is a membership test.
* - `names[id]` — readable part name for the selection label.
+ *
+ * Null-prototype for the same reason the layout maps are: a provider may name a
+ * part `toString`, and an inherited hit would resolve a click to a function.
*/
export function buildPartSelectionIndex(parts) {
- const owners = {};
- const ancestry = {};
- const names = {};
+ const owners = Object.create(null);
+ const ancestry = Object.create(null);
+ const names = Object.create(null);
const walk = (list, chain, owner) => {
for (const part of list || []) {
if (!part?.id) continue;
diff --git a/client/src/lib/threejsExplode.test.js b/client/src/lib/threejsExplode.test.js
index 9954b4a8b6..0bb0ff3315 100644
--- a/client/src/lib/threejsExplode.test.js
+++ b/client/src/lib/threejsExplode.test.js
@@ -36,6 +36,61 @@ describe('the shared part definition', () => {
expect(computeExplodeLayout([blade], 0).unitIds).toEqual(['blade']);
});
+ it('moves a geometry-bearing container as a unit AND descends into its children', () => {
+ // The canonical authored shape: a crate body with a trim strip on it. If the
+ // body were treated as a pure container it would be pinned in place and,
+ // with only one child, there would be nothing to separate at all.
+ const crate = part('crateBody', {
+ position: [0, 0, 0],
+ children: [part('frontTrim', { position: [0, 0, 0.64] })],
+ });
+ const layout = computeExplodeLayout([crate], 1);
+
+ expect(layout.unitIds).toEqual(['crateBody', 'frontTrim']);
+ // The body's offset applies to its own geometry, not to its group — moving
+ // the group would drag the trim along and separate nothing.
+ expect(layout.meshOffsets.crateBody).toBeDefined();
+ expect(layout.offsets.crateBody).toBeUndefined();
+ expect(magnitude(layout.meshOffsets.crateBody)).toBeGreaterThan(0);
+ expect(magnitude(offsetOf(layout, 'frontTrim'))).toBeGreaterThan(0);
+ });
+
+ it('ignores an organizational group that carries no geometry anywhere', () => {
+ const layout = computeExplodeLayout([
+ part('body', { position: [1, 0, 0] }),
+ part('anchor', { geometry: undefined, material: undefined, position: [-4, 0, 0] }),
+ ], 1);
+
+ // An invisible node must not become a unit — it would drag the centre and
+ // enable a slider that has nothing to move.
+ expect(layout.unitIds).toEqual(['body']);
+ expect(layout.offsets).toEqual({});
+ });
+
+ it('treats root-level relief as an ordinary part, matching what the picker owns', () => {
+ const parts = [part('floatingTrim', { explodeWithParent: true, position: [-1, 0, 0] }), part('body', { position: [1, 0, 0] })];
+ const layout = computeExplodeLayout(parts, 1);
+
+ // There is no parent to ride, and the picker self-owns it — so the two
+ // halves of the definition must not disagree about whether it is a part.
+ expect(layout.unitIds).toEqual(['floatingTrim', 'body']);
+ expect(buildPartSelectionIndex(parts).owners.floatingTrim).toBe('floatingTrim');
+ });
+
+ it('does not read part ids through Object.prototype', () => {
+ // idSchema accepts `toString`, and a plain-object lookup would hand back an
+ // inherited function that reads as an offset and renders NaN positions.
+ const parts = [part('toString', { position: [-1, 0, 0] }), part('constructor', { position: [1, 0, 0] })];
+ const layout = computeExplodeLayout(parts, 0);
+ const { owners, names, ancestry } = buildPartSelectionIndex(parts);
+
+ expect(layout.offsets.toString).toBeUndefined();
+ expect(layout.meshOffsets.constructor).toBeUndefined();
+ expect(owners.toString).toBe('toString');
+ expect(names.constructor).toBe('constructor name');
+ expect(ancestry.valueOf).toBeUndefined();
+ });
+
it('descends through a part whose children carry the geometry', () => {
const rig = part('rig', {
geometry: undefined,
diff --git a/docs/THREEJS_MODELS.md b/docs/THREEJS_MODELS.md
index 51dd4cc36d..3b2dfa34f9 100644
--- a/docs/THREEJS_MODELS.md
+++ b/docs/THREEJS_MODELS.md
@@ -6,7 +6,8 @@ procedural Three.js scene with:
- an explicit AI provider/model choice per generation or refinement;
- a validated, bounded JSON scene spec rather than model-authored executable
JavaScript;
-- a live in-browser orbit/zoom preview using PortOS's existing Three.js stack;
+- a live in-browser orbit/zoom preview using PortOS's existing Three.js stack,
+ with explode-to-disassemble and click-to-identify part picking;
- deterministic download/copy of a standalone `THREE.Group` factory;
- gallery-image lineage, run attribution, detail inventory, and honest
single-view limitations.
@@ -29,6 +30,35 @@ rendering it. The client maps that allowlist to Three.js primitives and bounded
`BufferGeometry`; it never evaluates provider-written JavaScript. Exported
source is produced deterministically from the validated spec.
+## Disassembly and part picking
+
+The preview's Explode slider separates the assembly and clicking any surface
+names the part it belongs to, highlighting that whole component. This is the
+only *structural* check that a model was actually built from parts rather than
+fused into one shape — every other check scores pixels.
+
+Separation is a layout **scale about the model centre** plus a base clearance,
+never a uniform outward push: displacing every part the same distance slides the
+arrangement without opening a gap between neighbours, so parts that touched
+would still touch. The camera re-frames to the disassembly's measured size.
+
+Explode and the picker share one definition of "a part"
+(`client/src/lib/threejsExplode.js`) — if they disagreed, both would be wrong:
+
+- `explodeWithParent: true` marks **surface relief** — serrations, stria, trim,
+ engraving, port floors: detail that belongs *to* a part rather than being one.
+ It rides its parent when the model comes apart, and a click on it selects the
+ parent, so a disassembly does not shatter into a comb of loose slivers.
+ Generation prompts instruct the provider to set it; it defaults to `false`.
+- Every other part carrying geometry is both a movable unit and a selectable
+ component. A part whose children carry the geometry is additionally descended
+ through, so those children separate too; a part with geometry *and*
+ geometry-bearing children moves its own shell while its children move freely.
+
+The exported standalone factory carries the same information —
+`buildThreejsFactorySource()` writes `partId` and `explodeWithParent` into each
+node's `userData` — so a consumer outside PortOS can build the same disassembly.
+
## Geometry vocabulary
Alongside the primitives (box, sphere, cylinder, cone, torus, capsule, lathe)