3D engine that AI agents drive
JavaScript 3d3d-engineagentic-aiai-agentsblenderclaude-codegame-enginegaussian-splattinggltfjavascriptmcpmcp-servermodel-context-protocolpath-tracerpath-tracingpbrrenderingthreejs-alternativewebgl2webgpu
Throw a torn-off part sideways and keep it on the car side of the wall plane (Part of #983)
Nguyen Xuan An3795b24ec807
diff --git a/docs/vehicle.md b/docs/vehicle.mdindex e53c7674..d0acf8ed 100644--- a/docs/vehicle.md+++ b/docs/vehicle.md@@ -222,7 +222,7 @@ In a recipe, a `dented` geometry does the same for a node (details in `scene_capThe source can be any geometry except a fragment or another dent. The vertex count stays the same.A part that comes off in a physics crash is a body joined to the car body by a `fixed` joint with `breakImpulse` ([breakable joints](physics.md#fracture-and-breakable-glue)); it breaks when a body takes a contact impulse over that number in one 1/60 s step.-For a drive, where nothing simulates the loose part, `detachedPartFlight(part, hit, { seed, gravity, groundY, restitution })` gives it a flight. `part` is `{ id, threshold, mass, position }` and `hit` is `{ impulse, direction }` from `findDriveImpact`. It returns null when the impulse stays below `threshold`, so the part stays on. Otherwise `flight.sample(seconds)` (0 to 30 s) returns `{ position, rotation, velocity, settled }`: the part leaves away from the car (against `direction`) at `(impulse - threshold) / (mass * 100)` m/s (at most 30) with a seeded sideways kick, an up kick and tumble, falls, bounces on the plane `groundY` and comes to rest. The same inputs and `seed` give the same numbers. Set the node's transform from the sample each frame.+For a drive, where nothing simulates the loose part, `detachedPartFlight(part, hit, { seed, gravity, groundY, restitution })` gives it a flight. `part` is `{ id, threshold, mass, position }` and `hit` is `{ impulse, direction, point }` from `findDriveImpact` (`point` is optional and defaults to the part's centre); the part never crosses the plane through `point` with normal `direction`, which is the wall. It returns null when the impulse stays below `threshold`, so the part stays on. Otherwise `flight.sample(seconds)` (0 to 30 s) returns `{ position, rotation, velocity, settled }`: the part leaves mostly sideways at `(impulse - threshold) / (mass * 100)` m/s (at most 30) (a seeded sign, across `direction`, with a small rebound along `direction` and an up kick) and tumbles, falls, bounces on the plane `groundY` and comes to rest. The same inputs and `seed` give the same numbers. Set the node's transform from the sample each frame.Not covered yet: hinged doors, hood and trunk that pop open, swapping broken glass for shards, and dents driven by the live vehicle controller. A drive is kinematic, so `findDriveImpact` only reports the moment of the hit; the car does not stop or bounce.diff --git a/src/vehicle-damage.js b/src/vehicle-damage.jsindex f0108527..fdddb5c0 100644--- a/src/vehicle-damage.js+++ b/src/vehicle-damage.js@@ -245,6 +245,7 @@ const FLIGHT_STEP_SECONDS = 1 / 120;const LAUNCH_IMPULSE_PER_KILOGRAM = 100;const LAUNCH_UPWARD_SHARE = 0.5;const SPREAD_SHARE = 0.3;+const REBOUND_SHARE = 0.2;const MAX_SPIN_RADIANS_PER_SECOND = 12;const GROUND_FRICTION = 0.6;const SETTLE_SPEED = 0.2;@@ -259,26 +260,41 @@ function seededUnitSequence(seed) {};}+function sidewaysOf(direction) {+ const horizontalLength = Math.hypot(direction[0], direction[2]);+ return horizontalLength < 1e-6 ? [1, 0, 0] : [-direction[2] / horizontalLength, 0, direction[0] / horizontalLength];+}+function launchVelocityOf(part, hit, nextUnit) {const direction = normalized(hit.direction);+ const sideways = sidewaysOf(direction);const speed = Math.min(MAX_LAUNCH_SPEED, (hit.impulse - part.threshold) / (part.mass * LAUNCH_IMPULSE_PER_KILOGRAM));- const horizontalLength = Math.hypot(direction[0], direction[2]);- const sideways = horizontalLength < 1e-6 ? [1, 0, 0] : [-direction[2] / horizontalLength, 0, direction[0] / horizontalLength];- const sidewaysKick = (nextUnit() < 0.5 ? -1 : 1) * (0.5 + nextUnit() * 0.5) * SPREAD_SHARE;- const upwardKick = LAUNCH_UPWARD_SHARE + nextUnit() * SPREAD_SHARE;+ const sidewaysShare = nextUnit() < 0.5 ? -1 : 1;+ const reboundShare = REBOUND_SHARE * (0.5 + nextUnit() * 0.5);+ const upwardShare = LAUNCH_UPWARD_SHARE + nextUnit() * SPREAD_SHARE;return [- (-direction[0] + sideways[0] * sidewaysKick) * speed,- (-direction[1] + upwardKick) * speed,- (-direction[2] + sideways[2] * sidewaysKick) * speed,+ (sideways[0] * sidewaysShare + direction[0] * reboundShare) * speed,+ (direction[1] * reboundShare + upwardShare) * speed,+ (sideways[2] * sidewaysShare + direction[2] * reboundShare) * speed,];}+function keepOnCarSide(state, wall, restitution) {+ const depth = (state.position[0] - wall.point[0]) * wall.normal[0] + (state.position[1] - wall.point[1]) * wall.normal[1] + (state.position[2] - wall.point[2]) * wall.normal[2];+ if (depth >= 0) return;+ for (let axis = 0; axis < 3; axis++) state.position[axis] -= depth * wall.normal[axis];+ const approach = state.velocity[0] * wall.normal[0] + state.velocity[1] * wall.normal[1] + state.velocity[2] * wall.normal[2];+ if (approach >= 0) return;+ for (let axis = 0; axis < 3; axis++) state.velocity[axis] -= (1 + restitution) * approach * wall.normal[axis];+}+function advanceFlight(state, flight, seconds) {const steps = Math.round(seconds / FLIGHT_STEP_SECONDS);for (let step = 0; step < steps && !state.settled; step++) {state.velocity[1] -= flight.gravity * FLIGHT_STEP_SECONDS;for (let axis = 0; axis < 3; axis++) state.position[axis] += state.velocity[axis] * FLIGHT_STEP_SECONDS;for (let axis = 0; axis < 3; axis++) state.rotation[axis] += state.spin[axis] * FLIGHT_STEP_SECONDS;+ keepOnCarSide(state, flight.wall, flight.restitution);if (state.position[1] > flight.groundY) continue;state.position[1] = flight.groundY;state.velocity[1] = -state.velocity[1] * flight.restitution;@@ -295,9 +311,9 @@ function advanceFlight(state, flight, seconds) {/*** The flight of a loose part a hit tears off. `part` is `{ id, threshold, mass, position }` (N s, kg, the part's centre in- * metres); `hit` is `{ impulse, direction }` from `findDriveImpact`. Returns null when the impulse stays below the- * threshold, so the part stays on. Otherwise it returns `{ id, launchVelocity, sample(time) }`: the part leaves away from- * the car, against `direction`, with a seeded sideways kick, an up kick and tumble, falls under gravity and bounces on the ground plane `groundY`.+ * metres); `hit` is `{ impulse, direction, point }` from `findDriveImpact` (`point` is optional and defaults to the part's centre). Returns null when the impulse stays below the+ * threshold, so the part stays on. Otherwise it returns `{ id, launchVelocity, sample(time) }`: the part leaves mostly+ * sideways (a seeded sign, across `direction`) with a small rebound along `direction` and an up kick, tumbles, falls under gravity and bounces on the ground plane `groundY`. It never crosses the wall plane through `point` with normal `direction`.* `sample(time)` gives `{ position, rotation (Euler radians), velocity, settled }` for 0 to 30 s, and the same inputs* with the same `seed` give the same numbers on every run.*/@@ -311,6 +327,7 @@ export function detachedPartFlight(part, hit, { seed = 0, gravity = 9.81, groundrequireNumber(hit.impulse, 'hit.impulse', 0, 1e9, 16800);const rawDirection = requireVector3(hit.direction, 'hit.direction', '[0, 0, -1]');if (Math.hypot(...rawDirection) < 1e-6) throw invalidField('hit.direction', rawDirection, 'a vector that is not zero, such as [0, 0, -1]');+ if (hit.point !== undefined) requireVector3(hit.point, 'hit.point', '[0, 0.5, 2.1]');requireNumber(seed, 'seed', 0, 4294967295, 7);requireNumber(gravity, 'gravity', 0, 100, 9.81);requireNumber(groundY, 'groundY', -1e4, 1e4, 0);@@ -319,7 +336,8 @@ export function detachedPartFlight(part, hit, { seed = 0, gravity = 9.81, groundconst nextUnit = seededUnitSequence(seed);const launchVelocity = launchVelocityOf(part, hit, nextUnit);const spin = [0, 1, 2].map(() => (nextUnit() * 2 - 1) * MAX_SPIN_RADIANS_PER_SECOND);- const flight = { gravity, groundY, restitution };+ const wall = { point: hit.point ?? part.position, normal: normalized(rawDirection) };+ const flight = { gravity, groundY, restitution, wall };return {id: part.id,launchVelocity,diff --git a/tests/vehicle-detached-part-flight.test.js b/tests/vehicle-detached-part-flight.test.jsindex 29df76c4..81c7ecd1 100644--- a/tests/vehicle-detached-part-flight.test.js+++ b/tests/vehicle-detached-part-flight.test.js@@ -3,14 +3,14 @@ import assert from 'node:assert/strict';import { detachedPartFlight, crashImpulse } from '../src/vehicle.js';const BUMPER = { id: 'front-bumper', threshold: 9000, mass: 12, position: [0, 0.5, 2] };-const WALL_HIT = { impulse: crashImpulse({ mass: 1400, speed: 12 }), direction: [0, 0, -1] };+const WALL_HIT = { impulse: crashImpulse({ mass: 1400, speed: 12 }), direction: [0, 0, -1], point: [0, 0.5, 2.1] };test('a part below its threshold stays on, and one above it flies off', () => {assert.equal(detachedPartFlight(BUMPER, { impulse: 8999, direction: [0, 0, -1] }), null);const flight = detachedPartFlight(BUMPER, WALL_HIT, { seed: 7 });assert.equal(flight.id, 'front-bumper');const later = flight.sample(0.5);- assert.ok(later.position[2] > BUMPER.position[2] + 1, `moved ${later.position}`);+ assert.ok(Math.abs(later.position[0]) > 1, `moved ${later.position}`);});test('the same seed gives the same transform, a different seed another', () => {@@ -37,12 +37,25 @@ test('bad input says what to pass instead', () => {assert.throws(() => detachedPartFlight(BUMPER, WALL_HIT).sample(31), /time/);});-test('the part leaves away from the car, with a sideways kick and an up kick', () => {+test('the part never crosses the wall and rests beside the nose', () => {for (const seed of [1, 2, 3, 4]) {- const [velocityX, velocityY, velocityZ] = detachedPartFlight(BUMPER, WALL_HIT, { seed }).launchVelocity;- const awayFromCar = velocityX * WALL_HIT.direction[0] + velocityZ * WALL_HIT.direction[2];- assert.ok(awayFromCar < 0, `seed ${seed} horizontal velocity dot direction ${awayFromCar}`);- assert.ok(velocityY > 0);- assert.notEqual(velocityX, 0);+ const flight = detachedPartFlight(BUMPER, WALL_HIT, { seed });+ for (let step = 0; step <= 30 * 60; step++) {+ const position = flight.sample(step / 60).position;+ const behindWall = (position[2] - WALL_HIT.point[2]) * WALL_HIT.direction[2];+ assert.ok(behindWall >= -1e-6, `seed ${seed} step ${step} crossed the wall by ${behindWall}`);+ if (flight.sample(step / 60).settled) break;+ }+ const rest = flight.sample(30);+ assert.equal(rest.settled, true);+ const sidewaysOffset = Math.abs(rest.position[0] - BUMPER.position[0]);+ const reboundDistance = (rest.position[2] - BUMPER.position[2]) * WALL_HIT.direction[2];+ assert.ok(sidewaysOffset > reboundDistance, `seed ${seed} sideways ${sidewaysOffset} rebound ${reboundDistance}`);+ assert.ok(flight.launchVelocity[1] > 0);}});++test('a part thrown at the wall is held on the car side of its plane', () => {+ const towardWall = detachedPartFlight({ ...BUMPER, position: [0, 0.5, 2.09] }, { ...WALL_HIT, direction: [0, 0, -1], point: [0, 0.5, 2.1] }, { seed: 2 });+ assert.ok(towardWall.sample(1).position[2] <= 2.1 + 1e-6);+});