Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Refine film character acting in 67js 0.8.1

Nguyen Xuan Anf17b19bf0ee4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 02afa603..f853efde 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,12 @@
# Changelog
+## 0.8.1
+
+- Refine the film scientist with integrated facial surfaces, inset eyes, swept hair and a shorter neck
+- Add independent blink, brow, mouth and gaze channels with deterministic cues for each set
+- Replace repeating actor motion with held poses and preserve shared geometry through backward seeks
+- Verify eyelid coverage across the complete eye aperture and render isolated blink comparisons on CPU
+
## 0.8.0
- Add stable imported source-node IDs, hierarchy inspection and local joint overrides.
diff --git a/docs/mcp.md b/docs/mcp.md
index 0615a0a9..39ced841 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -7,6 +7,8 @@ The [official SDK documentation](https://ts.sdk.modelcontextprotocol.io/v2/) des
Release `0.5.0` exposes twelve tools for bounded JSON scene authoring and local GLB imports.
Release `0.6.0` adds five render job tools for PNG images, still sequences and MP4 video.
Release `0.7.0` adds [procedural motion](agent-motion.md), transient preview seeks and motion sampling in snapshot jobs.
+Release `0.8.0` adds [imported character motion](agent-character-motion.md) with source joints and independent clip timing.
+
It renders one active scene and returns PNG images through MCP image content.
Tool results also contain JSON text and structured metadata.
The image bytes appear only in the image content block.
@@ -27,7 +29,7 @@ The MCP connection uses stdin and stdout, without an HTTP MCP listener.
```
Run the installed command with `npx 67js-mcp --backend gpu --memory 192`.
- For a standalone launch, use `npx --package @codepawlhq/[email protected] 67js-mcp --backend gpu --memory 192`.
+ For a standalone launch, use `npx --package @codepawlhq/[email protected] 67js-mcp --backend gpu --memory 192`.
`67js-mcp --help` lists options. `67js-mcp --version` reports the installed version.
2. Configure your MCP client with absolute paths to Node and the installed CLI:
diff --git a/docs/morph-targets.md b/docs/morph-targets.md
index 09930ff2..7ab01158 100644
--- a/docs/morph-targets.md
+++ b/docs/morph-targets.md
@@ -122,9 +122,20 @@ Other checks cover channel packing, independent poses, normal cancellation, iden
`scripts/smoke-morph.mjs` compares the actual built GPU module with a CPU-authored reference image.
It checks independent signed poses, the 64th target, retained buffers, atomic rejection and texture disposal.
`scripts/smoke-morph-composition.mjs` compares combined skinning, normal deltas, normal cancellation and shadow receivers with CPU-baked geometry.
-The film scientist uses shared eyelid geometry with one retained blink pose per actor.
+
+The film scientist uses shared head geometry with separate retained expression weights per actor.
+Its four channels control blink, brow tension, mouth tension and gaze.
+The sampled targets and normals stay fixed while deterministic scene cues update weights.
Visual quality and frame performance require separate scene measurements.
+Numerical validation does not detect self-intersections or guarantee that an eyelid covers its entire eyeball.
+Close views must check corners, intermediate weights and combined expressions as well as the central surface.
+The film smoke compares blink pixels independently of head motion and the other expression channels.
+
+Additive target normals approximate normals on the combined surface.
+The film checks compare open and closed expressions against normals sampled from that surface.
+One triangle normal can differ from a smooth vertex normal even on the undeformed mesh.
+
## GLB snapshots
`exportGlb(parts)` preserves relative position and normal target accessors and each node's current weights.
diff --git a/docs/release-verification.md b/docs/release-verification.md
index dfc870b9..15ebdc7f 100644
--- a/docs/release-verification.md
+++ b/docs/release-verification.md
@@ -1,5 +1,26 @@
# Release verification
+## 0.8.1
+
+Source checks used Windows Node.js, installed Chrome with CPU SwiftShader and FFmpeg H.264 encoding.
+Registry publication and live deployment require separate verification against the pushed commit.
+
+| Check | Measured result |
+| --- | --- |
+| Node tests | 417 tests passed. |
+| Face coverage | More than 800 rays checked the complete eye aperture across combined expressions. |
+| Smooth normals | Open, partial and closed expressions retained a minimum normal agreement above 0.985 against the continuous surface. |
+| Native blink | Suppressing only the blink channel changed pixels. Backward seeking reproduced exact PNG bytes without WebGL errors. |
+| Retained geometry | Four expression channels and scene cues preserved shared geometry and actor matrices. |
+| Native video | Seventy-two decoded frames formed a three-second portrait H.264 MP4 at 24 FPS with BT.709 metadata. |
+| CPU export | The 540 by 960 export took 24.23 seconds with one pending frame and 48.4 MB of estimated render memory. |
+
+The scientist uses inset eyes, a sculpted face and held poses for each set.
+Native open and closed closeups were inspected after the final normal correction.
+
+This character remains stylized. These checks do not establish realistic likeness, cinematic quality or hardware GPU performance.
+Additive normals remain an approximation of the combined surface. The tested expressions cover this actor, rather than arbitrary morph targets.
+
## 0.8.0
Source checks used Windows Node.js, installed Chrome with CPU SwiftShader and FFmpeg H.264 encoding.
diff --git a/package-lock.json b/package-lock.json
index 4ac0e856..65d404f7 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "@codepawlhq/67js",
- "version": "0.8.0",
+ "version": "0.8.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@codepawlhq/67js",
- "version": "0.8.0",
+ "version": "0.8.1",
"license": "MIT",
"dependencies": {
"playwright-core": "1.64.0"
diff --git a/package.json b/package.json
index 3862bbdf..ca8825ae 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "@codepawlhq/67js",
- "version": "0.8.0",
+ "version": "0.8.1",
"private": false,
"type": "module",
"description": "JavaScript tools for agent-driven 3D authoring, browser previews and memory-aware CPU/GPU rendering",
diff --git a/scripts/smoke-film-blink.mjs b/scripts/smoke-film-blink.mjs
index 1a01d915..b89c32b7 100644
--- a/scripts/smoke-film-blink.mjs
+++ b/scripts/smoke-film-blink.mjs
@@ -1,25 +1,38 @@
import assert from 'node:assert/strict';
import { writeFile } from 'node:fs/promises';
import { constants, setPriority } from 'node:os';
+import { spawn } from 'node:child_process';
import { chromium } from 'playwright';
setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);
-const browser = await chromium.launch({
- executablePath: 'C:/Program Files/Google/Chrome/Application/chrome.exe',
- headless: true,
- args: ['--enable-webgl', '--ignore-gpu-blocklist'],
-});
+const server = spawn(process.execPath, ['node_modules/vite/bin/vite.js', '--config',
+ 'scripts/render-vite.config.mjs', '--host', '127.0.0.1', '--port', '5194', '--strictPort'],
+ { windowsHide: true, stdio: 'pipe' });
+let browser;
try {
+ await new Promise((resolve, reject) => {
+ const timer = setTimeout(() => reject(new Error('Film blink server did not start.')), 15000);
+ server.stdout.on('data', bytes => {
+ if (bytes.toString().includes('127.0.0.1:5194')) { clearTimeout(timer); resolve(); }
+ });
+ server.on('error', error => { clearTimeout(timer); reject(error); });
+ server.on('exit', code => { clearTimeout(timer); reject(new Error(`Film blink server exited ${code}.`)); });
+ });
+ browser = await chromium.launch({
+ executablePath: 'C:/Program Files/Google/Chrome/Application/chrome.exe',
+ headless: true,
+ args: ['--enable-webgl', '--use-angle=swiftshader', '--enable-unsafe-swiftshader', '--disable-renderer-backgrounding'],
+ });
const page = await browser.newPage({ viewport: { width: 540, height: 960 } });
const errors = [];
page.on('pageerror', error => errors.push(error.message));
await page.route('**/blink-smoke.html', route => route.fulfill({
contentType: 'text/html', body: '<canvas style="width:540px;height:960px;display:block"></canvas>',
}));
- await page.goto('http://127.0.0.1:5173/blink-smoke.html');
+ await page.goto('http://127.0.0.1:5194/blink-smoke.html');
const report = await page.evaluate(async () => {
- const { Renderer67 } = await import('/build/67.module.js');
- const { createFilmScenes } = await import('/build/film.js');
+ const { Renderer67 } = await import('/src/renderer.js');
+ const { createFilmScenes } = await import('/src/film.js');
const scene = createFilmScenes().portrait;
const canvas = document.querySelector('canvas');
const renderer = new Renderer67(canvas, scene.parts, {
@@ -27,34 +40,41 @@ try {
shadowBounds: scene.shadowBounds, samples: 2, pixelRatio: 1,
hdr: true, memoryBudgetMiB: 128,
});
- const frame = { eye: [0, 1.72, 0.72], target: [0, 1.7, 0], fov: 36, time: 0, effects: { grain: 0, bloom: { strength: 0 } } };
+ const frame = { eye: [0, 1.72, 0.88], target: [0, 1.7, 0], fov: 36, time: 0, effects: { grain: 0, bloom: { strength: 0 } } };
function image(time, suppressBlink = false) {
scene.animate(time);
if (suppressBlink) {
- for (const part of scene.parts) if (part.morph) part.morph.weights.fill(0);
+ for (const part of scene.parts) if (part.morph) part.morph.weights[0] = 0;
}
renderer.updateParts(scene.parts);
renderer.render(frame);
return canvas.toDataURL('image/png');
}
- const open = image(0);
- const closed = image(1.92);
- const samePoseWithoutBlink = image(1.92, true);
+ const open = image(17.4);
+ const closed = image(17.65);
+ const samePoseWithoutBlink = image(17.65, true);
image(9);
- const repeated = image(1.92);
+ const repeated = image(17.65);
+ const debug = renderer.context.getExtension('WEBGL_debug_renderer_info');
+ const graphics = renderer.context.getParameter(debug ? debug.UNMASKED_RENDERER_WEBGL : renderer.context.RENDERER);
const error = renderer.context.getError();
const memory = renderer.memoryPlan;
renderer.dispose();
- return { open, closed, samePoseWithoutBlink, repeated, error, memory };
+ return { open, closed, samePoseWithoutBlink, repeated, error, memory, graphics };
});
assert.deepEqual(errors, []);
assert.equal(report.error, 0);
+ assert.match(report.graphics, /swiftshader/i);
assert.notEqual(report.closed, report.samePoseWithoutBlink, 'Eyelid geometry must change pixels independently of head movement');
assert.equal(report.closed, report.repeated);
for (const name of ['open', 'closed']) {
await writeFile(`artifacts/blink-${name}.png`, Buffer.from(report[name].split(',')[1], 'base64'));
}
- console.log(JSON.stringify({ glError: report.error, repeatExact: true, independentBlinkPixels: true, memory: report.memory }));
+ const metrics = { glError: report.error, repeatExact: true, independentBlinkPixels: true,
+ graphics: report.graphics, memory: report.memory, openTime: 17.4, closedTime: 17.65 };
+ await writeFile('artifacts/film-blink-proof.json', JSON.stringify(metrics, null, 2));
+ console.log(JSON.stringify(metrics));
} finally {
- await browser.close();
+ await browser?.close();
+ server.kill();
}
diff --git a/src/film-character.js b/src/film-character.js
index 184f508a..011b5637 100644
--- a/src/film-character.js
+++ b/src/film-character.js
@@ -8,9 +8,14 @@ function facialFeature(horizontal, height, center, level, width, length) {
return gaussian(horizontal - center, width) * gaussian(height - level, length);
}
+function lidFalloff(distance, inner, outer) {
+ const amount = Math.max(0, Math.min(1, (Math.abs(distance) - inner) / (outer - inner)));
+ return 1 - amount ** 3 * (10 - 15 * amount + 6 * amount * amount);
+}
+
// Internal film geometry: +Y is up, +Z is the face, and horizontal wraps once.
// Tiny polar caps preserve the film mesher's finite-difference normal convention.
-export function sampleScientistHead(horizontal, vertical) {
+export function sampleScientistHead(horizontal, vertical, expression = -1) {
const angle = horizontal * FULL_TURN;
const elevation = 0.008 + vertical * (Math.PI - 0.016);
const height = Math.cos(elevation);
@@ -19,27 +24,122 @@ export function sampleScientistHead(horizontal, vertical) {
const jawTransition = 1 / (1 + Math.exp((height + 0.46) * 12));
const templeIndent = 0.065 * gaussian(height - 0.34, 0.18);
const cheekWidth = 0.055 * gaussian(height + 0.13, 0.17);
- const width = 0.94 - 0.20 * jawTransition - templeIndent + cheekWidth;
+ const width = 0.98 - 0.12 * jawTransition - templeIndent + cheekWidth;
const horizontalPoint = Math.cos(angle) * radius * width;
let depth = Math.sin(angle) * radius * (1 - 0.075 * front ** 2);
// Features change the same continuous surface instead of adding nose or jaw solids.
- let facialDepth = 0.23 * facialFeature(horizontalPoint, height, 0, 0.035, 0.105, 0.31);
- facialDepth += 0.25 * facialFeature(horizontalPoint, height, 0, -0.14, 0.14, 0.095);
+ let facialDepth = 0.19 * facialFeature(horizontalPoint, height, 0, 0.035, 0.105, 0.31);
+ facialDepth += 0.19 * facialFeature(horizontalPoint, height, 0, -0.14, 0.14, 0.095);
facialDepth -= 0.055 * facialFeature(horizontalPoint, height, 0, -0.245, 0.085, 0.035);
- facialDepth += 0.09 * facialFeature(horizontalPoint, height, 0, -0.33, 0.31, 0.11);
- facialDepth -= 0.025 * facialFeature(horizontalPoint, height, 0, -0.335, 0.25, 0.016);
- facialDepth += 0.17 * facialFeature(horizontalPoint, height, 0, -0.65, 0.31, 0.16);
+ const mouthLine = -0.35 - 0.014 * (horizontalPoint / 0.3) ** 2;
+ facialDepth += 0.022 * facialFeature(horizontalPoint, height, 0, mouthLine + 0.020, 0.27, 0.026);
+ facialDepth += 0.030 * facialFeature(horizontalPoint, height, 0, mouthLine - 0.028, 0.25, 0.03);
+ facialDepth -= 0.015 * facialFeature(horizontalPoint, height, 0, mouthLine, 0.26, 0.012);
+ facialDepth += 0.19 * facialFeature(horizontalPoint, height, 0, -0.65, 0.36, 0.17);
facialDepth -= 0.045 * facialFeature(horizontalPoint, height, 0, -0.47, 0.28, 0.065);
for (const side of [-1, 1]) {
- facialDepth -= 0.17 * facialFeature(horizontalPoint, height, side * 0.42, 0.153, 0.20, 0.095);
- facialDepth += 0.115 * facialFeature(horizontalPoint, height, side * 0.40, 0.30, 0.255, 0.075);
+ const eyeHorizontal = (horizontalPoint - side * 0.40) / 0.21;
+ const eyeHeight = height - 0.155 - side * eyeHorizontal * 0.009;
+ const almond = Math.max(0, 1 - eyeHorizontal * eyeHorizontal);
+ facialDepth -= 0.14 * facialFeature(horizontalPoint, height, side * 0.40, 0.17, 0.24, 0.14);
+ // A convex inset eye and its rolled lid edge are part of the face grid.
+ facialDepth += 0.055 * gaussian(eyeHorizontal, 0.87) * gaussian(eyeHeight, 0.045);
+ facialDepth += 0.042 * gaussian(eyeHorizontal, 1.02) * gaussian(Math.abs(eyeHeight) - 0.060 * almond, 0.019);
+ facialDepth += 0.18 * facialFeature(horizontalPoint, height, side * 0.40, 0.30, 0.255, 0.075);
facialDepth += 0.095 * facialFeature(horizontalPoint, height, side * 0.53, -0.095, 0.23, 0.115);
facialDepth -= 0.065 * facialFeature(horizontalPoint, height, side * 0.51, -0.29, 0.19, 0.16);
facialDepth += 0.105 * facialFeature(horizontalPoint, height, side * 0.12, -0.175, 0.065, 0.065);
facialDepth -= 0.025 * facialFeature(horizontalPoint, height, side * 0.06, -0.265, 0.025, 0.05);
}
depth += front ** 6 * facialDepth;
- return [horizontalPoint, height, depth];
+ let posedHeight = height;
+ const facing = Math.min(1, front * 2);
+ for (const side of [-1, 1]) {
+ const eyeHorizontal = horizontalPoint - side * 0.40;
+ const eyeHeight = height - 0.155;
+ if (expression === 0) {
+ // The lid follows one elliptical socket contour. Its C2 radial blend
+ // avoids straight patch edges, and retaining XY prevents folded rows.
+ const socketRadius = Math.hypot(eyeHorizontal / 0.22, eyeHeight / 0.105);
+ const cover = 0.862 - 0.075 * socketRadius * socketRadius;
+ const difference = cover - depth;
+ const raised = (difference + Math.hypot(difference, 0.022)) / 2;
+ const region = lidFalloff(socketRadius, 0.8, 1.8) * facing;
+ const crease = 0.003 * gaussian(eyeHorizontal, 0.18) * gaussian(eyeHeight + 0.016, 0.022);
+ depth += (raised - crease) * region;
+ }
+ if (expression === 1) {
+ // Keep the brow's support above the mobile lid so additive normal targets
+ // do not drag the closed cap into a second, conflicting crease.
+ posedHeight -= 0.040 * facialFeature(horizontalPoint, height, side * 0.28, 0.34, 0.26, 0.09) * facing;
+ }
+ }
+ if (expression === 2) {
+ const lowerFace = gaussian(horizontalPoint, 0.40) * gaussian(height + 0.43, 0.23) * facing;
+ posedHeight -= 0.026 * lowerFace;
+ depth -= 0.035 * lowerFace;
+ }
+ return [horizontalPoint, posedHeight, depth];
+}
+
+/** Pigment follows the same vertices as the lips, eyelid rims and expressions. */
+export function scientistSkinColor([horizontal, height, depth]) {
+ const color = [0.48, 0.285, 0.19];
+ if (depth < 0.5) return color;
+ const blend = (pigment, amount) => {
+ for (let channel = 0; channel < 3; channel++) color[channel] += (pigment[channel] - color[channel]) * amount;
+ };
+ const cheek = facialFeature(Math.abs(horizontal), height, 0.53, -0.12, 0.23, 0.2);
+ blend([0.46, 0.235, 0.16], cheek * 0.32);
+ blend([0.30, 0.23, 0.18], gaussian(height + 0.58, 0.25) * 0.18);
+ const mouthLine = -0.35 - 0.014 * (horizontal / 0.3) ** 2;
+ blend([0.36, 0.185, 0.135], facialFeature(horizontal, height, 0, mouthLine, 0.27, 0.035) * 0.4);
+ blend([0.12, 0.057, 0.038], facialFeature(horizontal, height, 0, mouthLine, 0.26, 0.010) * 0.8);
+ for (const side of [-1, 1]) {
+ const browLevel = 0.31 - side * (horizontal - side * 0.40) * 0.12;
+ blend([0.045, 0.030, 0.022], facialFeature(horizontal, height, side * 0.40, browLevel, 0.235, 0.025) * 0.93);
+ blend([0.13, 0.065, 0.04], facialFeature(horizontal, height, side * 0.09, -0.207, 0.035, 0.016) * 0.85);
+ }
+ return color;
+}
+
+// These globes sit behind the rolled skin rim. The aperture is the intersection
+// of the two curved surfaces, so eyes keep real depth under side lighting.
+export function sampleScientistEye(horizontal, vertical, side, gaze = false) {
+ const longitude = horizontal * FULL_TURN;
+ const elevation = 0.008 + vertical * (Math.PI - 0.016);
+ const radius = Math.sin(elevation);
+ const point = [Math.cos(longitude) * radius * 0.195, Math.cos(elevation) * 0.072, Math.sin(longitude) * radius * 0.105];
+ if (gaze) {
+ const angle = 0.16;
+ const horizontalPoint = point[0];
+ point[0] = horizontalPoint * Math.cos(angle) + point[2] * Math.sin(angle);
+ point[2] = point[2] * Math.cos(angle) - horizontalPoint * Math.sin(angle);
+ }
+ return [point[0] + side * 0.40, point[1] + 0.155, point[2] + 0.735];
+}
+
+export function scientistEyeColor([horizontal, height, depth], side) {
+ if (depth < 0.8) return [0.37, 0.39, 0.33];
+ const radius = Math.hypot((horizontal - side * 0.40) / 0.060, (height - 0.155) / 0.043);
+ if (radius < 0.46) return [0.007, 0.01, 0.009];
+ if (radius < 0.90) return [0.065, 0.105, 0.09];
+ if (radius < 1.10) return [0.025, 0.045, 0.034];
+ return [0.37, 0.39, 0.33];
+}
+
+export function sampleScientistHair(horizontal, vertical) {
+ const angle = horizontal * FULL_TURN;
+ const front = Math.max(0, Math.sin(angle));
+ const hairline = 1.85 - front * 0.94 + 0.13 * Math.cos(angle) * front;
+ const elevation = 0.008 + vertical * hairline;
+ const height = Math.cos(elevation);
+ const radius = Math.sin(elevation);
+ const sweep = gaussian(height - 0.72, 0.4) * front;
+ const comb = 0.009 * Math.sin(angle * 18 + elevation * 4) * Math.sin(elevation);
+ return [Math.cos(angle) * radius * (1.00 + comb) - 0.085 * sweep,
+ height + 0.045 + 0.10 * sweep,
+ Math.sin(angle) * radius * (0.98 + comb) - 0.035];
}
diff --git a/src/film-rig.js b/src/film-rig.js
index 2e32f064..b3e26764 100644
--- a/src/film-rig.js
+++ b/src/film-rig.js
@@ -1,36 +1,144 @@
import { mat4, quat } from 'gl-matrix';
-import { createAnimationClip } from './animation.js';
-import { createAnimationMixer } from './animation-mixer.js';
+import { createAnimationClip, compileAnimationSampler } from './animation.js';
import { createSceneGraph } from './scene-graph.js';
-/** Rigid actor groups keep attached clothing and hands on the same authored joints. */
-export function createFilmActorRig(parts) {
- const groups = new Map();
+// Times are relative to the set's first shot, matching sampleFilm(). Repeated
+// values hold a thought; movements happen between those holds, never on a loop.
+// Columns: time, pitch, yaw, left arm, right arm, brow, mouth tension, gaze.
+const PERFORMANCES = {
+ portrait: {
+ poses: [
+ [0, 0.035, -0.10, 0.02, -0.025, 0.1, 0.15, -0.5],
+ [2.2, 0.035, -0.10, 0.02, -0.025, 0.1, 0.15, -0.5],
+ [3.5, 0.005, 0.04, 0.01, -0.06, 0.32, 0.35, 0.3],
+ [8.8, 0.005, 0.04, 0.01, -0.06, 0.32, 0.35, 0.3],
+ [16, -0.025, 0.11, 0.015, -0.045, 0.4, 0.45, 0.1],
+ [17.2, -0.025, 0.11, 0.015, -0.045, 0.4, 0.45, 0.1],
+ [18, 0.018, 0.065, 0.015, -0.08, 0.68, 0.75, -0.35],
+ [20, 0.018, 0.065, 0.015, -0.08, 0.68, 0.75, -0.35],
+ ],
+ blinks: [3.15, 7.4, 17.65],
+ },
+ office: {
+ poses: [
+ [0, 0.06, -0.08, -0.06, -0.025, 0.15, 0.12, -0.4],
+ [2, 0.06, -0.08, -0.06, -0.025, 0.15, 0.12, -0.4],
+ [4, 0, 0.06, -0.10, -0.12, 0.28, 0.2, 0.5],
+ [9, 0, 0.06, -0.10, -0.12, 0.28, 0.2, 0.5],
+ [53, 0.025, -0.16, 0.01, -0.035, 0.45, 0.5, -0.6],
+ [57, 0.025, -0.16, 0.01, -0.035, 0.45, 0.5, -0.6],
+ [59, -0.035, 0.05, -0.025, -0.15, 0.5, 0.2, 0.2],
+ [65, -0.035, 0.05, -0.025, -0.15, 0.5, 0.2, 0.2],
+ [85, 0.04, 0.10, -0.015, -0.04, 0.6, 0.6, 0.1],
+ [90, 0.04, 0.10, -0.015, -0.04, 0.6, 0.6, 0.1],
+ [154, 0.07, -0.05, 0.01, -0.02, 0.8, 0.7, -0.25],
+ [156, 0.07, -0.05, 0.01, -0.02, 0.8, 0.7, -0.25],
+ ],
+ blinks: [3.6, 7.8, 58.1, 63.2, 87.3, 155.1],
+ },
+ laboratory: {
+ poses: [
+ [0, 0.09, -0.05, -0.1, -0.22, 0.3, 0.2, -0.3],
+ [2, 0.09, -0.05, -0.1, -0.22, 0.3, 0.2, -0.3],
+ [3.2, 0.015, 0.13, -0.05, -0.10, 0.12, 0.08, 0.5],
+ [5, 0.015, 0.13, -0.05, -0.10, 0.12, 0.08, 0.5],
+ [92, 0.04, -0.10, -0.08, -0.12, 0.6, 0.5, -0.2],
+ [95, 0.04, -0.10, -0.08, -0.12, 0.6, 0.5, -0.2],
+ [97, -0.02, 0.06, -0.015, -0.04, 0.7, 0.6, 0.2],
+ [99, -0.02, 0.06, -0.015, -0.04, 0.7, 0.6, 0.2],
+ ],
+ blinks: [2.7, 94.2, 98.1],
+ },
+ settlement: {
+ poses: [
+ [0, 0.025, -0.08, 0.015, -0.02, 0.1, 0.1, -0.4],
+ [4, 0.025, -0.08, 0.015, -0.02, 0.1, 0.1, -0.4],
+ [7, -0.025, 0.14, -0.08, -0.025, 0.15, 0.15, 0.6],
+ [19, -0.025, 0.14, -0.08, -0.025, 0.15, 0.15, 0.6],
+ [22, 0.015, -0.03, -0.025, -0.08, 0.25, 0.25, -0.2],
+ [28, 0.015, -0.03, -0.025, -0.08, 0.25, 0.25, -0.2],
+ ],
+ blinks: [5.8, 13.4, 21.4, 26.2],
+ },
+ control: {
+ poses: [
+ [0, 0.10, -0.07, -0.12, -0.18, 0.2, 0.1, -0.4],
+ [2, 0.10, -0.07, -0.12, -0.18, 0.2, 0.1, -0.4],
+ [3.5, 0.02, 0.12, -0.06, -0.09, 0.3, 0.25, 0.4],
+ [6, 0.02, 0.12, -0.06, -0.09, 0.3, 0.25, 0.4],
+ [126, 0.06, -0.12, -0.04, -0.12, 0.5, 0.55, -0.3],
+ [129, 0.06, -0.12, -0.04, -0.12, 0.5, 0.55, -0.3],
+ [131, -0.01, 0.08, -0.08, -0.05, 0.6, 0.6, 0.25],
+ [133, -0.01, 0.08, -0.08, -0.05, 0.6, 0.6, 0.25],
+ [158, 0.08, -0.04, -0.12, -0.2, 0.75, 0.65, -0.2],
+ [161, 0.08, -0.04, -0.12, -0.2, 0.75, 0.65, -0.2],
+ [169, -0.015, 0.1, -0.025, -0.06, 0.8, 0.7, 0.15],
+ [171, -0.015, 0.1, -0.025, -0.06, 0.8, 0.7, 0.15],
+ ],
+ blinks: [2.7, 128.2, 132, 159.5, 170.3],
+ },
+};
+const CHANNELS = ['pitch', 'yaw', 'leftArm', 'rightArm', 'brow', 'mouth', 'gaze'];
+
+/** Rigid joints and facial pigment deform from absolute time without frame state. */
+export function createFilmActorRig(parts, sceneName = 'portrait') {
+ const joints = new Map();
const bindings = [];
+ const faces = parts.filter(part => part.name === 'Continuous sculpted head');
for (const part of parts) {
if (!part.actorJoint) continue;
- const joint = part.actorJoint;
- if (!groups.has(joint.name)) groups.set(joint.name, joint);
- bindings.push({ part, base: mat4.clone(part.matrix), joint: joint.name });
+ joints.set(part.actorJoint.name, part.actorJoint);
+ bindings.push({ part, base: mat4.clone(part.matrix), joint: part.actorJoint.name });
}
- if (!groups.size) return () => {};
- const graph = createSceneGraph(Array.from(groups.values(), joint => ({ name: joint.name, pivot: joint.pivot })));
- const tracks = Array.from(groups.values(), joint => {
- const poses = joint.kind === 'head'
- ? [[0, 0], [1.7, -0.055], [2.5, -0.055], [4.8, 0.095], [7, 0.095], [10.2, 0], [12, 0]]
- : [[0, 0], [2.2, -0.018], [4.3, -0.075], [5.7, -0.075], [8.8, -0.025], [10.5, 0], [12, 0]];
- return {
- target: joint.name,
- property: 'rotation',
+ if (!joints.size) return () => {};
+ const performance = PERFORMANCES[sceneName] ?? PERFORMANCES.laboratory;
+ const clip = createAnimationClip({
+ duration: performance.poses.at(-1)[0],
+ tracks: CHANNELS.map((channel, index) => ({
+ target: channel,
+ property: 'value',
interpolation: 'SMOOTH',
- keyframes: poses.map(([time, angle]) => ({ time, value: Array.from(quat.setAxisAngle(quat.create(), joint.axis, angle)) })),
+ keyframes: performance.poses.map(pose => ({ time: pose[0], value: pose[index + 1] })),
+ })),
+ });
+ const graph = createSceneGraph(Array.from(joints.values(), joint => ({ name: joint.name, pivot: joint.pivot })));
+ const actors = faces.map((face, index) => {
+ const prefix = face.actorJoint.name.slice(0, -5);
+ return {
+ face,
+ index,
+ sampler: compileAnimationSampler(clip),
+ joints: Array.from(joints.values()).filter(joint => joint.name.startsWith(`${prefix} `)).map(joint => ({
+ ...joint,
+ matrix: graph.getNode(joint.name).localMatrix,
+ })),
};
});
- const mixer = createAnimationMixer(graph.animationTargets);
- mixer.clipAction(createAnimationClip({ duration: 12, loop: true, tracks })).play({ at: 0 });
for (const binding of bindings) binding.worldMatrix = graph.getNode(binding.joint).worldMatrix;
+ const orientation = quat.create();
+ const pitchRotation = quat.create();
return time => {
- mixer.apply(time);
+ for (const actor of actors) {
+ const actorTime = time + actor.index * 0.43;
+ const tracks = actor.sampler.sample(actorTime);
+ const value = channel => tracks[channel].output[0];
+ for (const joint of actor.joints) {
+ if (joint.kind === 'head') {
+ quat.setAxisAngle(orientation, [0, 1, 0], value(1));
+ quat.setAxisAngle(pitchRotation, [Math.cos(joint.rotation), 0, -Math.sin(joint.rotation)], value(0));
+ quat.multiply(orientation, orientation, pitchRotation);
+ } else {
+ quat.setAxisAngle(orientation, joint.axis, value(joint.side < 0 ? 2 : 3));
+ }
+ mat4.fromQuat(joint.matrix, orientation);
+ }
+ let closure = 0;
+ for (const blinkTime of performance.blinks) {
+ const phase = Math.abs(actorTime - blinkTime) / 0.13;
+ if (phase < 1) closure = Math.cos(phase * Math.PI / 2) ** 2;
+ }
+ actor.face.morph.weights.set([closure, value(4), value(5), value(6)]);
+ }
graph.update();
for (const binding of bindings) mat4.multiply(binding.part.matrix, binding.worldMatrix, binding.base);
};
diff --git a/src/film.js b/src/film.js
index 2f6999a9..e5156fb7 100644
--- a/src/film.js
+++ b/src/film.js
@@ -5,7 +5,7 @@ import { fitPerspectiveDistance } from './camera.js';
import { box, cylinder, sphere, torus } from './geometry.js';
import { extrude } from './modeling.js';
import { createAnimationClip, createAnimationPlayer } from './animation.js';
-import { sampleScientistHead } from './film-character.js';
+import { sampleScientistHead, sampleScientistHair, sampleScientistEye, scientistSkinColor, scientistEyeColor } from './film-character.js';
import { createMorphPose } from './morph.js';
import { CRADLE, cradlePivot } from './film-physics-definition.js';
import cradleRecording from './film-physics-clip.json' with { type: 'json' };
@@ -109,42 +109,86 @@ function createFedoraCrown() {
}
function createScientistHeadMesh() {
- const geometry = sampledSurface(128, 96, sampleScientistHead);
- geometry.colors = new Float32Array(geometry.positions.length);
- for (let index = 0; index < geometry.positions.length; index += 3) {
- const horizontal = geometry.positions[index];
- const height = geometry.positions[index + 1];
- const front = Math.max(0, geometry.positions[index + 2]);
- const cheek = Math.exp(-1 * ((Math.abs(horizontal) - 0.52) / 0.23) ** 2 - ((height + 0.12) / 0.2) ** 2) * front;
- const underEye = Math.exp(-1 * ((Math.abs(horizontal) - 0.42) / 0.23) ** 2 - ((height - 0.04) / 0.085) ** 2) * front;
- const stubble = Math.exp(-1 * ((height + 0.55) / 0.23) ** 2) * front;
- geometry.colors[index] = 1 - underEye * 0.08 - stubble * 0.045;
- geometry.colors[index + 1] = 1 - cheek * 0.085 - underEye * 0.12 - stubble * 0.065;
- geometry.colors[index + 2] = 1 - cheek * 0.10 - underEye * 0.10 - stubble * 0.055;
- }
- return geometry;
-}
-
-function createEyelidMesh() {
- const surface = lowerLatitude => sampledSurface(32, 16, (horizontal, vertical) => {
- const longitude = (0.5 - horizontal) * 2.7;
- const latitude = 1.48 + vertical * (lowerLatitude - 1.48);
- const radius = 0.5;
- return [
- Math.sin(longitude) * Math.cos(latitude) * radius,
- Math.sin(latitude) * radius,
- Math.cos(longitude) * Math.cos(latitude) * radius,
- ];
+ const surfaces = [
+ { columns: 192, rows: 160, sample: sampleScientistHead, color: scientistSkinColor },
+ ...[-1, 1].map(side => ({
+ columns: 64,
+ rows: 48,
+ sample: (horizontal, vertical, expression) => sampleScientistEye(horizontal, vertical, side, expression === 3),
+ color: point => scientistEyeColor(point, side),
+ })),
+ ];
+ const meshes = surfaces.map(surface => {
+ const mesh = sampledSurface(surface.columns, surface.rows, surface.sample);
+ mesh.colors = new Float32Array(mesh.positions.length);
+ for (let index = 0; index < mesh.positions.length; index += 3) {
+ mesh.colors.set(surface.color(mesh.positions.subarray(index, index + 3)), index);
+ }
+ let closedLid;
+ mesh.morphTargets = Array.from({ length: 4 }, (_, expression) => {
+ const posed = sampledSurface(surface.columns, surface.rows, (horizontal, vertical) => surface.sample(horizontal, vertical, expression));
+ if (expression === 0) closedLid = posed;
+ let normalReference = mesh.normals;
+ let posedNormals = posed.normals;
+ if (expression === 1 && surface.sample === sampleScientistHead) {
+ // Brow and blink positions add independently. Sample both endpoint
+ // surfaces so one static brow delta balances the open and closed lid.
+ const combined = sampledSurface(surface.columns, surface.rows, (horizontal, vertical) => {
+ const base = sampleScientistHead(horizontal, vertical);
+ const closed = sampleScientistHead(horizontal, vertical, 0);
+ const brow = sampleScientistHead(horizontal, vertical, 1);
+ return closed.map((value, axis) => value + brow[axis] - base[axis]);
+ });
+ normalReference = closedLid.normals;
+ posedNormals = combined.normals;
+ }
+ const positions = new Float32Array(mesh.positions.length);
+ const normals = new Float32Array(mesh.normals.length);
+ for (let component = 0; component < positions.length; component++) {
+ positions[component] = posed.positions[component] - mesh.positions[component];
+ let referenceScale = 1;
+ let posedScale = 1;
+ if (surface.sample === sampleScientistHead && expression <= 1) {
+ const depthComponent = component - component % 3 + 2;
+ if (Math.abs(normalReference[depthComponent]) > 0.000001 && Math.abs(posedNormals[depthComponent]) > 0.000001) {
+ // Lid depth changes preserve XY. Equal Z components encode normal
+ // gradients, which blend correctly before the shader normalizes.
+ referenceScale = mesh.normals[depthComponent] / normalReference[depthComponent];
+ posedScale = mesh.normals[depthComponent] / posedNormals[depthComponent];
+ }
+ }
+ normals[component] = posedNormals[component] * posedScale - normalReference[component] * referenceScale;
+ if (surface.sample === sampleScientistHead && expression === 1) {
+ const depthComponent = component - component % 3 + 2;
+ const openScale = Math.abs(posed.normals[depthComponent]) > 0.000001 ? mesh.normals[depthComponent] / posed.normals[depthComponent] : 1;
+ const openDelta = posed.normals[component] * openScale - mesh.normals[component];
+ normals[component] = (normals[component] + openDelta) / 2;
+ }
+ }
+ return { positions, normals };
+ });
+ return mesh;
});
- const geometry = surface(0.55);
- const closed = surface(-0.75);
- const positions = new Float32Array(geometry.positions.length);
- const normals = new Float32Array(geometry.normals.length);
- for (let component = 0; component < positions.length; component++) {
- positions[component] = closed.positions[component] - geometry.positions[component];
- normals[component] = closed.normals[component] - geometry.normals[component];
- }
- geometry.morphTargets = [{ positions, normals }];
+ // One retained geometry keeps the iris bound to the head without extra draws.
+ const componentCount = meshes.reduce((total, mesh) => total + mesh.positions.length, 0);
+ const geometry = {
+ positions: new Float32Array(componentCount),
+ normals: new Float32Array(componentCount),
+ colors: new Float32Array(componentCount),
+ indices: new Uint32Array(meshes.reduce((total, mesh) => total + mesh.indices.length, 0)),
+ morphTargets: Array.from({ length: 4 }, () => ({ positions: new Float32Array(componentCount), normals: new Float32Array(componentCount) })),
+ };
+ let componentOffset = 0;
+ let indexOffset = 0;
+ for (const mesh of meshes) {
+ for (const channel of ['positions', 'normals', 'colors']) geometry[channel].set(mesh[channel], componentOffset);
+ for (let index = 0; index < mesh.indices.length; index++) geometry.indices[indexOffset + index] = mesh.indices[index] + componentOffset / 3;
+ for (let target = 0; target < 4; target++) {
+ for (const channel of ['positions', 'normals']) geometry.morphTargets[target][channel].set(mesh.morphTargets[target][channel], componentOffset);
+ }
+ componentOffset += mesh.positions.length;
+ indexOffset += mesh.indices.length;
+ }
return geometry;
}
@@ -389,7 +433,7 @@ function createIgnition(meshes) {
function addScientist(builder, position = [0, 0, 0], hat = true, rotation = 0) {
const { add } = builder;
const actorName = `Scientist ${builder.parts.length}`;
- const blinkPose = createMorphPose(1);
+ const expressionPose = createMorphPose(4);
const joints = new Map();
const transform = point => [position[0] + point[0] * Math.cos(rotation) + point[2] * Math.sin(rotation), position[1] + point[1], position[2] - point[0] * Math.sin(rotation) + point[2] * Math.cos(rotation)];
const actorMaterials = {
@@ -399,10 +443,7 @@ function addScientist(builder, position = [0, 0, 0], hat = true, rotation = 0) {
lapel: { ...materials.cloth, color: [0.055, 0.061, 0.055], roughness: 0.83 },
paper: { ...materials.paper, color: [0.8, 0.74, 0.6], roughness: 0.84 },
black: { ...materials.black, color: [0.012, 0.015, 0.017], roughness: 0.82 },
- eye: { color: [0.57, 0.59, 0.52], metallic: 0, roughness: 0.26, emission: 0 },
- iris: { color: [0.11, 0.23, 0.24], metallic: 0, roughness: 0.24, emission: 0 },
- pupil: { color: [0.006, 0.008, 0.009], metallic: 0, roughness: 0.16, emission: 0 },
- lip: { color: [0.28, 0.095, 0.069], metallic: 0, roughness: 0.68, emission: 0 },
+ face: { ...materials.skin, color: [1, 1, 1], roughness: 0.74 },
};
const shape = (name, mesh, point, scale, material, angles = [0, 0, 0]) => {
const surface = actorMaterials[material] ?? materials[material];
@@ -419,7 +460,9 @@ function addScientist(builder, position = [0, 0, 0], hat = true, rotation = 0) {
joints.set(jointName, {
name: jointName,
kind: head ? 'head' : 'arm',
- pivot: transform(head ? [0, 1.56, -0.005] : [side * 0.205, 1.425, -0.018]),
+ side,
+ rotation,
+ pivot: transform(head ? [0, 1.575, -0.005] : [side * 0.205, 1.455, -0.018]),
axis: head ? [0, 1, 0] : [Math.cos(rotation), 0, -Math.sin(rotation)],
});
}
@@ -434,40 +477,27 @@ function addScientist(builder, position = [0, 0, 0], hat = true, rotation = 0) {
shape('Shirt cuff', 'cylinder', [side * 0.276, 0.94, 0.007], [0.052, 0.04, 0.052], 'paper');
shape('Resting hand silhouette', 'sphere', [side * 0.28, 0.858, 0.016], [0.047, 0.079, 0.035], 'skin');
const mirror = side < 0 ? Math.PI : 0;
- shape('Notched wool lapel', 'lapel', [0, 1.32, 0.14], [1, 1, 1], 'lapel', [0, mirror, 0]);
- shape('Shirt collar', 'shirtCollar', [0, 1.465, 0.145], [1, 1, 1], 'paper', [0, mirror, 0]);
+ shape('Notched wool lapel', 'lapel', [0, 1.36, 0.125], [0.9, 1.08, 1], 'lapel', [0, mirror, 0]);
+ shape('Shirt collar', 'shirtCollar', [0, 1.525, 0.092], [0.9, 0.9, 1], 'paper', [0, mirror, 0]);
shape('Ear silhouette', 'sphere', [side * 0.104, 1.668, -0.004], [0.018, 0.036, 0.026], 'skin');
}
- shape('Sculpted tailored jacket', 'coat', [0, 1.16, 0], [0.25, 0.68, 0.145], 'cloth');
- shape('Tailored shoulder line', 'sphere', [0, 1.439, -0.012], [0.218, 0.025, 0.094], 'cloth');
- shape('Shirt front', 'box', [0, 1.39, 0.131], [0.09, 0.2, 0.012], 'paper');
- shape('Tie knot', 'sphere', [0, 1.448, 0.154], [0.014, 0.016, 0.009], 'graphite');
- shape('Narrow silk tie', 'box', [0, 1.355, 0.151], [0.019, 0.17, 0.006], 'graphite');
+ shape('Sculpted tailored jacket', 'coat', [0, 1.185, 0], [0.225, 0.73, 0.125], 'cloth');
+ shape('Tailored shoulder line', 'sphere', [0, 1.465, -0.012], [0.212, 0.042, 0.081], 'cloth');
+ shape('Shirt front', 'box', [0, 1.425, 0.114], [0.08, 0.22, 0.012], 'paper');
+ shape('Tie knot', 'sphere', [0, 1.50, 0.121], [0.013, 0.014, 0.008], 'graphite');
+ shape('Narrow silk tie', 'box', [0, 1.402, 0.128], [0.017, 0.17, 0.006], 'graphite');
shape('Welt breast pocket', 'box', [-0.135, 1.3, 0.13], [0.075, 0.008, 0.007], 'lapel');
for (const height of [1.18, 1.08]) {
shape('Horn jacket button', 'sphere', [0.017, height, 0.136], [0.009, 0.009, 0.003], 'graphite');
}
- shape('Neck', 'cylinder', [0, 1.533, -0.005], [0.053, 0.11, 0.057], 'skin');
- shape('Continuous sculpted head', 'head', [0, 1.686, -0.01], [0.11, 0.163, 0.106], 'skin');
- for (const side of [-1, 1]) {
- shape('Facial eye white', 'sphere', [side * 0.046, 1.711, 0.079], [0.021, 0.008, 0.013], 'eye');
- shape('Facial blue iris', 'sphere', [side * 0.046, 1.711, 0.0905], [0.0065, 0.0063, 0.0018], 'iris');
- shape('Facial pupil', 'sphere', [side * 0.046, 1.711, 0.092], [0.0027, 0.0034, 0.0009], 'pupil');
- const eyelid = shape('Facial upper eyelid', 'eyelid', [side * 0.046, 1.711, 0.085], [0.047, 0.018, 0.017], 'skin');
- eyelid.morph = blinkPose;
- shape('Facial lower eyelid', 'sphere', [side * 0.046, 1.704, 0.085], [0.022, 0.0035, 0.005], 'skin');
- shape('Facial eyebrow', 'sphere', [side * 0.046, 1.735, 0.09], [0.028, 0.004, 0.005], 'graphite', [0, 0, side * -0.11]);
- shape('Facial nostril', 'sphere', [side * 0.008, 1.66, 0.1245], [0.0038, 0.0022, 0.0018], 'lip');
- shape('Facial ear concha', 'sphere', [side * 0.117, 1.668, 0.002], [0.0025, 0.017, 0.012], 'lip');
- }
- shape('Facial upper lip', 'sphere', [0, 1.633, 0.096], [0.027, 0.0033, 0.005], 'lip');
- shape('Facial lower lip', 'sphere', [0, 1.627, 0.095], [0.026, 0.0038, 0.005], 'lip');
- shape('Facial mouth seam', 'sphere', [0, 1.631, 0.101], [0.024, 0.0011, 0.001], 'graphite');
- shape('Swept hair', 'sphere', [0, 1.795, -0.038], [0.109, 0.055, 0.086], 'graphite', [-0.2, 0, 0]);
+ shape('Neck', 'sphere', [0, 1.551, -0.011], [0.057, 0.064, 0.057], 'skin');
+ const face = shape('Continuous sculpted head', 'head', [0, 1.686, -0.01], [0.112, 0.157, 0.106], 'face');
+ face.morph = expressionPose;
+ shape('Swept hair', 'hair', [0, 1.686, -0.01], [0.114, 0.158, 0.108], 'graphite');
if (hat) {
- shape('Fedora sweeping brim', 'hatBrim', [0, 1.809, 0], [0.195, 0.13, 0.164], 'cloth', [-0.06, 0, -0.035]);
- shape('Fedora tapered felt crown', 'hatCrown', [0, 1.866, -0.022], [0.137, 0.11, 0.122], 'cloth');
- shape('Fedora grosgrain band', 'cylinder', [0, 1.827, -0.022], [0.137, 0.034, 0.121], 'graphite');
+ shape('Fedora sweeping brim', 'hatBrim', [0, 1.799, 0], [0.169, 0.11, 0.145], 'cloth', [-0.06, 0, -0.035]);
+ shape('Fedora tapered felt crown', 'hatCrown', [0, 1.844, -0.017], [0.123, 0.10, 0.112], 'cloth');
+ shape('Fedora grosgrain band', 'cylinder', [0, 1.815, -0.017], [0.123, 0.026, 0.111], 'graphite');
}
}
@@ -746,8 +776,7 @@ function createSparks(meshes) {
}
function animateSet(parts, sceneName) {
- const animateActors = createFilmActorRig(parts);
- const blinkPoses = [...new Set(parts.filter(part => part.morph).map(part => part.morph))];
+ const animateActors = createFilmActorRig(parts, sceneName);
const animatePhysics = sceneName === 'apparatus' ? createCradleAnimation(parts) : null;
const moving = parts.filter(part =>
sceneName === 'sparks' || sceneName === 'atom' ||
@@ -763,13 +792,6 @@ function animateSet(parts, sceneName) {
}
return function animate(time) {
animateActors(time);
- for (let index = 0; index < blinkPoses.length; index++) {
- const phase = ((time + index * 0.73) % 3.7 + 3.7) % 3.7;
- const closure = phase >= 1.8 && phase <= 2.04
- ? Math.sin((phase - 1.8) / 0.24 * Math.PI) ** 2
- : 0;
- blinkPoses[index].weights[0] = closure;
- }
animatePhysics?.(time);
moving.forEach((part, index) => {
const base = bases[index];
@@ -813,7 +835,7 @@ function animateSet(parts, sceneName) {
export function createFilmScenes() {
const meshes = {
- eyelid: createEyelidMesh(),
+ hair: sampledSurface(96, 48, sampleScientistHair),
box: box(0.025, 2),
head: createScientistHeadMesh(),
hatCrown: createFedoraCrown(),
diff --git a/tests/film.test.js b/tests/film.test.js
index 5a7b7b68..d804ea4b 100644
--- a/tests/film.test.js
+++ b/tests/film.test.js
@@ -3,6 +3,8 @@ import test from 'node:test';
import { createFilmScenes, FILM_DURATION, FILM_SHOTS, sampleFilm } from '../src/film.js';
import { resolveEffects } from '../src/effects.js';
import { planRenderSize } from '../src/budget.js';
+import { validateMorphGeometry, validateMorphTransform } from '../src/morph.js';
+import { sampleScientistHead } from '../src/film-character.js';
import { mat4 } from 'gl-matrix';
import { PerspectiveCamera, Vector3 } from 'three';
@@ -193,25 +195,43 @@ test('authored actor joints retain attached headwear and hands through holds and
}
assert.deepEqual(Array.from(head.matrix), held);
scene.animate(12);
- assert.deepEqual(Array.from(head.matrix), assembled);
+ assert.notDeepEqual(Array.from(head.matrix), assembled);
+ scene.animate(16);
+ const closeup = Array.from(head.matrix);
+ scene.animate(17.2);
+ assert.deepEqual(Array.from(head.matrix), closeup);
+ assert.notDeepEqual(closeup, held);
});
-test('facial features share the head joint and remain attached during arbitrary film seeks', () => {
+test('integrated face topology and expression targets retain identities through backward seeks', () => {
const scene = createFilmScenes().portrait;
const head = scene.parts.find(part => part.name === 'Continuous sculpted head');
- const features = scene.parts.filter(part => part.name.startsWith('Facial '));
- assert.ok(features.length >= 12);
assert.notEqual(head.material.tag, 'unlit');
- const relative = part => Array.from(mat4.multiply(mat4.create(), mat4.invert(mat4.create(), head.matrix), part.matrix));
- scene.animate(0);
- const initial = features.map(relative);
- for (const feature of features) assert.equal(feature.actorJoint, head.actorJoint);
- for (const time of [10.3, 2.7, 23.9, 0, 5]) {
+ assert.equal(scene.parts.filter(part => part.name.startsWith('Facial ')).length, 0);
+ const geometry = head.geometry;
+ const targets = geometry.morphTargets;
+ const weights = head.morph.weights;
+ const morphMetadata = validateMorphGeometry(geometry, head.morph);
+ assert.equal(targets.length, 4);
+ assert.ok(targets.every(target => target.positions.some(value => Math.abs(value) > 0.01)));
+ assert.ok(targets.every(target => target.normals.some(value => Math.abs(value) > 0.01)));
+ const base = new Float32Array(geometry.positions);
+ const normals = new Float32Array(geometry.normals);
+ const colors = new Float32Array(geometry.colors);
+ const snapshot = () => ({ matrix: Array.from(head.matrix), weights: Array.from(weights) });
+ scene.animate(17.65);
+ const expected = snapshot();
+ for (const time of [19.8, 2.7, 16, 0, 17.65]) {
scene.animate(time);
- features.forEach((feature, index) => {
- relative(feature).forEach((value, element) => assert.ok(Math.abs(value - initial[index][element]) < 0.00002));
- });
+ assert.equal(head.geometry, geometry);
+ assert.equal(head.geometry.morphTargets, targets);
+ assert.equal(head.morph.weights, weights);
+ validateMorphTransform(head.morph, morphMetadata, head.matrix);
}
+ assert.deepEqual(snapshot(), expected);
+ assert.deepEqual(geometry.positions, base);
+ assert.deepEqual(geometry.normals, normals);
+ assert.deepEqual(geometry.colors, colors);
});
test('narrow portrait shots retain face and headwear through camera moves and backward seeks', () => {
@@ -243,22 +263,148 @@ test('narrow portrait shots retain face and headwear through camera moves and ba
for (const aspect of [0, -1, NaN, Infinity, 1e-320]) assert.throws(() => sampleFilm(10, { aspect }));
});
-test('scientist blink poses are shared per eye pair and replay across arbitrary seeks', () => {
+test('blink closes both inset eye surfaces and retains independent actor expressions', () => {
const scene = createFilmScenes().portrait;
- const eyelids = scene.parts.filter(part => part.name === 'Facial upper eyelid');
- assert.equal(eyelids.length, 2);
- assert.equal(eyelids[0].morph, eyelids[1].morph);
- const weights = eyelids[0].morph.weights;
- const geometry = eyelids[0].geometry;
- scene.animate(0);
+ const face = scene.parts.find(part => part.name === 'Continuous sculpted head');
+ const weights = face.morph.weights;
+ const geometry = face.geometry;
+ scene.animate(17.4);
assert.equal(weights[0], 0);
- scene.animate(1.92);
+ scene.animate(17.65);
assert.ok(weights[0] > 0.999);
- scene.animate(11);
- scene.animate(1.92);
+ assert.ok(weights[1] > 0 && weights[2] > 0);
+ const projectFace = pose => {
+ const triangles = [];
+ const point = vertex => [0, 1, 2].map(axis => geometry.morphTargets.reduce((value, target, index) => value + pose[index] * target.positions[vertex * 3 + axis], geometry.positions[vertex * 3 + axis]));
+ for (let triangle = 0; triangle < geometry.indices.length; triangle += 3) {
+ const vertices = Array.from(geometry.indices.subarray(triangle, triangle + 3));
+ const isEye = vertices.some(vertex => [0, 1, 2].some(axis => geometry.morphTargets[3].positions[vertex * 3 + axis] !== 0));
+ const [first, second, third] = vertices.map(point);
+ if (Math.max(first[2], second[2], third[2]) < 0.5) continue;
+ const minimumX = Math.min(first[0], second[0], third[0]);
+ const maximumX = Math.max(first[0], second[0], third[0]);
+ const minimumY = Math.min(first[1], second[1], third[1]);
+ const maximumY = Math.max(first[1], second[1], third[1]);
+ if (maximumY < 0.07 || minimumY > 0.235 || minimumX > 0.61 || maximumX < -0.61) continue;
+ const divisor = (second[1] - third[1]) * (first[0] - third[0]) + (third[0] - second[0]) * (first[1] - third[1]);
+ if (Math.abs(divisor) < 1e-12) continue;
+ if (!isEye) {
+ const [baseFirst, baseSecond, baseThird] = vertices.map(vertex => geometry.positions.subarray(vertex * 3, vertex * 3 + 3));
+ const baseDivisor = (baseSecond[1] - baseThird[1]) * (baseFirst[0] - baseThird[0]) + (baseThird[0] - baseSecond[0]) * (baseFirst[1] - baseThird[1]);
+ assert.ok(baseDivisor * divisor > 0, `skin triangle ${triangle / 3} must not fold in pose ${pose}`);
+ }
+ triangles.push({ first, second, third, divisor, isEye, minimumX, maximumX, minimumY, maximumY });
+ }
+ return (horizontal, height, eyeball) => {
+ let depth = -Infinity;
+ for (const triangle of triangles) {
+ if (triangle.isEye !== eyeball || horizontal < triangle.minimumX || horizontal > triangle.maximumX || height < triangle.minimumY || height > triangle.maximumY) continue;
+ const { first, second, third, divisor } = triangle;
+ const firstWeight = ((second[1] - third[1]) * (horizontal - third[0]) + (third[0] - second[0]) * (height - third[1])) / divisor;
+ const secondWeight = ((third[1] - first[1]) * (horizontal - third[0]) + (first[0] - third[0]) * (height - third[1])) / divisor;
+ const thirdWeight = 1 - firstWeight - secondWeight;
+ if (Math.min(firstWeight, secondWeight, thirdWeight) >= -1e-6) depth = Math.max(depth, firstWeight * first[2] + secondWeight * second[2] + thirdWeight * third[2]);
+ }
+ return depth;
+ };
+ };
+ const openDepth = projectFace([0, 0, 0, 0]);
+ for (const side of [-1, 1]) {
+ for (const horizontal of [side * 0.4 - 0.055, side * 0.4, side * 0.4 + 0.055]) {
+ const eyeDepth = openDepth(horizontal, 0.155, true);
+ const openSkin = openDepth(horizontal, 0.155, false);
+ assert.ok(eyeDepth > openSkin + 0.008, `eye ${side} sits in an open socket`);
+ }
+ }
+ let coveredRays = 0;
+ for (const pose of [[1, 0, 0, 0], Array.from(weights), [1, 1, 1, 1], [1, 1, 1, -1]]) {
+ const closedDepth = projectFace(pose);
+ for (const side of [-1, 1]) {
+ for (let column = -10; column <= 10; column++) {
+ for (let row = -4; row <= 4; row++) {
+ const horizontal = side * 0.4 + column * 0.0195;
+ const height = 0.155 + row * 0.018;
+ const eyeDepth = closedDepth(horizontal, height, true);
+ if (!Number.isFinite(eyeDepth)) continue;
+ const skinDepth = closedDepth(horizontal, height, false);
+ assert.ok(skinDepth > eyeDepth + 0.003, `closed lid leaks at [${horizontal}, ${height}], pose ${pose}: skin ${skinDepth}, eye ${eyeDepth}`);
+ coveredRays++;
+ }
+ }
+ }
+ }
+ assert.ok(coveredRays > 800, 'cover corners, upper/lower edges and independent expression combinations');
+ const closedPose = Array.from(weights);
+ scene.animate(19);
+ scene.animate(17.65);
assert.ok(weights[0] > 0.999);
- assert.equal(eyelids[0].morph.weights, weights);
- assert.equal(eyelids[0].geometry, geometry);
- scene.animate(3.7);
+ assert.deepEqual(Array.from(weights), closedPose);
+ assert.equal(face.morph.weights, weights);
+ assert.equal(face.geometry, geometry);
+ scene.animate(17.9);
assert.equal(weights[0], 0);
+ const laboratory = createFilmScenes().laboratory;
+ const actors = laboratory.parts.filter(part => part.name === 'Continuous sculpted head');
+ assert.equal(actors.length, 2);
+ assert.equal(actors[0].geometry, actors[1].geometry);
+ assert.notEqual(actors[0].morph, actors[1].morph);
+ laboratory.animate(2.7);
+ assert.ok(actors[0].morph.weights[0] > 0.999);
+ assert.equal(actors[1].morph.weights[0], 0);
+ assert.notDeepEqual(Array.from(actors[0].morph.weights), Array.from(actors[1].morph.weights));
+});
+
+test('open and closed lids retain smooth surface normals throughout the brow range', () => {
+ const scene = createFilmScenes().portrait;
+ const face = scene.parts.find(part => part.morph);
+ const geometry = face.geometry;
+ scene.animate(17.65);
+ const actualPose = Array.from(face.morph.weights);
+ const poses = [actualPose];
+ for (const blink of [0, 0.5, 1]) {
+ for (const brow of [0, 0.25, 0.5, 0.75, 1]) {
+ for (const mouth of [0, 1]) poses.push([blink, brow, mouth, 0]);
+ }
+ }
+ const composedPoint = (horizontal, vertical, pose) => {
+ const base = sampleScientistHead(horizontal, vertical);
+ const result = [...base];
+ for (let target = 0; target < pose.length; target++) {
+ if (!pose[target]) continue;
+ const posed = sampleScientistHead(horizontal, vertical, target);
+ for (let axis = 0; axis < 3; axis++) result[axis] += pose[target] * (posed[axis] - base[axis]);
+ }
+ return result;
+ };
+ const minima = { open: 1, partial: 1, closed: 1, actual: 1 };
+ for (const pose of poses) {
+ let minimum = 1;
+ for (let row = 62; row < 82; row++) {
+ for (let column = 20; column < 78; column++) {
+ const vertex = (row * 193 + column) * 3;
+ const base = geometry.positions.subarray(vertex, vertex + 3);
+ if (Math.abs(Math.abs(base[0]) - 0.4) > 0.25 || Math.abs(base[1] - 0.155) > 0.12) continue;
+ const horizontal = column / 192;
+ const vertical = row / 160;
+ const right = composedPoint(horizontal + 0.0001, vertical, pose);
+ const left = composedPoint(horizontal - 0.0001, vertical, pose);
+ const below = composedPoint(horizontal, vertical + 0.0001, pose);
+ const above = composedPoint(horizontal, vertical - 0.0001, pose);
+ const tangent = right.map((value, axis) => value - left[axis]);
+ const bitangent = below.map((value, axis) => value - above[axis]);
+ const expected = [
+ tangent[1] * bitangent[2] - tangent[2] * bitangent[1],
+ tangent[2] * bitangent[0] - tangent[0] * bitangent[2],
+ tangent[0] * bitangent[1] - tangent[1] * bitangent[0],
+ ];
+ const blended = [0, 1, 2].map(axis => geometry.morphTargets.reduce((value, target, index) => value + pose[index] * target.normals[vertex + axis], geometry.normals[vertex + axis]));
+ const alignment = expected.reduce((sum, value, axis) => sum + value * blended[axis], 0) / Math.hypot(...expected) / Math.hypot(...blended);
+ minimum = Math.min(minimum, alignment);
+ }
+ }
+ const state = pose === actualPose ? 'actual' : pose[0] === 0 ? 'open' : pose[0] === 1 ? 'closed' : 'partial';
+ minima[state] = Math.min(minima[state], minimum);
+ assert.ok(minimum > 0.985, `combined surface normal agreement ${minimum} for pose ${pose}`);
+ }
+ console.log(JSON.stringify({ eyelidNormalAgreement: minima }));
});