Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Step the jelly presets by rebound and settle time, draw them large with named colours, bake 4 s (#852)

Nguyen Xuan Anebe97b4a4edf
diff --git a/docs/physics.md b/docs/physics.md
index 3df727a4..328c1b85 100644
--- a/docs/physics.md
+++ b/docs/physics.md
@@ -450,15 +450,17 @@ Jelly feel (`tests/soft-body-bounce.test.js`, measured): the 0.5 m rounded cube
| 0.02 | 0.9 | 0.065 m | 0.000 m | 0.093 m | 0.441 m |
| 0.02 | 0.1 | 0.099 m | 0.000 m | 0.100 m | 0.447 m |
-Before `bounce` existed, `shape` and `damping` were the only knobs that changed the rebound, and none gave a controlled one. Lowering `shape` or `stiffness` deepens the dent (0.026 to 0.099 m), so softness needed no new field. A very low `shape` has a price: with `shape` 0.02 and `stiffness` 0.1, 132 of the cube's 588 triangles turn inside out in the worst frame and the dent shows ragged, doubled edges. It is a real surface fold, not shading, and `selfCollision`, `bend`, more solver iterations and a gentler volume step do not remove it (measured). Keep `shape` at 0.15 or more for a jelly that has to look clean.
+Before `bounce` existed, `shape` and `damping` were the only knobs that changed the rebound, and none gave a controlled one. Lowering `shape` or `stiffness` deepens the dent (0.026 to 0.099 m), so softness needed no new field. A very low `shape` has a price: with `shape` 0.02 and `stiffness` 0.1, 132 of the cube's 588 triangles turn inside out in the worst frame and the dent shows ragged, doubled edges. It is a real surface fold, not shading, and `selfCollision`, `bend`, more solver iterations and a gentler volume step do not remove it (measured). Keep `shape` at 0.13 or more for a jelly that has to look clean.
-Three presets that step clearly (`JELLY_PRESETS` in `tests/support/jelly-cube.mjs`, previewed by `scripts/render-jelly-bounce.mjs` and labelled by `scripts/label-jelly-bounce.py`; no triangle folds in the test):
+Three presets that step clearly (`JELLY_PRESETS` in `tests/support/jelly-cube.mjs`, previewed by `scripts/render-jelly-bounce.mjs` and labelled by `scripts/label-jelly-bounce.py`; the preview is 960 by 540 at 60 fps, 4 seconds, from a long lens so the cubes carry no perspective skew, and each cube has a name label and its own colour):
-| Preset (cube colour in the preview) | `shape` | `stiffness` | `bounce` | Dent | Rebound |
-| --- | --- | --- | --- | --- | --- |
-| firm (blue) | 1 | 0.9 | 0 | 0.026 m | 0.102 m |
-| medium (amber) | 0.3 | 0.2 | 0.6 | 0.042 m | 0.216 m |
-| soft (pink) | 0.15 | 0.05 | 1 | 0.052 m | 0.464 m |
+| Preset (cube colour in the preview) | `shape` | `stiffness` | `bounce` | Dent | Sideways bulge | Rebound | Stops moving at step |
+| --- | --- | --- | --- | --- | --- | --- | --- |
+| firm (blue) | 1 | 0.9 | 0 | 0.026 m | 0.020 m | 0.102 m | 96 |
+| medium (orange) | 0.3 | 0.05 | 0.5 | 0.041 m | 0.038 m | 0.184 m | 126 |
+| soft (pink) | 0.13 | 0.01 | 0.9 | 0.049 m | 0.064 m | 0.377 m | 186 |
+
+A dent without folds stops near 5 cm, so the dent steps 1.6 and 1.2 times while the rebound steps 1.8 and 2.0 times; the soft cube also keeps wobbling about twice as long as the firm one. All three keep every triangle facing out (0 inverted in the bake), the top face is level within 0.05 degrees at the deepest dent and within 0.1 degrees at the end, and the sides bulge past the top at the dent (the soft cube is 0.564 m wide at the dent against a top face 0.385 m wide, equal on the left and right), so the lit side of that rim can look like a separate sliver in a still.
With `damping: 0` and the default shape, `bounce` 1 sends the cube back to 1.85 m of its 1.95 m drop.
diff --git a/scripts/label-jelly-bounce.py b/scripts/label-jelly-bounce.py
index 693316de..08208789 100644
--- a/scripts/label-jelly-bounce.py
+++ b/scripts/label-jelly-bounce.py
@@ -13,8 +13,8 @@ from pathlib import Path
from PIL import Image, ImageDraw, ImageFont
WIDTH, HEIGHT = 960, 540
-COLUMN_CENTERS = {"firm": 239, "medium": 480, "soft": 721}
-CHIP_COLORS = {"blue": (38, 115, 242), "amber": (250, 178, 26), "pink": (242, 77, 153)}
+COLUMN_CENTERS = {"firm": 197, "medium": 480, "soft": 763}
+CHIP_COLORS = {"blue": (38, 115, 242), "orange": (240, 90, 10), "pink": (217, 31, 115)}
FONT_PATH = "C:/Windows/Fonts/segoeuib.ttf"
@@ -30,11 +30,11 @@ def build_overlay(summary):
title = f"{cube_id.upper()}"
lines = [f"{cube['colorName']} cube", f"dent {cube['dentMeters'] * 100:.1f} cm", f"rebound {cube['reboundMeters'] * 100:.0f} cm"]
left, right = center - 100, center + 100
- draw.rounded_rectangle([left, 410, right, 516], radius=10, fill=(20, 24, 32, 215))
- draw.ellipse([left + 12, 421, left + 30, 439], fill=CHIP_COLORS[cube["colorName"]] + (255,))
- draw.text((left + 40, 414), title, font=font(26), fill=(255, 255, 255, 255))
+ draw.rounded_rectangle([left, 426, right, 526], radius=10, fill=(20, 24, 32, 215))
+ draw.ellipse([left + 12, 435, left + 30, 453], fill=CHIP_COLORS[cube["colorName"]] + (255,))
+ draw.text((left + 40, 428), title, font=font(26), fill=(255, 255, 255, 255))
for index, line in enumerate(lines):
- draw.text((left + 14, 446 + index * 22), line, font=font(18), fill=(215, 220, 230, 255))
+ draw.text((left + 14, 458 + index * 21), line, font=font(18), fill=(215, 220, 230, 255))
return overlay
@@ -59,12 +59,12 @@ def main():
still.convert("RGB").save(output / name)
cubes = summary["cubes"]
picks = [
- ("falling", 30),
+ ("falling", 36),
("contact", cubes["soft"]["contactStep"]),
("deepest dent (soft)", cubes["soft"]["deepestDentStep"]),
("firm rebound top", cubes["firm"]["reboundTopStep"]),
("soft rebound top", cubes["soft"]["reboundTopStep"]),
- ("end", 149),
+ ("end", 239),
]
frames = []
for label, step in picks:
diff --git a/scripts/render-jelly-bounce.mjs b/scripts/render-jelly-bounce.mjs
index ec96bfc3..513dd39c 100644
--- a/scripts/render-jelly-bounce.mjs
+++ b/scripts/render-jelly-bounce.mjs
@@ -11,15 +11,15 @@ import { Client } from '@modelcontextprotocol/client';
import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';
import '../tests/support/load-agent-scene-modules.mjs';
import { createAgentScene } from '../src/agent-scene.js';
-import { JELLY_FRAMES_PER_SECOND, JELLY_PRESETS, jellyCubeRecipe, measureBounce } from '../tests/support/jelly-cube.mjs';
+import { invertedTriangles, JELLY_FRAMES_PER_SECOND, JELLY_PRESETS, jellyCubeRecipe, measureBounce, topFaceTilt } from '../tests/support/jelly-cube.mjs';
const PREVIEW = { width: 960, height: 540, fps: JELLY_FRAMES_PER_SECOND };
-const FRAME_COUNT = 150;
+const FRAME_COUNT = 240;
const serverEntry = new URL('../bin/67js-mcp.mjs', import.meta.url).pathname.replace(/^\/(\w:)/, '$1');
// The presets are shared with the test (tests/support/jelly-cube.mjs). Colours are named so the labels and the docs agree:
-// blue is firm, amber is medium, pink is soft.
-const POSITIONS = { firm: { x: -1.2, color: [0.15, 0.45, 0.95] }, medium: { x: 0, color: [0.98, 0.7, 0.1] }, soft: { x: 1.2, color: [0.95, 0.3, 0.6] } };
+// blue is firm, orange is medium, pink is soft.
+const POSITIONS = { firm: { x: -0.85, color: [0.08, 0.3, 0.85] }, medium: { x: 0, color: [0.85, 0.15, 0.0] }, soft: { x: 0.85, color: [0.85, 0.12, 0.45] } };
const CUBES = JELLY_PRESETS.map(preset => ({ ...preset, ...POSITIONS[preset.id] }));
function threeCubeRecipe() {
@@ -29,7 +29,7 @@ function threeCubeRecipe() {
...single,
materials: [...CUBES.map(cube => ({ id: `${cube.id}-gel`, color: cube.color })), single.materials[1]],
nodes: [...cubeNodes, ...single.nodes.slice(1)],
- camera: { fov: 34, eye: [0, 0.6, 4.4], target: [0, 0.5, 0] },
+ camera: { fov: 11, eye: [0, 0.7, 8.4], target: [0, 0.42, 0] },
cloth: {
...single.cloth,
sheets: CUBES.map(cube => ({ node: cube.id, softBody: { pressure: 1, ...cube.softBody }, stiffness: 0.9, bend: 0, damping: 2, ...cube.sheet })),
@@ -53,6 +53,36 @@ function cubeFrames(recipe) {
return framesByCube;
}
+function horizontalExtent(frame) {
+ let low = Infinity;
+ let high = -Infinity;
+ for (let index = 0; index < frame.length; index += 3) {
+ low = Math.min(low, frame[index]);
+ high = Math.max(high, frame[index]);
+ }
+ return high - low;
+}
+
+// What the stills should show besides dent and rebound: sideways bulge at the deepest dent, the step the body stops moving,
+// the top face tilt at the deepest dent and at the last frame, and the inverted triangles of the single-cube bake.
+function restAndShape(id, frames, bounce) {
+ const preset = CUBES.find(cube => cube.id === id);
+ let settledStep = 0;
+ for (let step = 1; step < frames.length; step++) {
+ let move = 0;
+ for (let index = 0; index < frames[step].length; index++) move = Math.max(move, Math.abs(frames[step][index] - frames[step - 1][index]));
+ if (move > 0.0015) settledStep = step;
+ }
+ const single = jellyCubeRecipe({ softBody: { pressure: 1, ...preset.softBody }, sheet: preset.sheet, duration: FRAME_COUNT / JELLY_FRAMES_PER_SECOND });
+ return {
+ bulgeMeters: Number((horizontalExtent(frames[bounce.deepestFrame]) - horizontalExtent(frames[0])).toFixed(4)),
+ tiltAtDeepestDentDegrees: Number(topFaceTilt(frames[bounce.deepestFrame]).toFixed(2)),
+ tiltAtLastFrameDegrees: Number(topFaceTilt(frames.at(-1)).toFixed(2)),
+ lastMovingStep: settledStep,
+ invertedTriangles: invertedTriangles(single, FRAME_COUNT),
+ };
+}
+
async function renderJob(call, sessionId, settings) {
const submitted = await call('scene_render_submit', { sessionId, expectedRevision: 0, settings });
if (submitted.isError) throw new Error(submitted.content?.[0]?.text);
@@ -78,6 +108,7 @@ async function main() {
for (const [id, frames] of cubeFrames(recipe)) {
const bounce = measureBounce(frames);
measured[id] = { colorName: CUBES.find(cube => cube.id === id).colorName, ...CUBES.find(cube => cube.id === id).softBody, ...CUBES.find(cube => cube.id === id).sheet, contactStep: bounce.contact, deepestDentStep: bounce.deepestFrame, reboundTopStep: bounce.topFrame, dentMeters: Number(bounce.dent.toFixed(4)), reboundMeters: Number(bounce.reboundHeight.toFixed(4)) };
+ Object.assign(measured[id], restAndShape(id, frames, bounce));
stillTimes[`${id}-contact`] = bounce.contact / JELLY_FRAMES_PER_SECOND;
stillTimes[`${id}-deepest-dent`] = bounce.deepestFrame / JELLY_FRAMES_PER_SECOND;
stillTimes[`${id}-rebound-top`] = bounce.topFrame / JELLY_FRAMES_PER_SECOND;
diff --git a/tests/soft-body-bounce.test.js b/tests/soft-body-bounce.test.js
index 32074971..c5a879ad 100644
--- a/tests/soft-body-bounce.test.js
+++ b/tests/soft-body-bounce.test.js
@@ -2,7 +2,7 @@ import test from 'node:test';
import { createHash } from 'node:crypto';
import assert from 'node:assert/strict';
import { createCloth } from '../src/cloth.js';
-import { foldedTriangles, frameHashes, JELLY_PRESETS, jellyCubeRecipe, measureBounce, recordJelly } from './support/jelly-cube.mjs';
+import { foldedTriangles, frameHashes, invertedTriangles, JELLY_PRESETS, jellyCubeRecipe, measureBounce, recordJelly, topFaceTilt } from './support/jelly-cube.mjs';
const FRAME_COUNT = 110;
@@ -82,15 +82,30 @@ test('the firm, medium and soft presets step clearly in dent and rebound without
const results = JELLY_PRESETS.map(preset => measure(preset.softBody, preset.sheet));
const [firm, medium, soft] = results;
assert.ok(medium.dent > firm.dent * 1.4 && soft.dent > medium.dent * 1.1, `dents ${results.map(result => result.dent.toFixed(3)).join(', ')}`);
- assert.ok(medium.reboundHeight > firm.reboundHeight * 1.8 && soft.reboundHeight > medium.reboundHeight * 1.8, `rebounds ${results.map(result => result.reboundHeight.toFixed(3)).join(', ')}`);
- assert.ok(soft.dent > 0.045 && soft.reboundHeight > 0.4, `soft dent ${soft.dent}, rebound ${soft.reboundHeight}`);
+ assert.ok(medium.reboundHeight > firm.reboundHeight * 1.6 && soft.reboundHeight > medium.reboundHeight * 1.8, `rebounds ${results.map(result => result.reboundHeight.toFixed(3)).join(', ')}`);
+ assert.ok(soft.dent > 0.045 && soft.reboundHeight > 0.35, `soft dent ${soft.dent}, rebound ${soft.reboundHeight}`);
for (const preset of JELLY_PRESETS) {
const folded = foldedTriangles(jellyCubeRecipe({ softBody: preset.softBody, sheet: preset.sheet }), FRAME_COUNT);
assert.ok(folded <= 8, `${preset.id} folded ${folded} of 588 triangles in one frame`);
}
});
-test('a near-zero shape folds the surface on impact, which is why the soft preset keeps 0.15', () => {
+test('a near-zero shape folds the surface on impact, which is why the soft preset keeps 0.13 or more', () => {
const folded = foldedTriangles(jellyCubeRecipe({ softBody: { shape: 0.02, bounce: 1 }, sheet: { stiffness: 0.1 } }), FRAME_COUNT);
assert.ok(folded > 50, `shape 0.02 should fold more than 50 triangles, got ${folded}`);
});
+
+// The frames the preview shows: every preset keeps its surface the right way out, and each rests level once it has settled.
+test('the presets never invert a triangle and rest level after 4 seconds', () => {
+ for (const preset of JELLY_PRESETS) {
+ const recipe = jellyCubeRecipe({ softBody: preset.softBody, sheet: preset.sheet, duration: 4 });
+ const inverted = invertedTriangles(recipe, 240);
+ assert.ok(inverted <= 2, `${preset.id} inverted ${inverted} triangles in one frame`);
+ const frames = recordJelly(recipe, 240);
+ const tilt = topFaceTilt(frames.at(-1));
+ assert.ok(tilt < 0.5, `${preset.id} rests tilted ${tilt.toFixed(2)} degrees`);
+ let largestMove = 0;
+ for (let index = 0; index < frames.at(-1).length; index++) largestMove = Math.max(largestMove, Math.abs(frames.at(-1)[index] - frames.at(-10)[index]));
+ assert.ok(largestMove < 0.005, `${preset.id} still moved ${largestMove} m in 9 steps at the end`);
+ }
+});
diff --git a/tests/support/jelly-cube.mjs b/tests/support/jelly-cube.mjs
index cdcca8ae..f6cc3e2a 100644
--- a/tests/support/jelly-cube.mjs
+++ b/tests/support/jelly-cube.mjs
@@ -80,15 +80,64 @@ export function measureBounce(frames) {
}
/**
- * The three jellies of the preview, from firm to soft. The soft one keeps `shape` at 0.15: below about 0.1 the surface
- * folds over itself on impact (see `foldedTriangles`), which is how a deeper dent was paid for before.
+ * The three jellies of the preview, from firm to soft, with the colour each is drawn in. The soft one keeps `shape` at
+ * 0.13 or more: below about 0.1 the surface folds over itself on impact (see `foldedTriangles`), which is how a deeper
+ * dent was paid for before. A fold-free dent stops near 5 cm, so the steps between presets show most in the rebound.
*/
export const JELLY_PRESETS = [
{ id: 'firm', colorName: 'blue', softBody: { shape: 1, bounce: 0 }, sheet: {} },
- { id: 'medium', colorName: 'amber', softBody: { shape: 0.3, bounce: 0.6 }, sheet: { stiffness: 0.2 } },
- { id: 'soft', colorName: 'pink', softBody: { shape: 0.15, bounce: 1 }, sheet: { stiffness: 0.05 } },
+ { id: 'medium', colorName: 'orange', softBody: { shape: 0.3, bounce: 0.5 }, sheet: { stiffness: 0.05 } },
+ { id: 'soft', colorName: 'pink', softBody: { shape: 0.13, bounce: 0.9 }, sheet: { stiffness: 0.01 } },
];
+/** Angle in degrees of the plane through the highest vertices of a frame, against the horizontal, along x then z. */
+export function topFaceTilt(frame) {
+ let highest = -Infinity;
+ for (let index = 1; index < frame.length; index += 3) highest = Math.max(highest, frame[index]);
+ const points = [];
+ for (let index = 0; index < frame.length; index += 3) {
+ if (frame[index + 1] > highest - 0.06) points.push([frame[index], frame[index + 1], frame[index + 2]]);
+ }
+ const mean = [0, 1, 2].map(axis => points.reduce((sum, point) => sum + point[axis], 0) / points.length);
+ const slopeAlong = axis => {
+ let covariance = 0;
+ let variance = 0;
+ for (const point of points) {
+ covariance += (point[axis] - mean[axis]) * (point[1] - mean[1]);
+ variance += (point[axis] - mean[axis]) ** 2;
+ }
+ return Math.abs(Math.atan2(covariance, variance)) * 180 / Math.PI;
+ };
+ return Math.max(slopeAlong(0), slopeAlong(2));
+}
+
+/** Most triangles in any frame whose normal points against the normal they had at rest: an inverted triangle. */
+export function invertedTriangles(recipe, frameCount) {
+ const scene = createAgentScene(recipe);
+ let rest = null;
+ let worst = 0;
+ for (let frame = 0; frame < frameCount; frame++) {
+ scene.sampleMotion(frame / JELLY_FRAMES_PER_SECOND);
+ const { positions, indices } = scene.parts.find(part => part.name === 'cube').geometry;
+ const normals = [];
+ for (let corner = 0; corner < indices.length; corner += 3) {
+ const a = indices[corner] * 3;
+ const b = indices[corner + 1] * 3;
+ const c = indices[corner + 2] * 3;
+ const edgeOne = [positions[b] - positions[a], positions[b + 1] - positions[a + 1], positions[b + 2] - positions[a + 2]];
+ const edgeTwo = [positions[c] - positions[a], positions[c + 1] - positions[a + 1], positions[c + 2] - positions[a + 2]];
+ normals.push([edgeOne[1] * edgeTwo[2] - edgeOne[2] * edgeTwo[1], edgeOne[2] * edgeTwo[0] - edgeOne[0] * edgeTwo[2], edgeOne[0] * edgeTwo[1] - edgeOne[1] * edgeTwo[0]]);
+ }
+ rest ??= normals;
+ let inverted = 0;
+ normals.forEach((normal, index) => {
+ if (normal[0] * rest[index][0] + normal[1] * rest[index][1] + normal[2] * rest[index][2] < 0) inverted++;
+ });
+ worst = Math.max(worst, inverted);
+ }
+ return worst;
+}
+
/**
* Most triangles facing toward the body's centre in any one frame. A closed convex-ish jelly keeps every triangle facing
* out, so a count above zero means the surface folded over itself (a fold shows as ragged doubled edges).