Physics2D Plugin & Box2D Bridge
Relevant source files
The following files were used as context for generating this wiki page:
- pkg/plugin/physics2d/proto/pkg/plugin/physics2d/component/component.proto
- pkg/plugin/physics2d/plugin.go
- pkg/plugin/physics2d/system/pipeline.go
- pkg/plugin/physics2d/internal/cbridge/bridge.go
- pkg/plugin/physics2d/internal/cbridge/bridge.h
- pkg/plugin/physics2d/README.md
- pkg/plugin/physics2d/test/cardinal_integration_test.go
The Physics2D plugin integrates the Box2D v3 physics engine into the Cardinal gamechain SDK. It provides a deterministic simulation environment where all physics state lives on the C side, controlled and synchronized by Cardinal's Entity Component System (ECS). The plugin manages the lifecycle of rigid bodies, colliders, and collision events, ensuring that the C-side simulation stays in sync with Go-side component data.
This system utilizes a specialized C bridge (cbridge) to handle cross-language communication via CGO. It maps Cardinal Entity IDs to Box2D body userdata, allowing systems to perform queries like raycasting or AABB overlaps against the live simulation world.
Sources: pkg/plugin/physics2d/README.md, pkg/plugin/physics2d/plugin.go:1-32
Core Components and Enrollment
An entity participates in physics simulation only when it possesses a specific set of three components. If any component is missing, the reconciler ignores the entity and no corresponding body exists in the Box2D world.
| Component | Description |
|---|---|
Transform2D | Stores world-space position and rotation. This is the authoritative pose for the entity. |
Velocity2D | Contains linear and angular velocity vectors. |
PhysicsBody2D | Defines the body type, damping, gravity scale, and a list of ColliderShape objects. |
Sources: pkg/plugin/physics2d/README.md, pkg/plugin/physics2d/proto/pkg/plugin/physics2d/component/component.proto:47-75
Physics Body Types
The plugin supports four distinct body types that determine how simulation and writeback behave:
BodyTypeStatic: Immovable geometry. The simulation never updates these entities; they provide collision boundaries.BodyTypeDynamic: Fully simulated bodies affected by forces, gravity, and collisions. The pipeline writes new positions and velocities back to the ECS.BodyTypeKinematic: Velocity-driven bodies. Box2D integrates their position based on velocity, and the pipeline writes results back to the ECS.BodyTypeManual: Gameplay logic owns the position and velocity. Box2D only performs contact detection. The reconciler pushes ECS data to Box2D every tick, but Box2D never writes back to the ECS.
Sources: pkg/plugin/physics2d/README.md, pkg/plugin/physics2d/internal/cbridge/bridge.h:71-74
The Physics Pipeline
The PhysicsPipelineSystem executes as an atomic unit during the cardinal.PreUpdate hook. This ensures that the simulation completes before standard gameplay logic runs in the same tick.
The diagram shows the sequential flow of data from the ECS to the physics engine and back.
Pipeline Phases
- Reconcile: The system compares the current ECS state with the "shadow" state of the Box2D world. It creates new bodies, destroys orphaned bodies, and updates properties (like damping or shape filters) for existing bodies.
- Step: The system advances the Box2D world by a fixed time step (
FixedDT). This phase utilizes a two-phase CGO call to prevent event loss. - Writeback: Post-simulation positions and velocities for Dynamic and Kinematic bodies are written back to their respective ECS components.
Sources: pkg/plugin/physics2d/system/pipeline.go:56-116, pkg/plugin/physics2d/test/cardinal_integration_test.go:420-435
Box2D C Bridge (cbridge)
The bridge facilitates high-performance communication between Go and the Box2D C library. Identity is maintained by encoding the Cardinal EntityID into the Box2D body's userdata pointer.
Two-Phase Stepping
To ensure structural stability and prevent dropping contact events, cbridge splits the simulation step into two distinct CGO calls:
- Advance: Executes
b2World_Stepand returns the exact number of bodies moved and contact events generated. - Drain: Go allocates exactly sized buffers based on the counts from the Advance phase. The Drain call then copies the body states and events into these Go-side buffers.
The sequence diagram illustrates the handoff between Go and C to maintain memory safety and event integrity.
Sources: pkg/plugin/physics2d/internal/cbridge/bridge.go:214-250, pkg/plugin/physics2d/internal/cbridge/bridge.h:173-192
Query API
The plugin exposes built-in queries that allow systems to inspect the physics world without mutating state. These queries return results only if a C-side world exists (i.e., after the first reconcile).
| Query | Parameters | Returns |
|---|---|---|
Raycast | Origin, End, Filter | Closest hit (Entity, Shape Index, Position, Normal). |
OverlapAABB | Min, Max, Filter | List of all distinct (Entity, Shape Index) pairs overlapping the box. |
CircleSweep | Start, End, Radius, Filter | Earliest hit along the sweep path. |
Filters: Queries can include or exclude sensors and use bitmasks to target specific collision categories. By default, queries skip sensors and match all categories.
Sources: pkg/plugin/physics2d/plugin.go:88-118, pkg/plugin/physics2d/test/cardinal_integration_test.go:338-350
Contact and Trigger Events
Physics simulation produces events when shapes start or stop touching. These flow through Cardinal's system-event bus.
Event Types
ContactBeginEvent/ContactEndEvent: Fired when solid (non-sensor) colliders interact.TriggerBeginEvent/TriggerEndEvent: Fired when at least one shape in the pair is marked asIsSensor.
Each event includes the EntityID and ShapeIndex for both participants, allowing gameplay logic to identify which specific part of a compound collider caused the event.
Sources: pkg/plugin/physics2d/README.md, pkg/plugin/physics2d/proto/pkg/plugin/physics2d/component/component.proto:32-45
Usage and Configuration
The plugin is registered with a Config struct that defines the global simulation parameters.
cardinal.RegisterPlugin(world, physics2d.NewPlugin(physics2d.Config{
Gravity: physics2d.Vec2{X: 0, Y: -9.8},
TickRate: 60, // Should match Cardinal's TickRate
SubStepCount: 4, // Higher counts increase accuracy/stability
}))
Runtime Reset: Call physics2d.ResetRuntime() during snapshot restoration or world initialization. This discards all C-side state, forcing the next PreUpdate to perform a FullRebuildFromECS to ensure the simulation matches the restored component data.
Sources: pkg/plugin/physics2d/plugin.go:133-163, pkg/plugin/physics2d/README.md