World Simulation¶
This section provides a narrative introduction to the physical world of the life simulation game, documenting the mathematical models and physical phenomena that govern the behavior of entities, terrain, and matter. These equations are not theoretical—they are extracted from the active simulation code and represent the actual forces shaping the virtual world.
The Simulated World¶
The game world is a three-dimensional voxel-based environment where every cubic meter of space can contain terrain, water, vapor, biomass, or entities. Unlike static tile-based games, this simulation implements continuous physics where matter flows, heat transfers, objects fall, and energy transforms according to real physical principles.
Design Philosophy: The simulation draws inspiration from Dwarf Fortress’s emergent complexity while maintaining real-time performance through careful optimization. Static terrain data lives in sparse OpenVDB grids (memory-efficient), while dynamic behavior activates ECS entities on-demand (computation-efficient).
Spatial Structure:
Grid Storage: Sparse OpenVDB grids store only non-default values
Activation Model: Terrain transitions from “cold storage” (VDB-only) to “hot” (ECS entity) when exhibiting dynamic behavior
Thread Safety: Thread-local accessor caches enable O(1) concurrent voxel access
Units and Measurement¶
The simulation uses a consistent system of units based on the International System (SI) with game-specific adaptations. All physical equations in this document use these units unless otherwise specified.
Base Units¶
Spatial Units
Length: meter (m)
Voxel Resolution: 1 voxel = 1 cubic meter (1 m³)
Coordinate System: Right-handed Cartesian (x=East, y=South, z=Up)
Volume: cubic decimeters (dm³) for matter quantities
1 voxel = 1 m³ = 1000 dm³
Water/terrain matter stored in dm³ units for finer granularity
Temporal Units
Real-time: seconds (s)
Game Time Scale:
lifesim/time_manager.py1 game minute = 10 real seconds (6× speed)
1 game hour = 10 real minutes (debug mode)
1 game day = 4 real hours
1 game year = 4 real months
Physics Timestep: Variable \(\Delta t\) (typically 16.67 ms for 60 FPS)
Mass Units
Mass: kilograms (kg)
Entity Mass: Stored in
PhysicsStats.mass(include/components.hpp:30-35)Density Reference: Water = 1000 kg/m³ (1 kg/dm³)
Matter Quantities: Dimensionless units (approximately dm³ equivalent)
Thermal Units
Temperature: Kelvin (K) or context-dependent scale
Heat: Stored as dimensionless thermal energy in
PhysicsStats.heat(include/components.hpp:34)Heat Thresholds:
Evaporation: \(Q \geq 120.0\) (arbitrary units)
Condensation: Function of altitude and temperature
Heat Transfer Coefficients:
\(c_{evap} = 0.000002\) (heat per matter unit evaporated)
\(c_{cond} = 0.000002\) (heat per matter unit condensed)
Note: The simulation uses a simplified thermal model where heat is a scalar quantity without explicit temperature calculations. Heat thresholds trigger phase transitions rather than modeling precise thermodynamic states.
Derived Units¶
Kinematic Quantities
Velocity: meters per second (m/s)
Stored in
Velocitycomponent as \((v_x, v_y, v_z)\) (include/components.hpp:16-20)Speed magnitude: \(|\mathbf{v}| = \sqrt{v_x^2 + v_y^2 + v_z^2}\) (m/s)
Acceleration: meters per second squared (m/s²)
Gravity: \(g = 5.0 \, \text{m/s}^2\) (default)
Friction: \(a_f = \mu g = 5.0 \, \text{m/s}^2\) (with \(\mu = 1.0\))
Dynamic Quantities
Force: Newtons (N = kg⋅m/s²)
Applied through
translateAcceleration(force, ...)(src/physics_manager.cpp)Maximum force:
PhysicsStats.maxForce(N)
Momentum: kilogram-meters per second (kg⋅m/s)
\(\mathbf{p} = m \mathbf{v}\)
Conserved in collision systems
Energy: Joules (J = kg⋅m²/s²)
Kinetic energy: \(E_k = \frac{1}{2} m v^2\)
Potential energy: \(E_p = m g h\)
Energy cost per force: 0.000002 J (metabolism) (
src/physics_manager.cpp:36)
Flow and Matter
Matter Flow Rate: cubic decimeters per second (dm³/s)
Evaporation rate: \(\dot{m} = k_{evap} \cdot I_{sun}\) where \(k_{evap} = 8.0 \, \text{dm}^3/\text{s}\)
Water flow: Pressure-gradient driven (cellular automata)
Pressure: Pascals (Pa = N/m² = kg/(m⋅s²))
\(P = \rho g h + m_{water}\) (simplified hydrostatic model)
Used for flow direction determination
Special Conversions¶
Voxel Space ↔ World Space
// Voxel coordinates (discrete)
int vx = 10, vy = 20, vz = 5;
// World coordinates (continuous, in meters)
float wx = vx * 1.0f; // 10.0 m
float wy = vy * 1.0f; // 20.0 m
float wz = vz * 1.0f; // 5.0 m
Matter Quantity Interpretation
// Water in voxel (cubic decimeters)
int waterMatter = 500; // 500 dm³ = 0.5 m³ (half-full voxel)
// Mass of water (assuming density = 1 kg/dm³)
float mass_kg = waterMatter * 1.0f; // 500 kg
Time Dilation
// Real-time physics timestep
float dt_real = 0.01667f; // 16.67 ms (60 FPS)
// Game-time advancement
float game_minutes = dt_real * 6.0f; // 6× speedup
Unit Consistency in Equations¶
All equations in this document maintain dimensional consistency. For example:
Velocity Update:
Dimensional Analysis:
Force to Acceleration:
Readers can verify that all physical equations in subsequent sections are dimensionally correct using these base and derived units.
Kinematics & Dynamics¶
Motion in the simulated world follows classical Newtonian mechanics, implemented through discrete-time integration with fixed timesteps.
Position and Velocity¶
Every mobile entity has a Position component \(\mathbf{r} = (x, y, z)\) and Velocity component \(\mathbf{v} = (v_x, v_y, v_z)\).
Position Update (src/movement_system.cpp):
Speed Magnitude:
Implementation Details:
Time-to-move calculation: \(t_{move} = \frac{100.0}{|\mathbf{v}|}\) (time to traverse 100 voxels)
Movement completes when \(t_{elapsed} \geq t_{move}\)
Grid-aligned movement with smooth interpolation for rendering
Acceleration and Force¶
Forces modify velocity through acceleration according to Newton’s second law.
Velocity Update (src/physics_manager.cpp):
Translation Function (src/physics_manager.cpp:154-204):
The translateAcceleration function applies force-derived acceleration with speed limits:
// Acceleration magnitude bounded by entity's PhysicsStats
float accel = std::min(force, physicsStats.maxForce) / physicsStats.mass;
// Speed clamping
if (speed > maxSpeed) {
velocity *= (maxSpeed / speed); // Scale down to limit
}
if (speed < minSpeed && speed > 0) {
velocity = 0; // Stop if below minimum threshold
}
Multi-axis vs Single-axis Movement:
Multi-axis mode (
settings.py-ALLOW_DIAGONAL_MOVEMENT = True):All axes receive proportional acceleration
Diagonal movement penalty: \(v_{effective} = \frac{v}{1.414}\) when moving on multiple axes
Single-axis mode:
Only dominant axis (largest \(|v_i|\)) receives acceleration
Forces entity to align with cardinal directions
Gravity¶
Gravitational acceleration affects all entities with mass when not supported by solid terrain.
Gravity Force (src/movement_system.cpp:493-521):
where \(g = 5.0 \, \text{m/s}^2\) (configurable via PhysicsManager::getGravity()).
Velocity Update:
Fall Detection (src/movement_system.cpp:497):
// Entity falls if voxel below is empty or water (non-solid)
bool isFalling = !voxelGrid->hasTerrainAt(x, y, z-1) ||
terrainBelow.mainType == WATER;
Ground Contact: Velocity is zeroed when the entity contacts solid terrain (\(v_z\) changes sign), preventing bouncing.
Design Note: Default gravity is \(5.0 \, \text{m/s}^2\) for gameplay balance, though design documents reference Earth’s \(g = 9.81 \, \text{m/s}^2\) (settings.py:13).
Friction¶
Kinetic friction opposes motion when entities are in contact with surfaces.
Friction Force (src/movement_system.cpp:538-567):
where:
\(\mu = 1.0\) is the coefficient of friction (
PhysicsManager::getFriction())\(m\) is entity mass
\(g\) is gravitational acceleration
\(\hat{\mathbf{v}} = \frac{\mathbf{v}}{|\mathbf{v}|}\) is the velocity direction
Acceleration due to Friction:
With default values (\(\mu = 1.0\), \(g = 5.0\)):
Friction Application (src/movement_system.cpp:555):
// Only apply friction if entity is on stable ground
if (entity.isOnGround && entity.velocity.length() > 0) {
float frictionAccel = friction * gravity;
velocity -= frictionAccel * velocityDirection * deltaTime;
// Stop if friction would reverse direction
if (velocity.dot(oldVelocity) < 0) {
velocity = {0, 0, 0};
}
}
Stopping Condition: Entity stops moving when friction would reverse velocity direction, preventing oscillation.
Thermodynamics & Phase Transitions¶
The simulation implements a complete water cycle with phase transitions driven by thermal energy transfer.
Matter Containers¶
Each voxel contains a MatterContainer storing quantities of different matter types (include/components.hpp:85-90):
terrainMatter: Solid terrain (cubic decimeters)waterMatter: Liquid water (cubic decimeters)vaporMatter: Water vapor/steam (cubic decimeters at STP equivalent)biomassMatter: Organic material (cubic decimeters)
Conservation Law: Total matter is conserved across phase transitions:
Evaporation (Endothermic)¶
Liquid water absorbs thermal energy to transition to vapor when exposed to heat and air.
Evaporation Conditions (src/matter_physics_system.cpp:189-240):
\(Q \geq Q_{evap} = 120.0\) (heat threshold)
\(m_{water} \geq m_{min} = 120,000\) units (minimum water quantity)
Voxel exposed to air (not submerged)
Evaporation Rate:
where:
\(k_{evap} = 8.0\) is the evaporation coefficient (
EVAPORATION_COEFFICIENT)\(I_{sun} \in [0, 1]\) is solar intensity (time-of-day dependent)
Matter Transfer:
Energy Absorption (src/matter_physics_system.cpp:234):
where \(c_{evap} = 0.000002\) is heat absorbed per unit evaporated (HEAT_PER_EVAPORATION).
Physical Interpretation: Evaporation is endothermic—water absorbs heat from the voxel, cooling it. This implements latent heat of vaporization.
Condensation (Exothermic)¶
Water vapor releases thermal energy when cooling below saturation capacity, forming liquid water.
Saturation Model (src/matter_physics_system.cpp:242-295):
Vapor capacity decreases with:
Altitude: Higher elevations hold less vapor (lower pressure)
Temperature: Cooler air holds less vapor
Condensation Threshold:
where \(m_{sat}\) is the saturation capacity function.
Matter Transfer:
Energy Release (src/matter_physics_system.cpp:289):
where \(c_{cond}\) is heat released per unit condensed.
Physical Interpretation: Condensation is exothermic—vapor releases heat to the voxel, warming it. This implements latent heat of condensation.
Conservation of Energy: Over a complete evaporation-condensation cycle:
Precipitation (Rain)¶
Liquid water at high altitude falls as rain when \(z > z_{ground}\) and no support exists below.
Rain Physics (src/matter_physics_system.cpp:297-340):
Free Fall: Water accelerates downward under gravity
Terminal Velocity: Drag limits maximum fall speed
Ground Impact: Kinetic energy converts to:
Thermal energy (heating ground)
Lateral splash (momentum redistribution)
Simplified Model:
capped at terminal velocity \(v_{term} \approx 9 \, \text{m/s}\) for water droplets.
Fluid Dynamics (Water Flow)¶
Water flows through terrain following pressure gradients, implemented as cellular automata for real-time performance.
Pressure Model (src/matter_physics_system.cpp:342-450):
where:
\(\rho\) is water density
\(h\) is height of water column above
\(m_{water}\) is local water quantity
Flow Direction: Water moves down pressure gradients:
Flow Priority:
Downward (gravity): \(\Delta z < 0\) always preferred
Lateral (equilibrium): \(\Delta x, \Delta y\) when heights equalize
Parallel Implementation (src/matter_physics_system.cpp:150-187):
World divided into 32³ voxel boxes
Each box processed in parallel thread
Thread-local OpenVDB accessors eliminate locking
Conservative transfer: mass balanced across box boundaries
Structural Mechanics¶
Entities and terrain possess structural properties that govern stacking, collapse, and matter state behaviors.
Matter States¶
The MatterState enum (include/components.hpp:60-65) defines four phases:
enum struct MatterState {
SOLID = 1, // Subject to gravity, friction, collision
LIQUID = 2, // Flows, gravity, no ground friction
GAS = 3, // Diffuses, buoyant, no gravity/friction
PLASMA = 4 // Not implemented
};
Behavioral Differences:
State |
Gravity |
Friction |
Collision |
Flow |
|---|---|---|---|---|
SOLID |
Yes |
Yes |
Full |
No |
LIQUID |
Yes |
No |
Partial |
Yes |
GAS |
No* |
No |
No |
Diffusion |
PLASMA |
TBD |
TBD |
TBD |
TBD |
*Gas experiences buoyancy (negative effective gravity)
Structural Integrity¶
The StructuralIntegrityComponent (include/components.hpp:113-118) defines load-bearing properties:
struct StructuralIntegrityComponent {
bool canStackEntities; // Can others stand on this?
int maxLoadCapacity; // Max weight (-1 = infinite)
MatterState matterState; // SOLID/LIQUID/GAS/PLASMA
GradientVector gradientVector; // Terrain slope (gx, gy, gz)
};
Stacking Rules:
Entity can stand on voxel if:
canStackEntities == trueANDcurrentLoad + entityMass ≤ maxLoadCapacityTerrain collapse occurs when:
currentLoad > maxLoadCapacityInfinite capacity (
maxLoadCapacity = -1): Bedrock, stone, most solid terrain
Terrain Slopes and Ramps¶
Terrain supports non-block shapes through gradient vectors and subtype variants.
Terrain Variants (include/voxel.hpp:48-64):
FLAT(0): Standard cubeRAMP_EAST(1): Slope rising eastward (+x)RAMP_WEST(2): Slope rising westward (-x)RAMP_SOUTH(7): Slope rising southward (+y)RAMP_NORTH(8): Slope rising northward (-y)CORNER_*: Various corner configurations
Gradient Vector (include/components.hpp:68-72):
struct GradientVector {
int8_t gx; // X-axis slope (-1, 0, +1)
int8_t gy; // Y-axis slope (-1, 0, +1)
int8_t gz; // Z-axis slope (-1, 0, +1)
};
Movement on Slopes (src/movement_system.cpp:340-385):
When entity moves onto a ramp, target Z-coordinate adjusts:
This enables smooth “step-up” behavior without explicit climbing mechanics.
Physical Constants Reference¶
This section catalogs all physical parameters used in the simulation, extracted from source code.
Global Physics Parameters¶
Defined in src/physics_manager.cpp and include/physics_manager.hpp:
Parameter |
Symbol |
Value |
Description |
|---|---|---|---|
Gravitational Acceleration |
\(g\) |
5.0 m/s² |
Default gravity (configurable) |
Friction Coefficient |
\(\mu\) |
1.0 |
Kinetic friction for ground contact |
Allow Diagonal Movement |
— |
|
Permits multi-axis acceleration |
Diagonal Speed Penalty |
— |
\(1/\sqrt{2}\) |
Applied when moving on multiple axes |
Energy Cost per Force |
— |
0.000002 |
Metabolism cost for acceleration |
Thermodynamic Constants¶
Defined in src/matter_physics_system.cpp and include/matter_physics_system.hpp:
Parameter |
Symbol |
Value |
Description |
|---|---|---|---|
Evaporation Coefficient |
\(k_{evap}\) |
8.0 |
Rate multiplier for evaporation |
Heat Threshold (Evaporation) |
\(Q_{evap}\) |
120.0 |
Minimum heat for water evaporation |
Minimum Water for Evaporation |
\(m_{min}\) |
120,000 units |
Prevents trace water evaporation |
Heat per Evaporation |
\(c_{evap}\) |
0.000002 |
Energy absorbed per unit evaporated |
Condensation Threshold |
\(m_{sat,min}\) |
21 units |
Minimum vapor for condensation |
Heat per Condensation |
\(c_{cond}\) |
0.000002 |
Energy released per unit condensed |
Ecosystem Constants¶
Defined in src/matter_physics_system.cpp and related files:
Parameter |
Symbol |
Value |
Description |
|---|---|---|---|
Grid Box Size |
— |
32³ voxels |
Parallel processing partition size |
Water per Photosynthesis |
— |
0.1 |
Water consumed per biomass created |
Energy Production Rate |
— |
6.0 |
Energy generated per photosynthesis |
Max Task Priority |
— |
1000 |
Task scheduler cap |
Priority Aging |
— |
-10 |
Priority reduction per cycle |
Rendering Constants¶
Defined in settings.py:
Parameter |
Symbol |
Value |
Description |
|---|---|---|---|
Target Frame Rate |
— |
60 FPS |
Rendering target |
Voxel Render Size |
— |
32 pixels |
Screen space per voxel |
Design Gravity (Reference) |
\(g_{Earth}\) |
9.81 m/s² |
Not used in runtime physics |
Game Time Scale¶
Defined in lifesim/time_manager.py:
Game Time Unit |
Real-time Equivalent |
|---|---|
1 game minute |
10 real seconds |
1 game hour |
10 real minutes (debug mode) |
1 game day |
24 game hours |
1 game month |
28 days |
1 game year |
4 months |
Connection to Architecture¶
This document describes the physical models governing the simulation. For implementation details of how these models are encoded in the system architecture, see:
Architecture Overview: System Architecture - Complete system architecture including storage layers, coordination mechanisms, and data flow patterns
Physics Engine: Physics Engine - Implementation details of movement and collision
Ecosystem Engine: Ecosystem Engine - Implementation of water cycle and matter flow
Concurrency: Concurrency & Threading - Parallel processing strategies for physics simulation
Performance: Performance & Bottlenecks - Optimization techniques and benchmarking
The mathematical models here are realized through carefully orchestrated component systems (VoxelGrid, TerrainGridRepository, TerrainStorage), spatial indexing (OpenVDB grids), and lazy activation patterns documented in the architecture guide.