physics-engine
/physics-engine
Wyjaśnia i projektuje fizykę ciał sztywnych: fazy wykrywania kolizji, solwery więzów, CCD i kontrolery postaci.
- Autor
- j4flmao ↗
- Repozytorium
- agent-skills ↗
- Licencja
- MIT
- Ostatnia zmiana repozytorium
- 10.11.2026
Ocena i bezpieczeństwo
- Pliki w paczce
- 1
- Skrypty
- 0
- Komentarze HTML
- 0
- Adresy URL w SKILL.md
- 0
Brak sygnałów. Repozytorium zmienione 10.11.2026, bez odwołań do wycofanych modeli i API.
MIT, otwarta: można używać i zmieniać, z zachowaniem informacji o autorze.
Co robi i kiedy
Wyjaśnia i projektuje fizykę ciał sztywnych: fazy wykrywania kolizji, solwery więzów, CCD i kontrolery postaci.
Wyzwalacze z opisu
Oryginalny opis (EN)
Use this skill when the user says 'physics engine', 'collision detection', 'broad phase', 'narrow phase', 'GJK', 'EPA', 'constraint solver', 'rigid body', 'character controller', 'CCD'. Explains and designs rigid-body physics: broad/narrow phase, contact generation, constraint solvers, integration, sleeping, CCD, character controllers and scene queries. Do NOT use for: engine-specific physics settings only (use unity/unreal/godot), cloth/fluids research.
Jak działa
- Purpose
- Agent Protocol
- 1. The Physics Step Pipeline
- 2. Broad-Phase Collision Detection
- 3. Narrow-Phase Collision
- 4. Collision Resolution — the Solver
- 5. Integration
- 6. Joints & Constraints
- 7. Sleeping & Activation
- 8. Character Controllers
Podgląd SKILL.md
---
name: physics-engine
description: >
Use this skill when the user says 'physics engine', 'collision detection', 'broad phase', 'narrow phase', 'GJK', 'EPA', 'constraint solver', 'rigid body', 'character controller', 'CCD'. Explains and designs rigid-body physics: broad/narrow phase, contact generation, constraint solvers, integration, sleeping, CCD, character controllers and scene queries. Do NOT use for: engine-specific physics settings only (use unity/unreal/godot), cloth/fluids research.
version: "2.0.0"
author: "j4flmao"
license: "MIT"
tags: [game, physics, collision, solver]
---
# 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.
```cpp
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:
```cpp
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 contact)
For each contact: relative velocity at contact point
```
v_rel = (v_b + w_b x r_b) - (v_a + w_a x r_a)
vn = dot(v_rel, n) // approach velocity along normal
// bias: penetration restitution (bounce)
e = restitution(a,b)
j = -(1 + e) * vn / (invMass_a + invMass_b + r cross terms)
v_a -= j * invMass_a * n ; v_b += j * invMass_b * n
// + angular impulse terms
```
Iterate all contacts several times (4-20 iterations) to converge a global solution — each contact affects others.
### 4.3 Friction
Apply two orthogonal tangent impulses:
```
t = v_rel - dot(v_rel,n)*n (tangent direction)
jt = clamp(-v_rel_t * 1/(totalInvMass...), -mu*jn, mu*jn)
```
Use `mu` = Coulomb coefficient (static/dynamic blend).
### 4.4 Solver Order & Warm Starting
- Order contacts (e.g., by penetration) matters for determinism.
- **Warm starting**: store previous-frame impulses and apply them as initial guesses → stable stacks, big speedup.
- Contact persistence: keep manifolds between frames (don't rebuild) so stacks stay stable.
## 5. Integration
### 5.1 Choosing the integrator
| Method | Stability | Cost | Use |
|--------|-----------|------|-----|
| Explicit Euler | unstable (energy gains) | 1x | never in production |
| Semi-implicit Euler | stable, standard | 1x | default rigid-body |
| Verlet | good energy | ~1.3x | cloth, particles |
| RK4 | high accuracy | 4x | precise simulation/ragdolls |
Semi-implicit (symplectic):
```
v += a * dt
x += v * dt // velocity updated BEFORE position
```
### 5.2 Rigid Body State
```cpp
struct RigidBody {
Vec3 position;
Quat rotation;
Vec3 linearVelocity, angularVelocity;
float invMass, invI[3]; // inverse inertia tensor (diagonal local space)
Vec3 force, torque; // accumulated this tick
bool sleeping;
};
```
Integrate rotation: apply angular velocity about local axes via quaternion derivative and normalize.
### 5.3 CCD (Continuous Collision Detection)
High-speed small objects tunnel through thin walls at large dt. Solutions:
- Swept line/ball vs world (PhysX CCD): expand collider along velocity, find first hit.
- Substeps: split dt into smaller steps for fast movers only.
- Cast-double-check: `sweep` a test then narrow-phase at midpoint.
Rule: CCD only for fast bodies vs static world (never CCD-vs-dynamic — expensive/nonsensical).
## 6. Joints & Constraints
- **Distance joint**: keeps 2 anchor points at fixed distance.
- **Revolute joint (hinge)**: rotate about one axis.
- **Prismatic joint**: slide along one axis.
- **Ball/socket**: 3-MOI constraint point.
- **Pulley / gear**: derived from distance/velocity ratios.
Constraint form: `C = 0` (position) → `Cdot = J * v = 0` (velocity). Solve with the same sequential impulse pattern using Jacobian `J`.
```cpp
// generalized velocity constraint solve
lambda = -(J v + bias) / (J M^-1 J^T)
v = v + M^-1 J^T lambda
```
## 7. Sleeping & Activation
- Bodies accumulate kinetic energy; if below threshold for N ticks, mark `sleeping`.
- Wake via: any new contact/impulse, joint activity, or external query of sizable magnitude.
- Deterministic order: wake in fixed order, not map order.
## 8. Character Controllers
PhysX/Jolt expose character controllers that are NOT rigid-body player physics:
- Capsule body, ray/sweep down to floor.
- Move with `move_and_slide`-style: attempt move; slide along obstacles (collide-and-slide).
- Step over small obstacles (max step height), avoid vertical tunneling on slopes.
Implement yourself (matching forced checkpoints), or use engine built-in (Godot `CharacterBody3D`, Unreal `CharacterMovementComponent`, Unity `CharacterController`).
## 9. Scene Queries (Raycasts / Overlaps)
```cpp
// raycast against static + dynamic
Hit hit;
physics.rayCast(origin, dir, maxDist, out hit);
// overlap test
physics.overlapSphere(pos, radius, filter, out bodies[]);
```
Rules:
- Batch queries; per-frame thousands of raycasts in a loop → use `QueryFilterCallback` and broad-phase fast paths.
- Respect layer masks so objects don't self-collide.
- Cache query results when they don't need per-frame freshness.
## 10. Determinism & Networking
- Game server physics: authoritative; clients never simulate physics that matters for gameplay.
- Replays: log the *input stream* + fixed-step physics; deterministic engines can reproduce.
- Float determinism: same binary across all clients; avoid `sqrt` in solver hot paths where precision differs (or order-preserve).
- Lockstep (RTS): same inputs ticked identically; requires tick-aligned inputs with delay.
## 11. Tuning Cheat-Sheet
| Symptom | Fix |
|---------|-----|
| Jittery stack of boxes | warm-starting missing; iterations too low (>=8) |
| Tunneling bullets | CCD or substeps for fast bodies |
| Ragdoll explodes | solver iterations low; joints wrong axes; dt too big |
| Character sinks in floor | max step vs penetration resolution mismatch; reproject |
| Spinning car on apex | angular damping missing; inertia too low |
| Non-deterministic replays | map iteration + warm-start order |
| Sleeping bodies never wake | wake threshold too high |
## 12. Engine Comparison (when to choose what)
| Engine | Strengths | Weaknesses |
|--------|-----------|-----------|
| **PhysX** (NVIDIA, BSD-3 open source) | proven, fast, GPU features; Unity's built-in 3D physics | engine wrappers (Unity) hide most solver controls |
| **Jolt** (MIT; by Jorrit Rouwe, used in Horizon Forbidden West; Godot's default 3D engine since 4.6) | multithreaded, fast, optional cross-platform determinism build | younger ecosystem than PhysX |
| **Bullet** | open source (zlib), widely embedded | little active development; older API |
| **Box2D** (v3: C API, multithreaded, SIMD) | de facto standard 2D solver; small, fast | 2D only |
| Unity Physics / Havok Physics for Unity | ECS-native, Burst-compiled, stateless (Unity Physics) | requires the Entities stack |
## 13. References
- `skills/game/game-engine/patterns/SKILL.md` — engine patterns (game loop, fixed timestep)
- `skills/game/game-engine/patterns/references/spatial-partitioning.md` — broad-phase data structures
- `skills/game/game-engine/ecs-pattern/SKILL.md` — ECS storage relevant to physics hotspots
- `skills/game/game-engine/ecs-pattern/references/ecs-netcode.md` — deterministic sim across the wire
- `skills/game/multiplayer-netcode/SKILL.md` — server-authoritative simulation
Wersje
W bazie nie ma innych skilli o nazwie physics-engine.
Migawka bazy z 13.11.2026 · wersja paczki 3b420a8c27d7 (skrót SHA-256 całej paczki)
Pobrania w ostatnich 30 dniach: 0 · ranking
Zgłoś problem z tym skillem: szkodliwa treść, błędny opis albo prośba autora o usunięcie.
Podobne skille
- 100ue-physics-collision
Konfiguruje kanały i profile kolizji, zapytania line, sweep i overlap, zdarzenia hit i overlap oraz symulację brył sztywnych w Unreal Engine C++. - 90threejs-physics
Dodaje fizykę brył sztywnych w three.js i R3F przez Rapier: kolizje, ciała dynamiczne i kinematyczne oraz kontrolery postaci. - 100physics-tuning
Stroi fizykę gier pod stabilny, dobrze odczuwalny ruch: stały i zmienny krok czasowy, interpolacja, masa i grawitacja, CCD przeciw tunelowaniu, drgania oraz warstwy kolizji. - 100physics-matter
Obejmuje fizykę Matter.js w Phaser 4: ciała sztywne, ograniczenia, ciała złożone, czujniki, filtrowanie kolizji, konfigurację świata i niestandardowe kształty fizyczne. - 90godot-physics-3d
Podpowiada fizykę 3D w Godot: ragdolle, złącza, optymalizację raycastów i warstwy kolizji przy silniku Jolt lub PhysX. - 100gamedev-physics
Pomaga w fizyce silnika gier: bryły sztywne, collidery, warstwy kolizji, kontrolery postaci, siły i impulsy, raycasty oraz niestabilne symulacje (tunelowanie, drgania) w Godot, Unity i Unreal.