This document details the integration of the Rapier physics engine within the Vibe Coder 3D core framework.
- Dependencies: Integration relies on
rapier3d-compatand@react-three/rapier. - Setup: The Rapier physics world is initialized and managed within the main React Three Fiber render loop, handled through
@react-three/rapier's<Physics>component. - Synchronization: Physics simulation runs independently and needs synchronization with the Three.js scene graph and ECS system.
The engine provides multiple physics components for different use cases:
-
<PhysicsBody>: Enhanced physics body component insrc/core/components/physics/PhysicsBody.tsxwith comprehensive API:- Automatic ECS integration with entity creation
- Support for all Rapier body types (dynamic, kinematic, fixed)
- Material property configuration (friction, restitution, density)
- Imperative handle for external control
- Debug and metadata support
-
<PhysicsObject>: Base component insrc/core/components/physics/PhysicsObject.tsxfor simple physics integration:- Wraps
@react-three/rapier'sRigidBody - Automatic ECS entity creation and registration
- Basic collision handling
- Wraps
-
<PhysicsTrigger>: Non-solid trigger zones insrc/core/components/physics/PhysicsTrigger.tsx:- Creates sensor colliders for detection zones
- Integrates with ECS system for entity tracking
- Supports enter/exit event callbacks
-
<PhysicsBall>: Specialized ball physics insrc/core/components/physics/PhysicsBall.tsx:- Optimized for spherical objects
- Configurable physics properties (mass, restitution, damping)
- Built-in visual representation
-
<PhysicsJoint>: Joint system insrc/core/components/physics/PhysicsJoint.tsx:- Supports revolute, fixed, and spherical joints
- Connects multiple physics bodies
- Configurable joint parameters
<PhysicsObjectFactory>: Factory component for creating common physics objects<TaggablePhysicsObject>: Physics objects with tagging system for state management<PhysicsSystem>: System component that initializes physics integration
-
PhysicsBodyRef Component: Defined in
src/core/systems/PhysicsSyncSystem.ts, stores references to physics bodies:export const PhysicsBodyRef = defineComponent({ bodyId: Types.ui32, // Store an ID for body lookup isActive: Types.ui8, // Flag for active simulation priority: Types.ui8, // Update priority });
-
Registration System: Physics bodies are registered with the ECS using:
registerPhysicsBody(entityId, rigidBody): Links physics body to ECS entityunregisterPhysicsBody(entityId): Removes physics-ECS link
-
PhysicsSyncSystem: Synchronizes transforms between physics bodies and ECS entities:
- Queries entities with both Transform and PhysicsBodyRef components
- Updates ECS Transform data from physics body positions/rotations
- Handles bidirectional synchronization when needed
usePhysics(): Comprehensive physics utilities insrc/core/lib/physics.ts:- Access to Rapier world and API
- Raycasting utilities (
raycast,raycastAll) - Shape creation helpers (
createShape) - Material application (
applyMaterial) - Body manipulation utilities (forces, impulses, velocities)
useCollisionEvents(): Collision event management insrc/core/hooks/useCollisionEvents.ts:- Subscribe to collision enter/exit events
- Sensor event handling
- Entity-based event filtering
usePhysicsSystem(): System-level physics integrationPhysicsWorld: Wrapper component providing physics context and lighting
// Simple physics-enabled object
<PhysicsBody bodyType="dynamic" position={[0, 5, 0]}>
<mesh>
<boxGeometry />
<meshStandardMaterial />
</mesh>
</PhysicsBody>// Advanced physics body with custom properties
<PhysicsBody
bodyType="dynamic"
material={{ friction: 0.8, restitution: 0.6 }}
mass={2.5}
autoRegister={true}
debug={true}
>
<mesh>
<sphereGeometry />
<meshStandardMaterial />
</mesh>
</PhysicsBody>// Non-solid trigger for detection
<PhysicsTrigger
position={[0, 0, 0]}
size={[2, 2, 2]}
onEnter={(entityId) => console.log('Entity entered:', entityId)}
onExit={(entityId) => console.log('Entity exited:', entityId)}
/>EditorPhysicsIntegration: Component insrc/editor/components/physics/that manages physics in editor context:- Handles play/pause state for physics simulation
- Creates physics bodies for entities with RigidBody components
- Manages physics body lifecycle in editor mode
- Visual Debugger: Integration with
@react-three/rapier's<Debug />component for visualizing colliders and physics interactions - Performance Monitoring: Physics body tracking and performance metrics
- State Inspection: Access to physics body properties and simulation state
The physics world runs its simulation steps, and the results are synchronized with both the visual representation and the ECS system:
sequenceDiagram
participant GameLoop
participant PhysicsWorld
participant PhysicsSyncSystem
participant ECSSystems
participant ThreeScene
loop Frame Update
GameLoop->>PhysicsWorld: Step simulation (world.step())
PhysicsWorld-->>PhysicsWorld: Calculate new positions/rotations
GameLoop->>PhysicsSyncSystem: Run PhysicsSyncSystem
PhysicsSyncSystem->>PhysicsWorld: Read updated body transforms
PhysicsSyncSystem->>ECSSystems: Update ECS Transform components
GameLoop->>ECSSystems: Run other ECS systems
ECSSystems->>ThreeScene: Update visual object transforms
ThreeScene-->>GameLoop: Render updated scene
end
- Body Management: Efficient registration/unregistration of physics bodies
- Update Prioritization: Priority-based updates for performance-critical objects
- Collision Optimization: Efficient collision detection and event handling
- Memory Management: Proper cleanup of physics resources and ECS entities