physics-engine
Use when the user asks about a physics engine, collision detection, broad phase, narrow phase, GJK, EPA, constraint solvers, rigid bodies, CCD, character…
от j4flmao★ 47 звёзд на GitHub
Установить physics-engine в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Об этом скилле
Physics Engine Internals — Deep Guide
Purpose
A physics engine simulates rigid bodies through three pipelines every tick: collision detection (find contacts), collision resolution (apply impulses/constraints), and integration (advance positions/velocities). This guide gives a lead engineer's view of how real engines (PhysX, Jolt, Bullet, Box2D) work underneath.
Agent Protocol
Trigger
"physics engine", "collision detection", "broad phase", "narrow phase", "GJK", "EPA", "constraint solver", "rigid body", "character controller", "CCD".
Input Context
- Engine or library (custom, Jolt, PhysX, Box2D, Bullet)
- Body counts and tick rate
- Determinism requirements (netcode, replays)
Output Artifact
Physics design or code with stability/performance reasoning. No file unless requested.
Response Format
Stage: {broad | narrow | solve | integrate}
Approach: {algorithm}
Code: {snippet}
Stability: {iterations, substeps, tolerances}
1. The Physics Step Pipeline
1. For each body: apply forces -> linear/angular velocity (accelerate)
2. Broad-phase: generate candidate pairs of AABB-overlapping bodies
3. Narrow-phase: exact contact detection -> contact manifold (points, normals, penetration)
4. Constraint solver: iterate contacts + joints to correct penetration & velocities
5. Integration: x += v * dt; Rot += omega * dt (per body)
6. Sleep/wake: mark bodies nearly at rest for deactivation
1.1 Determinism vs Performance
- Fixed timestep required (see
skills/game/game-engine/patterns/SKILL.md→ game-loop section). - Deterministic engines (rollback netcode, replays) must avoid unordered map iteration, use fixed float ops, and sort contact manifolds deterministically.
2. Broad-Phase Collision Detection
Goal: reject distant pairs cheaply; output pairs of possibly-intersecting AABBs.
2.1 Sweep-and-Prune (SAP)
- Sort AABB min/max along one/main axis; maintain lists; in the sorted order, intervals that overlap can be tracked incrementally.
- O(N log N) sort + O(N + P) query.
- Great when most overlap is on one axis and lists are already nearly sorted frame-to-frame.
2.2 Dynamic Bounding Volume Hierarchy (DBVH)
- Tree of AABBs; leaf = one body; internal node = union.
- Insert/remove/update with surface-area-heuristic (SAH) rebalancing.
- O(log N) queries; supports fast updates per moving-body (refit, not rebuild).
- Used by PhysX, Jolt, most modern engines.
class DbvhNode {
AABB box;
DbvhNode* parent;
DbvhNode* children[2]; // internal
int32_t bodyIndex; // leaf: body id
int32_t height;
};
// update: if (invalidated) reinsert; else refit bbox walking up the tree
2.3 Uniform Grid / Hash Grid
- Cell-keyed hash of body IDs in each cell; only adjacent cells checked.
- Best for uniform-distribution particles (SPH, crowds). Non-uniform scenes degenerate — use hierarchical grid.
3. Narrow-Phase Collision
Given a pair, compute contact geometry: point(s), normal, penetration depth.
3.1 The Collider Zoo
| Shape | Query cost | Notes |
|---|---|---|
| Sphere | O(1) | cheap, common for ragdolls/CCD |
| Box (AABB/OBB) | O(1) | standard |
| Capsule | O(1) | characters (built from 2 spheres + cylinder) |
| Triangle mesh (static) | O(log N) via BVH | world geometry |
| Convex hull | O(log N) via facing/support | player phys |
| Heightfield | O(log N) | terrains |
3.2 SAT (Separating Axis Theorem)
For convex vs convex: if a separating axis exists, no collision. Project both shapes onto each candidate axis (edge + face normals); if separated → done; else find minimum overlap axis → contact plane.
3.3 GJK + EPA
- GJK: fast convex-vs-convex boolean test using Minkowski difference and evolving simplex; O(log N) iterations.
- EPA: extends GJK to extract penetration depth + normal (expanding polytope).
- Best for arbitrary convex hulls; less numerically fragile than SAT for many axes.
3.4 Contact Manifold
Result of narrow-phase: a contact manifold:
struct ContactPoint { Vec3 localA, localB, normal, position; float penetration; };
struct Manifold {
ContactPoint points[4]; // up to 4 (box-box), reduced for others
Vec3 normal; // shared frame
Body* a, * b;
};
Simplify: reduce to 1-1 points for spheres, up to 4 for box/box. Give the solver a small set of contact points, NOT the full polygon intersection.
4. Collision Resolution — the Solver
4.1 Impulse-Based vs Penalty
| Method | Approach | Used by |
|---|---|---|
| Impulse-based (constraint solver) | Compute change in velocity per contact to satisfy non-penetration | PhysX, Jolt, Bullet, Box2D |
| Position-based dynamics (PBD/XPBD) | Direct position correction, stable for cloth/soft | many UE chaos modes / Unreal cloth |
| Penalty force | spring force pushing apart | simple engines; unstable at large dt |
4.2 The Sequential Impulse Solver (per c
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл physics-engine?
Use when the user asks about a physics engine, collision detection, broad phase, narrow phase, GJK, EPA, constraint solvers, rigid bodies, CCD, character controllers or Jolt/PhysX internals. Produces rigid-body physics design and solver code. Not for engine-specific physics settings (use unity, unreal or godot).
Как установить скилл physics-engine?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл physics-engine запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
AnthropicGuide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
claude-api
AnthropicReference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
algorithmic-art
AnthropicCreating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
mcp-integration
AnthropicThis skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…