3D engine that AI agents drive
Add recorded Rapier physics and smoother shadow filtering
Nguyen Xuan An9f3d38afb564
diff --git a/README.md b/README.mdindex 5c1a62b2..733000bb 100644--- a/README.md+++ b/README.md@@ -158,6 +158,9 @@ The core exports animation helpers, camera views and effect presets. `renderer.uThe current source adds [camera paths](docs/camera-path.md) with cubic moves, target tracking, roll and focal-length conversion.These camera helpers are not included in the published `0.3.3` package yet.The current source also adds [GPU skinning](docs/skinning.md) and skeletal GLB import, with four influences per vertex.+The optional [physics addon](docs/physics.md) records Rapier contacts and articulated joints into a timeline for repeatable film seeks.+It requires the separate `@dimforge/[email protected]` dependency; the core does not import or bundle that solver.+Physics is source-only and is not included in the published `0.3.3` package.The trailer's rigid actor joints now use authored clips, with attached headwear and hands moving together.The [optional asset addon](docs/gltf.md) loads glTF/GLB meshes, base-color textures, opaque vertex colors and rigid node animation.It uses Three.js as a decoder. The core renderer and standalone module remain separate from this dependency.diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.mdindex 0c2a5b88..f57ea6bf 100644--- a/THIRD-PARTY-NOTICES.md+++ b/THIRD-PARTY-NOTICES.md@@ -55,3 +55,11 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.## Simple Icons (package-manager logos)The npm, pnpm, Yarn and Bun SVG marks are sourced from Simple Icons and distributed under CC0-1.0. See public/licenses/simple-icons.txt. Brand marks remain subject to their respective trademark rights.++## Rapier 3D 0.21.0 (optional physics peer dependency)++The physics addon loads `@dimforge/rapier3d-compat` as a separate dependency.+Rapier is distributed under the Apache License, Version 2.0.+Its dependency package includes the complete license text.+Rapier's JavaScript and WASM code are not bundled into the 67.js library archive.+Source and license: https://github.com/dimforge/rapier.js.diff --git a/docs/capability-audit.md b/docs/capability-audit.mdindex 76d963d3..9c1c5a1c 100644--- a/docs/capability-audit.md+++ b/docs/capability-audit.md@@ -21,14 +21,14 @@ The Blender references describe authoring capabilities. Their interpolation and| Modeling | Base primitives, lathe, hole extrusion with bevels, and curve tubes integrated in source | Mesh editing, subdivision, modifiers, package release | Edited models retain topology, normals, UVs, and export behavior || Animation curves | Linear, step, smooth and Hermite tangent interpolation in source | Curve editor; package release verification | Known curve samples, quaternion normalization, and continuous velocity checks || Animation composition | Weighted clips and absolute-time crossfades integrated in source | Additive motion, layer masks, events, package verification | Walking and gestures blend without pose discontinuities |-| Character deformation | Rigid parts | Skinning, morph targets, IK, retargeting | Animated imported character, expressions, and joint contact tests |-| Camera authoring | Manually coded shot endpoints | Paths, tracking, focus targets, lens presets | Reviewed moving shot previews across aspect ratios |+| Character deformation | Rigid joints, GPU skinning and skeletal GLB animation integrated in source | Morph targets, IK, retargeting, facial assets, package release | Animated imported character, expressions, and joint contact tests |+| Camera authoring | Absolute-time camera paths, target tracking, roll and focal-length conversion integrated in source | Focus control, editing, aspect-aware framing, package release | Reviewed moving shot previews across aspect ratios || Film authoring | Scene-specific shot list and player | Shared timeline, shot editing, transitions, audio cues | Edited timeline seeks and exports deterministically |-| Asset import | Opaque glTF meshes, five material maps and rigid animation integrated in source | Deformation, transparency, compression, streaming, package release | Blender fixtures preserve geometry, materials, and animation |+| Asset import | Opaque glTF meshes, five material maps, rigid and skeletal animation integrated in source | Morphs, transparency, compression, streaming, package release | Blender fixtures preserve geometry, materials, and animation || Materials | Factors and five PBR texture channels integrated in source | Layered materials, advanced extensions, authored tangents, package verification | Reference material scenes and texture budget checks || Lighting | Directional shadows and procedural studio illumination | Configurable lights, HDR environments, baked lighting, reflection probes | Reference lighting scenes, stable shadows, and measured render cost || Image rendering | HDR, bloom, grading, MSAA, FXAA | Depth of field, motion blur, temporal sampling, render passes | Reviewed stills and moving previews with measured artifacts |-| Simulation | Demo-specific wind, water, sparks, and ignition | Shared particles, collision, physics, cloth, hair, volumetric tools | Repeatable simulations, contact tests, and bounded resource usage |+| Simulation | Recorded Rapier rigid-body contacts, impulses, kinematics and articulated joints integrated in source; demo-specific wind, water, sparks and ignition | Joint limits, motors, worker baking, bone binding, shared particles, cloth, hair and volumetric tools; package release | Repeatable simulations, contact tests, and bounded resource usage || Interaction | Demo-specific orbit, zoom, and sliders | Picking, transform gizmos, reusable controls | Pointer, keyboard, and mobile interaction checks || Browser editor | Demonstration pages | Modeling, material, lighting, rig, curve, and timeline editing | Complete edit, save, reload, and export workflows || Runtime diagnostics | Render budget estimates and export reports | CPU/GPU timers, draw diagnostics, adaptive quality, LOD, culling | Matching-scene benchmarks with quality and memory measurements |@@ -94,19 +94,37 @@ Normal scratch buffers belong to uploaded parts and remain bounded by the sceneLive GPU frame timing and broader scene measurements remain required before claiming an overall speed improvement.+## Shadow filtering measurement++The current source interpolates depth comparisons within each shadow texel before applying the existing nine-tap filter.+This removes the visible stepped shadow bands in the scientist close-up without changing the shadow texture size or render allocation.+The implementation uses explicit texel comparisons because [WebGL 2 does not guarantee linear filtering for shadow samplers](https://registry.khronos.org/webgl/specs/latest/2.0/).++Run `node scripts/benchmark-shadows.mjs 1d4f4d0` to compare the previous shader with the checked-out shader.+The native RTX 3060 check used the same portrait scene at 1280 × 720, HDR and four MSAA samples.+After ten warmup draws, forty GPU timer queries reported medians of `0.811 ms` before and `0.838 ms` after.+Estimated render allocation remained `88,630,276` bytes. Both draws reported WebGL error zero.+The increase is about `0.027 ms` in this fixed scene; it is not a general performance result or an animation benchmark.+SwiftShader also rendered the updated shader without a WebGL error.+## Trailer acceptance requirementsThe current trailer does not meet the requested visual quality.The current source replaces the scientist's unlit silhouette with lit facial features, shared head attachments and shaped headwear.-The rendered close-up still looks like a stylized mannequin, with visible shadow bands and insufficient facial likeness.+The rendered close-up still looks like a stylized mannequin with insufficient facial likeness.+Portrait exports currently crop part of the headwear; aspect-aware film framing remains unfinished.This source change has not been deployed or published to npm.Rigid joint animation and GPU skinning provide motion tools, but do not solve character modeling or material quality by themselves.The environment has procedural shaders, fog, bloom and grading. These features do not yet produce convincing cinematic atmosphere.Volumetric lighting, smoke, dust, explosion detail and lighting continuity require visible shot-level validation.-The engine does not yet provide rigid-body physics, collision response, articulated constraints or ragdoll simulation.-The requested final state includes these systems, with deterministic playback or recorded simulation for arbitrary film seeks.+The current source provides an optional Rapier addon for rigid-body contacts and articulated spherical, revolute and fixed joints.+A native render fixture records twelve bodies and ten joints, then reproduces the same pose and pixels after a backward seek.+Its 241-frame timeline uses exactly `80,976` bytes; solver allocation is estimated separately and shared WASM capacity remains resident.+This is a technical fixture, not integrated trailer action or evidence of convincing humanoid motion.+Joint limits, motors, bone binding and off-thread baking remain unfinished.+The requested final state includes integrated physical interactions with deterministic playback or recorded simulation for arbitrary film seeks.Simple sine motion does not satisfy the physics requirement.Completion requires recognizable characters, a convincing environment and integrated physical interactions, demonstrated in rendered trailer shots.diff --git a/docs/physics.md b/docs/physics.mdnew file mode 100644index 00000000..1577e269--- /dev/null+++ b/docs/physics.md@@ -0,0 +1,254 @@+# Recorded rigid-body physics++This optional addon uses Rapier 3D to bake collisions and joint motion into a timeline.+Scene playback can seek forward or backward without changing the simulation.+The main renderer does not need Rapier for playback.+This API is available in the current source checkout and is not included in the published `0.3.3` package.+The library build exports it through `67js/addons/physics` when using the npm alias.+Rapier is an optional peer dependency and remains outside the core and library archive.++```sh+npm install @dimforge/[email protected]+```++Use a package-aware development server such as Vite to resolve the solver import.++```js+import { createPhysicsScene, planPhysicsScene } from '../src/physics.js';++const definition = {+ gravity: [0, -9.81, 0],+ bodies: [+ { name: 'floor', type: 'fixed', translation: [0, -0.5, 0] },+ { name: 'box', type: 'dynamic', translation: [0, 3, 0] },+ ],+ colliders: [+ { name: 'floor', body: 'floor', shape: 'cuboid', halfExtents: [5, 0.5, 5] },+ { name: 'box', body: 'box', shape: 'cuboid', halfExtents: [0.5, 0.5, 0.5], mass: 1 },+ ],+ events: [{ tick: 120, body: 'box', impulse: [2, 4, 0] }],+};+const options = { frameCount: 601, timestep: 1 / 60, maxMemoryBytes: 64 * 1024 * 1024 };+const plan = planPhysicsScene(definition, options);+const physics = await createPhysicsScene(definition, options);+const bindings = physics.bindParts([{ body: 'box', part: boxPart }]);+const updatedParts = [boxPart];++function applyAnimation(time) {+ bindings.apply(time);+ renderer.updateParts(updatedParts);+}++applyAnimation(5);+applyAnimation(1); // A backward seek produces the same recorded pose.+physics.dispose();+```++`boxPart` is an existing 67.js part with a retained `Float32Array(16)` matrix.+The binding replaces its world translation and rotation while keeping its scale and matrix identity.+The physics body origin must match the visual part origin.+Multiple visual parts can bind to one body when they share that origin.+Visual offsets need separate parts or body definitions.++## Definition++Names must be nonempty and unique within each body, collider, or joint list.+References use body names.+Arrays follow their declared creation order.+Unknown properties fail validation instead of changing the simulation silently.+Inputs are copied before asynchronous initialization.++Bodies use `dynamic`, `fixed`, or `kinematic` types.+The default type is `dynamic`.+Each body accepts `translation` and `rotation` in world space.+Rotation uses a unit quaternion `[x, y, z, w]`.+Dynamic bodies also accept `linearVelocity`, `angularVelocity`, `linearDamping`, `angularDamping`, and boolean `ccd`.+Every dynamic body needs at least one collider.++Colliders attach to a named body through `body`.+Their `translation` and `rotation` are relative to that body.+Multiple colliders form a compound body.+Collider scales come from their dimensions, independently of visual part scales.++| Shape | Required dimensions |+| --- | --- |+| `ball` | Positive `radius`. |+| `cuboid` | Three positive `halfExtents`. |+| `capsule` | Positive `radius` and `halfHeight` for its cylindrical segment along local Y. |++Each collider accepts either positive `mass` or positive `density`.+The default density is `1`.+Rapier computes the center of mass and angular inertia from these collider properties.+The default `friction` is `0.5` and the default `restitution` is `0`.+Restitution must stay between zero and one.++Joints connect `bodyA` and `bodyB` at local `anchorA` and `anchorB` points.+The default anchors are `[0, 0, 0]`.+Connected bodies do not collide unless `contactsEnabled` is `true`.++| Joint type | Additional fields |+| --- | --- |+| `spherical` | None. The joint permits relative rotation. |+| `revolute` | Required unit `axis` expressed in both bodies' local frames. |+| `fixed` | Optional unit `frameA` and `frameB` quaternions. Both default to identity. |++An articulated ragdoll is a graph of dynamic bodies, colliders, and joints.+This example connects two capsule bodies named `upperArm` and `forearm`.+Their initial translations and rotations must place these anchors together.++```js+definition.joints = [{+ name: 'elbow', type: 'revolute',+ bodyA: 'upperArm', bodyB: 'forearm',+ anchorA: [0, -0.5, 0], anchorB: [0, 0.5, 0],+ axis: [0, 0, 1], contactsEnabled: false,+}];+```++## Tick events++Events run before their tick's integration step.+Frame zero records the initial pose.+Tick zero events affect frame one.+The final valid tick is `frameCount - 2`.+Events run in ascending tick order, preserving declaration order within each tick.++An `impulse` event targets a dynamic body.+The default event type is `impulse`.+Its `impulse` and `torqueImpulse` vectors use world space.+An optional world `point` applies the linear impulse away from the center of mass.+At least one impulse vector is required.++```js+definition.events = [+ { tick: 0, body: 'forearm', torqueImpulse: [0, 0, 0.2] },+ { tick: 60, body: 'upperArm', impulse: [1, 2, 0], point: [0, 1, 0] },+];+```++A `kinematicPose` event targets a position-based kinematic body.+Its optional `translation` and `rotation` define the next world pose.+At least one field is required.+Rapier computes velocity from this target, so a moving kinematic collider can push dynamic bodies.+An unchanged target holds its previous position.++```js+definition.events = [+ { tick: 0, type: 'kinematicPose', body: 'platform', translation: [0, 1, 0] },+];+```++## Sampling and bindings++`physics.sample(time, out)` returns packed poses in `physics.bodyNames` order.+Each body occupies seven Float32 values `[x, y, z, qx, qy, qz, qw]`.+`physics.bodyIndex(name)` returns that body's index.+The output must have exactly `bodyNames.length * 7` values.+Omitting `out` allocates a new array.+Supplying a retained output avoids allocations during playback.++```js+const pose = new Float32Array(physics.bodyNames.length * 7);+physics.sample(1.25, pose);+const boxOffset = physics.bodyIndex('box') * 7;+const boxHeight = pose[boxOffset + 1];+```++Sampling clamps finite times to `[0, physics.duration]`.+Translations use linear interpolation.+Quaternions use normalized interpolation along the shortest arc.+Times at recorded ticks return their stored poses.+Interpolated poses do not run collision detection and can show small penetrations between frames.+A smaller timestep reduces these interpolation artifacts.++Bindings retain their sample buffer and transformation scratch matrices.+Their `apply(time)` method allocates no arrays during playback.+Bindings validate every target before updating any matrix.+Replacing a target matrix fails before any target changes.+Distinct matrix views must also occupy nonoverlapping byte ranges in their shared buffer.++Affine matrices with independent nonzero scales are supported.+Shear and perspective matrices fail validation.+Reflections use a negative X scale with the same handedness as the original matrix.++## Limits and disposal++`frameCount` defaults to `601` and includes frame zero.+`timestep` defaults to `1 / 60` seconds, rounded to Float32.+The maximum timestep is one second.+`solverIterations` defaults to `8` and accepts integers from `1` through `128`.+`duration` equals `(frameCount - 1) * timestep`.+Long timelines require larger frame limits and memory budgets.++| Option | Default | Maximum configurable value |+| --- | --- | --- |+| `maxBodies` | `256` | `4096` |+| `maxColliders` | `1024` | `8192` |+| `maxJoints` | `512` | `8192` |+| `maxEvents` | `10000` | `100000` |+| `maxFrames` | `3601` | `1000000` |+| `maxMemoryBytes` | `134217728` | `2147483647` |++`planPhysicsScene` validates the full definition without loading Rapier or allocating its world.+Its frozen result contains exact `timelineBytes` and an estimated `solverReserveBytes`.+The reservation accounts for body, collider, joint, and potential contact counts.+`estimatedPeakBytes` must fit `maxMemoryBytes` before WASM initialization and timeline allocation.+The reservation is not a hard measurement or cap on Rapier's WASM heap.+Shared WASM initialization, JavaScript metadata, caller outputs, and visual bindings are outside this estimate.++Numbers must remain finite in Float32.+Positive dimensions, mass, density, and timestep must remain positive after rounding.+Collider volume and inertia scales must also remain finite and positive.++Effective collider masses and conservative minimum inertia estimates must remain normal Float32 values, at least `2 ** -126`.+Their reciprocals and the timestep reciprocal must remain finite and positive.+This restriction prevents Rapier from treating very small masses or inertias as zero.+The minimum inertia estimate uses `0.1 * mass * smallestExtent ** 2` for each collider.+Compound bodies add these lower bounds.++Gravity, initial velocities, and impulse vectors must have finite Float32 squared norms.+Preflight also bounds accumulated velocity from gravity and declared impulses.+Angular bounds include torque impulses and off-center impulses divided by the minimum inertia estimate.+Lever-arm estimates include initial positions, collider offsets, and conservative travel over the whole recording.+These estimates ignore damping and contact resistance, so they can reject otherwise usable configurations.++Kinematic translation changes divided by the timestep must have finite Float32 squared norms.+Kinematic rotation targets require a finite squared bound of `(Math.PI / timestep) ** 2`.+Same-tick translation targets use the previous integrated translation for these checks.+These checks cover declared motion, without guaranteeing bounds on every force from contact or constraint solving.+Finite extreme velocities can also be changed by Rapier's internal motion limits.+The preflight checks prevent known overflow cases; they do not promise preservation of arbitrarily large authored speeds.++Large translations can lose small movements through Float32 rounding.+For example, `16777217` becomes `16777216`.+Nonfinite solver outputs fail the bake and release the world.++Every completed or failed bake frees the Rapier world and its contained solver resources.+`physics.dispose()` releases the recorded timeline reference and is safe to call repeatedly.+Sampling, binding creation, body lookup, and existing bindings fail after disposal.+Caller-owned arrays and part matrices remain available.+The shared Rapier module and its reusable WASM memory remain initialized.++JavaScript and WASM allocators can retain freed capacity for reuse.++## Design and boundaries++Two API shapes were considered.+One exposed a mutable solver world with delta-time callbacks.+The selected shape accepts a serializable body graph and explicit tick events, then records a bounded timeline.+This shape makes film seeks independent of playback order and keeps solver state out of render callbacks.++The addon supports rigid-body contacts, compound colliders, impulses, kinematics, and articulated graphs.+It does not implement cloth, soft bodies, mesh colliders, motors, joint limits, sensors, collision masks, or live solver editing.+It does not bind physics directly to skeletal bones or generate a humanoid skeleton.+Those features need additional public contracts.+Creating a scene bakes synchronously after asynchronous WASM initialization and can block the main thread.+A worker integration can move that bake off the render thread.++Repeat recordings require identical inputs, creation order, timestep, solver options, and Rapier version.+Rapier documents cross-platform determinism for its WASM solver under identical initial conditions.+Input calculations such as `Math.sin` can differ across platforms and invalidate that guarantee.+This addon does not promise identical trajectories across different Rapier versions.+The implementation uses `@dimforge/rapier3d-compat` version `0.21.0`, licensed under Apache 2.0.++Sources: [Rapier JavaScript setup](https://rapier.rs/docs/user_guides/javascript/getting_started_js/) and [Rapier determinism](https://rapier.rs/docs/user_guides/javascript/determinism/).diff --git a/package-lock.json b/package-lock.jsonindex 2cacd47a..5dfd4739 100644--- a/package-lock.json+++ b/package-lock.json@@ -10,6 +10,7 @@"license": "MIT","devDependencies": {"@codepawlhq/orglet-ui": "0.2.1",+ "@dimforge/rapier3d-compat": "0.21.0","gl-matrix": "3.4.4","highlight.js": "11.12.0","playwright": "1.64.0",@@ -18,6 +19,14 @@"three": "0.186.1","vite": "8.3.4","wrangler": "4.149.0"+ },+ "peerDependencies": {+ "@dimforge/rapier3d-compat": "0.21.0"+ },+ "peerDependenciesMeta": {+ "@dimforge/rapier3d-compat": {+ "optional": true+ }}},"node_modules/@cloudflare/kv-asset-handler": {@@ -160,6 +169,13 @@"node": ">=12"}},+ "node_modules/@dimforge/rapier3d-compat": {+ "version": "0.21.0",+ "resolved": "https://registry.npmjs.org/@dimforge/rapier3d-compat/-/rapier3d-compat-0.21.0.tgz",+ "integrity": "sha512-tCl1HPGwOhn5aCQbgqWbOH+Nx/5fnr3IPAnzQuR7zIhC/raqi2yxC6LhvZqjdI2El5hQgY5RDAwDrAjAi2FdPA==",+ "dev": true,+ "license": "Apache-2.0"+ },"node_modules/@emnapi/runtime": {"version": "1.11.3","resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz",diff --git a/package.json b/package.jsonindex 7a239b1e..a5fcbc8d 100644--- a/package.json+++ b/package.json@@ -28,7 +28,8 @@"docs/modeling.md","docs/scene-graph.md","docs/camera-path.md",- "docs/skinning.md"+ "docs/skinning.md",+ "docs/physics.md"],"main": "./build/67.module.js","module": "./build/67.module.js",@@ -41,6 +42,7 @@"./addons/canvas2d": "./build/canvas2d.js","./addons/gltf": "./build/gltf.js","./addons/modeling": "./build/modeling.js",+ "./addons/physics": "./build/physics.js","./package.json": "./package.json"},"scripts": {@@ -63,8 +65,17 @@"smoke:site": "node scripts/smoke-site.mjs","publish:ci": "node scripts/publish-ci.mjs"},+ "peerDependencies": {+ "@dimforge/rapier3d-compat": "0.21.0"+ },+ "peerDependenciesMeta": {+ "@dimforge/rapier3d-compat": {+ "optional": true+ }+ },"devDependencies": {"@codepawlhq/orglet-ui": "0.2.1",+ "@dimforge/rapier3d-compat": "0.21.0","gl-matrix": "3.4.4","highlight.js": "11.12.0","playwright": "1.64.0",diff --git a/scripts/benchmark-shadows.mjs b/scripts/benchmark-shadows.mjsnew file mode 100644index 00000000..c6ddb96e--- /dev/null+++ b/scripts/benchmark-shadows.mjs@@ -0,0 +1,56 @@+import { readFile, writeFile } from 'node:fs/promises';+import { execFileSync } from 'node:child_process';+import { constants, setPriority } from 'node:os';+import { chromium } from 'playwright';+setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);+const variants = {+ before: execFileSync('git', ['show', `${process.argv[2] ?? '1d4f4d0'}:src/shaders.js`], { encoding: 'utf8', windowsHide: true }),+ after: await readFile('src/shaders.js', 'utf8'),+};+const browser = await chromium.launch({ executablePath: 'C:/Program Files/Google/Chrome/Application/chrome.exe', headless: true, args: ['--enable-webgl', '--ignore-gpu-blocklist'] });+const results = {};+try {+ for (const [name, source] of Object.entries(variants)) {+ const page = await browser.newPage({ viewport: { width: 1280, height: 720 } });+ await page.route('**/src/shaders.js*', route => route.fulfill({ contentType: 'application/javascript', body: source }));+ await page.route('**/shadow-benchmark.html', route => route.fulfill({ contentType: 'text/html', body: '<canvas style="width:1280px;height:720px;display:block"></canvas>' }));+ await page.goto('http://127.0.0.1:5173/shadow-benchmark.html');+ results[name] = await page.evaluate(async () => {+ const { Renderer67 } = await import('/src/renderer.js');+ const { createFilmScenes, sampleFilm } = await import('/src/film.js');+ const scene = createFilmScenes().portrait;+ scene.animate(2.5);+ const renderer = new Renderer67(document.querySelector('canvas'), scene.parts, { world: true, ground: false, environment: scene.environment, shadowBounds: scene.shadowBounds, samples: 4, hdr: true, pixelRatio: 1, memoryBudgetMiB: 384 });+ const frame = { ...sampleFilm(162).camera, time: 2.5, effects: { grain: 0 } };+ const context = renderer.context;+ const timer = context.getExtension('EXT_disjoint_timer_query_webgl2');+ if (!timer) throw new Error('Native GPU timer unavailable');+ for (let index = 0; index < 10; index++) renderer.render(frame);+ const samples = [];+ for (let index = 0; index < 40; index++) {+ const query = context.createQuery();+ context.beginQuery(timer.TIME_ELAPSED_EXT, query);+ renderer.render(frame);+ context.endQuery(timer.TIME_ELAPSED_EXT);+ context.flush();+ const started = performance.now();+ while (!context.getQueryParameter(query, context.QUERY_RESULT_AVAILABLE)) {+ if (performance.now() - started > 2000) throw new Error('GPU timer query timed out');+ await new Promise(resolve => setTimeout(resolve, 2));+ }+ if (context.getParameter(timer.GPU_DISJOINT_EXT)) throw new Error('GPU timer disjoint');+ samples.push(context.getQueryParameter(query, context.QUERY_RESULT) / 1e6);+ context.deleteQuery(query);+ }+ const sorted = [...samples].sort((first, second) => first - second);+ const report = { medianMilliseconds: (sorted[19] + sorted[20]) / 2, p90Milliseconds: sorted[35], samples, glError: context.getError(), estimatedBytes: renderer.memoryPlan.estimatedBytes };+ renderer.dispose();+ return report;+ });+ await page.close();+ }+ await writeFile('artifacts/shadow-filter-benchmark.json', JSON.stringify(results, null, 2));+ console.log(JSON.stringify(Object.fromEntries(Object.entries(results).map(([name, result]) => [name, { medianMilliseconds: result.medianMilliseconds, p90Milliseconds: result.p90Milliseconds, glError: result.glError, estimatedBytes: result.estimatedBytes }]))));+} finally {+ await browser.close();+}diff --git a/scripts/smoke-package.mjs b/scripts/smoke-package.mjsindex 1eba4cf9..0145716e 100644--- a/scripts/smoke-package.mjs+++ b/scripts/smoke-package.mjs@@ -13,12 +13,19 @@ assert.equal(release.version, metadata.version);assert.equal(release.packageName, metadata.name);assert.equal(release.packageAlias, '67js');assert.equal(release.integrity, `sha512-${createHash('sha512').update(binary).digest('base64')}`);-assert.ok(binary.length < 1024 * 1024, 'Library plus optional glTF decoder must fit within a 1 MiB archive.');+assert.ok(binary.length < 1024 * 1024, 'Library and optional addon wrappers must fit within a 1 MiB archive.');assert.ok((await readFile('build/67.module.js')).length < 150000, 'The core must exclude the optional asset decoder.');const consumer = await mkdtemp(resolve(tmpdir(), '67js-consumer-'));await writeFile(resolve(consumer, 'package.json'), JSON.stringify({ private: true, type: 'module' }));const npmCli = process.env.npm_execpath ?? resolve(dirname(process.execPath), 'node_modules/npm/bin/npm-cli.js');-const installed = spawnSync(process.execPath, [npmCli, 'install', `67js@file:${archive.replaceAll('\\', '/')}`, '--ignore-scripts', '--no-audit', '--no-fund'], { cwd: consumer, windowsHide: true, encoding: 'utf8' });+// Release preparation preserves the registry archive for an already-published version.+// Validate the current source through a separate local pack, without replacing that archive.+const sourcePack = spawnSync(process.execPath, [npmCli, 'pack', '--ignore-scripts', '--json', '--pack-destination', consumer], { windowsHide: true, encoding: 'utf8' });+assert.equal(sourcePack.status, 0, sourcePack.stderr);+const packedSource = JSON.parse(sourcePack.stdout)[0];+assert.ok(packedSource.size < 1024 * 1024, 'The current source package must fit within a 1 MiB archive.');+const sourceArchive = resolve(consumer, packedSource.filename);+const installed = spawnSync(process.execPath, [npmCli, 'install', `67js@file:${sourceArchive.replaceAll('\\', '/')}`, '@dimforge/[email protected]', '--ignore-scripts', '--no-audit', '--no-fund'], { cwd: consumer, windowsHide: true, encoding: 'utf8' });assert.equal(installed.status, 0, installed.stderr);const example = `import assert from 'node:assert/strict';import { VERSION, Renderer67, box, assemblyOffset, cameraView, createAnimationClip, sampleAnimationClip, EFFECT_PRESETS } from '67js';@@ -28,6 +35,7 @@ import * as film from '67js/addons/film';import { createMotionScene } from '67js/addons/motion';import { createCanvas2D } from '67js/addons/canvas2d';import { parseGltf } from '67js/addons/gltf';+import { createPhysicsScene, planPhysicsScene } from '67js/addons/physics';assert.equal(VERSION, '${metadata.version}');assert.equal(typeof Renderer67, 'function');assert.ok(box().positions.length > 0);@@ -43,7 +51,18 @@ assert.equal(sampleAnimationClip(clip, 1)[0].value, 1);assert.ok(createMotionScene().parts.length > 0);assert.ok(createCanvas2D().parts.length > 0);assert.equal(typeof parseGltf, 'function');-console.log('Clean consumer: core, geometry, all addons and all574 explosion offsets passed.');`;+const physicsDefinition = {+ bodies: [{ name: 'floor', type: 'fixed', translation: [0, -0.5, 0] }, { name: 'ball', translation: [0, 2, 0] }],+ colliders: [{ name: 'floor', body: 'floor', shape: 'cuboid', halfExtents: [4, 0.5, 4] }, { name: 'ball', body: 'ball', shape: 'ball', radius: 0.25, mass: 1 }],+};+assert.ok(planPhysicsScene(physicsDefinition, { frameCount: 121 }).timelineBytes > 0);+const physics = await createPhysicsScene(physicsDefinition, { frameCount: 121 });+const finalPose = physics.sample(physics.duration);+assert.ok(finalPose[8] >= 0.23 && finalPose[8] < 0.3, 'Packed addon wrapper must run real Rapier floor contact.');+physics.sample(0);+assert.deepEqual(physics.sample(physics.duration), finalPose);+physics.dispose();+console.log('Clean consumer: core, geometry, addons, real physics contact and all574 explosion offsets passed.');`;await writeFile(resolve(consumer, 'check.mjs'), example);const result = spawnSync(process.execPath, ['check.mjs'], { cwd: consumer, windowsHide: true, encoding: 'utf8' });assert.equal(result.status, 0, result.stderr);diff --git a/scripts/smoke-physics.mjs b/scripts/smoke-physics.mjsnew file mode 100644index 00000000..930f73fb--- /dev/null+++ b/scripts/smoke-physics.mjs@@ -0,0 +1,109 @@+import assert from 'node:assert/strict';+import { mkdir, writeFile } from 'node:fs/promises';+import { constants, setPriority } from 'node:os';+import { chromium } from 'playwright';++setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);+await mkdir('artifacts', { recursive: true });+const base = process.argv[2] ?? 'http://127.0.0.1:5173';+const browser = await chromium.launch({+ executablePath: 'C:/Program Files/Google/Chrome/Application/chrome.exe',+ headless: true,+ args: ['--enable-webgl', '--ignore-gpu-blocklist'],+});+try {+ const page = await browser.newPage({ viewport: { width: 960, height: 720 } });+ const errors = [];+ page.on('pageerror', error => errors.push(error.message));+ await page.route('**/physics-smoke.html', route => route.fulfill({ contentType: 'text/html', body: '<canvas style="width:960px;height:720px;display:block"></canvas>' }));+ await page.goto(`${base}/physics-smoke.html`);+ const report = await page.evaluate(async () => {+ const { Renderer67 } = await import('/src/renderer.js');+ const { box, sphere } = await import('/src/geometry.js');+ const { createPhysicsScene } = await import('/src/physics.js');+ const { mat4 } = await import('/node_modules/gl-matrix/esm/index.js');+ const bodies = [+ { name: 'floor', type: 'fixed', translation: [0, -0.25, 0] },+ { name: 'torso', translation: [0, 2.95, 0] },+ { name: 'pelvis', translation: [0, 2.35, 0] },+ { name: 'head', translation: [0, 3.65, 0] },+ ];+ const colliders = [+ { name: 'floor', body: 'floor', shape: 'cuboid', halfExtents: [4, 0.25, 4] },+ { name: 'torso', body: 'torso', shape: 'cuboid', halfExtents: [0.3, 0.45, 0.16], mass: 4 },+ { name: 'pelvis', body: 'pelvis', shape: 'cuboid', halfExtents: [0.26, 0.18, 0.16], mass: 3 },+ { name: 'head', body: 'head', shape: 'ball', radius: 0.23, mass: 1 },+ ];+ const joints = [+ { name: 'spine', type: 'spherical', bodyA: 'torso', bodyB: 'pelvis', anchorA: [0, -0.45, 0], anchorB: [0, 0.15, 0] },+ { name: 'neck', type: 'spherical', bodyA: 'torso', bodyB: 'head', anchorA: [0, 0.47, 0], anchorB: [0, -0.23, 0] },+ ];+ for (const side of [-1, 1]) {+ const limbDefinitions = [+ [`upperArm${side}`, [side * 0.48, 3, 0], 0.1, 0.25, 1],+ [`forearm${side}`, [side * 0.48, 2.35, 0], 0.1, 0.25, 1],+ [`thigh${side}`, [side * 0.18, 1.85, 0], 0.13, 0.3, 2],+ [`shin${side}`, [side * 0.18, 1.05, 0], 0.13, 0.3, 2],+ ];+ for (const [name, translation, radius, halfHeight, mass] of limbDefinitions) {+ bodies.push({ name, translation });+ colliders.push({ name, body: name, shape: 'capsule', radius, halfHeight, mass });+ }+ joints.push(+ { name: `shoulder${side}`, type: 'spherical', bodyA: 'torso', bodyB: `upperArm${side}`, anchorA: [side * 0.35, 0.3, 0], anchorB: [-side * 0.13, 0.25, 0] },+ { name: `elbow${side}`, type: 'revolute', bodyA: `upperArm${side}`, bodyB: `forearm${side}`, anchorA: [0, -0.35, 0], anchorB: [0, 0.3, 0], axis: [1, 0, 0] },+ { name: `hip${side}`, type: 'spherical', bodyA: 'pelvis', bodyB: `thigh${side}`, anchorA: [side * 0.18, -0.1, 0], anchorB: [0, 0.4, 0] },+ { name: `knee${side}`, type: 'revolute', bodyA: `thigh${side}`, bodyB: `shin${side}`, anchorA: [0, -0.4, 0], anchorB: [0, 0.4, 0], axis: [1, 0, 0] },+ );+ }+ const bakeStarted = performance.now();+ const physics = await createPhysicsScene({ bodies, colliders, joints, events: [{ tick: 0, body: 'torso', impulse: [1.2, 0, 0.4], torqueImpulse: [0.3, 0.2, 0.6] }] }, { frameCount: 241, solverIterations: 16, maxMemoryBytes: 32 * 1024 * 1024 });+ const bakeMilliseconds = performance.now() - bakeStarted;+ const meshes = { box: box(0.025, 2), sphere: sphere(32, 20) };+ const parts = colliders.map(collider => {+ const dimensions = collider.halfExtents?.map(value => value * 2) ?? [collider.radius, collider.radius + (collider.halfHeight ?? 0), collider.radius];+ return { name: collider.name, geometry: collider.shape === 'cuboid' ? meshes.box : meshes.sphere, matrix: mat4.fromScaling(mat4.create(), dimensions), material: { color: collider.name === 'floor' ? [0.12, 0.14, 0.16] : collider.name === 'head' ? [0.6, 0.35, 0.2] : [0.09, 0.32, 0.38], metallic: 0.1, roughness: 0.55 } };+ });+ const binding = physics.bindParts(parts.map(part => ({ body: part.name, part })));+ const matrices = parts.map(part => part.matrix);+ const canvas = document.querySelector('canvas');+ const renderer = new Renderer67(canvas, parts, { ground: false, samples: 4, hdr: true, pixelRatio: 1, memoryBudgetMiB: 128, shadowBounds: { extent: 5, eye: [-3, 6, 4], target: [0, 1, 0], near: 0.1, far: 20 } });+ const frame = { eye: [5, 3.8, 7], target: [0, 1.6, 0], fov: 42, time: 0, effects: { grain: 0 } };+ function render(time) {+ binding.apply(time);+ renderer.updateParts(parts);+ renderer.render(frame);+ const pixels = new Uint8Array(canvas.width * canvas.height * 4);+ renderer.context.readPixels(0, 0, canvas.width, canvas.height, renderer.context.RGBA, renderer.context.UNSIGNED_BYTE, pixels);+ let checksum = 2166136261;+ for (const value of pixels) checksum = Math.imul(checksum ^ value, 16777619) >>> 0;+ return { checksum, glError: renderer.context.getError(), pose: Array.from(physics.sample(time)) };+ }+ const upright = render(0);+ const uprightImage = canvas.toDataURL('image/png');+ const fallen = render(3);+ const fallenImage = canvas.toDataURL('image/png');+ const repeated = render(0);+ const retained = parts.every((part, index) => part.matrix === matrices[index]);+ const memory = renderer.memoryPlan;+ const physicsMemory = physics.memoryPlan;+ renderer.dispose();+ physics.dispose();+ return { upright, fallen, repeated, retained, disposed: physics.disposed, memory, physicsMemory, bakeMilliseconds, uprightImage, fallenImage };+ });+ assert.deepEqual(errors, []);+ assert.equal(report.upright.glError, 0);+ assert.equal(report.fallen.glError, 0);+ assert.deepEqual(report.upright, report.repeated);+ assert.notEqual(report.upright.checksum, report.fallen.checksum);+ assert.equal(report.retained, true);+ assert.equal(report.disposed, true);+ for (const state of ['upright', 'fallen']) {+ await writeFile(`artifacts/physics-${state}.png`, Buffer.from(report[`${state}Image`].split(',')[1], 'base64'));+ delete report[`${state}Image`];+ }+ await writeFile('artifacts/physics-gpu.json', JSON.stringify(report, null, 2));+ console.log(JSON.stringify(report, null, 2));+} finally {+ await browser.close();+}diff --git a/skills/build-67js-scene/SKILL.md b/skills/build-67js-scene/SKILL.mdindex fe677d45..bae605cd 100644--- a/skills/build-67js-scene/SKILL.md+++ b/skills/build-67js-scene/SKILL.md@@ -18,8 +18,7 @@ Use `simplify-code` and `engineering-workflows` for implementation.- A keyframe scene uses `src/animation.js`, `src/motion.js` and `src/motion-player.js`.- An authored camera uses `src/camera-path.js` and the checkout's `docs/camera-path.md`.- A skeletal asset uses `src/skinning.js`, `src/gltf.js` and the checkout's `docs/skinning.md`.-- An authored camera uses `src/camera-path.js` and the checkout's `docs/camera-path.md`.-- A skeletal asset uses `src/skinning.js`, `src/gltf.js` and the checkout's `docs/skinning.md`.+- Recorded contacts or articulated physics use optional `src/physics.js` and the checkout's `docs/physics.md`.- A flat scene or axis view uses `src/canvas2d.js`, `src/camera.js` and `src/view2d.js`.- A GLB asset viewer uses the optional `src/gltf.js` addon and `src/asset-viewer.js`.- An image or video export uses `render-67js-media`.diff --git a/src/physics.js b/src/physics.jsnew file mode 100644index 00000000..aae278d6--- /dev/null+++ b/src/physics.js@@ -0,0 +1,721 @@+import { mat4, quat } from 'gl-matrix';++let rapierPromise;+const ZERO = [0, 0, 0];+const IDENTITY = [0, 0, 0, 1];+const MIN_NORMAL_FLOAT32 = 2 ** -126;+const LIMITS = {+ maxBodies: [256, 4096],+ maxColliders: [1024, 8192],+ maxJoints: [512, 8192],+ maxEvents: [10000, 100000],+ maxFrames: [3601, 1000000],+};++function fields(value, allowed, label) {+ if (!value || typeof value !== 'object' || Array.isArray(value)) {+ throw new TypeError(`${label} must be an object`);+ }+ for (const key of Object.keys(value)) {+ if (!allowed.includes(key)) {+ throw new TypeError(`${label}.${key} is unsupported`);+ }+ }+}++function scalar(value, label, min = -Infinity, max = Infinity) {+ const rounded = Math.fround(value);+ if (typeof value !== 'number' || !Number.isFinite(value) || !Number.isFinite(rounded) || value < min || value > max || rounded < min || rounded > max) {+ throw new RangeError(`${label} must be finite Float32 in [${min}, ${max}]`);+ }+ return rounded;+}++function positive(value, label) {+ const result = scalar(value, label, 0);+ if (result === 0) {+ throw new RangeError(`${label} must remain positive in Float32`);+ }+ return result;+}++function normalPositive(value, label) {+ const result = scalar(value, label, MIN_NORMAL_FLOAT32);+ positive(1 / result, `${label} reciprocal`);+ return result;+}++function vectorLength(value, label) {+ const squaredLength = value[0] ** 2 + value[1] ** 2 + value[2] ** 2;+ scalar(squaredLength, `${label} squared norm`, 0);+ return Math.sqrt(squaredLength);+}++function vector(value, size, label, fallback) {+ value ??= fallback;+ if (!value || value.length !== size) {+ throw new TypeError(`${label} must contain ${size} numbers`);+ }+ return Array.from(value, (number, index) => scalar(number, `${label}[${index}]`));+}++function rotation(value, label) {+ const result = vector(value, 4, label, IDENTITY);+ const length = Math.hypot(...result);+ if (!length || Math.abs(length - 1) > 1e-4) {+ throw new RangeError(`${label} must be a unit quaternion`);+ }+ return result.map(number => Math.fround(number / length));+}++function integer(value, label, min, max) {+ if (!Number.isSafeInteger(value) || value < min || value > max) {+ throw new RangeError(`${label} must be an integer in [${min}, ${max}]`);+ }+ return value;+}++function namedList(list, label, limit) {+ if (!Array.isArray(list) || list.length > limit) {+ throw new RangeError(`${label} must be an array with at most ${limit} entries`);+ }+ const names = new Set();+ for (const entry of list) {+ if (typeof entry?.name !== 'string' || !entry.name.length || names.has(entry.name)) {+ throw new TypeError(`${label} names must be nonempty and unique`);+ }+ names.add(entry.name);+ }+ return list;+}++function prepare(definition, options) {+ fields(definition, ['bodies', 'colliders', 'joints', 'events', 'gravity'], 'definition');+ fields(options, ['frameCount', 'timestep', 'solverIterations', 'maxMemoryBytes', ...Object.keys(LIMITS)], 'options');+ const limits = {};+ for (const [key, [fallback, cap]] of Object.entries(LIMITS)) {+ limits[key] = integer(options[key] ?? fallback, key, 1, cap);+ }+ const frameCount = integer(options.frameCount ?? 601, 'frameCount', 1, limits.maxFrames);+ const timestep = positive(options.timestep ?? 1 / 60, 'timestep');+ positive(1 / timestep, 'timestep reciprocal');+ if (timestep > 1) {+ throw new RangeError('timestep must be at most one second');+ }+ const solverIterations = integer(options.solverIterations ?? 8, 'solverIterations', 1, 128);+ const maxMemoryBytes = integer(options.maxMemoryBytes ?? 128 * 1024 * 1024, 'maxMemoryBytes', 1, 2 ** 31 - 1);+ const rawBodies = namedList(definition.bodies, 'bodies', limits.maxBodies);+ if (!rawBodies.length) {+ throw new RangeError('bodies must not be empty');+ }+ const rawColliders = namedList(definition.colliders ?? [], 'colliders', limits.maxColliders);+ const rawJoints = namedList(definition.joints ?? [], 'joints', limits.maxJoints);+ const rawEvents = definition.events ?? [];+ if (!Array.isArray(rawEvents) || rawEvents.length > limits.maxEvents) {+ throw new RangeError('events exceed maxEvents');+ }+ const timelineBytes = rawBodies.length * frameCount * 7 * Float32Array.BYTES_PER_ELEMENT;+ // Solver memory varies with contacts and WASM allocator reuse. This is a reservation estimate, not a heap measurement.+ const solverReserveBytes = 1048576 + rawBodies.length * 16384 + rawColliders.length * 16384 + rawJoints.length * 8192 + rawColliders.length ** 2 * 128;+ const estimatedPeakBytes = timelineBytes + solverReserveBytes;+ if (!Number.isSafeInteger(estimatedPeakBytes) || estimatedPeakBytes > maxMemoryBytes) {+ throw new RangeError(`physics memory plan ${estimatedPeakBytes} exceeds maxMemoryBytes ${maxMemoryBytes}`);+ }+ const bodies = rawBodies.map(body => {+ fields(body, ['name', 'type', 'translation', 'rotation', 'linearVelocity', 'angularVelocity', 'linearDamping', 'angularDamping', 'ccd'], `body ${body.name}`);+ const type = body.type ?? 'dynamic';+ if (!['dynamic', 'fixed', 'kinematic'].includes(type)) {+ throw new TypeError(`body ${body.name} has unsupported type`);+ }+ if (type !== 'dynamic' && (body.linearVelocity || body.angularVelocity || body.linearDamping !== undefined || body.angularDamping !== undefined || body.ccd !== undefined)) {+ throw new TypeError(`body ${body.name} only supports velocity, damping, and CCD when dynamic`);+ }+ if (body.ccd !== undefined && typeof body.ccd !== 'boolean') {+ throw new TypeError('ccd must be boolean');+ }+ return {+ name: body.name,+ type,+ translation: vector(body.translation, 3, 'translation', ZERO),+ rotation: rotation(body.rotation, 'rotation'),+ linearVelocity: vector(body.linearVelocity, 3, 'linearVelocity', ZERO),+ angularVelocity: vector(body.angularVelocity, 3, 'angularVelocity', ZERO),+ linearDamping: scalar(body.linearDamping ?? 0, 'linearDamping', 0),+ angularDamping: scalar(body.angularDamping ?? 0, 'angularDamping', 0),+ ccd: body.ccd ?? false,+ };+ });+ const bodyIndices = new Map(bodies.map((body, index) => [body.name, index]));+ function bodyIndex(name) {+ if (!bodyIndices.has(name)) {+ throw new TypeError(`unknown body ${name}`);+ }+ return bodyIndices.get(name);+ }+ const colliders = rawColliders.map(collider => {+ fields(collider, ['name', 'body', 'shape', 'radius', 'halfHeight', 'halfExtents', 'translation', 'rotation', 'mass', 'density', 'friction', 'restitution'], `collider ${collider.name}`);+ const body = bodyIndex(collider.body);+ let radius;+ let halfHeight;+ let halfExtents;+ let volume;+ let smallestExtent;+ if (collider.shape === 'ball') {+ if (collider.halfHeight !== undefined || collider.halfExtents !== undefined) {+ throw new TypeError('ball only accepts radius');+ }+ radius = positive(collider.radius, 'radius');+ volume = 4 * Math.PI * radius ** 3 / 3;+ smallestExtent = radius;+ } else if (collider.shape === 'cuboid') {+ if (collider.radius !== undefined || collider.halfHeight !== undefined) {+ throw new TypeError('cuboid only accepts halfExtents');+ }+ halfExtents = vector(collider.halfExtents, 3, 'halfExtents');+ for (const extent of halfExtents) {+ positive(extent, 'halfExtents');+ }+ volume = 8 * halfExtents[0] * halfExtents[1] * halfExtents[2];+ smallestExtent = Math.min(...halfExtents);+ } else if (collider.shape === 'capsule') {+ if (collider.halfExtents !== undefined) {+ throw new TypeError('capsule only accepts radius and halfHeight');+ }+ radius = positive(collider.radius, 'radius');+ halfHeight = positive(collider.halfHeight, 'halfHeight');+ volume = Math.PI * radius ** 2 * 2 * halfHeight + 4 * Math.PI * radius ** 3 / 3;+ smallestExtent = radius;+ } else {+ throw new TypeError(`unsupported collider shape ${collider.shape}`);+ }+ positive(volume, 'collider volume');+ if (collider.mass !== undefined && collider.density !== undefined) {+ throw new TypeError('collider accepts either mass or density');+ }+ const mass = collider.mass === undefined ? undefined : positive(collider.mass, 'mass');+ const density = mass === undefined ? positive(collider.density ?? 1, 'density') : undefined;+ const effectiveMass = normalPositive(mass ?? volume * density, 'collider effective mass');+ if (mass !== undefined) {+ positive(mass / volume, 'collider effective density');+ }+ const minimumInertia = normalPositive(0.1 * effectiveMass * smallestExtent ** 2, 'collider minimum inertia scale');+ const largestExtent = halfExtents ? Math.max(...halfExtents) : radius + (halfHeight ?? 0);+ positive(effectiveMass * largestExtent ** 2, 'collider maximum inertia scale');+ return {+ body,+ shape: collider.shape,+ radius,+ halfHeight,+ halfExtents,+ mass,+ density,+ effectiveMass,+ minimumInertia,+ largestExtent,+ translation: vector(collider.translation, 3, 'collider translation', ZERO),+ rotation: rotation(collider.rotation, 'collider rotation'),+ friction: scalar(collider.friction ?? 0.5, 'friction', 0),+ restitution: scalar(collider.restitution ?? 0, 'restitution', 0, 1),+ };+ });+ const massTotals = Array(bodies.length).fill(0);+ const inertiaTotals = Array(bodies.length).fill(0);+ const minimumInertiaTotals = Array(bodies.length).fill(0);+ const maximumColliderOffsets = Array(bodies.length).fill(0);+ for (const collider of colliders) {+ const index = collider.body;+ massTotals[index] = normalPositive(massTotals[index] + collider.effectiveMass, 'compound body mass');+ inertiaTotals[index] = positive(inertiaTotals[index] + collider.effectiveMass * (collider.largestExtent ** 2 + Math.hypot(...collider.translation) ** 2), 'compound body inertia scale');+ minimumInertiaTotals[index] = normalPositive(minimumInertiaTotals[index] + collider.minimumInertia, 'compound body minimum inertia');+ maximumColliderOffsets[index] = Math.max(maximumColliderOffsets[index], Math.hypot(...collider.translation));+ for (const component of collider.translation) {+ scalar(collider.effectiveMass * component, 'collider weighted center');+ }+ }+ for (let bodyIndex = 0; bodyIndex < bodies.length; bodyIndex++) {+ if (bodies[bodyIndex].type === 'dynamic' && massTotals[bodyIndex] === 0) {+ throw new TypeError(`dynamic body ${bodies[bodyIndex].name} requires a collider with mass`);+ }+ }+ const joints = rawJoints.map(joint => {+ fields(joint, ['name', 'type', 'bodyA', 'bodyB', 'anchorA', 'anchorB', 'axis', 'frameA', 'frameB', 'contactsEnabled'], `joint ${joint.name}`);+ if (!['spherical', 'revolute', 'fixed'].includes(joint.type)) {+ throw new TypeError('unsupported joint type');+ }+ const bodyA = bodyIndex(joint.bodyA);+ const bodyB = bodyIndex(joint.bodyB);+ if (bodyA === bodyB) {+ throw new TypeError('joint bodies must differ');+ }+ if (joint.contactsEnabled !== undefined && typeof joint.contactsEnabled !== 'boolean') {+ throw new TypeError('contactsEnabled must be boolean');+ }+ if (joint.type !== 'revolute' && joint.axis !== undefined) {+ throw new TypeError('axis requires a revolute joint');+ }+ if (joint.type !== 'fixed' && (joint.frameA !== undefined || joint.frameB !== undefined)) {+ throw new TypeError('joint frames require a fixed joint');+ }+ const axis = joint.type === 'revolute' ? vector(joint.axis, 3, 'axis') : undefined;+ if (axis && Math.abs(Math.hypot(...axis) - 1) > 1e-4) {+ throw new RangeError('axis must be a unit vector');+ }+ if (axis) {+ const axisLength = Math.hypot(...axis);+ for (let component = 0; component < 3; component++) {+ axis[component] = Math.fround(axis[component] / axisLength);+ }+ }+ return {+ type: joint.type,+ bodyA,+ bodyB,+ anchorA: vector(joint.anchorA, 3, 'anchorA', ZERO),+ anchorB: vector(joint.anchorB, 3, 'anchorB', ZERO),+ axis,+ frameA: rotation(joint.frameA, 'frameA'),+ frameB: rotation(joint.frameB, 'frameB'),+ contactsEnabled: joint.contactsEnabled ?? false,+ };+ });+ const events = rawEvents.map((event, order) => {+ fields(event, ['tick', 'body', 'type', 'impulse', 'torqueImpulse', 'point', 'translation', 'rotation'], `event ${order}`);+ const tick = integer(event.tick, 'event tick', 0, frameCount - 2);+ const body = bodyIndex(event.body);+ const type = event.type ?? 'impulse';+ if (type === 'impulse') {+ if (bodies[body].type !== 'dynamic') {+ throw new TypeError('impulses require a dynamic body');+ }+ if (event.translation !== undefined || event.rotation !== undefined || (event.impulse === undefined && event.torqueImpulse === undefined) || (event.point !== undefined && event.impulse === undefined)) {+ throw new TypeError('invalid impulse event fields');+ }+ return {+ tick,+ body,+ type,+ order,+ impulse: event.impulse === undefined ? undefined : vector(event.impulse, 3, 'impulse'),+ torqueImpulse: event.torqueImpulse === undefined ? undefined : vector(event.torqueImpulse, 3, 'torqueImpulse'),+ point: event.point === undefined ? undefined : vector(event.point, 3, 'point'),+ };+ }+ if (type !== 'kinematicPose' || bodies[body].type !== 'kinematic') {+ throw new TypeError('kinematicPose events require a kinematic body');+ }+ if (event.impulse !== undefined || event.torqueImpulse !== undefined || event.point !== undefined || (event.translation === undefined && event.rotation === undefined)) {+ throw new TypeError('invalid kinematicPose event fields');+ }+ return {+ tick,+ body,+ type,+ order,+ translation: event.translation === undefined ? undefined : vector(event.translation, 3, 'event translation'),+ rotation: event.rotation === undefined ? undefined : rotation(event.rotation, 'event rotation'),+ };+ }).sort((firstEvent, secondEvent) => firstEvent.tick - secondEvent.tick || firstEvent.order - secondEvent.order);+ const gravity = vector(definition.gravity, 3, 'gravity', [0, -9.81, 0]);+ validateMotionBounds(bodies, events, gravity, timestep, frameCount, massTotals, minimumInertiaTotals, maximumColliderOffsets);+ const memoryPlan = Object.freeze({+ timelineBytes,+ solverReserveBytes,+ estimatedPeakBytes,+ maxMemoryBytes,+ bodyCount: bodies.length,+ colliderCount: colliders.length,+ jointCount: joints.length,+ eventCount: events.length,+ frameCount,+ });+ return {+ bodies,+ colliders,+ joints,+ events,+ gravity,+ frameCount,+ timestep,+ solverIterations,+ memoryPlan,+ };+}++function validateMotionBounds(bodies, events, gravity, timestep, frameCount, massTotals, minimumInertiaTotals, maximumColliderOffsets) {+ const duration = (frameCount - 1) * timestep;+ const gravityMagnitude = vectorLength(gravity, 'gravity');+ const linearSpeedBounds = bodies.map(body => {+ const initialSpeed = vectorLength(body.linearVelocity, 'linearVelocity');+ const speedBound = initialSpeed + (body.type === 'dynamic' ? gravityMagnitude * duration : 0);+ scalar(speedBound ** 2, 'accumulated linear velocity squared norm', 0);+ return speedBound;+ });+ const angularSpeedBounds = bodies.map(body => vectorLength(body.angularVelocity, 'angularVelocity'));++ // Ignore damping and contact resistance to bound all declared impulses conservatively.+ for (const event of events) {+ if (event.type !== 'impulse') {+ continue;+ }+ if (event.impulse) {+ const impulseMagnitude = vectorLength(event.impulse, 'impulse');+ linearSpeedBounds[event.body] += impulseMagnitude / massTotals[event.body];+ scalar(linearSpeedBounds[event.body] ** 2, 'accumulated linear velocity squared norm', 0);+ }+ if (event.torqueImpulse) {+ const torqueMagnitude = vectorLength(event.torqueImpulse, 'torqueImpulse');+ angularSpeedBounds[event.body] += torqueMagnitude / minimumInertiaTotals[event.body];+ scalar(angularSpeedBounds[event.body] ** 2, 'accumulated angular velocity squared norm', 0);+ }+ }++ const kinematicTranslations = bodies.map(body => body.translation.slice());+ const kinematicTickBaseTranslations = bodies.map(body => body.translation.slice());+ const kinematicTicks = Array(bodies.length).fill(-1);+ for (const event of events) {+ const body = bodies[event.body];+ if (event.type === 'kinematicPose') {+ if (event.translation) {+ // Same-tick targets share the last integrated pose, and gaps hold that pose.+ if (kinematicTicks[event.body] !== event.tick) {+ kinematicTickBaseTranslations[event.body] = kinematicTranslations[event.body];+ }+ const previousTranslation = kinematicTickBaseTranslations[event.body];+ const targetVelocity = event.translation.map((component, axis) => (component - previousTranslation[axis]) / timestep);+ vectorLength(targetVelocity, 'kinematic target velocity');+ kinematicTranslations[event.body] = event.translation;+ kinematicTicks[event.body] = event.tick;+ }+ if (event.rotation) {+ scalar((Math.PI / timestep) ** 2, 'kinematic angular velocity squared norm', 0);+ }+ continue;+ }+ if (event.impulse && event.point) {+ const impulseMagnitude = vectorLength(event.impulse, 'impulse');+ const maximumTravel = linearSpeedBounds[event.body] * duration;+ const leverArm = Math.hypot(...event.point) + Math.hypot(...body.translation) + maximumTravel + maximumColliderOffsets[event.body];+ const torqueBound = impulseMagnitude * leverArm;+ scalar(torqueBound ** 2, 'off-center torque impulse squared norm', 0);+ angularSpeedBounds[event.body] += torqueBound / minimumInertiaTotals[event.body];+ scalar(angularSpeedBounds[event.body] ** 2, 'accumulated angular velocity squared norm', 0);+ }+ }+}++/** Validate and estimate memory without loading or allocating the Rapier WASM world. */+export function planPhysicsScene(definition, options = {}) {+ return prepare(definition, options).memoryPlan;+}++const xyz = array => ({ x: array[0], y: array[1], z: array[2] });+const xyzw = array => ({ ...xyz(array), w: array[3] });++/** Bake a named rigid-body graph with Rapier, then release its solver world. */+export async function createPhysicsScene(definition, options = {}) {+ const preparedScene = prepare(definition, options);+ rapierPromise ??= import('@dimforge/rapier3d-compat').then(async ({ default: rapier }) => {+ await rapier.init();+ return rapier;+ });+ const rapier = await rapierPromise;+ const world = new rapier.World(xyz(preparedScene.gravity));+ let timeline;+ try {+ world.timestep = preparedScene.timestep;+ world.numSolverIterations = preparedScene.solverIterations;+ const bodies = preparedScene.bodies.map(body => {+ let descriptor;+ if (body.type === 'dynamic') {+ descriptor = rapier.RigidBodyDesc.dynamic();+ } else if (body.type === 'fixed') {+ descriptor = rapier.RigidBodyDesc.fixed();+ } else {+ descriptor = rapier.RigidBodyDesc.kinematicPositionBased();+ }+ descriptor.setTranslation(...body.translation);+ descriptor.setRotation(xyzw(body.rotation));+ if (body.type === 'dynamic') {+ descriptor.setLinvel(...body.linearVelocity);+ descriptor.setAngvel(xyz(body.angularVelocity));+ descriptor.setLinearDamping(body.linearDamping);+ descriptor.setAngularDamping(body.angularDamping);+ descriptor.setCcdEnabled(body.ccd);+ }+ return world.createRigidBody(descriptor);+ });+ for (const collider of preparedScene.colliders) {+ let descriptor;+ if (collider.shape === 'ball') {+ descriptor = rapier.ColliderDesc.ball(collider.radius);+ } else if (collider.shape === 'cuboid') {+ descriptor = rapier.ColliderDesc.cuboid(...collider.halfExtents);+ } else {+ descriptor = rapier.ColliderDesc.capsule(collider.halfHeight, collider.radius);+ }+ descriptor.setTranslation(...collider.translation);+ descriptor.setRotation(xyzw(collider.rotation));+ descriptor.setFriction(collider.friction);+ descriptor.setRestitution(collider.restitution);+ if (collider.mass === undefined) {+ descriptor.setDensity(collider.density);+ } else {+ descriptor.setMass(collider.mass);+ }+ world.createCollider(descriptor, bodies[collider.body]);+ }+ for (const joint of preparedScene.joints) {+ const anchorA = xyz(joint.anchorA);+ const anchorB = xyz(joint.anchorB);+ let descriptor;+ if (joint.type === 'spherical') {+ descriptor = rapier.JointData.spherical(anchorA, anchorB);+ } else if (joint.type === 'revolute') {+ descriptor = rapier.JointData.revolute(anchorA, anchorB, xyz(joint.axis));+ } else {+ descriptor = rapier.JointData.fixed(anchorA, xyzw(joint.frameA), anchorB, xyzw(joint.frameB));+ }+ world.createImpulseJoint(descriptor, bodies[joint.bodyA], bodies[joint.bodyB], true).setContactsEnabled(joint.contactsEnabled);+ }+ timeline = new Float32Array(preparedScene.memoryPlan.timelineBytes / 4);+ let eventIndex = 0;+ for (let frame = 0; frame < preparedScene.frameCount; frame++) {+ if (frame > 0) {+ while (eventIndex < preparedScene.events.length && preparedScene.events[eventIndex].tick === frame - 1) {+ const event = preparedScene.events[eventIndex];+ eventIndex++;+ const body = bodies[event.body];+ if (event.type === 'kinematicPose') {+ if (event.translation) {+ body.setNextKinematicTranslation(xyz(event.translation));+ }+ if (event.rotation) {+ body.setNextKinematicRotation(xyzw(event.rotation));+ }+ } else {+ if (event.impulse) {+ if (event.point) {+ body.applyImpulseAtPoint(xyz(event.impulse), xyz(event.point), true);+ } else {+ body.applyImpulse(xyz(event.impulse), true);+ }+ }+ if (event.torqueImpulse) {+ body.applyTorqueImpulse(xyz(event.torqueImpulse), true);+ }+ }+ }+ world.step();+ }+ for (let bodyIndex = 0; bodyIndex < bodies.length; bodyIndex++) {+ const position = bodies[bodyIndex].translation();+ const bodyRotation = bodies[bodyIndex].rotation();+ const offset = (frame * bodies.length + bodyIndex) * 7;+ timeline[offset] = position.x;+ timeline[offset + 1] = position.y;+ timeline[offset + 2] = position.z;+ timeline[offset + 3] = bodyRotation.x;+ timeline[offset + 4] = bodyRotation.y;+ timeline[offset + 5] = bodyRotation.z;+ timeline[offset + 6] = bodyRotation.w;+ for (let component = 0; component < 7; component++) {+ if (!Number.isFinite(timeline[offset + component])) {+ throw new RangeError(`solver produced nonfinite pose at frame ${frame}, body ${preparedScene.bodies[bodyIndex].name}`);+ }+ }+ const quaternionLength = Math.hypot(bodyRotation.x, bodyRotation.y, bodyRotation.z, bodyRotation.w);+ if (!quaternionLength || Math.abs(quaternionLength - 1) > 1e-3) {+ throw new RangeError('solver produced invalid quaternion');+ }+ }+ }+ } finally {+ world.free();+ }+ return recordedScene(preparedScene, timeline);+}++function recordedScene(preparedScene, timeline) {+ const bodyNames = Object.freeze(preparedScene.bodies.map(body => body.name));+ const indices = new Map(bodyNames.map((name, index) => [name, index]));+ const poseStride = bodyNames.length * 7;+ const duration = (preparedScene.frameCount - 1) * preparedScene.timestep;+ function ensureAlive() {+ if (!timeline) {+ throw new Error('physics scene is disposed');+ }+ }+ function bodyIndex(name) {+ ensureAlive();+ if (!indices.has(name)) {+ throw new TypeError(`unknown body ${name}`);+ }+ return indices.get(name);+ }+ function sample(time, output) {+ ensureAlive();+ if (typeof time !== 'number' || !Number.isFinite(time)) {+ throw new RangeError('sample time must be finite');+ }+ output ??= new Float32Array(poseStride);+ if (!(output instanceof Float32Array) || output.length !== poseStride) {+ throw new TypeError(`sample output must be Float32Array(${poseStride})`);+ }+ let frame = Math.max(0, Math.min(duration, time)) / preparedScene.timestep;+ const nearestFrame = Math.round(frame);+ if (Math.abs(frame - nearestFrame) <= Number.EPSILON * Math.max(1, frame) * 4) {+ frame = nearestFrame;+ }+ const leftFrame = Math.min(preparedScene.frameCount - 1, Math.floor(frame));+ const rightFrame = Math.min(preparedScene.frameCount - 1, leftFrame + 1);+ const interpolation = frame - leftFrame;+ for (let bodyIndex = 0; bodyIndex < bodyNames.length; bodyIndex++) {+ const outputOffset = bodyIndex * 7;+ const leftOffset = leftFrame * poseStride + outputOffset;+ const rightOffset = rightFrame * poseStride + outputOffset;+ for (let axis = 0; axis < 3; axis++) {+ output[outputOffset + axis] = timeline[leftOffset + axis] * (1 - interpolation) + timeline[rightOffset + axis] * interpolation;+ }+ if (interpolation === 0 || leftFrame === rightFrame) {+ for (let component = 3; component < 7; component++) {+ output[outputOffset + component] = timeline[leftOffset + component];+ }+ continue;+ }+ let quaternionDot = 0;+ for (let component = 3; component < 7; component++) {+ quaternionDot += timeline[leftOffset + component] * timeline[rightOffset + component];+ }+ const quaternionSign = quaternionDot < 0 ? -1 : 1;+ quaternionDot = Math.min(1, Math.abs(quaternionDot));+ let leftWeight = 1 - interpolation;+ let rightWeight = interpolation;+ if (quaternionDot < 0.9995) {+ const angle = Math.acos(quaternionDot);+ const angleSine = Math.sin(angle);+ leftWeight = Math.sin((1 - interpolation) * angle) / angleSine;+ rightWeight = Math.sin(interpolation * angle) / angleSine;+ }+ let quaternionLengthSquared = 0;+ for (let component = 3; component < 7; component++) {+ const interpolatedComponent = leftWeight * timeline[leftOffset + component] + quaternionSign * rightWeight * timeline[rightOffset + component];+ output[outputOffset + component] = interpolatedComponent;+ quaternionLengthSquared += interpolatedComponent ** 2;+ }+ const quaternionLength = Math.sqrt(quaternionLengthSquared);+ for (let component = 3; component < 7; component++) {+ output[outputOffset + component] /= quaternionLength;+ }+ }+ return output;+ }+ function bindParts(bindings) {+ ensureAlive();+ if (!Array.isArray(bindings) || bindings.length > preparedScene.memoryPlan.bodyCount * 16) {+ throw new RangeError('bindings must be a bounded array');+ }+ const matrices = new Set();+ const matricesByBuffer = new Map();+ const retainedBindings = bindings.map(binding => {+ fields(binding, ['body', 'part'], 'binding');+ const index = bodyIndex(binding.body);+ const matrix = binding.part?.matrix;+ if (!(matrix instanceof Float32Array) || matrix.length !== 16 || matrices.has(matrix)) {+ throw new TypeError('each binding requires a distinct retained Float32 part.matrix');+ }+ matrices.add(matrix);+ let bufferMatrices = matricesByBuffer.get(matrix.buffer);+ if (!bufferMatrices) {+ bufferMatrices = [];+ matricesByBuffer.set(matrix.buffer, bufferMatrices);+ }+ bufferMatrices.push(matrix);+ for (const value of matrix) {+ scalar(value, 'binding matrix');+ }+ if (matrix[3] !== 0 || matrix[7] !== 0 || matrix[11] !== 0 || matrix[15] !== 1) {+ throw new TypeError('binding matrix must be affine');+ }+ const scale = [Math.hypot(matrix[0], matrix[1], matrix[2]), Math.hypot(matrix[4], matrix[5], matrix[6]), Math.hypot(matrix[8], matrix[9], matrix[10])];+ for (const size of scale) {+ positive(size, 'binding scale');+ }+ for (const [firstAxis, secondAxis] of [[0, 1], [0, 2], [1, 2]]) {+ const axisDot = matrix[firstAxis * 4] * matrix[secondAxis * 4] + matrix[firstAxis * 4 + 1] * matrix[secondAxis * 4 + 1] + matrix[firstAxis * 4 + 2] * matrix[secondAxis * 4 + 2];+ if (Math.abs(axisDot / scale[firstAxis] / scale[secondAxis]) > 1e-5) {+ throw new TypeError('binding matrix shear is unsupported');+ }+ }+ if (mat4.determinant(matrix) < 0) {+ scale[0] *= -1;+ }+ return {+ part: binding.part,+ matrix,+ index,+ scale,+ position: new Float32Array(3),+ rotation: quat.create(),+ scratchMatrix: mat4.create(),+ };+ });+ for (const bufferMatrices of matricesByBuffer.values()) {+ bufferMatrices.sort((firstMatrix, secondMatrix) => firstMatrix.byteOffset - secondMatrix.byteOffset);+ for (let matrixIndex = 1; matrixIndex < bufferMatrices.length; matrixIndex++) {+ const previousMatrix = bufferMatrices[matrixIndex - 1];+ const currentMatrix = bufferMatrices[matrixIndex];+ if (previousMatrix.byteOffset + previousMatrix.byteLength > currentMatrix.byteOffset) {+ throw new TypeError('binding matrix views must not overlap');+ }+ }+ }+ const sampledPose = new Float32Array(poseStride);+ return Object.freeze({+ apply(time) {+ ensureAlive();+ for (let bindingIndex = 0; bindingIndex < retainedBindings.length; bindingIndex++) {+ if (retainedBindings[bindingIndex].part.matrix !== retainedBindings[bindingIndex].matrix) {+ throw new Error('binding part.matrix identity changed');+ }+ }+ sample(time, sampledPose);+ for (let bindingIndex = 0; bindingIndex < retainedBindings.length; bindingIndex++) {+ const binding = retainedBindings[bindingIndex];+ const offset = binding.index * 7;+ for (let axis = 0; axis < 3; axis++) {+ binding.position[axis] = sampledPose[offset + axis];+ }+ for (let component = 0; component < 4; component++) {+ binding.rotation[component] = sampledPose[offset + component + 3];+ }+ mat4.fromRotationTranslationScale(binding.scratchMatrix, binding.rotation, binding.position, binding.scale);+ for (let component = 0; component < 16; component++) {+ if (!Number.isFinite(binding.scratchMatrix[component])) {+ throw new RangeError('binding transform exceeds Float32 range');+ }+ }+ }+ for (let bindingIndex = 0; bindingIndex < retainedBindings.length; bindingIndex++) {+ retainedBindings[bindingIndex].matrix.set(retainedBindings[bindingIndex].scratchMatrix);+ }+ return bindings;+ },+ });+ }+ return Object.freeze({+ bodyNames,+ frameCount: preparedScene.frameCount,+ timestep: preparedScene.timestep,+ duration,+ memoryPlan: preparedScene.memoryPlan,+ bodyIndex,+ sample,+ bindParts,+ dispose() {+ timeline = null;+ },+ get disposed() {+ return timeline === null;+ },+ });+}diff --git a/src/shaders.js b/src/shaders.jsindex 2747b2db..e1c6f5a1 100644--- a/src/shaders.js+++ b/src/shaders.js@@ -182,16 +182,29 @@ vec3 fresnel(float cosine, vec3 reflectance) {return reflectance + (1.0 - reflectance) * pow(1.0 - cosine, 5.0);}+float filteredShadow(vec2 coordinates, float receiverDepth, ivec2 dimensions) {+ vec2 pixel = coordinates * vec2(dimensions) - 0.5;+ ivec2 origin = ivec2(floor(pixel));+ vec2 blend = fract(pixel);+ ivec2 maximum = dimensions - 1;+ float lowerLeft = step(receiverDepth, texelFetch(shadowMap, clamp(origin, ivec2(0), maximum), 0).r);+ float lowerRight = step(receiverDepth, texelFetch(shadowMap, clamp(origin + ivec2(1, 0), ivec2(0), maximum), 0).r);+ float upperLeft = step(receiverDepth, texelFetch(shadowMap, clamp(origin + ivec2(0, 1), ivec2(0), maximum), 0).r);+ float upperRight = step(receiverDepth, texelFetch(shadowMap, clamp(origin + ivec2(1, 1), ivec2(0), maximum), 0).r);+ return mix(mix(lowerLeft, lowerRight, blend.x), mix(upperLeft, upperRight, blend.x), blend.y);+}+float shadowVisibility(vec3 normal) {vec3 projected = shadowPosition.xyz / shadowPosition.w * 0.5 + 0.5;if (projected.z > 1.0 || projected.z < 0.0 || any(lessThan(projected.xy, vec2(0.0))) || any(greaterThan(projected.xy, vec2(1.0)))) return 1.0;float bias = max(0.0006, 0.002 * (1.0 - dot(normal, normalize(lightDirection))));float visibility = 0.0;- vec2 texel = 1.0 / vec2(textureSize(shadowMap, 0));+ ivec2 dimensions = textureSize(shadowMap, 0);+ vec2 texel = 1.0 / vec2(dimensions);for (int row = -1; row <= 1; row++) {for (int column = -1; column <= 1; column++) {- float depth = texture(shadowMap, projected.xy + vec2(column, row) * texel * 2.5).r;- visibility += projected.z - bias <= depth ? 1.0 : 0.18;+ float comparison = filteredShadow(projected.xy + vec2(column, row) * texel * 2.5, projected.z - bias, dimensions);+ visibility += mix(0.18, 1.0, comparison);}}return visibility / 9.0;diff --git a/tests/physics.test.js b/tests/physics.test.jsnew file mode 100644index 00000000..00f67268--- /dev/null+++ b/tests/physics.test.js@@ -0,0 +1,367 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { mat4, vec3 } from 'gl-matrix';+import { createPhysicsScene, planPhysicsScene } from '../src/physics.js';++function fallingBoxDefinition() {+ return {+ bodies: [+ { name: 'floor', type: 'fixed', translation: [0, -0.5, 0] },+ { name: 'box', translation: [0, 3, 0] },+ ],+ colliders: [+ { name: 'ground', body: 'floor', shape: 'cuboid', halfExtents: [5, 0.5, 5] },+ { name: 'box', body: 'box', shape: 'cuboid', halfExtents: [0.5, 0.5, 0.5], mass: 1 },+ ],+ };+}+function bodyPose(scene, time, name) {+ const poseOffset = scene.bodyIndex(name) * 7;+ return scene.sample(time).slice(poseOffset, poseOffset + 7);+}++function anchor(pose, localAnchor) {+ const result = vec3.transformQuat(vec3.create(), localAnchor, pose.subarray(3));+ return vec3.add(result, result, pose.subarray(0, 3));+}++function near(actual, expected, tolerance = 1e-4) {+ assert.ok(Math.abs(actual - expected) < tolerance, `${actual} differs from ${expected}`);+}++test('memory plan bounds counts and rejects the bake before allocating Rapier or timeline', async () => {+ const definition = fallingBoxDefinition();+ const plan = planPhysicsScene(definition, { frameCount: 31 });+ assert.equal(plan.timelineBytes, 31 * 2 * 7 * 4);+ assert.equal(plan.estimatedPeakBytes, plan.timelineBytes + plan.solverReserveBytes);+ assert.ok(Object.isFrozen(plan));+ assert.throws(() => planPhysicsScene(definition, { frameCount: 100, maxFrames: 10 }), /frameCount/);+ assert.throws(() => planPhysicsScene(definition, { maxBodies: 1 }), /bodies/);+ assert.throws(() => planPhysicsScene(definition, { maxColliders: 1 }), /colliders/);+ await assert.rejects(createPhysicsScene(definition, { maxMemoryBytes: 1 }), /memory plan/);+ assert.throws(() => planPhysicsScene(definition, { frameCount: 1000001, maxFrames: 1000000 }), /frameCount/);+});++test('actual Rapier contact stops a falling box and supports a stable stack', async () => {+ const definition = fallingBoxDefinition();+ definition.bodies.push({ name: 'upper', translation: [0, 4.05, 0] });+ definition.colliders.push({ name: 'upper', body: 'upper', shape: 'cuboid', halfExtents: [0.5, 0.5, 0.5], mass: 1 });+ const scene = await createPhysicsScene(definition, { frameCount: 361 });+ near(bodyPose(scene, scene.duration, 'box')[1], 0.5, 0.03);+ near(bodyPose(scene, scene.duration, 'upper')[1], 1.5, 0.05);+ assert.ok(bodyPose(scene, 0.3, 'box')[1] < 3);+ assert.deepEqual(bodyPose(scene, scene.duration, 'floor'), bodyPose(scene, 0, 'floor'));+ scene.dispose();+});++test('ball and capsule contacts use real collider dimensions', async () => {+ const definition = fallingBoxDefinition();+ definition.bodies[1].translation = [-1, 3, 0];+ definition.colliders[1] = { name: 'ball', body: 'box', shape: 'ball', radius: 0.4, mass: 1 };+ definition.bodies.push({ name: 'capsule', translation: [1, 3, 0] });+ definition.colliders.push({ name: 'capsule', body: 'capsule', shape: 'capsule', radius: 0.3, halfHeight: 0.6, mass: 1 });+ const scene = await createPhysicsScene(definition, { frameCount: 241 });+ near(bodyPose(scene, scene.duration, 'box')[1], 0.4, 0.03);+ near(bodyPose(scene, scene.duration, 'capsule')[1], 0.9, 0.03);+ scene.dispose();+});++test('compound collider mass and density both contribute to real impulse response', async () => {+ const definition = {+ gravity: [0, 0, 0],+ bodies: [{ name: 'body' }],+ colliders: [+ { name: 'left', body: 'body', shape: 'ball', radius: 0.5, translation: [-0.5, 0, 0], mass: 2 },+ { name: 'right', body: 'body', shape: 'ball', radius: 0.5, translation: [0.5, 0, 0], density: 6 / Math.PI },+ ],+ events: [{ tick: 0, body: 'body', impulse: [3, 0, 0] }],+ };+ const scene = await createPhysicsScene(definition, { frameCount: 61 });+ near(scene.sample(scene.duration)[0], scene.duration, 1e-5);+ near(scene.sample(scene.duration)[6], 1);+ scene.dispose();+});++for (const type of ['spherical', 'revolute', 'fixed']) {+ test(`${type} ragdoll constraint retains anchors while bodies collide with the floor`, async () => {+ const definition = fallingBoxDefinition();+ definition.bodies[1].translation = [0, 2.5, 0];+ definition.colliders[1] = { name: 'upper', body: 'box', shape: 'capsule', radius: 0.2, halfHeight: 0.3, mass: 1 };+ definition.bodies.push({ name: 'lower', translation: [0, 1.5, 0] });+ definition.colliders.push({ name: 'lower', body: 'lower', shape: 'capsule', radius: 0.2, halfHeight: 0.3, mass: 1 });+ definition.joints = [{+ name: 'joint',+ type,+ bodyA: 'box',+ bodyB: 'lower',+ anchorA: [0, -0.5, 0],+ anchorB: [0, 0.5, 0],+ ...(type === 'revolute' ? { axis: [0, 0, 1] } : {}),+ }];+ definition.events = [{ tick: 0, body: 'lower', impulse: [1, 0, 0], torqueImpulse: [0, 0, 0.2] }];+ const scene = await createPhysicsScene(definition, { frameCount: 241, solverIterations: 12 });+ for (const time of [0.25, 1, scene.duration]) {+ const upperPose = bodyPose(scene, time, 'box');+ const lowerPose = bodyPose(scene, time, 'lower');+ assert.ok(vec3.distance(anchor(upperPose, [0, -0.5, 0]), anchor(lowerPose, [0, 0.5, 0])) < 0.04);+ assert.ok(upperPose[1] > 0.15 && lowerPose[1] > 0.15);+ }+ if (type !== 'fixed') {+ assert.ok(Math.abs(bodyPose(scene, 0.25, 'lower')[5] - bodyPose(scene, 0.25, 'box')[5]) > 0.01, 'joint visibly bends');+ }+ scene.dispose();+ });+}++test('impulses, off-center impulses, and torque impulses are applied at declared ticks', async () => {+ const definition = {+ gravity: [0, 0, 0],+ bodies: [{ name: 'body' }],+ colliders: [{ name: 'ball', body: 'body', shape: 'ball', radius: 1, mass: 2 }],+ events: [+ { tick: 10, body: 'body', impulse: [2, 0, 0] },+ { tick: 20, body: 'body', impulse: [0, 2, 0], point: [1, 0, 0] },+ { tick: 30, body: 'body', torqueImpulse: [0, 0, 0.5] },+ ],+ };+ const scene = await createPhysicsScene(definition, { frameCount: 61 });+ near(scene.sample(scene.timestep * 10)[0], 0);+ near(scene.sample(scene.timestep * 11)[0], scene.timestep);+ assert.ok(scene.sample(scene.duration)[1] > 0.5);+ assert.ok(Math.abs(scene.sample(scene.duration)[5]) > 0.1);+ scene.dispose();+});++test('recording repeats bit exactly, and backward seeks do not change later samples', async () => {+ const definition = fallingBoxDefinition();+ definition.events = [+ { tick: 60, body: 'box', impulse: [2, 1, 0] },+ { tick: 60, body: 'box', torqueImpulse: [0, 0, 0.3] },+ { tick: 0, body: 'box', impulse: [-0.5, 0, 0] },+ ];+ const firstScene = await createPhysicsScene(definition, { frameCount: 121 });+ const secondScene = await createPhysicsScene(definition, { frameCount: 121 });+ const retainedOutput = new Float32Array(14);+ for (const tick of [120, 0, 80, 4, 120, 42]) {+ const time = tick * firstScene.timestep;+ assert.equal(firstScene.sample(time, retainedOutput), retainedOutput);+ assert.deepEqual(retainedOutput, secondScene.sample(time));+ }+ const finalPose = firstScene.sample(firstScene.duration);+ firstScene.sample(0);+ assert.deepEqual(firstScene.sample(firstScene.duration), finalPose);+ assert.deepEqual(firstScene.sample(-100), firstScene.sample(0));+ assert.deepEqual(firstScene.sample(100), finalPose);+ firstScene.dispose();+ secondScene.dispose();+});++test('kinematic targets push a dynamic body and samples interpolate translation and unit quaternions', async () => {+ const definition = {+ gravity: [0, 0, 0],+ bodies: [+ { name: 'platform', type: 'kinematic', translation: [-2, 0, 0] },+ { name: 'ball', translation: [0, 0, 0] },+ ],+ colliders: [+ { name: 'platform', body: 'platform', shape: 'cuboid', halfExtents: [0.5, 2, 2] },+ { name: 'ball', body: 'ball', shape: 'ball', radius: 0.5, mass: 1 },+ ],+ events: Array.from({ length: 60 }, (_, tick) => ({+ tick,+ type: 'kinematicPose',+ body: 'platform',+ translation: [-2 + (tick + 1) / 30, 0, 0],+ ...(tick === 59 ? { rotation: [0, 0, Math.SQRT1_2, Math.SQRT1_2] } : {}),+ })),+ };+ const scene = await createPhysicsScene(definition, { frameCount: 61 });+ assert.ok(bodyPose(scene, scene.duration, 'ball')[0] > 0.5);+ const previousPose = bodyPose(scene, 59 * scene.timestep, 'platform');+ const finalPose = bodyPose(scene, scene.duration, 'platform');+ const halfwayPose = bodyPose(scene, 59.5 * scene.timestep, 'platform');+ near(halfwayPose[0], (previousPose[0] + finalPose[0]) / 2);+ near(Math.hypot(...halfwayPose.subarray(3)), 1);+ near(halfwayPose[5], Math.sin(Math.PI / 8));+ scene.dispose();+});++test('part binding keeps matrix identity and scales, and updates all bindings atomically', async () => {+ const scene = await createPhysicsScene(fallingBoxDefinition(), { frameCount: 31 });+ const part = { matrix: mat4.fromScaling(mat4.create(), [-2, 3, 4]) };+ const other = { matrix: mat4.create() };+ const matrix = part.matrix;+ const binding = scene.bindParts([{ body: 'box', part }, { body: 'floor', part: other }]);+ binding.apply(scene.duration);+ assert.equal(part.matrix, matrix);+ near(part.matrix[0], -2);+ near(part.matrix[5], 3);+ near(part.matrix[10], 4);+ near(part.matrix[13], bodyPose(scene, scene.duration, 'box')[1]);+ const previous = part.matrix.slice();+ other.matrix = mat4.create();+ assert.throws(() => binding.apply(0), /identity changed/);+ assert.deepEqual(part.matrix, previous);+ scene.dispose();+ assert.throws(() => binding.apply(0), /disposed/);+});++test('malformed bodies, colliders, constraints, and events fail at the boundary', () => {+ const cases = [+ definition => definition.bodies.push({ name: 'box' }),+ definition => definition.bodies[1].rotation = [0, 0, 0, 0],+ definition => definition.bodies[1].translation = [Infinity, 0, 0],+ definition => definition.bodies[0].linearVelocity = [1, 0, 0],+ definition => definition.bodies[1].type = 'soft',+ definition => definition.colliders[1].mass = -1,+ definition => definition.colliders[1].density = 1,+ definition => definition.colliders[1].halfExtents = [0, 1, 1],+ definition => definition.colliders[1].body = 'missing',+ definition => definition.colliders[1].shape = 'mesh',+ definition => definition.colliders[1].sensor = true,+ definition => definition.colliders = [definition.colliders[0]],+ definition => definition.joints = [{ name: 'j', type: 'spherical', bodyA: 'box', bodyB: 'box' }],+ definition => definition.joints = [{ name: 'j', type: 'revolute', bodyA: 'box', bodyB: 'floor', axis: [0, 0, 0] }],+ definition => definition.events = [{ tick: 100, body: 'box', impulse: [1, 0, 0] }],+ definition => definition.events = [{ tick: 0, body: 'floor', impulse: [1, 0, 0] }],+ definition => definition.events = [{ tick: 0, body: 'box', impulse: [1, 0, 0], translation: [1, 0, 0] }],+ definition => definition.events = [{ tick: 0, body: 'box', type: 'kinematicPose', translation: [1, 0, 0] }],+ ];+ for (const mutate of cases) {+ const definition = fallingBoxDefinition();+ mutate(definition);+ assert.throws(() => planPhysicsScene(definition, { frameCount: 10 }));+ }+});++test('binding rejects distinct overlapping matrix views before changing either target', async () => {+ const definition = fallingBoxDefinition();+ definition.bodies[1].type = 'fixed';+ const scene = await createPhysicsScene(definition, { frameCount: 1 });+ const buffer = new ArrayBuffer(21 * Float32Array.BYTES_PER_ELEMENT);+ const firstMatrix = new Float32Array(buffer, 0, 16);+ const secondMatrix = new Float32Array(buffer, 5 * Float32Array.BYTES_PER_ELEMENT, 16);+ mat4.identity(firstMatrix);+ mat4.identity(secondMatrix);+ const beforeBinding = new Float32Array(buffer).slice();+ assert.throws(() => scene.bindParts([+ { body: 'floor', part: { matrix: firstMatrix } },+ { body: 'box', part: { matrix: secondMatrix } },+ ]), /must not overlap/);+ assert.deepEqual(new Float32Array(buffer), beforeBinding);+ scene.dispose();+});++test('Float32 validation rejects rounded zero, overflow, and unsafe geometry inertia', async () => {+ for (const value of [1e-50, 1e40, NaN]) {+ const definition = fallingBoxDefinition();+ definition.colliders[1].mass = value;+ assert.throws(() => planPhysicsScene(definition), /Float32/);+ }+ const thin = fallingBoxDefinition();+ thin.colliders[1].halfExtents = [1e-15, 1e15, 1e15];+ delete thin.colliders[1].mass;+ assert.throws(() => planPhysicsScene(thin), /inertia/);+ assert.throws(() => planPhysicsScene(fallingBoxDefinition(), { timestep: 1e-50 }), /Float32/);+ const compound = fallingBoxDefinition();+ compound.colliders[1].mass = 2e38;+ compound.colliders.push({ ...compound.colliders[1], name: 'second' });+ assert.throws(() => planPhysicsScene(compound), /compound body mass/);+ const rounded = fallingBoxDefinition();+ rounded.bodies[1].translation = [0, 16777217, 0];+ const scene = await createPhysicsScene(rounded, { frameCount: 1 });+ assert.equal(bodyPose(scene, 0, 'box')[1], 16777216);+ scene.dispose();+});++test('solver preflight rejects normal-looking inputs that freeze or overflow Rapier motion', () => {+ function ballDefinition() {+ return {+ gravity: [0, 0, 0],+ bodies: [{ name: 'ball' }],+ colliders: [{ name: 'ball', body: 'ball', shape: 'ball', radius: 1, mass: 1 }],+ };+ }+ for (const tinyMass of [1e-38, 1e-40]) {+ const definition = ballDefinition();+ definition.gravity = [0, -9.81, 0];+ definition.colliders[0].mass = tinyMass;+ assert.throws(() => planPhysicsScene(definition, { frameCount: 3 }), /effective mass/);+ }+ for (const velocityField of ['linearVelocity', 'angularVelocity']) {+ const definition = ballDefinition();+ definition.bodies[0][velocityField] = [1e20, 0, 0];+ assert.throws(() => planPhysicsScene(definition, { frameCount: 3 }), /squared norm/);+ }+ const gravityOverflow = ballDefinition();+ gravityOverflow.gravity = [1e20, 0, 0];+ assert.throws(() => planPhysicsScene(gravityOverflow), /gravity squared norm/);+ for (const impulseField of ['impulse', 'torqueImpulse']) {+ const definition = ballDefinition();+ definition.events = [{ tick: 0, body: 'ball', [impulseField]: [1e20, 0, 0] }];+ assert.throws(() => planPhysicsScene(definition), /squared norm/);+ }+ const inducedVelocityOverflow = ballDefinition();+ inducedVelocityOverflow.colliders[0].mass = 1e-10;+ inducedVelocityOverflow.events = [{ tick: 0, body: 'ball', impulse: [1e10, 0, 0] }];+ assert.throws(() => planPhysicsScene(inducedVelocityOverflow), /accumulated linear velocity/);+ const offCenterOverflow = ballDefinition();+ offCenterOverflow.events = [{ tick: 0, body: 'ball', impulse: [0, 1e10, 0], point: [1e10, 0, 0] }];+ assert.throws(() => planPhysicsScene(offCenterOverflow), /off-center torque impulse/);+ const kinematicOverflow = {+ gravity: [0, 0, 0],+ bodies: [{ name: 'platform', type: 'kinematic' }],+ events: [{ tick: 0, body: 'platform', type: 'kinematicPose', translation: [1, 0, 0] }],+ };+ assert.throws(() => planPhysicsScene(kinematicOverflow, { timestep: 1e-40, frameCount: 3 }), /timestep reciprocal/);+ kinematicOverflow.events[0].translation = [1e20, 0, 0];+ assert.throws(() => planPhysicsScene(kinematicOverflow, { frameCount: 3 }), /kinematic target velocity/);+ kinematicOverflow.events = [1e19, 2e19].map(translation => ({ tick: 0, body: 'platform', type: 'kinematicPose', translation: [translation, 0, 0] }));+ assert.throws(() => planPhysicsScene(kinematicOverflow, { timestep: 1, frameCount: 3 }), /kinematic target velocity/);+});++test('small normal mass still responds to gravity instead of silently freezing', async () => {+ const definition = {+ bodies: [{ name: 'ball', translation: [0, 3, 0] }],+ colliders: [{ name: 'ball', body: 'ball', shape: 'ball', radius: 1, mass: 1e-20 }],+ };+ const scene = await createPhysicsScene(definition, { frameCount: 3 });+ assert.ok(scene.sample(scene.duration)[1] < scene.sample(0)[1]);+ scene.dispose();+});++test('inputs are copied before awaiting WASM initialization, and event/joint limits are enforced', async () => {+ const definition = fallingBoxDefinition();+ const pending = createPhysicsScene(definition, { frameCount: 2 });+ definition.bodies[1].translation[1] = 99;+ definition.colliders[1].halfExtents[1] = 99;+ const scene = await pending;+ near(bodyPose(scene, 0, 'box')[1], 3);+ scene.dispose();+ definition.joints = ['one', 'two'].map(name => ({ name, type: 'spherical', bodyA: 'floor', bodyB: 'box' }));+ assert.throws(() => planPhysicsScene(definition, { maxJoints: 1 }), /joints/);+ definition.joints = [];+ definition.events = [0, 1].map(tick => ({ tick, body: 'box', impulse: [1, 0, 0] }));+ assert.throws(() => planPhysicsScene(definition, { maxEvents: 1 }), /maxEvents/);+});++test('invalid samples and bindings cannot mutate matrices, and disposed scenes reject calls', async () => {+ const scene = await createPhysicsScene(fallingBoxDefinition(), { frameCount: 1 });+ assert.throws(() => scene.sample(NaN), /finite/);+ assert.throws(() => scene.sample(0, new Float32Array(1)), /output/);+ assert.throws(() => scene.bodyIndex('missing'), /unknown/);+ const part = { matrix: mat4.create() };+ part.matrix[4] = 0.25;+ assert.throws(() => scene.bindParts([{ body: 'box', part }]), /shear/);+ part.matrix[4] = 0;+ part.matrix[3] = 1e-6;+ assert.throws(() => scene.bindParts([{ body: 'box', part }]), /affine/);+ part.matrix[3] = 0;+ assert.throws(() => scene.bindParts([{ body: 'box', part }, { body: 'floor', part }]), /distinct/);+ scene.dispose();+ scene.dispose();+ assert.equal(scene.disposed, true);+ assert.throws(() => scene.sample(0), /disposed/);+ assert.throws(() => scene.bodyIndex('box'), /disposed/);+ assert.throws(() => scene.bindParts([]), /disposed/);+});diff --git a/vite.lib.config.js b/vite.lib.config.jsindex b7b180ce..bb4db8ac 100644--- a/vite.lib.config.js+++ b/vite.lib.config.js@@ -4,7 +4,10 @@ import { defineConfig } from 'vite';export default defineConfig({build: {copyPublicDir: false,- rolldownOptions: { output: { banner: `/*! ${readFileSync('LICENSE', 'utf8')}\nOptional glTF decoder: ${readFileSync('THIRD-PARTY-NOTICES.md', 'utf8')} */` } },+ rolldownOptions: {+ external: ['@dimforge/rapier3d-compat'],+ output: { banner: `/*! ${readFileSync('LICENSE', 'utf8')}\nThird-party notices: ${readFileSync('THIRD-PARTY-NOTICES.md', 'utf8')} */` },+ },outDir: 'build',lib: {entry: {@@ -16,6 +19,7 @@ export default defineConfig({canvas2d: 'src/canvas2d.js',gltf: 'src/gltf.js',modeling: 'src/modeling.js',+ physics: 'src/physics.js',},formats: ['es'],fileName: (_, entry) => entry === 'core' ? '67.module.js' : `${entry}.js`,