chuk-mcp-physics 0.5.1
MCP server for physics simulations and calculations using Rapier physics engine
Requires Python: >=3.11

# Physics MCP Server

[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Python 3.11+](https://img.shields.io/badge/python-3.11+-blue.svg)](https://www.python.org/downloads/)
[![Test Coverage](https://img.shields.io/badge/coverage-98%25-brightgreen.svg)](https://github.com/yourusername/chuk-mcp-physics)
[![Tests](https://img.shields.io/badge/tests-515%20passing-brightgreen.svg)](https://github.com/yourusername/chuk-mcp-physics)

**Features:** 🌀 Magnus Force • 💨 Wind Effects • 🏔️ Altitude • 🌡️ Temperature • 🔄 Tumbling Drag • 🎮 Rigid-Body Sims • 📊 515 Tests

**A Model Context Protocol (MCP) server that brings comprehensive physics simulation and calculation capabilities to Large Language Models.**

Transform your LLM into a physics engine! This MCP server provides 55 specialized tools spanning classical mechanics, fluid dynamics, rotational motion, and rigid-body simulations. Built for seamless integration with Claude, ChatGPT, and any MCP-compatible AI system.

## 📚 Table of Contents

- [What is This?](#-what-is-this)
- [What's Included](#-whats-included)
- [Quick Start](#-quick-start-30-seconds)
- [Use Cases](#-use-cases)
- [Available Tools](#-available-tools)
  - [Common Drag Coefficients](#common-drag-coefficients-cd-reference)
  - [Advanced Projectile Features](#advanced-projectile-features) 🌀💨🏔️
- [Examples](#-examples)
- [Development](#-development)

## 🌟 What is This?

**Physics MCP Server** enables LLMs to perform sophisticated physics calculations and simulations through a standardized protocol. Instead of hallucinating physics formulas or making calculation errors, LLMs can now:

- **Calculate precisely**: Use validated physics formulas for exact results
- **Simulate realistically**: Run rigid-body physics with the Rapier engine
- **Visualize motion**: Generate trajectory data for React Three Fiber, Remotion, and other 3D frameworks
- **Teach interactively**: Answer physics questions with real calculations, not memorized facts
- **Design intelligently**: Analyze forces, collisions, and motion for engineering applications

### Why MCP?

The [Model Context Protocol](https://modelcontextprotocol.io/) provides a standardized way to extend LLM capabilities beyond text generation. This server implements MCP to give language models direct access to:

- ⚡ **Instant physics calculations** (projectile motion, forces, energy)
- 🎮 **Rigid-body simulations** (collisions, bounces, stacking)
- 📊 **Motion analysis** (trajectory fitting, kinematics, velocity profiles)
- 🌊 **Fluid dynamics** (drag, buoyancy, lift, Bernoulli)
- 🔄 **Rotational mechanics** (torque, angular momentum, gyroscopes)
- ⚖️ **Static analysis** (equilibrium, beam reactions, friction)
- 🔄 **Unit conversions** (62 unit types: velocity, distance, mass, time, acceleration, torque, frequency, data size, and more)

## 📦 What's Included

### 55 Physics Tools Across 10 Categories

| Category | Tools | Description |
|----------|-------|-------------|
| **Basic Mechanics** | 8 tools | Projectile motion, forces, energy, momentum, collisions |
| **Fluid Dynamics** | 10 tools | Drag, buoyancy, terminal velocity, lift, Magnus force, Bernoulli |
| **Rotational Dynamics** | 5 tools | Torque, moment of inertia, angular momentum, rotational KE |
| **Oscillations** | 5 tools | Springs, pendulums, harmonic motion, damping |
| **Circular Motion** | 5 tools | Centripetal force, orbits, banking angles, escape velocity |
| **Statics** | 7 tools | Force balance, torque balance, friction, beam reactions |
| **Kinematics** | 7 tools | Motion analysis, trajectory fitting, velocity calculations, projectile with drag |
| **Collisions** | 2 tools | Elastic and inelastic 3D collisions with energy loss |
| **Conservation Laws** | 4 tools | Energy, momentum, and angular momentum verification |
| **Unit Conversions** | 2 tools | 62 unit types across 16 categories (velocity, distance, mass, time, acceleration, torque, frequency, data, etc.) |

### Realistic vs Ideal Physics Comparison

See the dramatic difference when including real-world effects:

| Sport | Scenario | Ideal (No Drag) | Realistic (With Enhancements) | Difference |
|-------|----------|----------------|-------------------------------|------------|
| ⚾ Baseball | 90 mph fastball | 87.5m | 52.3m (with drag) | **-40%** range |
| ⛳ Golf | Pro drive at sea level | 251m | 129m (with drag) | **-49%** range |
| ⛳ Golf | Same drive in Denver | 251m | 181m (drag + altitude) | **-28%** range |
| ⚽ Soccer | Free kick with wind | 25m straight | 26m + 5.6m curve (wind + spin) | **Bends 5.6m!** |
| 🎾 Tennis | Serve on hot day | 27m | 26.8m (less drag) | **+2.3%** vs cold |

💡 **Key Insight**: Real physics matters! Air resistance can reduce range by 20-70% depending on the sport.

### Two Calculation Modes

1. **Analytic Mode** (Built-in, no setup)
   - Instant mathematical calculations
   - Perfect for education and quick answers
   - Exact solutions using physics formulas
   - **Now includes**: Advanced drag, spin (Magnus), wind, altitude effects

2. **Simulation Mode** (Requires Rapier service)
   - Full rigid-body dynamics
   - Complex multi-object interactions
   - Realistic material properties and constraints

## 🚀 Quick Start (30 seconds)

```bash
# Try it instantly with uvx (no installation needed)
uvx chuk-mcp-physics

# Or with the public Rapier service for simulations
RAPIER_SERVICE_URL=https://rapier.chukai.io uvx chuk-mcp-physics

# Or use the public hosted MCP server (no local installation)
# Add to Claude Desktop config with URL: https://physics.chukai.io/mcp
```

**For Claude Desktop:** Add to your config file:

**Option 1: Public Hosted MCP Server (Easiest - No Installation)**
```json
{
  "mcpServers": {
    "physics": {
      "command": "node",
      "args": ["-e", "require('https').get('physics.chukai.io/mcp')"]
    }
  }
}
```

**Option 2: Local uvx (Recommended)**
```json
{
  "mcpServers": {
    "physics": {
      "command": "uvx",
      "args": ["chuk-mcp-physics"],
      "env": {
        "RAPIER_SERVICE_URL": "https://rapier.chukai.io"
      }
    }
  }
}
```

---

## 🎯 Use Cases

### 1. **Interactive Physics Education**
**LLM as Physics Tutor**
```
User: "If I throw a ball at 20 m/s at 45°, how far will it go?"
LLM: [calls calculate_projectile_motion]
     "The ball will travel 40.8 meters and reach a maximum height of 10.2 meters..."
     [generates visualization with trajectory points]
```

**Real-World Problem Solving**
- Students ask physics questions in natural language
- LLM calculates exact answers using the MCP tools
- Can generate trajectory plots, force diagrams, energy graphs
- Interactive "what-if" scenarios: "What if gravity was half?"

---

### 2. **Game Development & Prototyping**
**Ballistics Design**
```
User: "I'm designing a cannon in my game. Initial velocity 50 m/s, 30° angle.
       Will it clear a 15m wall at 80m distance?"
LLM: [calls calculate_projectile_motion]
     "At 80m, the projectile is at 18.6m height - it WILL clear the wall.
      It lands at 110.9m range."
```

**Collision Detection**
```
User: "Two spaceships: Ship A at (0,0,0) moving at (10,0,0) m/s, Ship B at (100,5,0)
       moving at (-8,0,0) m/s. Will they collide?"
LLM: [calls check_collision]
     "Yes, collision in 5.3 seconds at position (53.0, 2.65, 0.0) with impact speed 18 m/s"
```

**Rapid Iteration**
- Test different launch angles, speeds, masses without coding
- Verify collision logic before implementation
- Generate realistic physics data for procedural content

---

### 3. **3D Visualization & Animation (React Three Fiber)**
**Automated Animation Data Generation**
```
User: "Create a realistic basketball shot animation - 7m throw into 3m high basket"
LLM: [calls calculate_projectile_motion with solved angle]
     [returns trajectory_points array]
     "Here's the trajectory data for R3F. The ball needs 52° launch angle..."

     <mesh position={interpolate(trajectory)}>
       <sphereGeometry args={[0.12]} />
     </mesh>
```

**Rigid-Body Simulations**
```
User: "Simulate 10 boxes falling and stacking in a pile"
LLM: [calls create_simulation]
     [calls add_rigid_body for ground + 10 boxes with random positions]
     [calls record_trajectory for each box]
     "Here are 10 trajectory arrays for your R3F scene, ready to use..."
```

**Use Cases:**
- Product visualizations (dropping phones, bouncing balls)
- Architectural collapse simulations (building demolition previews)
- Sports analytics visualizations (ball trajectories, collision analysis)
- Sci-fi effects (asteroid fields, debris clouds)

---

### 4. **Engineering & Design Analysis**
**Vehicle Crash Prediction**
```
User: "Two cars: Car A (1500kg) at 30 m/s, Car B (1200kg) at 25 m/s approaching.
       Distance 100m. When do they collide and what's the impact energy?"
LLM: [calls check_collision for timing]
     [calls calculate_kinetic_energy for both cars]
     [calls calculate_momentum for momentum analysis]
     "Collision in 1.82 seconds. Total kinetic energy: 1,050,000 J..."
```

**Safety Analysis**
- Calculate impact forces for crash test scenarios
- Predict collision times for autonomous vehicle planning
- Analyze momentum transfer in industrial equipment

**Structural Testing (with Rapier simulations)**
- Simulate falling objects hitting structures
- Test load-bearing capacity under dynamic loads
- Model chain reactions (domino effects)

---

### 5. **Sports & Athletics**
**Realistic Ball Trajectories with Air Resistance**
```
User: "How far does a 90 mph baseball fastball actually travel with air resistance?"
LLM: [calls calculate_projectile_with_drag with baseball parameters]
     "With drag (realistic): 52.3m range
      Without drag (vacuum): 87.5m range
      Air resistance reduces range by 40%! Energy lost to drag: 89.2 J..."
```

**Golf Drive Analysis**
```
User: "Pro golfer hits 70 m/s (155 mph) at 12° angle. How far with real air resistance?"
LLM: [calls calculate_projectile_with_drag with golf ball parameters]
     "With drag: 129.4m (142 yards)
      Without drag: 251.0m (274 yards)
      Dimples reduce drag coefficient from 0.47 to 0.25 - saves ~50% range loss!"
```

**Basketball 3-Pointer**
```
User: "What launch angle for a 7.5 m/s shot from 6.75m away (3-point line)?"
LLM: [calls calculate_projectile_with_drag iterating angles]
     "With air resistance, optimal angle is 48° (high arc).
      Range: 6.73m (close!), max height: 3.2m, flight time: 1.1s..."
```

**Shot Analysis Applications**
- **Baseball**: Pitch trajectories, drag reduces 90mph fastball range by 40%
- **Golf**: Drive distance with dimpled ball (Cd=0.25 vs smooth ball Cd=0.47)
- **Basketball**: Arc optimization for free throws and 3-pointers
- **Soccer**: Penalty kick trajectories, minimal drag at short distances
- **Track & field**: Javelin, shot put with realistic air resistance
- **Tennis**: Serve and groundstroke trajectory analysis

---

### 6. **Astrophysics & Space Exploration**
**Orbital Mechanics (Simplified)**
```
User: "Two asteroids on collision course. A: 500m radius at (0,0,0) moving 15 km/s.
       B: 300m radius at (100km, 2km, 0) moving -12 km/s. Impact prediction?"
LLM: [calls check_collision with appropriate units]
     "Collision in 3.47 seconds at closest approach distance 650m.
      They will NOT collide - miss distance is 150m..."
```

**Applications:**
- Asteroid impact prediction
- Satellite collision avoidance
- Debris field analysis
- Launch trajectory planning (simplified cases)

---

### 7. **Fluid Dynamics & Marine/Aerospace Engineering**
**Underwater Torpedo Simulation**
```
User: "A torpedo is launched underwater at 20 m/s. It weighs 100kg, has a
       streamlined shape (Cd=0.04), and cross-section of 0.03 m².
       How far does it travel in 30 seconds?"
LLM: [calls simulate_underwater_motion]
     "The torpedo travels 147.5 meters before drag and buoyancy slow it down.
      Final velocity: 0.2 m/s. Maximum depth: 729.9 m..."
```

**Terminal Velocity & Drag Analysis**
```
User: "What's the terminal velocity of a skydiver (70kg, 0.7m² area)?"
LLM: [calls calculate_terminal_velocity]
     "Terminal velocity is 40 m/s (90 mph) in belly-down position.
      Takes 12.2 seconds to reach 95% of terminal velocity..."
```

**Buoyancy & Float/Sink Predictions**
```
User: "Will a 1kg steel ball (10cm diameter) float in water?"
LLM: [calls calculate_buoyancy]
     "No, it will sink. Buoyant force is 5.14 N, but weight is 9.81 N.
      The ball is denser than water..."
```

**Applications:**
- **Marine engineering:** Submarine drag, torpedo trajectories, underwater vehicles
- **Aerospace:** Parachute descent, atmospheric re-entry, drag optimization
- **Sports science:** Swimming efficiency, diving trajectories
- **Product design:** Floatation devices, drag reduction, hydrodynamics
- **Environmental:** Particle settling rates, pollutant dispersion

---

### 8. **Film & VFX Pre-visualization**
**Stunt Planning**
```
User: "Car jumps off 3m ramp at 25 m/s, 20° angle. How far does it fly and where does it land?"
LLM: [calls calculate_projectile_motion]
     "Airtime: 1.75 seconds, landing at 42.9m horizontal distance,
      impact speed 26.3 m/s. Recommend crashmat at 40-45m mark..."
```

**Destruction Sequences**
- Building collapses with rigid-body sim
- Explosion debris trajectories
- Vehicle stunts and crashes
- Realistic object interactions

---

### 8. **Military & Defense (Training/Education)**
**Ballistics Training**
```
User: "Artillery shell: muzzle velocity 800 m/s, 45° elevation. Range and time of flight?"
LLM: [calls calculate_projectile_motion]
     "Range: 65.3 km, flight time: 115.5 seconds, max altitude: 16.3 km"
```

**Collision Avoidance**
- Projectile trajectory analysis
- Impact point prediction
- Intercept course calculations

---

### 9. **Robotics & Automation**
**Path Planning**
```
User: "Robot arm needs to toss part into bin 2m away, 0.5m higher.
       What velocity is needed?"
LLM: [reverse-calculates using projectile_motion multiple times]
     "Minimum velocity: 4.7 m/s at 38° angle. Recommend 5.0 m/s for safety margin..."
```

**Collision Detection**
- Multi-robot coordination
- Object catching/throwing
- Assembly line optimization

---

### 10. **Data Science & Research**
**Physics Simulations for ML Training Data**
```python
# Generate thousands of collision scenarios for ML model training
for i in range(10000):
    result = await check_collision(random_params())
    training_data.append({
        'features': params,
        'label': result.will_collide,
        'impact_time': result.collision_time
    })
```

**Use Cases:**
- Generate labeled physics data for ML models
- Validate physics-informed neural networks
- Test scientific hypotheses with rapid iteration
- Monte Carlo simulations (vary parameters, aggregate results)

---

## 🚀 Real-World Example Workflows

### Workflow 1: Basketball Shot Optimizer
```
1. User: "I'm 2m tall shooting from free-throw line (4.6m). Basket is 3.05m high.
          What's the minimum velocity needed?"

2. LLM calls calculate_projectile_motion with varying velocities
   - Try v=5 m/s → doesn't reach
   - Try v=7 m/s → reaches
   - Binary search finds minimum: v=6.2 m/s at 52° angle

3. LLM: "Minimum velocity is 6.2 m/s at 52° launch angle.
         For comfortable margin, use 7.0 m/s (typical free throw speed).
         Here's the trajectory visualization..."
```

### Workflow 2: Car Crash Investigation
```
1. User: "Analyze accident: Car A (1500kg) skid marks 30m, Car B (1200kg) skid marks 25m.
          Coefficient of friction 0.7. What were impact speeds?"

2. LLM:
   - Calculates deceleration from friction: a = μg = 0.7 × 9.81 = 6.87 m/s²
   - Uses v² = 2ad to find velocities
   - Calls calculate_kinetic_energy for both cars
   - Calls calculate_momentum for momentum analysis

3. LLM: "Car A impact speed: ~20.3 m/s (45 mph), Car B: ~18.5 m/s (41 mph).
         Total kinetic energy at impact: 513,000 J. Here's the force analysis..."
```

### Workflow 3: Game Level Design with Physics Simulation
```
1. User: "Create a Rube Goldberg machine: ball rolls down ramp, hits dominos,
          dominos knock ball into basket"

2. LLM:
   - Calls create_simulation(gravity_y=-9.81)
   - Adds ground plane (static)
   - Adds ramp (static, angled)
   - Adds ball (dynamic, sphere, position at ramp top)
   - Adds 10 dominos (dynamic boxes in a line)
   - Adds basket (static)
   - Calls step_simulation(steps=1000)
   - Analyzes contacts to verify chain reaction
   - Calls record_trajectory for each piece

3. LLM: "Simulation complete! Ball triggers all dominos successfully.
         Here are the trajectories for R3F visualization.
         Domino #3 falls at t=1.2s, domino #7 at t=2.1s..."
```

### Workflow 4: Satellite Collision Warning
```
1. User: "Satellite A: position (6700km, 0, 0), velocity (0, 7.5km/s, 0)
          Satellite B: position (6650km, 50km, 0), velocity (0, 7.6km/s, 0.1km/s)
          Collision risk?"

2. LLM:
   - Calls check_collision with satellite data
   - Analyzes closest approach

3. LLM: "No collision. Closest approach: 48.3 km at t=412 seconds.
         Satellites are in similar orbits but safe separation.
         Recommend: monitor as orbits may precess over time."
```

---

## 🎨 Visualization Integration

### React Three Fiber (R3F) Example
```tsx
function PhysicsAnimation() {
  const [trajectory, setTrajectory] = useState([]);

  useEffect(() => {
    // LLM generated this trajectory data via MCP
    fetch('/api/mcp/record_trajectory', {
      body: JSON.stringify({
        sim_id: "sim_xyz",
        body_id: "ball",
        steps: 300
      })
    }).then(res => setTrajectory(res.frames));
  }, []);

  return (
    <Canvas>
      <AnimatedBall trajectory={trajectory} />
      <Ground />
    </Canvas>
  );
}

function AnimatedBall({ trajectory }) {
  const ref = useRef();

  useFrame((state) => {
    const t = state.clock.getElapsedTime();
    const frame = trajectory[Math.floor(t / 0.016) % trajectory.length];
    if (frame && ref.current) {
      ref.current.position.fromArray(frame.position);
      ref.current.quaternion.fromArray(frame.orientation);
    }
  });

  return (
    <mesh ref={ref}>
      <sphereGeometry args={[0.5]} />
      <meshStandardMaterial color="orange" />
    </mesh>
  );
}
```

---

## 📊 Trajectory Data Format

All trajectory recordings follow a canonical schema for maximum interoperability with R3F, Remotion, Three.js, and other animation systems.

### Schema Definition

```typescript
interface Trajectory {
  dt: number;              // Time step between frames (seconds)
  frames: Frame[];         // Ordered list of frames
  meta: {
    body_id: string;       // Fully qualified: "rapier://sim-123/body-1"
    total_time: number;    // Total duration (seconds)
    num_frames: number;    // Frame count
  };
}

interface Frame {
  t: number;                               // Absolute time (seconds)
  position: [number, number, number];      // [x, y, z] in meters
  rotation: [number, number, number, number];  // Quaternion [x, y, z, w]
  velocity?: [number, number, number];     // Optional: linear velocity (m/s)
  angular_velocity?: [number, number, number];  // Optional: angular velocity (rad/s)
}
```

### JSON Example

```json
{
  "dt": 0.016,
  "frames": [
    {
      "t": 0.0,
      "position": [0, 1, 0],
      "rotation": [0, 0, 0, 1],
      "velocity": [0, 0, 0]
    },
    {
      "t": 0.016,
      "position": [0.1, 1.01, 0],
      "rotation": [0, 0.01, 0, 0.9999],
      "velocity": [6.25, 0.61, 0]
    }
  ],
  "meta": {
    "body_id": "rapier://sim-abc123/ball",
    "total_time": 4.8,
    "num_frames": 300
  }
}
```

### Usage in React Three Fiber

```tsx
import { useRef } from "react";
import { useFrame } from "@react-three/fiber";

function AnimatedObject({ trajectory }) {
  const ref = useRef();

  useFrame((state) => {
    const elapsed = state.clock.getElapsedTime();
    const frameIdx = Math.floor(elapsed / trajectory.dt);
    const frame = trajectory.frames[frameIdx % trajectory.frames.length];

    if (frame && ref.current) {
      ref.current.position.fromArray(frame.position);
      ref.current.quaternion.fromArray(frame.rotation);
    }
  });

  return (
    <mesh ref={ref}>
      <sphereGeometry args={[0.5]} />
      <meshStandardMaterial color="orange" />
    </mesh>
  );
}
```

### Usage in Remotion

```tsx
import { useCurrentFrame } from "remotion";
import { ThreeCanvas } from "@remotion/three";

export const PhysicsAnimation = ({ trajectory }) => {
  const frame = useCurrentFrame();
  const frameData = trajectory.frames[frame];

  return (
    <AbsoluteFill>
      <ThreeCanvas>
        <mesh position={frameData.position}>
          <sphereGeometry />
        </mesh>
      </ThreeCanvas>
    </AbsoluteFill>
  );
};
```

### Design Notes

- **Quaternions for rotation:** More compact and interpolation-friendly than Euler angles
- **Absolute time:** Each frame has absolute time `t`, making scrubbing easier
- **Constant dt:** Frames are evenly spaced, simplifying playback
- **Optional velocities:** Include if needed for motion blur or physics visualization
- **Qualified body_id:** Format is `rapier://sim-{id}/{body_id}` for traceability

---

## 🛠️ Installation

### Prerequisites
- Python 3.11+
- For simulations: Rapier service (see [RAPIER_SERVICE.md](RAPIER_SERVICE.md))
  - **Public service available at: https://rapier.chukai.io**
  - Or run locally with Docker (see below)

### Quick Start with uvx (Recommended)

The fastest way to try chuk-mcp-physics without installation:

```bash
# Run directly with uvx (no installation needed)
uvx chuk-mcp-physics

# With environment variables
uvx --with chuk-mcp-physics chuk-mcp-physics
```

### Installation Methods

#### Option 1: Install from PyPI (Recommended)

```bash
# Install globally
pip install chuk-mcp-physics

# Or with pipx (isolated environment)
pipx install chuk-mcp-physics

# Run the server
chuk-mcp-physics

# Or via python module
python -m chuk_mcp_physics.server
```

#### Option 2: Install from Source

```bash
# Clone repository
git clone https://github.com/yourusername/chuk-mcp-physics
cd chuk-mcp-physics

# Install in development mode
make dev-install

# Run the server
chuk-mcp-physics
```

### With Claude Desktop

Add to your Claude Desktop config (`~/Library/Application Support/Claude/claude_desktop_config.json` on macOS):

#### Option 1: Using uvx (Recommended - No Installation Required)

```json
{
  "mcpServers": {
    "physics": {
      "command": "uvx",
      "args": ["chuk-mcp-physics"],
      "env": {
        "PHYSICS_PROVIDER": "rapier",
        "RAPIER_SERVICE_URL": "https://rapier.chukai.io"
      }
    }
  }
}
```

#### Option 2: Using Installed Package

```json
{
  "mcpServers": {
    "physics": {
      "command": "python",
      "args": ["-m", "chuk_mcp_physics.server"],
      "env": {
        "PHYSICS_PROVIDER": "rapier",
        "RAPIER_SERVICE_URL": "https://rapier.chukai.io"
      }
    }
  }
}
```

#### Option 3: Analytic Only (No External Service)

```json
{
  "mcpServers": {
    "physics": {
      "command": "uvx",
      "args": ["chuk-mcp-physics"],
      "env": {
        "PHYSICS_PROVIDER": "analytic"
      }
    }
  }
}
```

---

## 📖 Available Tools

### Tool Organization

Tools are organized into two tiers to help you choose the right abstraction:

#### 1️⃣ Analytic Primitives (No External Service)

**Best for:** Quick calculations, education, simple scenarios

Direct formula-based calculations that return instant results:

| Tool | What It Does | Example Use Case |
|------|--------------|------------------|
| `calculate_projectile_motion` | Ballistic trajectory using kinematic equations | "How far does a cannonball go?" |
| `check_collision` | Predict if two spheres will collide | "Will these asteroids hit?" |
| `calculate_force` | F = ma calculations | "What force accelerates this car?" |
| `calculate_kinetic_energy` | KE = ½mv² | "How much energy in this crash?" |
| `calculate_momentum` | p = mv | "What's the momentum transfer?" |
| `calculate_potential_energy` | PE = mgh | "What's the energy at height?" |
| `calculate_work_power` | Work (F·d) and power (W/t) | "How much work lifting this box?" |
| `calculate_elastic_collision` | 1D elastic collision (conserves energy & momentum) | "Pool balls colliding?" |
| `calculate_drag_force` | Air/water resistance (F = ½ρv²C_dA) | "What's the drag on this car?" |
| `calculate_buoyancy` | Will it float? (Archimedes) | "Does a steel ball float in water?" |
| `calculate_terminal_velocity` | Maximum fall speed | "How fast does a skydiver fall?" |
| `simulate_underwater_motion` | Underwater trajectory with drag & buoyancy | "How far does a torpedo travel?" |

**Characteristics:**
- ⚡ Instant execution (< 1ms)
- 📦 No external dependencies
- 🎯 Exact mathematical solutions
- ✅ Always available (no service required)

**Limitations:**
- Only spherical objects (for collisions)
- No complex shapes
- No multi-body interactions
- No friction or material properties

#### 2️⃣ Simulation Primitives (Requires Rapier Service)

**Best for:** Complex physics, multi-body dynamics, visualization data

Low-level building blocks for rigid-body simulations:

| Tool | What It Does | When to Use |
|------|--------------|-------------|
| `create_simulation` | Initialize physics world | Start any simulation |
| `add_rigid_body` | Add objects (box, sphere, capsule, etc.) | Build scene |
| `step_simulation` | Advance time | Run physics |
| `record_trajectory` | Capture motion for R3F/Remotion | Generate animation data |
| `destroy_simulation` | Cleanup resources | End simulation |

**Characteristics:**
- 🦀 Requires Rapier service
- 🔄 Stateful (track simulation ID)
- 🧩 Composable (combine for complex scenarios)
- 💪 Full rigid-body dynamics

**Typical workflow:**
```python
# 1. Create world
sim = create_simulation(gravity_y=-9.81)

# 2. Add objects
add_rigid_body(sim.sim_id, "ground", type="static", shape="plane")
add_rigid_body(sim.sim_id, "ball", type="dynamic", shape="sphere",
               radius=0.5, position=[0, 5, 0])

# 3. Run simulation
step_simulation(sim.sim_id, steps=300)

# 4. Record for visualization
trajectory = record_trajectory(sim.sim_id, "ball", steps=300)

# 5. Cleanup
destroy_simulation(sim.sim_id)
```

---

## 📋 Complete Tool Reference

### Basic Mechanics (8 tools)

| Tool | Purpose | Example |
|------|---------|---------|
| `calculate_projectile_motion` | Ballistic trajectories | "How far does a cannonball travel?" |
| `check_collision` | Predict sphere collisions | "Will these asteroids hit?" |
| `calculate_force` | F = ma calculations | "What force accelerates this car?" |
| `calculate_kinetic_energy` | KE = ½mv² | "Energy in moving object?" |
| `calculate_momentum` | p = mv | "Momentum of moving object?" |
| `calculate_potential_energy` | PE = mgh | "Energy at height?" |
| `calculate_work_power` | Work (F·d) and power (W/t) | "Work done lifting object?" |
| `calculate_elastic_collision` | 1D elastic collision | "Pool ball velocities after impact?" |

### Fluid Dynamics (10 tools)

| Tool | Purpose | Example |
|------|---------|---------|
| `calculate_drag_force` | Air/water resistance | "Drag on car at speed?" |
| `calculate_buoyancy` | Will it float? (Archimedes) | "Does steel ball float?" |
| `calculate_terminal_velocity` | Maximum fall speed | "Skydiver terminal velocity?" |
| `simulate_underwater_motion` | Underwater trajectory | "How far does torpedo travel?" |
| `calculate_lift_force` | Aerodynamic lift | "Lift on aircraft wing?" |
| `calculate_magnus_force` | Force on spinning ball | "Why does curveball curve?" |
| `calculate_bernoulli` | Pressure in flowing fluid | "Pressure in pipe constriction?" |
| `calculate_pressure_at_depth` | Hydrostatic pressure | "Pressure at 30m depth?" |
| `calculate_reynolds_number` | Flow regime classification | "Is flow turbulent?" |
| `calculate_venturi_effect` | Flow through constriction | "Velocity in throat?" |

### Rotational Dynamics (5 tools)

| Tool | Purpose | Example |
|------|---------|---------|
| `calculate_torque` | τ = r × F (cross product) | "Torque from wrench?" |
| `calculate_moment_of_inertia` | Rotational inertia | "MOI of spinning disk?" |
| `calculate_angular_momentum` | L = Iω | "Angular momentum of wheel?" |
| `calculate_rotational_kinetic_energy` | Rotational KE = ½Iω² | "Energy in flywheel?" |
| `calculate_angular_acceleration` | α = τ/I | "How fast does it spin up?" |

### Oscillations & Waves (5 tools)

| Tool | Purpose | Example |
|------|---------|---------|
| `calculate_hookes_law` | Spring force F = -kx | "Force in compressed spring?" |
| `calculate_spring_mass_period` | Oscillation period | "How fast does mass oscillate?" |
| `calculate_simple_harmonic_motion` | Position at time t | "Where is mass at t=2s?" |
| `calculate_damped_oscillation` | Motion with damping | "How quickly does it settle?" |
| `calculate_pendulum_period` | Pendulum swing time | "Period of 1m pendulum?" |

### Circular Motion & Orbits (5 tools)

| Tool | Purpose | Example |
|------|---------|---------|
| `calculate_centripetal_force` | F_c = mv²/r | "Force for circular motion?" |
| `calculate_orbital_period` | Kepler's 3rd law | "Satellite orbital period?" |
| `calculate_banking_angle` | Optimal curve angle | "Banking for highway curve?" |
| `calculate_escape_velocity` | Escape from gravity | "Earth escape velocity?" |
| `analyze_circular_orbit` | Complete orbital analysis | "Analyze ISS orbit?" |

### Statics & Equilibrium (7 tools)

| Tool | Purpose | Example |
|------|---------|---------|
| `check_force_balance` | Verify ΣF = 0 | "Are forces balanced?" |
| `check_torque_balance` | Verify Στ = 0 | "Will seesaw balance?" |
| `calculate_center_of_mass` | Balance point | "Where is center of mass?" |
| `calculate_static_friction` | Max friction force | "Will object slip?" |
| `calculate_normal_force` | Force on incline | "Normal force on ramp?" |
| `check_equilibrium` | Force + torque balance | "Is structure stable?" |
| `calculate_beam_reactions` | Support forces | "Reaction forces on beam?" |

### Kinematics Analysis (7 tools)

| Tool | Purpose | Example |
|------|---------|---------|
| `calculate_acceleration_from_position` | Derive from position data | "Acceleration from motion capture?" |
| `calculate_jerk` | Rate of acceleration change | "How jerky is motion?" |
| `fit_trajectory` | Find trajectory equation | "Fit parabola to data?" |
| `generate_motion_graph` | Position/velocity/accel graphs | "Generate motion graphs?" |
| `calculate_average_speed` | Speed along path | "Average speed on route?" |
| `calculate_instantaneous_velocity` | Velocity at exact time | "Speed at t=2.5s?" |
| `calculate_projectile_with_drag` | Realistic projectile with air resistance | "How far does baseball actually go?" |

### Advanced Collisions (2 tools)

| Tool | Purpose | Example |
|------|---------|---------|
| `calculate_elastic_collision_3d` | 3D perfect collision | "Pool balls in 3D?" |
| `calculate_inelastic_collision_3d` | 3D collision with energy loss | "Car crash analysis?" |

### Conservation Laws (4 tools)

| Tool | Purpose | Example |
|------|---------|---------|
| `check_energy_conservation` | Verify energy conserved | "Is collision realistic?" |
| `check_momentum_conservation` | Verify momentum conserved | "Is momentum preserved?" |
| `check_angular_momentum_conservation` | Verify L conserved | "Is rotation valid?" |
| `track_energy_dissipation` | Energy loss over time | "Where did energy go?" |

### Unit Conversions (2 tools)

| Tool | Purpose | Supported Units |
|------|---------|-----------------|
| `convert_unit` | Convert between units | **Velocity**: m/s, km/h, mph, ft/s, knots<br/>**Distance**: m, km, mi, ft, yd, in<br/>**Mass**: kg, g, lb, oz<br/>**Force**: N, kN, lbf<br/>**Energy**: J, kJ, cal, BTU, kWh<br/>**Power**: W, kW, hp<br/>**Temperature**: K, C, F<br/>**Angle**: rad, deg<br/>**Pressure**: Pa, kPa, bar, psi, atm<br/>**Area**: m², km², ft², acre<br/>**Volume**: m³, L, gal, ft³<br/>**Time**: s, min, hr, day<br/>**Acceleration**: m/s², g, ft/s²<br/>**Torque**: N·m, lb·ft, lb·in<br/>**Frequency**: Hz, kHz, MHz, GHz<br/>**Data Size**: B, KB, MB, GB |
| `list_unit_conversions` | Get all supported units | Returns complete list of conversions |

**Examples:**
```python
# Natural language queries work perfectly
"Convert 60 mph to m/s"  # → 26.82 m/s
"How fast is 100 km/h in mph?"  # → 62.14 mph
"What's 10 kg in pounds?"  # → 22.05 lb
"Convert 100 feet to meters"  # → 30.48 m
"What's 98.6°F in Celsius?"  # → 37°C
"Convert 3 g-force to m/s²"  # → 29.42 m/s²
"What's 300 N·m in lb·ft?"  # → 221.27 lb·ft
"Convert 1 hour to seconds"  # → 3600 s
```

**Features:**
- ⚡ Instant conversions (no external service needed)
- 🔄 Automatic indirect conversions (e.g., mph → km/h via m/s)
- 📐 **70+ unit types across 16 categories**
- 🎯 Perfect for natural language physics queries
- 🚀 Includes engineering units (torque, acceleration, frequency)

---

### Common Drag Coefficients (Cd) Reference

For use with `calculate_projectile_with_drag` tool:

| Object | Drag Coefficient (Cd) | Notes |
|--------|----------------------|-------|
| **Sports Balls** | | |
| Baseball | 0.4 | Stitched surface |
| Golf ball (dimpled) | 0.25 | Dimples reduce drag by ~50% |
| Golf ball (smooth) | 0.47 | Without dimples (don't use!) |
| Basketball | 0.55 | Large, textured surface |
| Soccer ball | 0.25 | Modern, smooth panels |
| Tennis ball | 0.55 | Fuzzy surface |
| Football (American) | 0.05-0.15 | Highly streamlined, orientation-dependent |
| **Generic Shapes** | | |
| Sphere (smooth) | 0.47 | Default reference |
| Flat plate (perpendicular) | 1.28 | Maximum drag |
| Streamlined body | 0.04 | Teardrop/airfoil |
| Cylinder (perpendicular) | 1.15 | Like a pole |
| **Vehicles** | | |
| Car (modern) | 0.25-0.35 | Aerodynamic design |
| Truck | 0.6-0.9 | Boxy shape |
| Bicycle + rider | 0.9 | Upright position |
| **Human Body** | | |
| Skydiver (belly-down) | 1.0-1.3 | Maximum drag |
| Skydiver (head-down) | 0.7 | Streamlined |
| **Projectiles** | | |
| Bullet (supersonic) | 0.295 | Pointed nose |
| Artillery shell | 0.15-0.25 | Streamlined |

**Basic Usage Example:**
```python
# Baseball pitch with realistic drag
result = await calculate_projectile_with_drag(
    initial_velocity=40.23,  # 90 mph
    angle_degrees=10,
    mass=0.145,
    cross_sectional_area=0.0043,  # π × (0.037m)²
    drag_coefficient=0.4  # Baseball Cd
)
```

---

### Advanced Projectile Features

The `calculate_projectile_with_drag` tool supports optional enhancements for ultra-realistic simulations:

#### 🌀 Magnus Force (Spin Effects)

Spin creates a pressure differential that deflects the ball's path. Essential for:
- **Baseball**: Curveballs (topspin drops), fastballs (backspin lifts)
- **Golf**: Backspin increases carry, sidespin causes slices/hooks
- **Soccer**: Bending free kicks around defensive walls
- **Tennis**: Topspin brings ball down faster

```python
# Baseball curveball with topspin
result = await calculate_projectile_with_drag(
    initial_velocity=35,
    angle_degrees=0,
    mass=0.145,
    cross_sectional_area=0.0043,
    drag_coefficient=0.4,
    spin_rate=261.8,  # 2500 rpm = 261.8 rad/s
    spin_axis=[0, 0, -1]  # Topspin (negative z-axis)
)
# Returns lateral_deflection and magnus_force_max
```

**Spin Parameters:**
- `spin_rate`: Rotation speed in rad/s (convert from RPM: rpm × 2π/60)
- `spin_axis`: Unit vector [x, y, z] indicating spin direction
  - `[0, 0, 1]` = Backspin (lifts)
  - `[0, 0, -1]` = Topspin (drops)
  - `[0, 1, 0]` = Sidespin (hooks/slices)

#### 💨 Wind Effects

Constant wind vector affects trajectory throughout flight:

```python
# Soccer free kick with 5 m/s crosswind
result = await calculate_projectile_with_drag(
    initial_velocity=28,
    angle_degrees=12,
    mass=0.43,
    cross_sectional_area=0.0388,
    drag_coefficient=0.25,
    wind_velocity=[5.0, 0.0]  # [horizontal, vertical] in m/s
)
# Returns wind_drift showing total deflection
```

**Wind Types:**
- **Tailwind**: `[+X, 0]` - increases range
- **Headwind**: `[-X, 0]` - decreases range
- **Crosswind**: `[X, 0]` - lateral deflection
- **Updraft**: `[0, +Y]` - increases height and flight time
- **Downdraft**: `[0, -Y]` - decreases height

#### 🏔️ Altitude & Temperature Effects

Air density varies with elevation and temperature, dramatically affecting drag:

```python
# Golf drive in Denver (1600m elevation, 20°C)
result = await calculate_projectile_with_drag(
    initial_velocity=70,
    angle_degrees=12,
    mass=0.0459,
    cross_sectional_area=0.00143,
    drag_coefficient=0.25,
    altitude=1600,  # meters above sea level
    temperature=20  # Celsius
)
# Returns effective_air_density showing actual density used
```

**Real-World Impact:**
- **Denver (1600m)**: ~10% longer drives than sea level
- **Hot day (+20°C)**: ~2-3% less drag than cold day
- **Everest Base Camp (5300m)**: ~50% less air density!

**Air Density Formula:**
```
ρ(h,T) = ρ₀ × exp(-Mgh/RT₀) × (T₀/T)
```
Where:
- ρ₀ = sea level density (1.225 kg/m³)
- h = altitude (meters)
- T = temperature (Kelvin)
- M = molar mass of air (0.029 kg/mol)
- g = gravity (9.81 m/s²)
- R = gas constant (8.314 J/(mol·K))

#### 🌟 Combined Effects Example

```python
# Golf ball with ALL effects (spin + wind + altitude)
result = await calculate_projectile_with_drag(
    initial_velocity=70,
    angle_degrees=12,
    mass=0.0459,
    cross_sectional_area=0.00143,
    drag_coefficient=0.25,
    spin_rate=200,  # Backspin
    spin_axis=[0, 0, 1],
    wind_velocity=[3, 0],  # Tailwind
    altitude=1000,  # Moderate elevation
    temperature=25  # Warm day
)
# All effects combine for maximum realism!
```

**See Examples:**
- `examples/sports_projectiles_with_drag.py` - Basic drag effects
- `examples/advanced_projectile_effects.py` - Magnus force, wind, altitude

---

### 🔄 Orientation-Dependent Drag (Rapier Simulations)

For tumbling objects like footballs, frisbees, and javelins, drag varies dramatically based on orientation. A football in a perfect spiral has **3-6× less drag** than when tumbling end-over-end!

**Available via Rapier rigid-body simulations** using the `add_rigid_body` tool with orientation-dependent drag parameters.

#### How It Works

Objects moving through air experience drag that depends on their orientation:
- **Football spiral**: Streamlined along flight path → low drag (~0.1 Cd)
- **Football tumbling**: Broadside to airflow → high drag (~0.6 Cd)
- **Frisbee flat**: Minimal cross-section → low drag (~0.08 Cd)
- **Frisbee tilted**: Larger cross-section → higher drag

**New `add_rigid_body` Parameters:**
```python
drag_coefficient: float      # Base Cd value
drag_area: float             # Reference cross-sectional area (m²)
drag_axis_ratios: [x, y, z]  # Drag variation along body axes
fluid_density: float         # Fluid density (air=1.225, water=1000)
```

#### Example: Football Spiral vs Tumble

```python
# Perfect spiral (low drag along Y-axis)
await add_rigid_body(
    sim_id,
    id="spiral",
    shape="capsule",
    size=[0.17, 0.28],  # diameter, length
    mass=0.42,
    position=[0, 2, 0],
    velocity=[vx, vy, 0],
    angular_velocity=[0, 126, 0],  # 20 rev/s spin
    # Orientation-dependent drag
    drag_coefficient=0.1,
    drag_area=0.023,  # End-on area
    drag_axis_ratios=[1.0, 0.2, 1.0],  # 5× less drag along Y
    fluid_density=1.225
)

# Tumbling (higher drag, averaging all orientations)
await add_rigid_body(
    sim_id,
    id="tumble",
    shape="capsule",
    size=[0.17, 0.28],
    mass=0.42,
    position=[0, 2