# Metaverse Physics Engine

The metaverse client ships with a lightweight physics facade that mirrors
Rapier/Cannon.js concepts while remaining deterministic in Node/Vitest
environments. This module (`web/src/lib/physics-engine.ts`) provides rigid body
management, gravity integration, impulse application, and broad-phase collision
handling for axis-aligned box colliders.

## World configuration

Create a physics world with gravity and fixed timestep:

```ts
import { PhysicsEngine, RigidBodyType } from '@/lib/physics-engine';

const engine = new PhysicsEngine({
  gravity: { x: 0, y: -9.81, z: 0 },
  timeStep: 1 / 60,
});
```

The engine uses semi-implicit Euler integration and recalculates collision pairs
every step.

## Rigid bodies

```ts
const ground = engine.createRigidBody({
  id: 'ground',
  type: RigidBodyType.Static,
  shape: { kind: 'box', size: { x: 12, y: 1, z: 12 } },
  position: { x: 0, y: -0.5, z: 0 },
});

const avatar = engine.createRigidBody({
  id: 'avatar',
  type: RigidBodyType.Dynamic,
  shape: { kind: 'box', size: { x: 0.8, y: 1.8, z: 0.8 } },
  position: { x: 0, y: 3, z: 0 },
  mass: 80,
});
```

- Static bodies act as immovable colliders.
- Dynamic bodies respond to gravity, impulses, and collision resolution.
- Kinematic bodies (future work) can be animated explicitly while still
  colliding.

## Forces and impulses

```ts
engine.applyImpulse('avatar', { x: 0, y: 200, z: 0 }); // jump

engine.step(); // integrates 1/60 s and resolves collisions
```

Impulses are mass-aware (`Δv = impulse / mass`). Additional force helpers can be
layered on top by accumulating impulses between steps.

## Collision events

```ts
engine.onCollision(({ bodyA, bodyB, normal, penetration }) => {
  console.log('collision', bodyA.id, bodyB.id, normal, penetration);
});
```

Collisions are detected via AABB overlap tests with minimal-axis separation
resolution. The engine repositions dynamic bodies against static colliders and
zeroes the velocity component along the contact normal to avoid sinking.

## Testing

Vitest coverage ensures gravity integration, impulse handling, and static
contact resolution remain stable:

```bash
cd web
timeout -k 5 30000 npm run test -- src/lib/__tests__/physics-engine.test.ts
```

When wiring into gameplay systems (e.g., avatars, interactive props), prefer
consuming the facade so the same suite remains deterministic in CI. Replace the
adapter with Rapier or Cannon.js in production as needed.
