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: add pose-aware physical audits to Three.js models (#4543)

[._.]/ Adam Eivy89bebc0a14b1
diff --git a/client/src/pages/ThreejsModelDetail.jsx b/client/src/pages/ThreejsModelDetail.jsx
index 9448b4266a..55b785211c 100644
--- a/client/src/pages/ThreejsModelDetail.jsx
+++ b/client/src/pages/ThreejsModelDetail.jsx
@@ -406,6 +406,9 @@ export default function ThreejsModelDetail() {
const coverageFindings = Array.isArray(record.coverage?.findings) ? record.coverage.findings : null;
const flatnessFindings = Array.isArray(record.flatness?.findings) ? record.flatness.findings : null;
const penetrationFindings = Array.isArray(record.penetration?.findings) ? record.penetration.findings : null;
+ const physicalAuditFindings = Array.isArray(record.physicalAudit?.findings)
+ ? record.physicalAudit.findings
+ : null;
const materialFindings = Array.isArray(record.materialPlausibility?.findings)
? record.materialPlausibility.findings
: null;
@@ -422,6 +425,7 @@ export default function ThreejsModelDetail() {
// refinement is told to fix — so the footer only promises a refinement when
// there is an actual defect above it.
const penetrationDefects = countSeverities(penetrationFindings || []);
+ const physicalAuditDefects = countSeverities(physicalAuditFindings || []);
const coverageErrors = countSeverities(coverageFindings || []).error;
// Only present when the generation ran with a family — a record generated
// under `general` (or before families shipped) has no checklist to render.
@@ -628,6 +632,19 @@ export default function ThreejsModelDetail() {
/>
)}
+ {physicalAuditFindings && (
+ <GatePanel
+ title="Physical audit"
+ findings={physicalAuditFindings}
+ cleanLabel="Assembly satisfies physical attachment, exposure, and coplanarity rules"
+ footer={`This check inspects the model across resting and animation poses to detect floating parts, swallowed geometry, z-fighting coplanar surfaces, and unprovenanced appearing geometry.${
+ physicalAuditDefects.error + physicalAuditDefects.warning > 0
+ ? ' Refining without your own feedback will also target physical conformance defects.'
+ : ''
+ }`}
+ />
+ )}
+
{materialFindings && (
<GatePanel
title="Material plausibility"
diff --git a/client/src/pages/ThreejsModelDetail.test.jsx b/client/src/pages/ThreejsModelDetail.test.jsx
index f7be3ea2a9..4fcfb225e7 100644
--- a/client/src/pages/ThreejsModelDetail.test.jsx
+++ b/client/src/pages/ThreejsModelDetail.test.jsx
@@ -235,6 +235,55 @@ describe('ThreejsModelDetail cross-part penetration gate', () => {
});
});
+describe('ThreejsModelDetail physical audit gate', () => {
+ beforeEach(resetMocks);
+
+ it('lists the physical audit finding and says an unsteered refinement will target physical conformance defects', async () => {
+ getThreejsModel.mockResolvedValue({
+ ...baseRecord,
+ physicalAudit: {
+ errorCount: 0,
+ warningCount: 1,
+ noteCount: 0,
+ evaluatedPartCount: 2,
+ evaluatedPoseCount: 1,
+ findings: [{
+ code: 'floating-part',
+ severity: 'warning',
+ partIds: ['orb'],
+ message: 'Part "Floating Orb" floats unattached in space.',
+ }],
+ },
+ });
+ renderDetail();
+
+ await waitFor(() => expect(screen.getByText('Physical audit')).toBeInTheDocument());
+ expect(screen.getByText('Part "Floating Orb" floats unattached in space.')).toBeInTheDocument();
+ expect(screen.getByText('0 error · 1 warning · 0 note')).toBeInTheDocument();
+ expect(screen.getByText(/target physical conformance defects/)).toBeInTheDocument();
+ });
+
+ it('reports physical compliance on a clean pass', async () => {
+ getThreejsModel.mockResolvedValue({
+ ...baseRecord,
+ physicalAudit: { errorCount: 0, warningCount: 0, noteCount: 0, findings: [] },
+ });
+ renderDetail();
+
+ await waitFor(() => expect(screen.getByText('Physical audit')).toBeInTheDocument());
+ expect(screen.getByText('Assembly satisfies physical attachment, exposure, and coplanarity rules')).toBeInTheDocument();
+ expect(screen.queryByText(/target physical conformance defects/)).not.toBeInTheDocument();
+ });
+
+ it('hides the section for a record generated before the gate existed', async () => {
+ getThreejsModel.mockResolvedValue({ ...baseRecord, physicalAudit: null });
+ renderDetail();
+
+ await waitFor(() => expect(screen.getByText('Example Beacon')).toBeInTheDocument());
+ expect(screen.queryByText('Physical audit')).not.toBeInTheDocument();
+ });
+});
+
describe('ThreejsModelDetail material plausibility gate', () => {
beforeEach(resetMocks);
diff --git a/server/lib/README.md b/server/lib/README.md
index c465355474..f327147e47 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -178,6 +178,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `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. |
| `threejsModelPenetration.js` | `evaluateThreejsPenetration(spec)` — cross-part penetration gate over an already-validated Three.js spec, the one check that compares two parts to each other. Rebuilds each part's world placement (the same `THREE.Euler` 'XYZ' composition the preview applies), derives an analytic solid per geometry type, and samples one part's interior against another's to flag a part entirely buried inside an unrelated one (`error`) or unrelated parts occupying substantially the same space (`warning`). Parts in the same subtree and declared `attachmentPartIds` are exempt — embedding is what those relationships are *for* — and a shallow or transparent-container overlap is reported as an undecided `note`, never as a defect. `buildThreejsPenetrationFeedback(penetration)` turns the errors and warnings (never the undecided notes) into default refinement feedback. |
+| `threejsModelPhysicalAudit.js` | `evaluateThreejsPhysicalAudit(spec)` — pure bounds and pose audit gate over an already-validated Three.js spec: inspects static resting poses and animated clip poses to detect floating parts (`floating-part`), swallowed geometry (`buried-geometry`), z-fighting coplanar surfaces (`coplanar-surface`), and unprovenanced appearing geometry (`unprovenanced-transition`). `buildThreejsPhysicalAuditFeedback(physicalAudit)` turns actionable findings into default refinement feedback. |
| `threejsModelPlayerSource.js` | `THREEJS_PLAYER_SOURCE` — the fixed clip-player source `buildThreejsFactorySource` emits into every exported Three.js module, giving a standalone consumer `createSculptAnimationPlayer(root, { onCue })` (plus `evaluateSculptClipPose` / `collectSculptCues`) over the node map and validated `animation` block the factory already carries. A STRING constant, not generated text: nothing provider-authored is interpolated into it, so the export stays data-plus-PortOS-code. It takes `update(deltaSeconds)` from the host render loop rather than owning one, scrubs silently and fires cues only on playback (mirroring the preview), and clones a shared material before driving `opacity`. Semantics mirror `client/src/lib/threejsAnimation.js` — change one and change the other. |
| `threejsModelRig.js` | `evaluateThreejsRigReadiness(spec)` — honest rig-readiness report over an already-validated Three.js spec: `{ articulationReady, reasons, jointCount, socketCount, attachmentCount, rootJointId, subjectType }`. The schema proves the optional `articulation` graph is well *formed* (one root, no cycles or forward refs, joints and pivots pointed at real parts/sockets); this reports whether it is *useful* (more than a lone root, every child joint carrying a pivot axis) and names the reason when it is not. It reports rather than rejects, and never claims skinning: PortOS generates static assemblies and declared articulation intent, not skeletons or bind poses. |
| `pgFileFacade.js` | Shared PG/file store-backend backbone for the six storage dispatchers (pipeline series/issues, story builder, universe builder, catalog user-types, writers room). `isFileBackend()` (dev/test escape-hatch predicate) · `resolvePgBackend({ requirement, migrate?, loadDb, makePg })` (health-check → `ensureSchema` → one-time migration → import `db.js` → build the PG backend) · `createPgFileFacade({ makeFile, makePg })` (promise-memoized lazy selection so concurrent first calls don't run the migration twice; returns `{ getBackend, getBackendName, reset }`). Each store keeps its own `makeFile`/`makePg` factories + public surface. `createRecordStoreBackendSelector({ label, loadFileBackend, loadDbBackend, requireDbMessage?, isTestMode?, onDbReady? })` wraps the same backbone for the stores whose backends are whole MODULES rather than built objects (Creative Director, Music Video, Sprites) → `{ selectBackend, getBackendName }` where the name is `'file'`/`'postgres'`; `isTestMode` lets a store use the stronger `isTestRunner()` signal (Sprites). |
diff --git a/server/lib/index.js b/server/lib/index.js
index ffc693a74c..1831c066dc 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -54,6 +54,7 @@ export * from './threejsModelAnimation.js';
export * from './threejsModelCoverage.js';
export * from './threejsModelFamilies.js';
export * from './threejsModelPenetration.js';
+export * from './threejsModelPhysicalAudit.js';
export * from './threejsModelPlayerSource.js';
export * from './threejsModelRig.js';
diff --git a/server/lib/threejsModelPhysicalAudit.js b/server/lib/threejsModelPhysicalAudit.js
new file mode 100644
index 0000000000..6b0d838946
--- /dev/null
+++ b/server/lib/threejsModelPhysicalAudit.js
@@ -0,0 +1,521 @@
+/**
+ * Physical-conformance audit gate for an already-validated Three.js scene spec.
+ *
+ * Checks static assemblies and animated clips across key poses for:
+ * 1. `floating-part`: Parts touching no parent, sibling, joint, attachment, or ground surface.
+ * 2. `buried-geometry`: Parts swallowed completely or heavily inside another part without hierarchy/attachment exemption.
+ * 3. `coplanar-surface`: Sibling or unrelated part pairs sharing a near-coplanar surface (z-fighting).
+ * 4. `unprovenanced-transition`: Animated parts that pop into existence in open space without emerging from a parent or ground level.
+ */
+
+import { listSpecNames } from './threejsModel.js';
+
+const EPSILON = 1e-4;
+const COPLANAR_TOLERANCE = 1e-3;
+const TOUCH_TOLERANCE = 0.02;
+const MAX_AUDIT_POSES = 16;
+
+const degreesToRadians = (degrees) => (degrees * Math.PI) / 180;
+
+const rotationMatrix = ([xDegrees, yDegrees, zDegrees]) => {
+ const [c1, s1] = [Math.cos(degreesToRadians(xDegrees)), Math.sin(degreesToRadians(xDegrees))];
+ const [c2, s2] = [Math.cos(degreesToRadians(yDegrees)), Math.sin(degreesToRadians(yDegrees))];
+ const [c3, s3] = [Math.cos(degreesToRadians(zDegrees)), Math.sin(degreesToRadians(zDegrees))];
+ return [
+ c2 * c3, -c2 * s3, s2,
+ (c1 * s3) + (s1 * c3 * s2), (c1 * c3) - (s1 * s3 * s2), -s1 * c2,
+ (s1 * s3) - (c1 * c3 * s2), (s1 * c3) + (c1 * s3 * s2), c1 * c2,
+ ];
+};
+
+const multiplyLinear = (a, b) => {
+ const out = new Array(9);
+ for (let row = 0; row < 3; row += 1) {
+ for (let column = 0; column < 3; column += 1) {
+ out[(row * 3) + column] = (a[row * 3] * b[column])
+ + (a[(row * 3) + 1] * b[3 + column])
+ + (a[(row * 3) + 2] * b[6 + column]);
+ }
+ }
+ return out;
+};
+
+const applyLinear = (linear, [x, y, z]) => [
+ (linear[0] * x) + (linear[1] * y) + (linear[2] * z),
+ (linear[3] * x) + (linear[4] * y) + (linear[5] * z),
+ (linear[6] * x) + (linear[7] * y) + (linear[8] * z),
+];
+
+const applyTransform = (transform, point) => {
+ const rotated = applyLinear(transform.linear, point);
+ return [
+ rotated[0] + transform.translation[0],
+ rotated[1] + transform.translation[1],
+ rotated[2] + transform.translation[2],
+ ];
+};
+
+const IDENTITY_TRANSFORM = { linear: [1, 0, 0, 0, 1, 0, 0, 0, 1], translation: [0, 0, 0] };
+
+const composeTransform = (parent, position, rotationDegrees, scale) => {
+ const rotation = rotationMatrix(rotationDegrees || [0, 0, 0]);
+ const [sx, sy, sz] = scale || [1, 1, 1];
+ const local = [
+ rotation[0] * sx, rotation[1] * sy, rotation[2] * sz,
+ rotation[3] * sx, rotation[4] * sy, rotation[5] * sz,
+ rotation[6] * sx, rotation[7] * sy, rotation[8] * sz,
+ ];
+ const pos = position || [0, 0, 0];
+ const offset = applyLinear(parent.linear, pos);
+ return {
+ linear: multiplyLinear(parent.linear, local),
+ translation: [
+ offset[0] + parent.translation[0],
+ offset[1] + parent.translation[1],
+ offset[2] + parent.translation[2],
+ ],
+ };
+};
+
+function getLocalBounds(geometry) {
+ if (!geometry) return null;
+ switch (geometry.type) {
+ case 'box': {
+ const [x, y, z] = [geometry.width / 2, geometry.height / 2, geometry.depth / 2];
+ return [[-x, -y, -z], [x, y, z]];
+ }
+ case 'sphere': {
+ const r = geometry.radius;
+ return [[-r, -r, -r], [r, r, r]];
+ }
+ case 'cylinder':
+ case 'cone': {
+ const top = geometry.type === 'cone' ? 0 : (geometry.radiusTop ?? geometry.radius);
+ const bottom = geometry.type === 'cone' ? geometry.radius : (geometry.radiusBottom ?? geometry.radius);
+ const half = geometry.height / 2;
+ const widest = Math.max(top, bottom);
+ return [[-widest, -half, -widest], [widest, half, widest]];
+ }
+ case 'capsule': {
+ const r = geometry.radius;
+ const half = geometry.length / 2;
+ return [[-r, -(half + r), -r], [r, half + r, r]];
+ }
+ case 'torus': {
+ const outer = geometry.radius + geometry.tube;
+ return [[-outer, -outer, -geometry.tube], [outer, outer, geometry.tube]];
+ }
+ case 'lathe': {
+ const points = geometry.points || [];
+ let maxR = 0;
+ let minY = Infinity;
+ let maxY = -Infinity;
+ for (const [x, y] of points) {
+ maxR = Math.max(maxR, Math.abs(x));
+ minY = Math.min(minY, y);
+ maxY = Math.max(maxY, y);
+ }
+ if (!Number.isFinite(minY)) { minY = -1; maxY = 1; maxR = 1; }
+ return [[-maxR, minY, -maxR], [maxR, maxY, maxR]];
+ }
+ case 'extrude': {
+ const outline = geometry.outline || [];
+ let minX = Infinity;
+ let maxX = -Infinity;
+ let minY = Infinity;
+ let maxY = -Infinity;
+ for (const [x, y] of outline) {
+ minX = Math.min(minX, x);
+ maxX = Math.max(maxX, x);
+ minY = Math.min(minY, y);
+ maxY = Math.max(maxY, y);
+ }
+ if (!Number.isFinite(minX)) { minX = 0; maxX = 1; minY = 0; maxY = 1; }
+ return [[minX, minY, 0], [maxX, maxY, geometry.depth || 1]];
+ }
+ case 'tube': {
+ const path = geometry.path || [];
+ const r = geometry.radius || 0.1;
+ let minX = Infinity; let maxX = -Infinity;
+ let minY = Infinity; let maxY = -Infinity;
+ let minZ = Infinity; let maxZ = -Infinity;
+ for (const [x, y, z] of path) {
+ minX = Math.min(minX, x); maxX = Math.max(maxX, x);
+ minY = Math.min(minY, y); maxY = Math.max(maxY, y);
+ minZ = Math.min(minZ, z); maxZ = Math.max(maxZ, z);
+ }
+ if (!Number.isFinite(minX)) { minX = 0; maxX = 1; minY = 0; maxY = 1; minZ = 0; maxZ = 1; }
+ return [[minX - r, minY - r, minZ - r], [maxX + r, maxY + r, maxZ + r]];
+ }
+ case 'custom': {
+ const vertices = geometry.vertices || [];
+ let minX = Infinity; let maxX = -Infinity;
+ let minY = Infinity; let maxY = -Infinity;
+ let minZ = Infinity; let maxZ = -Infinity;
+ for (let i = 0; i < vertices.length; i += 3) {
+ const x = vertices[i]; const y = vertices[i + 1]; const z = vertices[i + 2];
+ minX = Math.min(minX, x); maxX = Math.max(maxX, x);
+ minY = Math.min(minY, y); maxY = Math.max(maxY, y);
+ minZ = Math.min(minZ, z); maxZ = Math.max(maxZ, z);
+ }
+ if (!Number.isFinite(minX)) { minX = -1; maxX = 1; minY = -1; maxY = 1; minZ = -1; maxZ = 1; }
+ return [[minX, minY, minZ], [maxX, maxY, maxZ]];
+ }
+ default:
+ return null;
+ }
+}
+
+function getWorldAABB(localBounds, transform) {
+ const [[minX, minY, minZ], [maxX, maxY, maxZ]] = localBounds;
+ const corners = [
+ [minX, minY, minZ], [minX, minY, maxZ], [minX, maxY, minZ], [minX, maxY, maxZ],
+ [maxX, minY, minZ], [maxX, minY, maxZ], [maxX, maxY, minZ], [maxX, maxY, maxZ],
+ ].map((p) => applyTransform(transform, p));
+
+ return [0, 1, 2].map((axis) => [
+ Math.min(...corners.map((c) => c[axis])),
+ Math.max(...corners.map((c) => c[axis])),
+ ]);
+}
+
+function aabbDistance(a, b) {
+ const dx = Math.max(0, a[0][0] - b[0][1], b[0][0] - a[0][1]);
+ const dy = Math.max(0, a[1][0] - b[1][1], b[1][0] - a[1][1]);
+ const dz = Math.max(0, a[2][0] - b[2][1], b[2][0] - a[2][1]);
+ return Math.hypot(dx, dy, dz);
+}
+
+function aabbContains(container, subject, tolerance = EPSILON) {
+ return [0, 1, 2].every((axis) => (
+ subject[axis][0] >= container[axis][0] - tolerance
+ && subject[axis][1] <= container[axis][1] + tolerance
+ ));
+}
+
+function faceAreaOverlap2D(minA1, maxA1, minA2, maxA2, minB1, maxB1, minB2, maxB2) {
+ const overlap1 = Math.max(0, Math.min(maxA1, maxB1) - Math.max(minA1, minB1));
+ const overlap2 = Math.max(0, Math.min(maxA2, maxB2) - Math.max(minA2, minB2));
+ return overlap1 * overlap2;
+}
+
+const isTransparent = (material) => Boolean(material)
+ && ((material.transparent === true && (material.opacity ?? 1) < 1) || (material.transmission ?? 0) > 0);
+
+function getPoseStateResolver(clip, timeSeconds) {
+ const sequences = Array.isArray(clip?.sequences) ? clip.sequences : [];
+
+ const getChannelValue = (sequence, channel, t) => {
+ const range = sequence.channels?.[channel];
+ if (!range) return null;
+ if (channel === 'visible' || channel === 'opacity') {
+ if (t >= sequence.endSeconds) return range.to;
+ if (t < sequence.startSeconds) return range.from;
+ if (channel === 'visible') return range.to;
+ }
+ if (t <= sequence.startSeconds) return range.from;
+ if (t >= sequence.endSeconds) return range.to;
+
+ const duration = sequence.endSeconds - sequence.startSeconds;
+ const progress = duration > 0 ? (t - sequence.startSeconds) / duration : 1;
+ let eased = progress;
+ if (sequence.easing === 'easeIn') eased = progress * progress;
+ else if (sequence.easing === 'easeOut') eased = progress * (2 - progress);
+ else if (sequence.easing === 'easeInOut') eased = progress < 0.5 ? 2 * progress * progress : -1 + ((4 - (2 * progress)) * progress);
+
+ if (Array.isArray(range.from) && Array.isArray(range.to)) {
+ return range.from.map((v, i) => v + ((range.to[i] - v) * eased));
+ }
+ if (typeof range.from === 'number' && typeof range.to === 'number') {
+ return range.from + ((range.to - range.from) * eased);
+ }
+ return range.to;
+ };
+
+ const partSequences = new Map();
+ for (const seq of sequences) {
+ if (!seq.partId) continue;
+ const list = partSequences.get(seq.partId) || [];
+ list.push(seq);
+ partSequences.set(seq.partId, list);
+ }
+
+ return (part) => {
+ const seqs = partSequences.get(part.id) || [];
+ let pos = part.position || [0, 0, 0];
+ let rot = part.rotationDegrees || [0, 0, 0];
+ let sca = part.scale || [1, 1, 1];
+ let vis = part.visible !== false;
+ let opac = part.opacity ?? 1;
+
+ for (const channel of ['position', 'rotationDegrees', 'scale', 'visible', 'opacity']) {
+ const drivingSeqs = seqs.filter((s) => s.channels?.[channel] && s.startSeconds <= timeSeconds);
+ if (drivingSeqs.length > 0) {
+ drivingSeqs.sort((a, b) => a.startSeconds - b.startSeconds);
+ const active = drivingSeqs[drivingSeqs.length - 1];
+ const val = getChannelValue(active, channel, timeSeconds);
+ if (val !== null) {
+ if (channel === 'position') pos = val;
+ else if (channel === 'rotationDegrees') rot = val;
+ else if (channel === 'scale') sca = val;
+ else if (channel === 'visible') vis = Boolean(val);
+ else if (channel === 'opacity') opac = Number(val);
+ }
+ }
+ }
+ return { position: pos, rotationDegrees: rot, scale: sca, visible: vis, opacity: opac };
+ };
+}
+
+function collectPoseVolumes(spec, getPartState) {
+ const volumes = [];
+ const walk = (part, parentTransform, ancestorIds) => {
+ const state = getPartState ? getPartState(part) : {
+ position: part.position,
+ rotationDegrees: part.rotationDegrees,
+ scale: part.scale,
+ visible: part.visible !== false,
+ opacity: part.opacity ?? 1,
+ };
+
+ const transform = composeTransform(parentTransform, state.position, state.rotationDegrees, state.scale);
+ const localBounds = getLocalBounds(part.geometry);
+
+ if (localBounds) {
+ const worldBounds = getWorldAABB(localBounds, transform);
+ volumes.push({
+ id: part.id,
+ name: part.name || part.id,
+ geometry: part.geometry,
+ materialId: part.material || null,
+ explodeWithParent: part.explodeWithParent === true,
+ ancestorIds,
+ visible: state.visible,
+ opacity: state.opacity,
+ worldBounds,
+ });
+ }
+
+ for (const child of part.children || []) {
+ walk(child, transform, [...ancestorIds, part.id]);
+ }
+ };
+
+ for (const part of spec?.parts || []) {
+ walk(part, IDENTITY_TRANSFORM, []);
+ }
+
+ return volumes;
+}
+
+/**
+ * @param {object|null} spec a validated Three.js scene spec
+ * @returns {{findings: Array, errorCount: number, warningCount: number, noteCount: number,
+ * evaluatedPartCount: number, evaluatedPoseCount: number}}
+ */
+export function evaluateThreejsPhysicalAudit(spec) {
+ if (!spec || !Array.isArray(spec.parts)) {
+ return {
+ findings: [],
+ errorCount: 0,
+ warningCount: 0,
+ noteCount: 0,
+ evaluatedPartCount: 0,
+ evaluatedPoseCount: 0,
+ };
+ }
+
+ const materials = spec.materials && typeof spec.materials === 'object' ? spec.materials : {};
+ const attachments = new Set(spec.articulation?.attachmentPartIds || []);
+ const jointPartIds = new Set((spec.articulation?.joints || []).map((j) => j.partId).filter(Boolean));
+
+ const findings = [];
+ const seenKeys = new Set();
+
+ const addFinding = (finding) => {
+ const key = `${finding.code}|${[...finding.partIds].sort().join(',')}|${finding.clipId || ''}|${finding.sequenceId || ''}`;
+ if (seenKeys.has(key)) return;
+ seenKeys.add(key);
+ findings.push(finding);
+ };
+
+ // 1. Static Resting Pose Evaluation
+ const staticVolumes = collectPoseVolumes(spec, null);
+ const evaluatedPartCount = staticVolumes.length;
+ let evaluatedPoseCount = 1;
+
+ const visibleStaticVolumes = staticVolumes.filter((v) => v.visible && v.opacity > 0);
+
+ // Floating check & Buried & Coplanar on resting pose
+ for (let i = 0; i < visibleStaticVolumes.length; i += 1) {
+ const subject = visibleStaticVolumes[i];
+
+ // Ground contact check: min Y <= TOUCH_TOLERANCE
+ const touchesGround = subject.worldBounds[1][0] <= TOUCH_TOLERANCE;
+ const isAttachment = attachments.has(subject.id) || jointPartIds.has(subject.id);
+ const hasParent = subject.ancestorIds.length > 0;
+
+ let touchesAnyOther = touchesGround || isAttachment || hasParent;
+
+ for (let j = 0; j < visibleStaticVolumes.length; j += 1) {
+ if (i === j) continue;
+ const other = visibleStaticVolumes[j];
+
+ // Check distance
+ const dist = aabbDistance(subject.worldBounds, other.worldBounds);
+ if (dist <= TOUCH_TOLERANCE) {
+ touchesAnyOther = true;
+ }
+
+ if (i < j) {
+ // Buried check (subject inside container or other inside subject)
+ const isAncestorChild = subject.ancestorIds.includes(other.id) || other.ancestorIds.includes(subject.id);
+ const seeThrough = isTransparent(materials[other.materialId]) || isTransparent(materials[subject.materialId]);
+
+ if (!seeThrough && !isAncestorChild && !attachments.has(subject.id) && !attachments.has(other.id)) {
+ if (aabbContains(other.worldBounds, subject.worldBounds)) {
+ addFinding({
+ code: 'buried-geometry',
+ severity: 'error',
+ partIds: [subject.id, other.id],
+ message: `Part "${subject.name}" is completely buried inside "${other.name}". Move it out to an exposed surface or parent it properly.`,
+ });
+ } else if (aabbContains(subject.worldBounds, other.worldBounds)) {
+ addFinding({
+ code: 'buried-geometry',
+ severity: 'error',
+ partIds: [other.id, subject.id],
+ message: `Part "${other.name}" is completely buried inside "${subject.name}". Move it out to an exposed surface or parent it properly.`,
+ });
+ }
+ }
+
+ // Coplanar surface check
+ if (!isAncestorChild) {
+ for (let axis = 0; axis < 3; axis += 1) {
+ const axis1 = (axis + 1) % 3;
+ const axis2 = (axis + 2) % 3;
+
+ const planeMatches = Math.abs(subject.worldBounds[axis][0] - other.worldBounds[axis][0]) < COPLANAR_TOLERANCE
+ || Math.abs(subject.worldBounds[axis][1] - other.worldBounds[axis][1]) < COPLANAR_TOLERANCE
+ || Math.abs(subject.worldBounds[axis][1] - other.worldBounds[axis][0]) < COPLANAR_TOLERANCE
+ || Math.abs(subject.worldBounds[axis][0] - other.worldBounds[axis][1]) < COPLANAR_TOLERANCE;
+
+ if (planeMatches) {
+ const area = faceAreaOverlap2D(
+ subject.worldBounds[axis1][0], subject.worldBounds[axis1][1],
+ subject.worldBounds[axis2][0], subject.worldBounds[axis2][1],
+ other.worldBounds[axis1][0], other.worldBounds[axis1][1],
+ other.worldBounds[axis2][0], other.worldBounds[axis2][1],
+ );
+ const minArea = Math.min(
+ (subject.worldBounds[axis1][1] - subject.worldBounds[axis1][0])
+ * (subject.worldBounds[axis2][1] - subject.worldBounds[axis2][0]),
+ (other.worldBounds[axis1][1] - other.worldBounds[axis1][0])
+ * (other.worldBounds[axis2][1] - other.worldBounds[axis2][0]),
+ );
+
+ if (minArea > EPSILON && area / minArea >= 0.25) {
+ const axisName = axis === 0 ? 'X' : axis === 1 ? 'Y' : 'Z';
+ addFinding({
+ code: 'coplanar-surface',
+ severity: 'warning',
+ partIds: [subject.id, other.id],
+ message: `Parts "${subject.name}" and "${other.name}" share a coplanar surface along the ${axisName} axis, causing z-fighting flickering. Shift one slightly or offset their bounds.`,
+ });
+ }
+ }
+ }
+ }
+ }
+ }
+
+ if (!touchesAnyOther) {
+ addFinding({
+ code: 'floating-part',
+ severity: 'warning',
+ partIds: [subject.id],
+ message: `Part "${subject.name}" floats unattached in space without touching any parent, sibling, joint, or ground surface.`,
+ });
+ }
+ }
+
+ // 2. Animated Clips & Pose Evaluation
+ const clips = Array.isArray(spec.animation?.clips) ? spec.animation.clips : [];
+ let remainingBudget = MAX_AUDIT_POSES - 1;
+
+ for (const clip of clips) {
+ if (remainingBudget <= 0) break;
+
+ const sequences = Array.isArray(clip.sequences) ? clip.sequences : [];
+ const sampleTimes = new Set([0, clip.durationSeconds || 0]);
+ for (const seq of sequences) {
+ if (Number.isFinite(seq.startSeconds)) sampleTimes.add(seq.startSeconds);
+ if (Number.isFinite(seq.endSeconds)) sampleTimes.add(seq.endSeconds);
+ }
+
+ const timesToTest = [...sampleTimes].sort((a, b) => a - b).slice(0, remainingBudget);
+ remainingBudget -= timesToTest.length;
+ evaluatedPoseCount += timesToTest.length;
+
+ // Check unprovenanced transitions for sequences that toggle visibility/opacity
+ for (const seq of sequences) {
+ const visCh = seq.channels?.visible;
+ const opacCh = seq.channels?.opacity;
+ const appears = (visCh && visCh.from === false && visCh.to === true)
+ || (opacCh && opacCh.from === 0 && opacCh.to > 0);
+
+ if (appears && seq.startSeconds > 0) {
+ const getPoseState = getPoseStateResolver(clip, seq.startSeconds);
+ const poseVolumes = collectPoseVolumes(spec, getPoseState);
+ const partVolume = poseVolumes.find((v) => v.id === seq.partId);
+
+ if (partVolume) {
+ const parentVolume = poseVolumes.find((v) => partVolume.ancestorIds.includes(v.id));
+ const touchesGround = partVolume.worldBounds[1][0] <= TOUCH_TOLERANCE;
+ const insideParent = parentVolume && aabbDistance(partVolume.worldBounds, parentVolume.worldBounds) <= TOUCH_TOLERANCE;
+
+ if (!touchesGround && !insideParent) {
+ addFinding({
+ code: 'unprovenanced-transition',
+ severity: 'warning',
+ partIds: [seq.partId],
+ clipId: clip.id,
+ sequenceId: seq.id,
+ timeSeconds: seq.startSeconds,
+ message: `In clip "${clip.name || clip.id}", sequence "${seq.name || seq.id}" makes part "${partVolume.name}" appear at ${seq.startSeconds}s in open air without emerging from a parent part or ground level.`,
+ });
+ }
+ }
+ }
+ }
+ }
+
+ const countBy = (severity) => findings.filter((f) => f.severity === severity).length;
+
+ return {
+ findings,
+ errorCount: countBy('error'),
+ warningCount: countBy('warning'),
+ noteCount: countBy('note'),
+ evaluatedPartCount,
+ evaluatedPoseCount,
+ };
+}
+
+/**
+ * Default refinement feedback for a physical audit report.
+ * Returns '' when there are no actionable errors or warnings.
+ *
+ * @param {object|null} physicalAudit a stored `evaluateThreejsPhysicalAudit` result
+ * @returns {string}
+ */
+export function buildThreejsPhysicalAuditFeedback(physicalAudit) {
+ const actionable = (physicalAudit?.findings || []).filter((f) => f.severity === 'error' || f.severity === 'warning');
+ if (actionable.length === 0) return '';
+ return [
+ 'The previous pass failed physical conformance audits:',
+ ...actionable.map((finding, index) => `${index + 1}. ${finding.message}`),
+ 'Ensure every part is physically attached to a parent, sibling, or ground plane, keep geometry exposed rather than buried inside unrelated parts, avoid exact coplanar surfaces that cause flickering, and make animated parts emerge cleanly from parents or hidden containers.',
+ ].join('\n');
+}
diff --git a/server/lib/threejsModelPhysicalAudit.test.js b/server/lib/threejsModelPhysicalAudit.test.js
new file mode 100644
index 0000000000..05b2bad55f
--- /dev/null
+++ b/server/lib/threejsModelPhysicalAudit.test.js
@@ -0,0 +1,249 @@
+import { describe, expect, it } from 'vitest';
+import {
+ buildThreejsPhysicalAuditFeedback,
+ evaluateThreejsPhysicalAudit,
+} from './threejsModelPhysicalAudit.js';
+
+describe('threejsModelPhysicalAudit', () => {
+ it('returns clean result for null/empty spec', () => {
+ const res = evaluateThreejsPhysicalAudit(null);
+ expect(res).toEqual({
+ findings: [],
+ errorCount: 0,
+ warningCount: 0,
+ noteCount: 0,
+ evaluatedPartCount: 0,
+ evaluatedPoseCount: 0,
+ });
+ });
+
+ it('evaluates clean static model without findings', () => {
+ const spec = {
+ name: 'Clean Box',
+ parts: [
+ {
+ id: 'base',
+ name: 'Base',
+ geometry: { type: 'box', width: 2, height: 1, depth: 2 },
+ position: [0, 0.5, 0],
+ children: [
+ {
+ id: 'top',
+ name: 'Top',
+ geometry: { type: 'sphere', radius: 0.5 },
+ position: [0, 0.8, 0],
+ },
+ ],
+ },
+ ],
+ };
+ const res = evaluateThreejsPhysicalAudit(spec);
+ expect(res.evaluatedPartCount).toBe(2);
+ expect(res.evaluatedPoseCount).toBe(1);
+ expect(res.errorCount).toBe(0);
+ expect(res.warningCount).toBe(0);
+ expect(res.findings).toEqual([]);
+ expect(buildThreejsPhysicalAuditFeedback(res)).toBe('');
+ });
+
+ it('detects floating part touching nothing', () => {
+ const spec = {
+ name: 'Floating Spec',
+ parts: [
+ {
+ id: 'ground_plate',
+ name: 'Ground Plate',
+ geometry: { type: 'box', width: 2, height: 0.2, depth: 2 },
+ position: [0, 0.1, 0],
+ },
+ {
+ id: 'floating_sphere',
+ name: 'Floating Orb',
+ geometry: { type: 'sphere', radius: 0.5 },
+ position: [5, 5, 5],
+ },
+ ],
+ };
+ const res = evaluateThreejsPhysicalAudit(spec);
+ expect(res.warningCount).toBeGreaterThanOrEqual(1);
+ const finding = res.findings.find((f) => f.code === 'floating-part');
+ expect(finding).toBeDefined();
+ expect(finding.partIds).toContain('floating_sphere');
+ expect(finding.message).toContain('Floating Orb');
+
+ const feedback = buildThreejsPhysicalAuditFeedback(res);
+ expect(feedback).toContain('Floating Orb');
+ });
+
+ it('detects buried geometry inside another part', () => {
+ const spec = {
+ name: 'Buried Spec',
+ parts: [
+ {
+ id: 'container',
+ name: 'Outer Container',
+ geometry: { type: 'box', width: 4, height: 4, depth: 4 },
+ position: [0, 2, 0],
+ },
+ {
+ id: 'swallowed',
+ name: 'Inner Gem',
+ geometry: { type: 'box', width: 1, height: 1, depth: 1 },
+ position: [0, 2, 0],
+ },
+ ],
+ };
+ const res = evaluateThreejsPhysicalAudit(spec);
+ expect(res.errorCount).toBeGreaterThanOrEqual(1);
+ const finding = res.findings.find((f) => f.code === 'buried-geometry');
+ expect(finding).toBeDefined();
+ expect(finding.partIds).toEqual(['swallowed', 'container']);
+ });
+
+ it('detects coplanar surfaces causing z-fighting', () => {
+ const spec = {
+ name: 'Coplanar Spec',
+ parts: [
+ {
+ id: 'block1',
+ name: 'Left Block',
+ geometry: { type: 'box', width: 2, height: 2, depth: 2 },
+ position: [-1, 1, 0],
+ },
+ {
+ id: 'block2',
+ name: 'Right Block',
+ geometry: { type: 'box', width: 2, height: 2, depth: 2 },
+ position: [1, 1, 0],
+ },
+ ],
+ };
+ const res = evaluateThreejsPhysicalAudit(spec);
+ const finding = res.findings.find((f) => f.code === 'coplanar-surface');
+ expect(finding).toBeDefined();
+ expect(finding.partIds).toContain('block1');
+ expect(finding.partIds).toContain('block2');
+ });
+
+ it('exempts hidden parts (visible: false) from floating and buried checks', () => {
+ const spec = {
+ name: 'Hidden Parts Spec',
+ parts: [
+ {
+ id: 'main',
+ name: 'Main',
+ geometry: { type: 'box', width: 2, height: 1, depth: 2 },
+ position: [0, 0.5, 0],
+ },
+ {
+ id: 'hidden_float',
+ name: 'Hidden Float',
+ geometry: { type: 'sphere', radius: 0.5 },
+ position: [10, 10, 10],
+ visible: false,
+ },
+ ],
+ };
+ const res = evaluateThreejsPhysicalAudit(spec);
+ expect(res.findings.filter((f) => f.partIds.includes('hidden_float'))).toHaveLength(0);
+ });
+
+ it('exempts parent/child and declared attachments from false positives', () => {
+ const spec = {
+ name: 'Attachment Spec',
+ articulation: {
+ attachmentPartIds: ['strapped_pack'],
+ },
+ parts: [
+ {
+ id: 'torso',
+ name: 'Torso',
+ geometry: { type: 'box', width: 2, height: 3, depth: 1 },
+ position: [0, 1.5, 0],
+ },
+ {
+ id: 'strapped_pack',
+ name: 'Backpack',
+ geometry: { type: 'box', width: 1, height: 1, depth: 0.5 },
+ position: [0, 1.5, 0.5],
+ },
+ ],
+ };
+ const res = evaluateThreejsPhysicalAudit(spec);
+ expect(res.findings.filter((f) => f.code === 'floating-part')).toHaveLength(0);
+ expect(res.findings.filter((f) => f.code === 'buried-geometry')).toHaveLength(0);
+ });
+
+ it('evaluates rotated parts and transforms correctly', () => {
+ const spec = {
+ name: 'Rotated Spec',
+ parts: [
+ {
+ id: 'base',
+ name: 'Base',
+ geometry: { type: 'box', width: 2, height: 0.2, depth: 2 },
+ position: [0, 0.1, 0],
+ },
+ {
+ id: 'tilted_arm',
+ name: 'Tilted Arm',
+ geometry: { type: 'box', width: 0.2, height: 2, depth: 0.2 },
+ position: [0, 0.5, 0],
+ rotationDegrees: [0, 0, 45],
+ },
+ ],
+ };
+ const res = evaluateThreejsPhysicalAudit(spec);
+ expect(res.findings.filter((f) => f.code === 'floating-part')).toHaveLength(0);
+ });
+
+ it('detects unprovenanced transitions in animated clip poses', () => {
+ const spec = {
+ name: 'Animated Spec',
+ parts: [
+ {
+ id: 'hull',
+ name: 'Hull',
+ geometry: { type: 'box', width: 4, height: 1, depth: 4 },
+ position: [0, 0.5, 0],
+ },
+ {
+ id: 'pop_part',
+ name: 'Popping Cannon',
+ geometry: { type: 'cylinder', radiusTop: 0.2, radiusBottom: 0.2, height: 1 },
+ position: [0, 5, 0],
+ visible: false,
+ },
+ ],
+ animation: {
+ clips: [
+ {
+ id: 'deploy',
+ name: 'Deploy',
+ durationSeconds: 2,
+ sequences: [
+ {
+ id: 'appear',
+ name: 'Appear Sequence',
+ partId: 'pop_part',
+ startSeconds: 1,
+ endSeconds: 2,
+ channels: {
+ visible: { from: false, to: true },
+ },
+ },
+ ],
+ },
+ ],
+ },
+ };
+ const res = evaluateThreejsPhysicalAudit(spec);
+ expect(res.evaluatedPoseCount).toBeGreaterThan(1);
+ const finding = res.findings.find((f) => f.code === 'unprovenanced-transition');
+ expect(finding).toBeDefined();
+ expect(finding.partIds).toContain('pop_part');
+ expect(finding.clipId).toBe('deploy');
+ expect(finding.sequenceId).toBe('appear');
+ expect(finding.timeSeconds).toBe(1);
+ });
+});
diff --git a/server/services/threejsModels/db.js b/server/services/threejsModels/db.js
index 9409e28e66..6d1d93d978 100644
--- a/server/services/threejsModels/db.js
+++ b/server/services/threejsModels/db.js
@@ -108,6 +108,10 @@ export async function createModel(input) {
// `coverage` and `flatness`: an older record reads back undefined, which
// every consumer treats as "not evaluated" rather than "plausible".
materialPlausibility: null,
+ // Physical-conformance findings for `spec`, written alongside it by
+ // `evaluateThreejsPhysicalAudit`. Same additive-field contract: an older
+ // record reads back undefined, which every consumer treats as "not evaluated".
+ physicalAudit: null,
error: null,
generationOperationId: null,
runs: [],
diff --git a/server/services/threejsModels/index.js b/server/services/threejsModels/index.js
index 1bba0b3ff9..9384bff6f4 100644
--- a/server/services/threejsModels/index.js
+++ b/server/services/threejsModels/index.js
@@ -19,6 +19,7 @@ import {
import { buildThreejsAnimationFeedback, summarizeThreejsAnimation } from '../../lib/threejsModelAnimation.js';
import { buildThreejsCoverageFeedback, evaluateThreejsPartCoverage } from '../../lib/threejsModelCoverage.js';
import { buildThreejsPenetrationFeedback, evaluateThreejsPenetration } from '../../lib/threejsModelPenetration.js';
+import { buildThreejsPhysicalAuditFeedback, evaluateThreejsPhysicalAudit } from '../../lib/threejsModelPhysicalAudit.js';
import { evaluateThreejsRigReadiness } from '../../lib/threejsModelRig.js';
import { GENERAL_FAMILY_ID } from '../../lib/threejsModelFamilies.js';
import { resolveCliEffort } from '../../lib/providerModels.js';
@@ -117,6 +118,9 @@ async function executeGeneration({
// still renders, and from the hero angle it still looks right, so the
// finding is recorded and fed back rather than thrown away.
const penetration = evaluateThreejsPenetration(spec);
+ // And likewise for deterministic physical-conformance audits: floating parts,
+ // swallowed geometry, coplanar z-fighting surfaces, and unprovenanced clip transitions.
+ const physicalAudit = evaluateThreejsPhysicalAudit(spec);
// And likewise for a spec whose materials parse cleanly but describe the
// wrong substance — metalness 0.9 oak, transmission 1.0 steel. Advisory by
// construction: a stylized model is entitled to break the priors, so the
@@ -146,6 +150,7 @@ async function executeGeneration({
coverage,
flatness,
penetration,
+ physicalAudit,
rig,
animation,
materialPlausibility,
@@ -171,6 +176,9 @@ async function executeGeneration({
if (penetration.errorCount > 0 || penetration.warningCount > 0) {
console.warn(`⚠️ Three.js model ${id} cross-part penetration: ${penetration.errorCount} error, ${penetration.warningCount} warning finding(s) over ${penetration.comparedPairCount} compared pair(s)`);
}
+ if (physicalAudit.errorCount > 0 || physicalAudit.warningCount > 0) {
+ console.warn(`⚠️ Three.js model ${id} physical audit: ${physicalAudit.errorCount} error, ${physicalAudit.warningCount} warning finding(s) across ${physicalAudit.evaluatedPoseCount} pose(s)`);
+ }
if (materialPlausibility.warningCount > 0) {
console.warn(`⚠️ Three.js model ${id} material plausibility: ${materialPlausibility.warningCount} of ${materialPlausibility.matchedMaterialCount} recognized material(s) carry values their substance does not support`);
}
@@ -246,6 +254,7 @@ export async function startGeneration(id, {
buildThreejsCoverageFeedback(current.coverage),
buildThreejsFlatnessFeedback(current.flatness),
buildThreejsPenetrationFeedback(current.penetration),
+ buildThreejsPhysicalAuditFeedback(current.physicalAudit),
buildThreejsMaterialFeedback(current.materialPlausibility),
buildThreejsAnimationFeedback(current.animation),
].filter(Boolean).join('\n\n');