Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Load the buoyancy code on demand so physics entries do not grow (#982)

Nguyen Xuan An7563fa6ef34f
diff --git a/scripts/agent-preview-browser.js b/scripts/agent-preview-browser.js
index b67cd2ec..916ffee3 100644
--- a/scripts/agent-preview-browser.js
+++ b/scripts/agent-preview-browser.js
@@ -1,6 +1,6 @@
import { exportNativeSceneTables, nativeTexelTracerIfAvailable } from './native-bake-page.js';
import { buildWithKernels, kernelWorkersAvailable, kernelStats, resetKernelStats } from '../src/kernel-offload.js';
-import { createAgentScene, applyCameraFields, loadAllAgentSceneModules, allAgentSceneModulesLoaded, needsMeshBooleans, loadMeshBooleans, meshBooleansLoaded, setManifoldModuleLoader, needsPhysics, loadPhysicsEngine, physicsEngineLoaded, setPhysicsModuleLoader } from '../src/agent-scene.js';
+import { createAgentScene, applyCameraFields, loadAllAgentSceneModules, allAgentSceneModulesLoaded, needsMeshBooleans, loadMeshBooleans, meshBooleansLoaded, setManifoldModuleLoader, needsPhysics, needsBuoyancy, loadPhysicsEngine, physicsEngineLoaded, setPhysicsModuleLoader } from '../src/agent-scene.js';
import { Renderer67 } from '../src/renderer.js';
import { skyOpenness } from '../src/closed-room.js';
import { fogSkyVisibility } from '../src/fog-sky-visibility.js';
@@ -620,7 +620,7 @@ function afterMeshBooleans(value, run) {
if (!allAgentSceneModulesLoaded()) return loadAllAgentSceneModules().then(() => afterMeshBooleans(value, run));
const loads = [];
if (!meshBooleansLoaded() && needsMeshBooleans(value)) loads.push(loadMeshBooleans());
- if (!physicsEngineLoaded() && needsPhysics(value)) loads.push(loadPhysicsEngine());
+ if (needsPhysics(value) && (!physicsEngineLoaded() || needsBuoyancy(value))) loads.push(loadPhysicsEngine({ buoyancy: needsBuoyancy(value) }));
if (!loads.length) return run();
return Promise.all(loads).then(run);
}
diff --git a/scripts/render-buoyancy-film.mjs b/scripts/render-buoyancy-film.mjs
index f3d64169..375d00b4 100644
--- a/scripts/render-buoyancy-film.mjs
+++ b/scripts/render-buoyancy-film.mjs
@@ -70,7 +70,7 @@ function buildRecipe(boatAssetId) {
geometries: [
{ id: 'crate', type: 'box' },
{ id: 'hull', type: 'box' },
- { id: 'sea', type: 'mesh', base: { type: 'box', bevel: 0 }, edits: seaEdits, stack: [{ op: 'ocean', windSpeed: 6, choppiness: 0.4, size: 30, seed: 5, resolution: 5 }] },
+ { id: 'sea', type: 'mesh', base: { type: 'box', bevel: 0 }, edits: seaEdits, stack: [{ op: 'ocean', windSpeed: 4.5, choppiness: 0.4, size: 30, seed: 5, resolution: 5 }] },
],
materials: [
{ id: 'wood', color: [0.55, 0.34, 0.16], roughness: 0.8 },
@@ -90,7 +90,7 @@ function buildRecipe(boatAssetId) {
ocean: { geometry: 'sea' },
bodies: [
...crates.map(entry => entry.body),
- { node: 'hull', density: 350, float: { drag: 1.5, angularDrag: 1.5, points: [[-0.6, 0, -1.4], [0.6, 0, -1.4], [-0.6, 0, 1.4], [0.6, 0, 1.4]] } },
+ { node: 'hull', density: 300, float: { drag: 1.5, angularDrag: 1.5, points: [[-0.6, 0, -1.4], [0.6, 0, -1.4], [-0.6, 0, 1.4], [0.6, 0, 1.4]] } },
],
},
};
diff --git a/src/agent-scene-modules.js b/src/agent-scene-modules.js
index 8d84677f..d6163716 100644
--- a/src/agent-scene-modules.js
+++ b/src/agent-scene-modules.js
@@ -113,6 +113,11 @@ export function needsPhysics(value) {
return text.includes('"physics":{') || text.includes('"fracture-node"') || text.includes('"type":"settle"');
}
+/** True when a recipe has a body with a float field, so the host passes { buoyancy: true } to loadPhysicsEngine. */
+export function needsBuoyancy(value) {
+ return JSON.stringify(value ?? null).includes('"float":{');
+}
+
/** Names of the on-demand modules a recipe, or a list of edit operations, needs. */
export function agentSceneModulesNeeded(value) {
let text;
diff --git a/src/agent-scene.js b/src/agent-scene.js
index f29a64cd..497ee14a 100644
--- a/src/agent-scene.js
+++ b/src/agent-scene.js
@@ -25,7 +25,7 @@ import { OWN_SECTIONS as NULLABLE_SECTION_OPERATIONS } from './agent-apply-repor
export { describeApplication } from './agent-apply-report.js';
export {
needsMeshBooleans, loadMeshBooleans, meshBooleansLoaded, setManifoldModuleLoader,
- needsPhysics, loadPhysicsEngine, physicsEngineLoaded, setPhysicsModuleLoader,
+ needsPhysics, needsBuoyancy, loadPhysicsEngine, physicsEngineLoaded, setPhysicsModuleLoader,
loadAgentSceneModules, loadAllAgentSceneModules, registerAgentSceneFont, allAgentSceneModulesLoaded, agentSceneModulesNeeded,
} from './agent-scene-modules.js';
diff --git a/src/physics-runtime.js b/src/physics-runtime.js
index 209fab1f..1eb0b3a5 100644
--- a/src/physics-runtime.js
+++ b/src/physics-runtime.js
@@ -4,8 +4,7 @@
// so the bake path and the live path share one adapter. Another engine plugs in as an object with the same shape as
// `rapierAdapter`; see docs/physics-runtime.md. Nothing here touches the film path.
import { mat4, quat } from 'gl-matrix';
-import { applyBuoyancy } from './physics-buoyancy.js';
-import { applyForceFieldImpulses, createRapierWorld, loadPhysicsEngine, prepareLivePhysics, requireRapier } from './physics.js';
+import { applyBuoyancyImpulses, applyForceFieldImpulses, createRapierWorld, loadPhysicsBuoyancy, loadPhysicsEngine, prepareLivePhysics, requireRapier } from './physics.js';
export const PHYSICS_RUNTIME_LIMITS = Object.freeze({
maximumListeners: 64,
@@ -102,7 +101,7 @@ export const rapierAdapter = Object.freeze({
step(stepSeconds, elapsedSeconds) {
world.timestep = stepSeconds;
if (prepared.fields.length) applyForceFieldImpulses({ ...prepared, timestep: stepSeconds }, bodies, elapsedSeconds);
- if (prepared.buoyancy) applyBuoyancy({ ...prepared, timestep: stepSeconds }, bodies, elapsedSeconds);
+ if (prepared.buoyancy) applyBuoyancyImpulses({ ...prepared, timestep: stepSeconds }, bodies, elapsedSeconds);
world.step(eventQueue);
},
readPose(bodyIndex, output) {
@@ -194,6 +193,7 @@ export async function createPhysicsSystem(definition, options = {}) {
const { adapter: requestedAdapter, name, bindings: initialBindings, ...engineOptions } = options;
const adapter = validateAdapter(requestedAdapter ?? rapierAdapter);
const timestep = engineOptions.timestep ?? 1 / 60;
+ if (definition?.bodies?.some(body => body.float !== undefined)) await loadPhysicsBuoyancy();
const prepared = prepareLivePhysics(definition, { ...engineOptions, timestep });
await adapter.load?.();
const world = adapter.createWorld(prepared);
diff --git a/src/physics.js b/src/physics.js
index 9f765ac7..b68f2e7c 100644
--- a/src/physics.js
+++ b/src/physics.js
@@ -1,9 +1,9 @@
import { mat4, quat, vec3 } from 'gl-matrix';
import { evaluateForceFields, normalizeForceFields } from './force-fields.js';
-import { applyBuoyancy, checkBuoyancyWork, floatingBody, normalizeFloat, normalizeOcean } from './physics-buoyancy.js';
let rapierPromise;
let rapierEngine;
+let buoyancyModule;
let loadRapierModule = () => import('@dimforge/rapier3d-compat');
const ZERO = [0, 0, 0];
const IDENTITY = [0, 0, 0, 1];
@@ -35,8 +35,28 @@ export function setPhysicsModuleLoader(loader) {
rapierEngine = undefined;
}
-/** Load the Rapier WASM engine once. After it resolves, bakePhysicsScene runs synchronously. */
-export function loadPhysicsEngine() {
+/** Load the code for floating bodies once. It is a separate chunk so a scene without floating bodies never fetches it. */
+export async function loadPhysicsBuoyancy() {
+ buoyancyModule ??= await import('./physics-buoyancy.js');
+}
+
+function requireBuoyancy(label) {
+ if (!buoyancyModule) {
+ throw new Error(`${label} floats, which needs the buoyancy code. Await loadPhysicsEngine({ buoyancy: true }) before baking or creating the system.`);
+ }
+ return buoyancyModule;
+}
+
+/**
+ * Load the Rapier WASM engine once. After it resolves, bakePhysicsScene runs synchronously.
+ * Pass `{ buoyancy: true }` when any body has a `float` field.
+ */
+export function loadPhysicsEngine(options = {}) {
+ const engine = loadRapierEngine();
+ return options.buoyancy ? Promise.all([engine, loadPhysicsBuoyancy()]).then(([rapier]) => rapier) : engine;
+}
+
+function loadRapierEngine() {
rapierPromise ??= loadRapierModule().then(async module => {
const rapier = module.default ?? module;
await rapier.init();
@@ -311,7 +331,7 @@ function prepare(definition, options) {
return {
name: body.name,
type,
- float: body.float === undefined ? undefined : normalizeFloat(body.float, `body ${body.name}.float`),
+ float: body.float === undefined ? undefined : requireBuoyancy(`body ${body.name}`).normalizeFloat(body.float, `body ${body.name}.float`),
translation: vector(body.translation, 3, 'translation', ZERO),
rotation: rotation(body.rotation, 'rotation'),
linearVelocity: vector(body.linearVelocity, 3, 'linearVelocity', ZERO),
@@ -589,14 +609,15 @@ function prepare(definition, options) {
/** The sea and the floating bodies of a definition, or null when no body has a float field. */
function buoyancyPlan(oceanInput, bodies, colliders, frameCount) {
+ if (!bodies.some(body => body.float !== undefined)) return null;
+ const { checkBuoyancyWork, floatingBody, normalizeOcean } = buoyancyModule;
const floating = [];
bodies.forEach((body, bodyIndex) => {
if (body.float === undefined) return;
const bodyColliders = colliders.filter(collider => collider.body === bodyIndex);
floating.push({ bodyIndex, ...floatingBody(body.float, bodyColliders, `body ${body.name}`) });
});
- const ocean = oceanInput === undefined ? null : normalizeOcean(oceanInput);
- if (!floating.length) return null;
+ const ocean = normalizeOcean(oceanInput);
checkBuoyancyWork(ocean, floating, frameCount);
return { ocean, floating };
}
@@ -856,6 +877,11 @@ export function createRapierWorld(rapier, preparedScene) {
}
}
+/** Push every floating body by the sea at `time`, as one impulse over a step. The buoyancy code is loaded whenever a body floats. */
+export function applyBuoyancyImpulses(preparedScene, bodies, time) {
+ buoyancyModule.applyBuoyancy(preparedScene, bodies, time);
+}
+
/** Push every dynamic body by the force fields at `fieldTime`, as one impulse over a step. */
export function applyForceFieldImpulses(preparedScene, bodies, fieldTime) {
const fieldAccel = [0, 0, 0];
@@ -947,7 +973,7 @@ function bakePrepared(preparedScene) {
}
}
if (preparedScene.fields.length) applyForceFieldImpulses(preparedScene, bodies, (frame - 1) * preparedScene.timestep);
- if (preparedScene.buoyancy) applyBuoyancy(preparedScene, bodies, (frame - 1) * preparedScene.timestep);
+ if (preparedScene.buoyancy) applyBuoyancyImpulses(preparedScene, bodies, (frame - 1) * preparedScene.timestep);
world.step(eventQueue);
eventQueue.drainCollisionEvents((firstHandle, secondHandle, started) => {
if (contactEvents.length >= preparedScene.maxContactEvents) {
diff --git a/tests/physics-buoyancy-recipe.test.js b/tests/physics-buoyancy-recipe.test.js
index d396fa14..50e3fd72 100644
--- a/tests/physics-buoyancy-recipe.test.js
+++ b/tests/physics-buoyancy-recipe.test.js
@@ -3,7 +3,7 @@ import test from 'node:test';
import assert from 'node:assert/strict';
import { createAgentScene, loadPhysicsEngine } from '../src/agent-scene.js';
-await loadPhysicsEngine();
+await loadPhysicsEngine({ buoyancy: true });
function seaRecipe(physics, oceanNode = { op: 'ocean', windSpeed: 0.5, size: 50, seed: 4 }) {
return {
diff --git a/tests/physics-buoyancy.test.js b/tests/physics-buoyancy.test.js
index 16c205bc..6a0c67c2 100644
--- a/tests/physics-buoyancy.test.js
+++ b/tests/physics-buoyancy.test.js
@@ -31,7 +31,7 @@ function digest(scene, seconds) {
return hash.digest('hex');
}
-test.before(() => loadPhysicsEngine());
+test.before(() => loadPhysicsEngine({ buoyancy: true }));
test('a box of density 500 on a calm sea settles at half its height under water', () => {
const scene = bake(crateDefinition(), 20);