# Metaverse Physics System

Technical documentation for Lilith's physics simulation powering metaverse
interactions.

## Overview

The Lilith platform implements a custom physics engine designed for
browser-based 3D environments. The system provides rigid body dynamics,
collision detection, character controllers, and raycasting with a
Rapier-compatible API design.

## Architecture

```
┌─────────────────────────────────────────────────────────────┐
│                   Physics Engine                             │
├─────────────────────────────────────────────────────────────┤
│                                                              │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────────┐  │
│  │   Rigid      │  │  Character   │  │    Raycast       │  │
│  │   Bodies     │  │ Controllers  │  │    System        │  │
│  └──────┬───────┘  └──────┬───────┘  └────────┬─────────┘  │
│         │                 │                    │            │
│  ┌──────▼─────────────────▼────────────────────▼─────────┐  │
│  │              Collision Detection                       │  │
│  │  ┌─────────────────┐  ┌─────────────────┐             │  │
│  │  │  Spatial Hash   │  │  Narrow Phase   │             │  │
│  │  │  (Broad Phase)  │  │   (AABB/Sphere) │             │  │
│  │  └─────────────────┘  └─────────────────┘             │  │
│  └───────────────────────────────────────────────────────┘  │
│                                                              │
│  ┌───────────────────────────────────────────────────────┐  │
│  │              Physics Integration                       │  │
│  │  ┌─────────┐  ┌──────────┐  ┌──────────┐  ┌────────┐ │  │
│  │  │ Forces  │  │ Velocity │  │ Position │  │Damping │ │  │
│  │  └─────────┘  └──────────┘  └──────────┘  └────────┘ │  │
│  └───────────────────────────────────────────────────────┘  │
│                                                              │
└─────────────────────────────────────────────────────────────┘
```

## Core Components

### 1. Physics Engine

**Location**: `services/metaverse/src/physics/PhysicsEngine.ts`

The main physics engine class managing simulation state and updates.

#### Configuration

```typescript
interface PhysicsConfig {
  gravity?: Vector3; // Default: { x: 0, y: -9.81, z: 0 }
  timestep?: number; // Default: 1/60 (60 Hz)
  cellSize?: number; // Default: 10 (spatial hash cell size)
}
```

#### Initialization

```typescript
import { PhysicsEngine } from '@/physics/PhysicsEngine';

const physics = new PhysicsEngine({
  gravity: { x: 0, y: -9.81, z: 0 },
  timestep: 1 / 60,
  cellSize: 10,
});

// In game loop
function update() {
  physics.step();
  requestAnimationFrame(update);
}
```

---

### 2. Rigid Bodies

Physical objects in the simulation with mass, velocity, and collision
properties.

#### Body Types

| Type        | Description                    | Use Case                    |
| ----------- | ------------------------------ | --------------------------- |
| `dynamic`   | Affected by forces and gravity | Players, props, projectiles |
| `kinematic` | Moved by code, affects others  | Moving platforms, doors     |
| `fixed`     | Static, never moves            | Floors, walls, terrain      |

#### Rigid Body Configuration

```typescript
interface RigidBodyDesc {
  id: string;
  type: 'dynamic' | 'kinematic' | 'fixed';
  position: Vector3;
  rotation: Quaternion;
  mass: number;
  linearDamping: number; // Velocity friction (0-1)
  angularDamping: number; // Rotation friction (0-1)
  gravityScale: number; // Gravity multiplier
  canSleep: boolean; // Allow sleep optimization
  colliderType: 'box' | 'sphere' | 'capsule' | 'cylinder' | 'cone' | 'mesh';
  colliderSize: Vector3;
  friction: number; // Surface friction (0-1)
  restitution: number; // Bounciness (0-1)
  isSensor: boolean; // Trigger only, no collision response
}
```

#### Creating Bodies

