# Cargo.toml
[package]
name = "deterministic-physics"
version = "0.1.0"
edition = "2021"
[dependencies]
approx = "0.5" # For non-determinism tolerance tests if needed
[dev-dependencies]
approx = "0.5"
rust
// src/lib.rs
use std::ops::{Add, AddAssign, Mul, Sub, SubAssign};
/// A deterministic 2D vector using f32 with explicit scalar operations for reproducibility.
#[derive(Copy, Clone, Debug, Default, PartialEq)]
pub struct Vec2 {
pub x: f32,
pub y: f32,
}
impl Vec2 {
pub const ZERO: Vec2 = Vec2 { x: 0.0, y: 0.0 };
pub fn new(x: f32, y: f32) -> Self {
Self { x, y }
}
pub fn dot(self, other: Vec2) -> f32 {
self.x * other.x + self.y * other.y
}
pub fn length(self) -> f32 {
f32::sqrt(self.dot(self))
}
pub fn length_squared(self) -> f32 {
self.dot(self)
}
/// Normalizes if length > 0.
pub fn normalize(self) -> Vec2 {
let len_sq = self.length_squared();
if len_sq > 0.0 {
let inv_len = 1.0 / f32::sqrt(len_sq);
self * inv_len
} else {
Vec2::ZERO
}
}
}
impl Add for Vec2 {
type Output = Vec2;
fn add(self, rhs: Vec2) -> Vec2 {
Vec2::new(self.x + rhs.x, self.y + rhs.y)
}
}
impl<'a, 'b> Add<&'b Vec2> for &'a Vec2 {
type Output = Vec2;
fn add(self, rhs: &'b Vec2) -> Vec2 {
Vec2::new(self.x + rhs.x, self.y + rhs.y)
}
}
impl AddAssign for Vec2 {
fn add_assign(&mut self, rhs: Vec2) {
self.x += rhs.x;
self.y += rhs.y;
}
}
impl<'a> AddAssign<&'a Vec2> for Vec2 {
fn add_assign(&mut self, rhs: &'a Vec2) {
self.x += rhs.x;
self.y += rhs.y;
}
}
impl Sub for Vec2 {
type Output = Vec2;
fn sub(self, rhs: Vec2) -> Vec2 {
Vec2::new(self.x - rhs.x, self.y - rhs.y)
}
}
impl<'a, 'b> Sub<&'b Vec2> for &'a Vec2 {
type Output = Vec2;
fn sub(self, rhs: &'b Vec2) -> Vec2 {
Vec2::new(self.x - rhs.x, self.y - rhs.y)
}
}
impl SubAssign for Vec2 {
fn sub_assign(&mut self, rhs: Vec2) {
self.x -= rhs.x;
self.y -= rhs.y;
}
}
impl Mul<f32> for Vec2 {
type Output = Vec2;
fn mul(self, rhs: f32) -> Vec2 {
Vec2::new(self.x * rhs, self.y * rhs)
}
}
impl Mul<Vec2> for f32 {
type Output = Vec2;
fn mul(self, rhs: Vec2) -> Vec2 {
rhs * self
}
}
impl<'a> Mul<f32> for &'a Vec2 {
type Output = Vec2;
fn mul(self, rhs: f32) -> Vec2 {
Vec2::new(self.x * rhs, self.y * rhs)
}
}
/// Trait for force models that accumulate forces on particles.
pub trait ForceModel {
fn accumulate_forces(
&self,
positions: &[Vec2],
velocities: &[Vec2],
inv_masses: &[f32],
forces: &mut [Vec2],
);
}
/// Uniform gravitational field.
#[derive(Clone, Copy, Debug)]
pub struct Gravity {
pub g: Vec2, // acceleration due to gravity
}
impl Gravity {
pub fn new(g: Vec2) -> Self {
Self { g }
}
}
impl ForceModel for Gravity {
fn accumulate_forces(
&self,
_positions: &[Vec2],
_velocities: &[Vec2],
inv_masses: &[f32],
forces: &mut [Vec2],
) {
for (force, &inv_mass) in forces.iter_mut().zip(inv_masses.iter()) {
*force += self.g * inv_mass; // force = m * g = g / inv_mass, but since inv_mass = 1/m, g * (1/inv_mass)? Wait, no:
// m = 1.0 / inv_mass, force = m * g = g / inv_mass
// Correction:
// *force += self.g * (1.0 / inv_mass);
// But since f32 mul assoc, but to be precise:
}
// Fixed: force = m * g = g * m = g * (1.0 / inv_mass)
for (force, &inv_mass) in forces.iter_mut().zip(inv_masses) {
if inv_mass != 0.0 {
*force += self.g * (1.0 / inv_mass);
}
}
}
}
/// Linear drag: force = -coeff * velocity
#[derive(Clone, Copy, Debug)]
pub struct LinearDrag {
pub coeff: f32,
}
impl LinearDrag {
pub fn new(coeff: f32) -> Self {
Self { coeff }
}
}
impl ForceModel for LinearDrag {
fn accumulate_forces(
&self,
_positions: &[Vec2],
velocities: &[Vec2],
_inv_masses: &[f32],
forces: &mut [Vec2],
) {
for (force, &vel) in forces.iter_mut().zip(velocities) {
*force += vel * -self.coeff;
}
}
}
/// Spring constraint between two particles.
#[derive(Clone, Copy, Debug)]
pub struct Spring {
pub i: usize,
pub j: usize,
pub rest_length: f32,
pub stiffness: f32,
pub damping: f32,
}
impl Spring {
pub fn new(i: usize, j: usize, rest_length: f32, stiffness: f32, damping: f32) -> Self {
Self {
i,
j,
rest_length,
stiffness,
damping,
}
}
}
impl ForceModel for Spring {
fn accumulate_forces(
&self,
positions: &[Vec2],
velocities: &[Vec2],
_inv_masses: &[f32],
forces: &mut [Vec2],
) {
if self.i >= positions.len() || self.j >= positions.len() {
return;
}
let p_i = positions[self.i];
let p_j = positions[self.j];
let delta_p = p_j - p_i;
let len = delta_p.length();
if len > 0.0 {
let dir = delta_p * (1.0 / len);
let spring_f = dir * (self.stiffness * (len - self.rest_length));
let v_rel = velocities[self.j] - velocities[self.i];
let damp_f = dir * (-self.damping * dir.dot(v_rel));
let total_f = spring_f + damp_f;
forces[self.i] += total_f;
forces[self.j] -= total_f;
}
}
}
/// Supported numerical integrators.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Integrator {
/// Explicit Euler: unstable for most simulations.
ExplicitEuler,
/// Semi-implicit Euler: symplectic, energy conserving-ish.
SemiImplicitEuler,
/// Runge-Kutta 4: high accuracy, 4 force evaluations.
RK4,
}
/// The main physics world using Structure of Arrays for efficient batch operations.
#[derive(Debug)]
pub struct World {
positions: Vec<Vec2>,
velocities: Vec<Vec2>,
inv_masses: Vec<f32>,
force_models: Vec<Box<dyn ForceModel>>,
integrator: Integrator,
}
impl World {
/// Creates a new empty world with SemiImplicitEuler as default.
pub fn new() -> Self {
Self {
positions: Vec::new(),
velocities: Vec::new(),
inv_masses: Vec::new(),
force_models: Vec::new(),
integrator: Integrator::SemiImplicitEuler,
}
}
/// Adds a particle. Returns its index.
pub fn add_particle(&mut self, position: Vec2, velocity: Vec2, mass: f32) -> usize {
let inv_mass = if mass > 0.0 { 1.0 / mass } else { 0.0 };
let idx = self.positions.len();
self.positions.push(position);
self.velocities.push(velocity);
self.inv_masses.push(inv_mass);
idx
}
/// Adds a force model.
pub fn add_force_model<F>(&mut self, model: F)
where
F: ForceModel + 'static,
{
self.force_models.push(Box::new(model));
}
/// Sets the integrator type.
pub fn set_integrator(&mut self, integrator: Integrator) {
self.integrator = integrator;
}
/// Performs one simulation step.
pub fn step(&mut self, dt: f32) {
if self.positions.is_empty() {
return;
}
match self.integrator {
Integrator::ExplicitEuler => self.integrate_explicit_euler(dt),
Integrator::SemiImplicitEuler => self.integrate_semi_implicit_euler(dt),
Integrator::RK4 => self.integrate_rk4(dt),
}
}
/// Steps multiple times.
pub fn step_many(&mut self, steps: usize, dt: f32) {
for _ in 0..steps {
self.step(dt);
}
}
fn compute_accels(&self, positions: &[Vec2], velocities: &[Vec2]) -> Vec<Vec2> {
let n = positions.len();
let mut forces = vec![Vec2::ZERO; n];
for force_model in &self.force_models {
force_model.accumulate_forces(positions, velocities, &self.inv_masses, &mut forces);
}
let mut accels = vec![Vec2::ZERO; n];
for i in 0..n {
accels[i] = forces[i] * self.inv_masses[i];
}
accels
}
fn integrate_explicit_euler(&mut self, dt: f32) {
let accels = self.compute_accels(&self.positions, &self.velocities);
let n = self.positions.len();
for i in 0..n {
self.positions[i] += self.velocities[i] * dt;
self.velocities[i] += accels[i] * dt;
}
}
fn integrate_semi_implicit_euler(&mut self, dt: f32) {
let accels = self.compute_accels(&self.positions, &self.velocities);
let n = self.positions.len();
for i in 0..n {
self.velocities[i] += accels[i] * dt;
}
for i in 0..n {
self.positions[i] += self.velocities[i] * dt;
}
}
fn integrate_rk4(&mut self, dt: f32) {
let n = self.positions.len();
// k1
let k1_vel = self.compute_accels(&self.positions, &self.velocities);
let k1_vel = k1_vel.iter().map(|&a| a * dt).collect::<Vec<_>>();
let k1_pos = self.velocities.iter().map(|&v| v * dt).collect::<Vec<_>>();
// k2
let tmp_pos2: Vec<Vec2> = self
.positions
.iter()
.zip(&k1_pos)
.map(|(&p, &k)| p + k * 0.5)
.collect();
let tmp_vel2: Vec<Vec2> = self
.velocities
.iter()
.zip(&k1_vel)
.map(|(&v, &k)| v + k * 0.5)
.collect();
let k2_vel = self.compute_accels(&tmp_pos2, &tmp_vel2);
let k2_vel = k2_vel.iter().map(|&a| a * dt).collect::<Vec<_>>();
let k2_pos: Vec<Vec2> = tmp_vel2.iter().map(|&v| v * dt).collect();
// k3
let tmp_pos3: Vec<Vec2> = self
.positions
.iter()
.zip(&k2_pos)
.map(|(&p, &k)| p + k * 0.5)
.collect();
let tmp_vel3: Vec<Vec2> = self
.velocities
.iter()
.zip(&k2_vel)
.map(|(&v, &k)| v + k * 0.5)
.collect();
let k3_vel = self.compute_accels(&tmp_pos3, &tmp_vel3);
let k3_vel = k3_vel.iter().map(|&a| a * dt).collect::<Vec<_>>();
let k3_pos: Vec<Vec2> = tmp_vel3.iter().map(|&v| v * dt).collect();
// k4
let tmp_pos4: Vec<Vec2> = self
.positions
.iter()
.zip(&k3_pos)
.map(|(&p, &k)| p + k)
.collect();
let tmp_vel4: Vec<Vec2> = self
.velocities
.iter()
.zip(&k3_vel)
.map(|(&v, &k)| v + k)
.collect();
let k4_vel = self.compute_accels(&tmp_pos4, &tmp_vel4);
let k4_vel = k4_vel.iter().map(|&a| a * dt).collect::<Vec<_>>();
let k4_pos: Vec<Vec2> = tmp_vel4.iter().map(|&v| v * dt).collect();
// Weighted sum
let w1 = 1.0 / 6.0;
let w2 = 2.0 / 6.0;
let mut delta_pos = vec![Vec2::ZERO; n];
let mut delta_vel = vec![Vec2::ZERO; n];
for i in 0..n {
delta_pos[i] = k1_pos[i] * w1 + k2_pos[i] * w2 + k3_pos[i] * w2 + k4_pos[i] * w1;
delta_vel[i] = k1_vel[i] * w1 + k2_vel[i] * w2 + k3_vel[i] * w2 + k4_vel[i] * w1;
}
// Update
for i in 0..n {
self.positions[i] += delta_pos[i];
self.velocities[i] += delta_vel[i];
}
}
}
/// Testing harness for determinism.
#[cfg(test)]
pub mod testing {
use super::*;
/// Asserts that a simulation is deterministic: runs twice from same setup, compares finals exactly.
pub fn assert_deterministic<F>(mut setup: F, steps: usize, dt: f32)
where
F: FnMut() -> World,
{
let mut world1 = setup();
let init_pos = world1.positions.clone();
let init_vel = world1.velocities.clone();
world1.step_many(steps, dt);
let final_pos1 = world1.positions.clone();
let final_vel1 = world1.velocities.clone();
let mut world2 = setup();
// Verify initial state same
assert_eq!(world2.positions, init_pos);
assert_eq!(world2.velocities, init_vel);
world2.step_many(steps, dt);
assert_eq!(world2.positions, final_pos1);
assert_eq!(world2.velocities, final_vel1);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::testing::assert_deterministic;
use approx::assert_relative_eq;
fn setup_spring_world() -> World {
let mut world = World::new();
let idx0 = world.add_particle(Vec2::new(0.0, 0.0), Vec2::ZERO, 1.0);
let idx1 = world.add_particle(Vec2::new(1.5, 0.0), Vec2::ZERO, 1.0);
world.add_force_model(Gravity::new(Vec2::new(0.0, -9.81)));
world.add_force_model(LinearDrag::new(0.1));
world.add_force_model(Spring::new(idx0, idx1, 1.0, 500.0, 20.0));
world.set_integrator(Integrator::SemiImplicitEuler);
world
}
#[test]
fn determinism_semi_implicit_euler() {
assert_deterministic(setup_spring_world, 1000, 0.001);
}
#[test]
fn determinism_rk4() {
let mut setup = setup_spring_world;
setup.set_integrator(Integrator::RK4);
assert_deterministic(setup, 500, 0.001); // Fewer steps, RK4 expensive
}
#[test]
fn basic_energy_conservation() {
let mut world = setup_spring_world();
let init_ke: f32 = world.velocities.iter().map(|v| 0.5 * v.dot(*v)).sum();
let init_pe: f32 = 0.125; // Approximate initial spring PE
let init_e = init_ke + init_pe;
world.step_many(100, 0.01);
let final_ke: f32 = world.velocities.iter().map(|v| 0.5 * v.dot(*v)).sum();
// PE approx, tolerance
assert_relative_eq!(init_e, final_ke + 0.125, epsilon = 0.1);
}
}
Usage Example (in examples/basic.rs)
rust
use deterministic_physics::*;
fn main() {
let mut world = World::new();
let ground = world.add_particle(Vec2::new(0.0, 0.0), Vec2::ZERO, 1.0); // Fixed, but inv_mass=1
let ball = world.add_particle(Vec2::new(0.0, 5.0), Vec2::new(1.0, 0.0), 1.0);
world.add_force_model(Gravity::new(Vec2::new(0.0, -9.81)));
world.add_force_model(LinearDrag::new(0.05));
world.add_force_model(Spring::new(ground, ball, 5.0, 100.0, 5.0));
world.set_integrator(Integrator::RK4);
for i in 0..1000 {
world.step(0.016); // ~60 FPS
println!("Step {}: ball pos = {:?}", i, world.positions[ball]);
}
}
Key Features & Design Decisions
Cross-platform: Pure Rust, no unsafe, no platform intrinsics. Builds with cargo build --target x86_64-pc-windows-msvc, --target aarch64-apple-darwin, wasm32-unknown-unknown (add wasm-bindgen for web).
Floating-point determinism: Scalar f32 ops only, fixed iteration order (0..n), no auto-vectorization reordering. Identical on same architecture/compiler. Cross-arch minor diffs possible (FMA flags); use fixed-point extension for perfect.
Integrator selection: set_integrator(Integrator::RK4) etc. Zero-cost enum dispatch.