```typescript
// Dynamic body (player)
physics.addRigidBody({
  id: 'player',
  type: 'dynamic',
  position: { x: 0, y: 1, z: 0 },
  rotation: { x: 0, y: 0, z: 0, w: 1 },
  mass: 70,
  linearDamping: 0.1,
  angularDamping: 0.1,
  gravityScale: 1,
  canSleep: false,
  colliderType: 'capsule',
  colliderSize: { x: 0.5, y: 1.8, z: 0.5 },
  friction: 0.5,
  restitution: 0,
  isSensor: false,
});

// Static body (floor)
physics.addRigidBody({
  id: 'floor',
  type: 'fixed',
  position: { x: 0, y: 0, z: 0 },
  rotation: { x: 0, y: 0, z: 0, w: 1 },
  mass: 0,
  linearDamping: 0,
  angularDamping: 0,
  gravityScale: 0,
  canSleep: true,
  colliderType: 'box',
  colliderSize: { x: 100, y: 1, z: 100 },
  friction: 0.8,
  restitution: 0,
  isSensor: false,
});
```

#### Body Operations

```typescript
// Apply force (continuous, e.g., wind)
physics.applyForce('player', { x: 10, y: 0, z: 0 });

// Apply impulse (instant, e.g., jump)
physics.applyImpulse('player', { x: 0, y: 500, z: 0 });

// Set velocity directly
physics.setVelocity('player', { x: 5, y: 0, z: 0 });

// Teleport body
physics.setPosition('player', { x: 10, y: 5, z: 10 });

// Rotate body
physics.setRotation('player', { x: 0, y: 0.707, z: 0, w: 0.707 });

// Remove body
physics.removeRigidBody('player');
```

---

### 3. Collision Detection

Two-phase collision detection system for efficient broad-phase culling and
accurate narrow-phase testing.

#### Broad Phase: Spatial Hash

The spatial hash divides the world into cells for efficient neighbor queries.

```
World Space                    Spatial Hash Cells
┌───────────────────────┐      ┌───┬───┬───┬───┐
│    ○                  │      │ A │   │   │   │
│         ●             │  →   ├───┼───┼───┼───┤
│              ○        │      │   │ B │ C │   │
│      ●                │      ├───┼───┼───┼───┤
└───────────────────────┘      │   │ D │   │   │
                               └───┴───┴───┴───┘

Only objects in same cell checked for collision
```

#### Narrow Phase: Shape Tests

Currently supported collision shapes:

| Shape  | Description  | Test Method                |
| ------ | ------------ | -------------------------- |
| Sphere | Radius-based | Sphere-sphere intersection |

_Note: Box, capsule, cylinder, cone, and mesh shapes use bounding sphere
approximation._

#### Collision Events

```typescript
interface CollisionEvent {
  body1: string; // First body ID
  body2: string; // Second body ID
  contactPoint: Vector3; // Collision point
  contactNormal: Vector3; // Collision normal
  penetrationDepth: number; // Overlap amount
  timestamp: number; // Event time
}

// Get current collisions
const collisions = physics.getCollisions();

// Check for specific collision
const playerCollisions = collisions.filter(
  (c) => c.body1 === 'player' || c.body2 === 'player'
);
```

#### Collision Response

The engine automatically:

1. Calculates relative velocity along collision normal
2. Applies restitution (bounce) based on material properties
3. Applies impulse to separate bodies
4. Corrects penetration to prevent sinking

```typescript
// Collision response formula
impulse = (-(1 + restitution) * velocityAlongNormal) / (1 / mass1 + 1 / mass2);
```

---

### 4. Character Controllers

Specialized controllers for player movement with ground detection and slope
handling.

#### Configuration

```typescript
interface CharacterController {
  id: string;
  bodyId: string; // Associated rigid body
  height: number; // Character height
  radius: number; // Character radius
  stepHeight: number; // Max step height
  slopeLimit: number; // Max walkable slope (degrees)
  isGrounded: boolean; // Ground contact status
  velocity: Vector3; // Current velocity
}
```

#### Usage

```typescript
// Create character body first
physics.addRigidBody({
  id: 'player-body',
  type: 'dynamic',
  // ... body config
});

// Add character controller
physics.addCharacterController({
  id: 'player-controller',
  bodyId: 'player-body',
  height: 1.8,
  radius: 0.3,
  stepHeight: 0.5,
  slopeLimit: 45,
  isGrounded: false,
  velocity: { x: 0, y: 0, z: 0 },
});

// Move character
physics.moveCharacter('player-controller', {
  x: 5, // Forward/back
  y: 0, // Vertical (usually 0 unless jumping)
  z: 2, // Left/right
});

// Check if grounded (for jump)
const controller = physics.controllers.get('player-controller');
if (controller?.isGrounded) {
  physics.applyImpulse('player-body', { x: 0, y: 300, z: 0 });
}
```

---

### 5. Raycasting

Cast rays through the physics world to detect intersections.

#### Basic Raycast

```typescript
interface RaycastResult {
  hit: boolean;
  bodyId?: string; // Hit body ID
  point?: Vector3; // Hit point
  normal?: Vector3; // Surface normal at hit
  distance: number; // Distance to hit
}

// Cast ray
const result = physics.raycast(
  { x: 0, y: 5, z: 0 }, // Origin
  { x: 0, y: -1, z: 0 }, // Direction (normalized)
  100 // Max distance
);

if (result.hit) {
  console.log(`Hit ${result.bodyId} at distance ${result.distance}`);
  console.log(`Hit point: ${result.point}`);
  console.log(`Surface normal: ${result.normal}`);
}
```

#### Common Use Cases

```typescript
// Ground check
function isGrounded(position: Vector3): boolean {
  const result = physics.raycast(
    position,
    { x: 0, y: -1, z: 0 },
    1.1 // Slightly more than standing height
  );
  return result.hit;
}

// Look-at target selection
function getTargetUnderCursor(
  camera: Camera,
  mousePos: Vector2
): string | null {
  const direction = camera.screenToWorld(mousePos);
  const result = physics.raycast(camera.position, direction, 1000);
  return result.hit ? result.bodyId : null;
}

// Line of sight check
function hasLineOfSight(from: Vector3, to: Vector3): boolean {
  const direction = normalize(subtract(to, from));
  const distance = length(subtract(to, from));
  const result = physics.raycast(from, direction, distance);
  return !result.hit || result.distance >= distance - 0.1;
}
```

---

## Physics Simulation Loop

The simulation follows this order each step:

```
┌─────────────────────────────────────────────────────────────┐
│ 1. Apply Gravity                                            │
│    - Add gravitational force to all dynamic bodies          │
└─────────────────────────────┬───────────────────────────────┘
                              │
┌─────────────────────────────▼───────────────────────────────┐
│ 2. Integrate Forces                                         │
│    - Sum all forces on each body                            │
│    - Calculate acceleration: a = F/m                        │
│    - Update velocity: v = v + a*dt                          │
│    - Apply impulses: v += impulse/m                         │
└─────────────────────────────┬───────────────────────────────┘
                              │
┌─────────────────────────────▼───────────────────────────────┐
│ 3. Update Spatial Hash                                      │
│    - Clear previous hash                                    │
│    - Assign bodies to cells based on position               │
└─────────────────────────────┬───────────────────────────────┘
                              │
┌─────────────────────────────▼───────────────────────────────┐
│ 4. Detect Collisions                                        │
│    - Broad phase: Check same-cell body pairs                │
│    - Narrow phase: Sphere intersection tests                │
└─────────────────────────────┬───────────────────────────────┘
                              │
┌─────────────────────────────▼───────────────────────────────┐
│ 5. Resolve Collisions                                       │
│    - Calculate collision impulses                           │
│    - Apply velocity changes                                 │
│    - Correct penetration                                    │
└─────────────────────────────┬───────────────────────────────┘
                              │
┌─────────────────────────────▼───────────────────────────────┐
│ 6. Integrate Velocity                                       │
│    - Update positions: p = p + v*dt                         │
└─────────────────────────────┬───────────────────────────────┘
                              │
┌─────────────────────────────▼───────────────────────────────┐
│ 7. Update Character Controllers                             │
│    - Ground detection via raycast                           │
│    - Apply movement velocity                                │
└─────────────────────────────┬───────────────────────────────┘
                              │
┌─────────────────────────────▼───────────────────────────────┐
│ 8. Apply Damping & Sleep                                    │
│    - Reduce velocity by damping factor                      │
│    - Put slow bodies to sleep                               │
└─────────────────────────────────────────────────────────────┘
```

---

## Performance Statistics

Monitor physics performance with built-in statistics:

```typescript
interface PhysicsStats {
  bodyCount: number; // Total bodies
  activeBodyCount: number; // Awake bodies
  collisionCount: number; // Current collisions
  stepTime: number; // Last step duration (ms)
  fps: number; // Physics FPS
}

const stats = physics.getStats();
console.log(`Bodies: ${stats.bodyCount} (${stats.activeBodyCount} active)`);
console.log(`Collisions: ${stats.collisionCount}`);
console.log(`Step time: ${stats.stepTime}ms (${stats.fps} FPS)`);
```

---

## Configuration Options

### Gravity

```typescript
// Default Earth gravity
physics.setGravity({ x: 0, y: -9.81, z: 0 });

// Low gravity (moon)
physics.setGravity({ x: 0, y: -1.62, z: 0 });

// Zero gravity (space)
physics.setGravity({ x: 0, y: 0, z: 0 });

// Custom gravity direction
physics.setGravity({ x: 0, y: 0, z: -9.81 }); // Horizontal gravity
```

### Timestep

```typescript
// 60 Hz (smooth, higher CPU)
const physics = new PhysicsEngine({ timestep: 1 / 60 });

// 30 Hz (lower CPU, less smooth)
const physics = new PhysicsEngine({ timestep: 1 / 30 });

// Variable timestep (not recommended)
function update(deltaTime: number) {
  physics.timestep = deltaTime;
  physics.step();
}
```

### Spatial Hash Cell Size

```typescript
// Small cells (more precise, higher CPU)
const physics = new PhysicsEngine({ cellSize: 5 });

// Large cells (lower CPU, more collision checks)
const physics = new PhysicsEngine({ cellSize: 20 });
```

---

## Best Practices

### Performance

- **Enable sleep**: Set `canSleep: true` for objects that settle
- **Use appropriate cell size**: Match to average object size
- **Limit dynamic bodies**: Keep under 500 for 60 FPS
- **Use sensors for triggers**: Don't need full collision response

### Stability

- **Use fixed timestep**: Avoid variable delta time
- **Limit velocity**: Cap maximum velocity for predictability
- **Add damping**: Prevents infinite bouncing/sliding
- **Use proper mass ratios**: Avoid 1000:1 mass differences

### Integration

```typescript
// Recommended game loop
let accumulator = 0;
const fixedTimestep = 1 / 60;

function gameLoop(currentTime: number) {
  const deltaTime = currentTime - lastTime;
  lastTime = currentTime;

  accumulator += deltaTime / 1000;

  while (accumulator >= fixedTimestep) {
    physics.step();
    accumulator -= fixedTimestep;
  }

  // Interpolate rendering (optional)
  const alpha = accumulator / fixedTimestep;
  render(alpha);

  requestAnimationFrame(gameLoop);
}
```

---

## Troubleshooting

### Objects Fall Through Floor

1. Check collision shape sizes match visual mesh
2. Verify floor body is type `fixed`
3. Ensure timestep isn't too large
4. Check penetration correction is working

### Jittery Movement

1. Use fixed timestep, not variable
2. Increase damping values
3. Check for multiple forces being applied
4. Verify mass values are reasonable

### Poor Performance

1. Enable sleep for static objects
2. Reduce body count
3. Increase spatial hash cell size
4. Profile with `getStats()`

### Missing Collisions

1. Verify bodies are not sleeping
2. Check collider sizes aren't too small
3. Ensure velocities aren't too high (tunneling)
4. Verify spatial hash cell size is appropriate

---

## Related Documentation

- [Rendering System](./rendering-system.md)
- [Avatar System](./avatar-system.md)
- [Networking](./networking.md)

---

_Last Updated: January 2026_
