Initial commit: Fabrilis docs, rules and deterministic core

Docs (architecture, decisions, coupling, determinism, UI, references), code rules enforced by tools/limits, deterministic core with units, time, math, sched, snapshot, vec and rng, plus smoke tests. ref/ stays out of git.
This commit is contained in:
Loki 2026-11-16 19:09:10 +01:00
commit 79928b645b
Signed by: boba
GPG key ID: 6CDE87BC9A778D97
222 changed files with 5335 additions and 0 deletions

16
crates/core/Cargo.toml Normal file
View file

@ -0,0 +1,16 @@
[package]
name = "fabrilis-core"
version.workspace = true
edition.workspace = true
license.workspace = true
authors.workspace = true
publish = false
[lints]
workspace = true
[dependencies]
libm = "0.2.16"
[build-dependencies]
fabrilis-limits = { path = "../../tools/limits" }

5
crates/core/build.rs Normal file
View file

@ -0,0 +1,5 @@
//! Enforces the repository rules at build time (see tools/limits).
fn main() {
fabrilis_limits::enforce_crate();
}

View file

@ -0,0 +1,88 @@
//! Fidelity: per-subsystem accuracy profile. Modes are presets (docs/MODES.md).
use crate::time::SimDelta;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Mode {
Bench,
Lab,
World,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CpuAccuracy {
CycleAccurate,
/// Batched: this many cycles per quantum, interrupts are quantized.
Batched {
cycles: u32,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MuscleModel {
Simple,
Hill,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MechanicsModel {
RigidBody,
BeamFem,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AeroModel {
Coefficients,
Panel,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Fidelity {
pub physics_step: SimDelta,
pub analog_step: SimDelta,
pub cpu: CpuAccuracy,
pub muscle: MuscleModel,
pub mechanics: MechanicsModel,
pub aero: AeroModel,
}
impl Fidelity {
#[must_use]
pub const fn for_mode(mode: Mode) -> Self {
match mode {
Mode::Bench => Self {
physics_step: SimDelta::from_millis(1),
analog_step: SimDelta::from_micros(1),
cpu: CpuAccuracy::CycleAccurate,
muscle: MuscleModel::Simple,
mechanics: MechanicsModel::RigidBody,
aero: AeroModel::Coefficients,
},
Mode::Lab => Self {
physics_step: SimDelta::from_micros(100),
analog_step: SimDelta::from_micros(1),
cpu: CpuAccuracy::CycleAccurate,
muscle: MuscleModel::Hill,
mechanics: MechanicsModel::BeamFem,
aero: AeroModel::Panel,
},
Mode::World => Self {
physics_step: SimDelta::from_millis(4),
analog_step: SimDelta::from_micros(40),
cpu: CpuAccuracy::Batched { cycles: 1000 },
muscle: MuscleModel::Simple,
mechanics: MechanicsModel::RigidBody,
aero: AeroModel::Coefficients,
},
}
}
/// Scheduler epoch length: the longest of the periods.
#[must_use]
pub fn epoch(&self) -> SimDelta {
self.physics_step.max(self.analog_step)
}
}
#[cfg(test)]
mod tests;

View file

@ -0,0 +1,22 @@
use super::*;
#[test]
fn every_period_divides_the_epoch() {
for mode in [Mode::Bench, Mode::Lab, Mode::World] {
let f = Fidelity::for_mode(mode);
assert!(f.epoch().is_multiple_of(f.physics_step), "{mode:?}");
assert!(f.epoch().is_multiple_of(f.analog_step), "{mode:?}");
}
}
#[test]
fn bench_and_lab_never_batch_the_cpu() {
assert_eq!(
Fidelity::for_mode(Mode::Bench).cpu,
CpuAccuracy::CycleAccurate
);
assert_eq!(
Fidelity::for_mode(Mode::Lab).cpu,
CpuAccuracy::CycleAccurate
);
}

90
crates/core/src/id/mod.rs Normal file
View file

@ -0,0 +1,90 @@
//! Typed identifiers: an `Id<Part>` cannot be confused with an `Id<Joint>`.
use core::cmp::Ordering;
use core::fmt;
use core::hash::{Hash, Hasher};
use core::marker::PhantomData;
pub struct Id<T> {
raw: u32,
_marker: PhantomData<fn() -> T>,
}
impl<T> Id<T> {
#[must_use]
pub const fn from_raw(raw: u32) -> Self {
Self {
raw,
_marker: PhantomData,
}
}
#[must_use]
pub const fn raw(self) -> u32 {
self.raw
}
#[must_use]
pub const fn index(self) -> usize {
self.raw as usize
}
}
impl<T> Clone for Id<T> {
fn clone(&self) -> Self {
*self
}
}
impl<T> Copy for Id<T> {}
impl<T> PartialEq for Id<T> {
fn eq(&self, other: &Self) -> bool {
self.raw == other.raw
}
}
impl<T> Eq for Id<T> {}
impl<T> PartialOrd for Id<T> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl<T> Ord for Id<T> {
fn cmp(&self, other: &Self) -> Ordering {
self.raw.cmp(&other.raw)
}
}
impl<T> Hash for Id<T> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.raw.hash(state);
}
}
impl<T> fmt::Debug for Id<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Id({})", self.raw)
}
}
/// Hands out sequential identifiers 0, 1, 2, ...
pub struct IdGen<T> {
next: u32,
_marker: PhantomData<fn() -> T>,
}
impl<T> Default for IdGen<T> {
fn default() -> Self {
Self {
next: 0,
_marker: PhantomData,
}
}
}
impl<T> IdGen<T> {
pub fn alloc(&mut self) -> Id<T> {
let id = Id::from_raw(self.next);
self.next += 1;
id
}
}
#[cfg(test)]
mod tests;

View file

@ -0,0 +1,14 @@
use super::*;
struct Part;
#[test]
fn ids_are_sequential_and_ordered() {
let mut generator = IdGen::<Part>::default();
let a = generator.alloc();
let b = generator.alloc();
assert_eq!((a.raw(), b.raw()), (0, 1));
assert!(a < b);
assert_eq!(b.index(), 1);
assert_eq!(format!("{a:?}"), "Id(0)");
}

10
crates/core/src/lib.rs Normal file
View file

@ -0,0 +1,10 @@
//! SI units, simulation time (integer ns), multi-rate scheduler, Fidelity, state snapshots, deterministic math
pub mod fidelity;
pub mod id;
pub mod math;
pub mod rng;
pub mod sched;
pub mod snapshot;
pub mod time;
pub mod units;
pub mod vec;

125
crates/core/src/math/mod.rs Normal file
View file

@ -0,0 +1,125 @@
//! Deterministic math.
//!
//! The system libm behind `std` differs between operating systems, so transcendental
//! functions come from the pure-Rust `libm` crate. `std`'s `sqrt` is an IEEE-exact CPU operation,
//! identical everywhere. See docs/DETERMINISM.md.
pub use core::f64::consts::{E, PI, TAU};
#[inline]
#[must_use]
pub fn sin(x: f64) -> f64 {
libm::sin(x)
}
#[inline]
#[must_use]
pub fn cos(x: f64) -> f64 {
libm::cos(x)
}
#[inline]
#[must_use]
pub fn sin_cos(x: f64) -> (f64, f64) {
libm::sincos(x)
}
#[inline]
#[must_use]
pub fn tan(x: f64) -> f64 {
libm::tan(x)
}
#[inline]
#[must_use]
pub fn asin(x: f64) -> f64 {
libm::asin(x)
}
#[inline]
#[must_use]
pub fn acos(x: f64) -> f64 {
libm::acos(x)
}
#[inline]
#[must_use]
pub fn atan(x: f64) -> f64 {
libm::atan(x)
}
#[inline]
#[must_use]
pub fn atan2(y: f64, x: f64) -> f64 {
libm::atan2(y, x)
}
#[inline]
#[must_use]
pub fn sinh(x: f64) -> f64 {
libm::sinh(x)
}
#[inline]
#[must_use]
pub fn cosh(x: f64) -> f64 {
libm::cosh(x)
}
#[inline]
#[must_use]
pub fn tanh(x: f64) -> f64 {
libm::tanh(x)
}
#[inline]
#[must_use]
pub fn exp(x: f64) -> f64 {
libm::exp(x)
}
#[inline]
#[must_use]
pub fn ln(x: f64) -> f64 {
libm::log(x)
}
#[inline]
#[must_use]
pub fn log10(x: f64) -> f64 {
libm::log10(x)
}
#[inline]
#[must_use]
pub fn log2(x: f64) -> f64 {
libm::log2(x)
}
#[inline]
#[must_use]
pub fn pow(x: f64, y: f64) -> f64 {
libm::pow(x, y)
}
#[inline]
#[must_use]
pub fn cbrt(x: f64) -> f64 {
libm::cbrt(x)
}
#[inline]
#[must_use]
pub fn hypot(x: f64, y: f64) -> f64 {
libm::hypot(x, y)
}
/// IEEE-exact square root (hardware, identical on all platforms).
#[inline]
#[must_use]
pub fn sqrt(x: f64) -> f64 {
x.sqrt()
}
#[cfg(test)]
mod tests;

View file

@ -0,0 +1,18 @@
use super::*;
#[test]
fn basic_values() {
assert_eq!(sin(0.0), 0.0);
assert_eq!(cos(0.0), 1.0);
assert_eq!(pow(2.0, 10.0), 1024.0);
assert_eq!(sqrt(9.0), 3.0);
assert!((atan2(1.0, 1.0) - PI / 4.0).abs() < 1e-15);
assert!((exp(1.0) - E).abs() < 1e-15);
}
#[test]
fn sin_cos_matches_parts() {
let (s, c) = sin_cos(0.7);
assert!((s - sin(0.7)).abs() < 1e-15);
assert!((c - cos(0.7)).abs() < 1e-15);
}

100
crates/core/src/rng/mod.rs Normal file
View file

@ -0,0 +1,100 @@
//! Deterministic seeded random numbers: xoshiro256**, seeded through SplitMix64.
//!
//! Only integer arithmetic, so the sequence is identical on every platform. The state
//! will be stored in a snapshot (docs/DETERMINISM.md).
/// A seeded generator; the same seed always gives the same sequence.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Rng {
state: [u64; 4],
}
const GAMMA: u64 = 0x9E37_79B9_7F4A_7C15;
fn split_mix(counter: &mut u64) -> u64 {
*counter = counter.wrapping_add(GAMMA);
let mut z = *counter;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^ (z >> 31)
}
impl Rng {
/// Creates a generator from a seed; every seed is valid.
#[must_use]
pub fn new(seed: u64) -> Self {
let mut counter = seed;
let mut state = [
split_mix(&mut counter),
split_mix(&mut counter),
split_mix(&mut counter),
split_mix(&mut counter),
];
// xoshiro cannot start from the all-zero state; split_mix never produces it
// for a real seed, but the invariant is made explicit.
if state == [0; 4] {
state[0] = GAMMA;
}
Self { state }
}
/// The next 64 random bits.
pub fn next_u64(&mut self) -> u64 {
let result = self.state[1].wrapping_mul(5).rotate_left(7).wrapping_mul(9);
let t = self.state[1] << 17;
self.state[2] ^= self.state[0];
self.state[3] ^= self.state[1];
self.state[1] ^= self.state[2];
self.state[0] ^= self.state[3];
self.state[2] ^= t;
self.state[3] = self.state[3].rotate_left(45);
result
}
/// The next 32 random bits, taken from the high half of the 64-bit output.
pub fn next_u32(&mut self) -> u32 {
(self.next_u64() >> 32) as u32
}
/// A fair coin.
pub fn next_bool(&mut self) -> bool {
self.next_u64() >> 63 == 1
}
/// A uniform value in `[0, 1)`, with 53 bits of precision.
pub fn next_f64(&mut self) -> f64 {
const SCALE: f64 = 1.0 / (1u64 << 53) as f64;
(self.next_u64() >> 11) as f64 * SCALE
}
/// A uniform value in `[0, bound)` without modulo bias; `0` when `bound` is zero.
pub fn below(&mut self, bound: u64) -> u64 {
if bound == 0 {
return 0;
}
let threshold = bound.wrapping_neg() % bound;
loop {
let value = self.next_u64();
if value >= threshold {
return value % bound;
}
}
}
/// A uniform value in `[low, high)`; `low` when the range is empty or reversed.
pub fn range_u64(&mut self, low: u64, high: u64) -> u64 {
if high <= low {
low
} else {
low + self.below(high - low)
}
}
/// A uniform value in `[low, high)`.
pub fn range_f64(&mut self, low: f64, high: f64) -> f64 {
low + (high - low) * self.next_f64()
}
}
#[cfg(test)]
mod tests;

View file

@ -0,0 +1,60 @@
use super::*;
#[test]
fn known_sequence_is_pinned() {
let mut rng = Rng::new(42);
let expected = [
0x1578_0b2e_0c2e_c716,
0x6104_d986_6d11_3a7e,
0xae17_5332_39e4_99a1,
0xecb8_ad47_03b3_60a1,
0xfde6_dc7f_e2ec_5e64,
];
for value in expected {
assert_eq!(rng.next_u64(), value);
}
}
#[test]
fn the_same_seed_repeats_the_sequence() {
let mut a = Rng::new(7);
let mut b = Rng::new(7);
for _ in 0..100 {
assert_eq!(a.next_u64(), b.next_u64());
}
}
#[test]
fn different_seeds_diverge() {
let mut a = Rng::new(1);
let mut b = Rng::new(2);
assert_ne!(a.next_u64(), b.next_u64());
}
#[test]
fn floats_stay_in_the_unit_interval() {
let mut rng = Rng::new(9);
for _ in 0..10_000 {
let value = rng.next_f64();
assert!((0.0..1.0).contains(&value), "{value}");
}
}
#[test]
fn range_is_half_open() {
let mut rng = Rng::new(11);
for _ in 0..1_000 {
let value = rng.range_u64(10, 20);
assert!((10..20).contains(&value), "{value}");
}
let value = rng.range_f64(-1.0, 1.0);
assert!((-1.0..1.0).contains(&value), "{value}");
}
#[test]
fn degenerate_ranges_return_the_lower_bound() {
let mut rng = Rng::new(13);
assert_eq!(rng.below(0), 0);
assert_eq!(rng.range_u64(5, 5), 5);
assert_eq!(rng.range_u64(5, 1), 5);
}

View file

@ -0,0 +1,141 @@
//! Multi-rate scheduler.
//!
//! Time is split into fixed-length epochs. Within an epoch subsystems step
//! in order of (step start time, registration order), so the result does not
//! depend on threads or chance. Subsystems exchange data only at
//! sync points at the end of an epoch (see `bridge`).
use core::fmt;
use crate::time::{SimDelta, SimTime};
#[cfg(test)]
mod tests;
/// A subsystem with its own step period.
pub trait Subsystem {
fn name(&self) -> &'static str;
/// A step of length `dt` that starts at `now`.
fn step(&mut self, now: SimTime, dt: SimDelta);
}
/// Sync point: called at the end of every epoch.
pub trait SyncPoint {
fn sync(&mut self, now: SimTime);
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SchedError {
ZeroPeriod,
PeriodDoesNotDivideEpoch { period: SimDelta, epoch: SimDelta },
}
impl fmt::Display for SchedError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::ZeroPeriod => write!(f, "период должен быть больше нуля"),
Self::PeriodDoesNotDivideEpoch { period, epoch } => write!(
f,
"период {} нс не делит эпоху {} нс",
period.nanos(),
epoch.nanos()
),
}
}
}
impl std::error::Error for SchedError {}
struct Slot {
sub: Box<dyn Subsystem>,
period: SimDelta,
next: SimTime,
}
pub struct Scheduler {
epoch: SimDelta,
now: SimTime,
slots: Vec<Slot>,
syncs: Vec<Box<dyn SyncPoint>>,
}
impl Scheduler {
/// # Errors
/// `ZeroPeriod` if the epoch is zero.
pub fn new(epoch: SimDelta) -> Result<Self, SchedError> {
if epoch == SimDelta::ZERO {
return Err(SchedError::ZeroPeriod);
}
Ok(Self {
epoch,
now: SimTime::ZERO,
slots: Vec::new(),
syncs: Vec::new(),
})
}
/// Registers a subsystem. Registration order breaks ties in time.
///
/// # Errors
/// The period is zero or does not divide the epoch evenly.
pub fn add(&mut self, sub: Box<dyn Subsystem>, period: SimDelta) -> Result<(), SchedError> {
if period == SimDelta::ZERO {
return Err(SchedError::ZeroPeriod);
}
if !self.epoch.is_multiple_of(period) {
return Err(SchedError::PeriodDoesNotDivideEpoch {
period,
epoch: self.epoch,
});
}
self.slots.push(Slot {
sub,
period,
next: self.now,
});
Ok(())
}
pub fn add_sync(&mut self, sync: Box<dyn SyncPoint>) {
self.syncs.push(sync);
}
#[must_use]
pub fn now(&self) -> SimTime {
self.now
}
#[must_use]
pub fn epoch(&self) -> SimDelta {
self.epoch
}
/// Index of the subsystem whose step starts earliest, before `end`.
fn next_due(&self, end: SimTime) -> Option<usize> {
self.slots
.iter()
.enumerate()
.filter(|(_, s)| s.next < end)
.min_by_key(|(i, s)| (s.next, *i))
.map(|(i, _)| i)
}
pub fn run_epoch(&mut self) {
let end = self.now + self.epoch;
while let Some(i) = self.next_due(end) {
let slot = &mut self.slots[i];
slot.sub.step(slot.next, slot.period);
slot.next += slot.period;
}
self.now = end;
for sync in &mut self.syncs {
sync.sync(end);
}
}
pub fn run_epochs(&mut self, count: u64) {
for _ in 0..count {
self.run_epoch();
}
}
}

View file

@ -0,0 +1,79 @@
use std::cell::RefCell;
use std::rc::Rc;
use super::*;
type Log = Rc<RefCell<Vec<String>>>;
struct Recorder {
name: &'static str,
log: Log,
}
impl Subsystem for Recorder {
fn name(&self) -> &'static str {
self.name
}
fn step(&mut self, now: SimTime, _dt: SimDelta) {
self.log
.borrow_mut()
.push(format!("{}@{}", self.name, now.nanos()));
}
}
struct SyncRecorder(Log);
impl SyncPoint for SyncRecorder {
fn sync(&mut self, now: SimTime) {
self.0.borrow_mut().push(format!("sync@{}", now.nanos()));
}
}
fn rec(name: &'static str, log: &Log) -> Box<Recorder> {
Box::new(Recorder {
name,
log: Rc::clone(log),
})
}
#[test]
fn steps_interleave_by_time_then_registration_order() {
let log: Log = Rc::default();
let mut s = Scheduler::new(SimDelta(4)).unwrap();
s.add(rec("slow", &log), SimDelta(4)).unwrap();
s.add(rec("fast", &log), SimDelta(1)).unwrap();
s.add_sync(Box::new(SyncRecorder(Rc::clone(&log))));
s.run_epoch();
assert_eq!(
*log.borrow(),
["slow@0", "fast@0", "fast@1", "fast@2", "fast@3", "sync@4"]
);
assert_eq!(s.now(), SimTime(4));
}
#[test]
fn second_epoch_continues_timeline() {
let log: Log = Rc::default();
let mut s = Scheduler::new(SimDelta(2)).unwrap();
s.add(rec("a", &log), SimDelta(1)).unwrap();
s.run_epochs(2);
assert_eq!(*log.borrow(), ["a@0", "a@1", "a@2", "a@3"]);
}
#[test]
fn rejects_bad_periods() {
let log: Log = Rc::default();
let mut s = Scheduler::new(SimDelta(4)).unwrap();
assert_eq!(
s.add(rec("x", &log), SimDelta(3)),
Err(SchedError::PeriodDoesNotDivideEpoch {
period: SimDelta(3),
epoch: SimDelta(4)
})
);
assert_eq!(
s.add(rec("x", &log), SimDelta(0)),
Err(SchedError::ZeroPeriod)
);
assert!(Scheduler::new(SimDelta(0)).is_err());
}

View file

@ -0,0 +1,53 @@
//! State hash (FNV-1a 64) for determinism golden tests.
const OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
const PRIME: u64 = 0x0000_0100_0000_01b3;
/// One canonical bit pattern for every NaN.
const CANONICAL_NAN: u64 = 0x7ff8_0000_0000_0000;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StateHasher(u64);
impl Default for StateHasher {
fn default() -> Self {
Self::new()
}
}
impl StateHasher {
#[must_use]
pub const fn new() -> Self {
Self(OFFSET)
}
pub fn write_bytes(&mut self, bytes: &[u8]) {
for &b in bytes {
self.0 ^= u64::from(b);
self.0 = self.0.wrapping_mul(PRIME);
}
}
pub fn write_u64(&mut self, value: u64) {
self.write_bytes(&value.to_le_bytes());
}
/// Hashes the bits of a number; every NaN and `-0.0` are normalized.
pub fn write_f64(&mut self, value: f64) {
let bits = if value.is_nan() {
CANONICAL_NAN
} else if value == 0.0 {
0
} else {
value.to_bits()
};
self.write_u64(bits);
}
#[must_use]
pub const fn finish(self) -> u64 {
self.0
}
}
#[cfg(test)]
mod tests;

View file

@ -0,0 +1,30 @@
use super::*;
#[test]
fn matches_known_fnv1a_vector() {
let mut h = StateHasher::new();
h.write_bytes(b"a");
assert_eq!(h.finish(), 0xaf63_dc4c_8601_ec8c);
}
#[test]
fn nan_and_negative_zero_are_canonical() {
let mut a = StateHasher::new();
let mut b = StateHasher::new();
a.write_f64(f64::NAN);
b.write_f64(-f64::NAN);
a.write_f64(0.0);
b.write_f64(-0.0);
assert_eq!(a, b);
}
#[test]
fn order_matters() {
let mut a = StateHasher::new();
let mut b = StateHasher::new();
a.write_u64(1);
a.write_u64(2);
b.write_u64(2);
b.write_u64(1);
assert_ne!(a.finish(), b.finish());
}

View file

@ -0,0 +1,59 @@
//! State snapshots: a double buffer between the simulation and readers (render, UI).
pub mod hash;
use crate::time::SimTime;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Header {
pub tick: u64,
pub time: SimTime,
}
/// The simulation writes into `back_mut`, then `publish` exposes it to readers.
///
/// After `publish` the back buffer holds the previous snapshot: the writer must
/// overwrite it completely.
pub struct DoubleBuffer<T> {
front: T,
back: T,
header: Header,
}
impl<T: Clone> DoubleBuffer<T> {
#[must_use]
pub fn new(initial: T) -> Self {
Self {
front: initial.clone(),
back: initial,
header: Header::default(),
}
}
}
impl<T> DoubleBuffer<T> {
#[must_use]
pub fn front(&self) -> &T {
&self.front
}
#[must_use]
pub fn header(&self) -> Header {
self.header
}
pub fn back_mut(&mut self) -> &mut T {
&mut self.back
}
pub fn publish(&mut self, time: SimTime) {
core::mem::swap(&mut self.front, &mut self.back);
self.header = Header {
tick: self.header.tick + 1,
time,
};
}
}
#[cfg(test)]
mod tests;

View file

@ -0,0 +1,17 @@
use super::*;
#[test]
fn publish_swaps_and_counts() {
let mut buf = DoubleBuffer::new(0_u32);
*buf.back_mut() = 7;
assert_eq!(*buf.front(), 0);
buf.publish(SimTime(100));
assert_eq!(*buf.front(), 7);
assert_eq!(
buf.header(),
Header {
tick: 1,
time: SimTime(100)
}
);
}

View file

@ -0,0 +1,93 @@
//! Simulation time: integer nanoseconds, no float drift.
use core::ops::{Add, AddAssign, Sub};
use crate::units::Seconds;
pub const NS_PER_S: u64 = 1_000_000_000;
/// A point in simulation time, ns since the start.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct SimTime(pub u64);
/// A duration, ns.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct SimDelta(pub u64);
impl SimDelta {
pub const ZERO: Self = Self(0);
#[must_use]
pub const fn from_nanos(ns: u64) -> Self {
Self(ns)
}
#[must_use]
pub const fn from_micros(us: u64) -> Self {
Self(us * 1_000)
}
#[must_use]
pub const fn from_millis(ms: u64) -> Self {
Self(ms * 1_000_000)
}
/// Period of frequency `hz`; `None` if the period is not a whole number of ns.
#[must_use]
pub const fn from_hz(hz: u64) -> Option<Self> {
if hz == 0 || !NS_PER_S.is_multiple_of(hz) {
None
} else {
Some(Self(NS_PER_S / hz))
}
}
#[must_use]
pub const fn nanos(self) -> u64 {
self.0
}
/// Seconds for physics formulas. Deterministic: a single division.
#[must_use]
pub fn as_seconds(self) -> Seconds {
Seconds(self.0 as f64 / NS_PER_S as f64)
}
/// Whether `self` is evenly divisible by `period` (and `period > 0`).
#[must_use]
pub const fn is_multiple_of(self, period: Self) -> bool {
period.0 != 0 && self.0.is_multiple_of(period.0)
}
}
impl SimTime {
pub const ZERO: Self = Self(0);
#[must_use]
pub const fn nanos(self) -> u64 {
self.0
}
}
impl Add<SimDelta> for SimTime {
type Output = Self;
fn add(self, rhs: SimDelta) -> Self {
Self(self.0 + rhs.0)
}
}
impl AddAssign<SimDelta> for SimTime {
fn add_assign(&mut self, rhs: SimDelta) {
self.0 += rhs.0;
}
}
impl Sub for SimTime {
type Output = SimDelta;
fn sub(self, rhs: Self) -> SimDelta {
SimDelta(self.0 - rhs.0)
}
}
#[cfg(test)]
mod tests;

View file

@ -0,0 +1,23 @@
use super::*;
#[test]
fn hz_must_be_whole_nanoseconds() {
assert_eq!(SimDelta::from_hz(250), Some(SimDelta::from_millis(4)));
assert_eq!(SimDelta::from_hz(1_000), Some(SimDelta::from_millis(1)));
assert_eq!(SimDelta::from_hz(240), None);
assert_eq!(SimDelta::from_hz(0), None);
}
#[test]
fn arithmetic_and_conversion() {
let t = SimTime::ZERO + SimDelta::from_millis(3);
assert_eq!(t - SimTime(1_000_000), SimDelta::from_millis(2));
assert_eq!(SimDelta::from_millis(500).as_seconds(), Seconds(0.5));
}
#[test]
fn multiples() {
assert!(SimDelta::from_millis(4).is_multiple_of(SimDelta::from_micros(40)));
assert!(!SimDelta::from_millis(4).is_multiple_of(SimDelta::from_micros(3_000)));
assert!(!SimDelta::from_millis(4).is_multiple_of(SimDelta::ZERO));
}

View file

@ -0,0 +1,194 @@
//! SI units as newtypes over `f64`.
//!
//! Only identical units can be added; mixed operations
//! (Ohm's law, power, energy) are defined explicitly below.
use core::ops::{Add, AddAssign, Div, Mul, Neg, Sub, SubAssign};
macro_rules! quantity {
($(#[$meta:meta])* $name:ident) => {
$(#[$meta])*
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Default)]
pub struct $name(pub f64);
impl $name {
pub const ZERO: Self = Self(0.0);
#[inline]
#[must_use]
pub const fn new(value: f64) -> Self {
Self(value)
}
#[inline]
#[must_use]
pub const fn get(self) -> f64 {
self.0
}
}
impl Add for $name {
type Output = Self;
#[inline]
fn add(self, rhs: Self) -> Self {
Self(self.0 + rhs.0)
}
}
impl Sub for $name {
type Output = Self;
#[inline]
fn sub(self, rhs: Self) -> Self {
Self(self.0 - rhs.0)
}
}
impl Neg for $name {
type Output = Self;
#[inline]
fn neg(self) -> Self {
Self(-self.0)
}
}
impl AddAssign for $name {
#[inline]
fn add_assign(&mut self, rhs: Self) {
self.0 += rhs.0;
}
}
impl SubAssign for $name {
#[inline]
fn sub_assign(&mut self, rhs: Self) {
self.0 -= rhs.0;
}
}
impl Mul<f64> for $name {
type Output = Self;
#[inline]
fn mul(self, rhs: f64) -> Self {
Self(self.0 * rhs)
}
}
impl Mul<$name> for f64 {
type Output = $name;
#[inline]
fn mul(self, rhs: $name) -> $name {
$name(self * rhs.0)
}
}
impl Div<f64> for $name {
type Output = Self;
#[inline]
fn div(self, rhs: f64) -> Self {
Self(self.0 / rhs)
}
}
impl Div for $name {
type Output = f64;
#[inline]
fn div(self, rhs: Self) -> f64 {
self.0 / rhs.0
}
}
};
}
quantity!(/// Length, m.
Meters);
quantity!(/// Mass, kg.
Kilograms);
quantity!(/// Time, s (for physics; the scheduler step is set in integer ns).
Seconds);
quantity!(/// Speed, m/s.
MetersPerSecond);
quantity!(/// Force, N.
Newtons);
quantity!(/// Pressure and material stress, Pa.
Pascals);
quantity!(/// Energy, J.
Joules);
quantity!(/// Power, W.
Watts);
quantity!(/// Temperature, K.
Kelvin);
quantity!(/// Electric potential, V.
Volts);
quantity!(/// Current, A.
Amps);
quantity!(/// Resistance, Ohm.
Ohms);
quantity!(/// Angle, rad.
Radians);
quantity!(/// Angular velocity, rad/s.
RadiansPerSecond);
quantity!(/// Acceleration, m/s².
MetersPerSecondSquared);
quantity!(/// Torque, N·m.
NewtonMeters);
impl Radians {
/// Converts degrees to radians; degrees exist only at the UI and import boundary.
#[inline]
#[must_use]
pub fn from_degrees(degrees: f64) -> Self {
Self(degrees * core::f64::consts::PI / 180.0)
}
/// The angle in degrees, for display only.
#[inline]
#[must_use]
pub fn to_degrees(self) -> f64 {
self.0 * 180.0 / core::f64::consts::PI
}
}
impl Mul<Amps> for Volts {
type Output = Watts;
#[inline]
fn mul(self, rhs: Amps) -> Watts {
Watts(self.0 * rhs.0)
}
}
impl Div<Ohms> for Volts {
type Output = Amps;
#[inline]
fn div(self, rhs: Ohms) -> Amps {
Amps(self.0 / rhs.0)
}
}
impl Div<Amps> for Volts {
type Output = Ohms;
#[inline]
fn div(self, rhs: Amps) -> Ohms {
Ohms(self.0 / rhs.0)
}
}
impl Mul<Seconds> for Watts {
type Output = Joules;
#[inline]
fn mul(self, rhs: Seconds) -> Joules {
Joules(self.0 * rhs.0)
}
}
impl Div<Seconds> for Meters {
type Output = MetersPerSecond;
#[inline]
fn div(self, rhs: Seconds) -> MetersPerSecond {
MetersPerSecond(self.0 / rhs.0)
}
}
impl Mul<Seconds> for MetersPerSecondSquared {
type Output = MetersPerSecond;
#[inline]
fn mul(self, rhs: Seconds) -> MetersPerSecond {
MetersPerSecond(self.0 * rhs.0)
}
}
impl Mul<Seconds> for RadiansPerSecond {
type Output = Radians;
#[inline]
fn mul(self, rhs: Seconds) -> Radians {
Radians(self.0 * rhs.0)
}
}
#[cfg(test)]
mod tests;

View file

@ -0,0 +1,41 @@
use super::*;
#[test]
fn ohms_law_and_power() {
let i = Volts(12.0) / Ohms(4.0);
assert_eq!(i, Amps(3.0));
assert_eq!(Volts(12.0) * i, Watts(36.0));
assert_eq!(Volts(12.0) / i, Ohms(4.0));
}
#[test]
fn energy_and_speed() {
assert_eq!(Watts(10.0) * Seconds(3.0), Joules(30.0));
assert_eq!(Meters(6.0) / Seconds(2.0), MetersPerSecond(3.0));
}
#[test]
fn same_unit_arithmetic() {
let mut m = Kilograms(2.0) + Kilograms(3.0);
m -= Kilograms(1.0);
assert_eq!(m, Kilograms(4.0));
assert_eq!(m / Kilograms(2.0), 2.0);
assert_eq!(2.0 * m, Kilograms(8.0));
assert_eq!(-m, Kilograms(-4.0));
}
#[test]
fn degrees_convert_to_radians() {
let half_turn = Radians::from_degrees(180.0);
assert!((half_turn.get() - core::f64::consts::PI).abs() < 1e-12);
assert!((half_turn.to_degrees() - 180.0).abs() < 1e-12);
assert_eq!(Radians(1.0) + Radians(2.0), Radians(3.0));
}
#[test]
fn derived_motion_units() {
let gravity = MetersPerSecondSquared(9.81);
assert_eq!(gravity * Seconds(2.0), MetersPerSecond(19.62));
let rate = RadiansPerSecond(3.0);
assert_eq!(rate * Seconds(2.0), Radians(6.0));
}

View file

@ -0,0 +1,15 @@
//! Deterministic 3D vector math on `f64`.
//!
//! Trigonometry goes through [`crate::math`] (pure Rust `libm`), so results do not
//! depend on the operating system. See docs/DETERMINISM.md.
mod rotation;
mod transform;
mod vec3;
pub use rotation::{Mat3, Quat};
pub use transform::Transform;
pub use vec3::Vec3;
#[cfg(test)]
mod tests;

View file

@ -0,0 +1,226 @@
//! Rotations: a 3×3 matrix and a unit quaternion.
//!
//! Both are `f64` and use [`crate::math`] for trigonometry, so results do not depend
//! on the operating system. See docs/DETERMINISM.md.
use core::ops::{Div, Mul};
use super::Vec3;
use crate::math;
use crate::units::Radians;
/// A 3×3 matrix; column `i` is the image of the basis vector `i`.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Mat3 {
cols: [Vec3; 3],
}
impl Mat3 {
/// The identity matrix.
pub const IDENTITY: Self = Self::from_cols(Vec3::X, Vec3::Y, Vec3::Z);
/// Builds a matrix from its columns.
#[inline]
#[must_use]
pub const fn from_cols(x: Vec3, y: Vec3, z: Vec3) -> Self {
Self { cols: [x, y, z] }
}
/// A diagonal matrix.
#[inline]
#[must_use]
pub const fn from_diagonal(diagonal: Vec3) -> Self {
Self::from_cols(
Vec3::new(diagonal.x, 0.0, 0.0),
Vec3::new(0.0, diagonal.y, 0.0),
Vec3::new(0.0, 0.0, diagonal.z),
)
}
/// The columns.
#[inline]
#[must_use]
pub const fn cols(self) -> [Vec3; 3] {
self.cols
}
/// The transposed matrix.
#[inline]
#[must_use]
pub fn transpose(self) -> Self {
let [x, y, z] = self.cols;
Self::from_cols(
Vec3::new(x.x, y.x, z.x),
Vec3::new(x.y, y.y, z.y),
Vec3::new(x.z, y.z, z.z),
)
}
/// The determinant.
#[inline]
#[must_use]
pub fn determinant(self) -> f64 {
let [a, b, c] = self.cols;
a.dot(b.cross(c))
}
/// The inverse, or `None` for a singular or non-finite matrix.
#[inline]
#[must_use]
pub fn inverse(self) -> Option<Self> {
let [a, b, c] = self.cols;
let det = self.determinant();
if det == 0.0 || !det.is_finite() {
return None;
}
let inv_det = 1.0 / det;
let r0 = b.cross(c);
let r1 = c.cross(a);
let r2 = a.cross(b);
Some(Self::from_cols(
Vec3::new(r0.x, r1.x, r2.x) * inv_det,
Vec3::new(r0.y, r1.y, r2.y) * inv_det,
Vec3::new(r0.z, r1.z, r2.z) * inv_det,
))
}
}
impl Mul<Vec3> for Mat3 {
type Output = Vec3;
#[inline]
fn mul(self, rhs: Vec3) -> Vec3 {
let [a, b, c] = self.cols;
a * rhs.x + b * rhs.y + c * rhs.z
}
}
impl Mul<Mat3> for Mat3 {
type Output = Self;
#[inline]
fn mul(self, rhs: Mat3) -> Self {
let [x, y, z] = rhs.cols;
Self::from_cols(self * x, self * y, self * z)
}
}
/// A rotation as a quaternion `w + xi + yj + zk`.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Quat {
pub w: f64,
pub x: f64,
pub y: f64,
pub z: f64,
}
impl Quat {
/// The identity rotation.
pub const IDENTITY: Self = Self::new(1.0, 0.0, 0.0, 0.0);
/// Builds a quaternion from its components; it is not normalized here.
#[inline]
#[must_use]
pub const fn new(w: f64, x: f64, y: f64, z: f64) -> Self {
Self { w, x, y, z }
}
/// A rotation of `angle` around `axis`, or `None` for a zero axis.
#[inline]
#[must_use]
pub fn from_axis_angle(axis: Vec3, angle: Radians) -> Option<Self> {
let axis = axis.normalized()?;
let (sin, cos) = math::sin_cos(angle.get() * 0.5);
Some(Self::new(cos, axis.x * sin, axis.y * sin, axis.z * sin))
}
/// The squared norm; `1.0` for a unit quaternion.
#[inline]
#[must_use]
pub fn norm_squared(self) -> f64 {
self.w * self.w + self.x * self.x + self.y * self.y + self.z * self.z
}
/// The negation of the vector part, which is the inverse for a unit quaternion.
#[inline]
#[must_use]
pub fn conjugate(self) -> Self {
Self::new(self.w, -self.x, -self.y, -self.z)
}
/// The inverse, or `None` for the zero quaternion.
#[inline]
#[must_use]
pub fn inverse(self) -> Option<Self> {
let norm_squared = self.norm_squared();
if norm_squared > 0.0 && norm_squared.is_finite() {
Some(self.conjugate() / norm_squared)
} else {
None
}
}
/// The unit quaternion, or `None` for the zero quaternion.
#[inline]
#[must_use]
pub fn normalize(self) -> Option<Self> {
let norm_squared = self.norm_squared();
if norm_squared > 0.0 && norm_squared.is_finite() {
Some(self / math::sqrt(norm_squared))
} else {
None
}
}
/// Rotates a vector; a non-unit quaternion is normalized first.
#[inline]
#[must_use]
pub fn rotate(self, v: Vec3) -> Vec3 {
let Some(unit) = self.normalize() else {
return v;
};
let qv = Vec3::new(unit.x, unit.y, unit.z);
let t = qv.cross(v) * 2.0;
v + t * unit.w + qv.cross(t)
}
/// The rotation matrix equivalent to this rotation.
#[inline]
#[must_use]
pub fn to_mat3(self) -> Mat3 {
let Some(q) = self.normalize() else {
return Mat3::IDENTITY;
};
let (w, x, y, z) = (q.w, q.x, q.y, q.z);
let (xx, yy, zz) = (x * x, y * y, z * z);
let (xy, xz, yz) = (x * y, x * z, y * z);
let (wx, wy, wz) = (w * x, w * y, w * z);
Mat3::from_cols(
Vec3::new(1.0 - 2.0 * (yy + zz), 2.0 * (xy + wz), 2.0 * (xz - wy)),
Vec3::new(2.0 * (xy - wz), 1.0 - 2.0 * (xx + zz), 2.0 * (yz + wx)),
Vec3::new(2.0 * (xz + wy), 2.0 * (yz - wx), 1.0 - 2.0 * (xx + yy)),
)
}
}
impl Mul for Quat {
type Output = Self;
/// Composition: `(a * b).rotate(v) == a.rotate(b.rotate(v))`.
#[inline]
fn mul(self, rhs: Self) -> Self {
let a = Vec3::new(self.x, self.y, self.z);
let b = Vec3::new(rhs.x, rhs.y, rhs.z);
let vector = b * self.w + a * rhs.w + a.cross(b);
Self::new(self.w * rhs.w - a.dot(b), vector.x, vector.y, vector.z)
}
}
impl Div<f64> for Quat {
type Output = Self;
#[inline]
fn div(self, rhs: f64) -> Self {
Self::new(self.w / rhs, self.x / rhs, self.y / rhs, self.z / rhs)
}
}

View file

@ -0,0 +1,230 @@
use super::*;
use crate::units::Radians;
fn close(a: f64, b: f64) -> bool {
(a - b).abs() < 1e-12
}
fn assert_vec(actual: Vec3, expected: Vec3) {
assert!(
close(actual.x, expected.x) && close(actual.y, expected.y) && close(actual.z, expected.z),
"{actual:?} != {expected:?}"
);
}
#[test]
fn dot_and_cross_follow_the_right_hand_rule() {
let x = Vec3::X;
let y = Vec3::Y;
assert_eq!(x.dot(y), 0.0);
assert_eq!(x.cross(y), Vec3::Z);
assert_eq!(y.cross(x), -Vec3::Z);
assert_eq!(x.dot(x), 1.0);
}
#[test]
fn cross_of_parallel_vectors_is_zero() {
let v = Vec3::new(1.0, 2.0, 3.0);
assert_eq!(v.cross(v), Vec3::ZERO);
}
#[test]
fn length_and_normalize() {
let v = Vec3::new(3.0, 4.0, 0.0);
assert_eq!(v.length(), 5.0);
assert_eq!(v.length_squared(), 25.0);
let unit = v.normalized().expect("a non-zero vector normalizes");
assert!(close(unit.length(), 1.0));
assert!(close(unit.x, 0.6));
}
#[test]
fn zero_vector_does_not_normalize() {
assert_eq!(Vec3::ZERO.normalized(), None);
}
#[test]
fn vector_arithmetic() {
let a = Vec3::new(1.0, 2.0, 3.0);
let b = Vec3::new(4.0, 5.0, 6.0);
assert_eq!(a + b, Vec3::new(5.0, 7.0, 9.0));
assert_eq!(b - a, Vec3::new(3.0, 3.0, 3.0));
assert_eq!(a * 2.0, Vec3::new(2.0, 4.0, 6.0));
assert_eq!(2.0 * a, Vec3::new(2.0, 4.0, 6.0));
assert_eq!(-a, Vec3::new(-1.0, -2.0, -3.0));
}
#[test]
fn identity_leaves_vectors_alone() {
let v = Vec3::new(1.0, -2.0, 3.5);
assert_eq!(Mat3::IDENTITY * v, v);
}
#[test]
fn columns_are_the_images_of_the_basis() {
let m = Mat3::from_cols(Vec3::Y, Vec3::Z, Vec3::X);
assert_eq!(m * Vec3::X, Vec3::Y);
assert_eq!(m * Vec3::Y, Vec3::Z);
}
#[test]
fn transpose_and_determinant() {
let m = Mat3::from_cols(
Vec3::new(1.0, 2.0, 3.0),
Vec3::new(0.0, 1.0, 4.0),
Vec3::new(5.0, 6.0, 0.0),
);
assert_eq!(m.determinant(), 1.0);
assert_eq!(m.transpose().transpose(), m);
let scaled = Mat3::from_diagonal(Vec3::new(2.0, 3.0, 4.0));
assert_eq!(scaled.determinant(), 24.0);
}
#[test]
fn inverse_round_trip() {
let m = Mat3::from_cols(
Vec3::new(2.0, 0.0, 0.0),
Vec3::new(0.0, 3.0, 0.0),
Vec3::new(1.0, 0.0, 4.0),
);
let inv = m.inverse().expect("the matrix is invertible");
let identity = m * inv;
for (actual, expected) in [
(identity * Vec3::X, Vec3::X),
(identity * Vec3::Y, Vec3::Y),
(identity * Vec3::Z, Vec3::Z),
] {
assert!(close(actual.x, expected.x));
assert!(close(actual.y, expected.y));
assert!(close(actual.z, expected.z));
}
}
#[test]
fn singular_matrix_has_no_inverse() {
assert_eq!(
Mat3::from_diagonal(Vec3::new(1.0, 0.0, 1.0)).inverse(),
None
);
}
#[test]
fn matrix_product_matches_sequential_application() {
let a = Mat3::from_diagonal(Vec3::new(2.0, 3.0, 4.0));
let b = Mat3::from_cols(Vec3::Y, Vec3::Z, Vec3::X);
let v = Vec3::new(1.0, 2.0, 3.0);
assert_eq!((a * b) * v, a * (b * v));
}
#[test]
fn identity_rotates_nothing() {
assert_vec(Quat::IDENTITY.rotate(Vec3::X), Vec3::X);
}
#[test]
fn quarter_turn_about_z_maps_x_to_y() {
let q = Quat::from_axis_angle(Vec3::Z, Radians::from_degrees(90.0)).expect("axis is non-zero");
assert_vec(q.rotate(Vec3::X), Vec3::Y);
assert_vec(q.rotate(Vec3::Y), -Vec3::X);
assert_vec(q.rotate(Vec3::Z), Vec3::Z);
}
#[test]
fn double_turn_about_an_axis_maps_the_opposite_way() {
let q = Quat::from_axis_angle(Vec3::X, Radians::from_degrees(180.0)).expect("axis is non-zero");
assert_vec(q.rotate(Vec3::Y), -Vec3::Y);
}
#[test]
fn zero_axis_is_rejected() {
assert_eq!(Quat::from_axis_angle(Vec3::ZERO, Radians(1.0)), None);
}
#[test]
fn composition_applies_the_right_factor_first() {
let x90 = Quat::from_axis_angle(Vec3::X, Radians::from_degrees(90.0)).expect("axis");
let z90 = Quat::from_axis_angle(Vec3::Z, Radians::from_degrees(90.0)).expect("axis");
let v = Vec3::Y;
assert_vec((z90 * x90).rotate(v), z90.rotate(x90.rotate(v)));
}
#[test]
fn inverse_undoes_the_rotation() {
let q = Quat::from_axis_angle(Vec3::new(1.0, 2.0, 3.0), Radians(0.7)).expect("axis");
let v = Vec3::new(1.0, -2.0, 0.5);
let back = q
.inverse()
.expect("a unit quaternion is invertible")
.rotate(q.rotate(v));
assert_vec(back, v);
}
#[test]
fn to_mat3_matches_rotate() {
let q = Quat::from_axis_angle(Vec3::new(1.0, 1.0, 0.0), Radians(0.3)).expect("axis");
let v = Vec3::new(0.5, 2.0, -1.0);
assert_vec(q.to_mat3() * v, q.rotate(v));
}
#[test]
fn normalization_scales_to_unit_length() {
let q = Quat::new(2.0, 0.0, 0.0, 0.0);
let unit = q.normalize().expect("non-zero quaternion");
assert!(close(unit.w, 1.0));
assert_eq!(Quat::new(0.0, 0.0, 0.0, 0.0).normalize(), None);
}
#[test]
fn identity_maps_everything_to_itself() {
let p = Vec3::new(1.0, 2.0, 3.0);
assert_vec(Transform::IDENTITY.transform_point(p), p);
}
#[test]
fn point_is_rotated_then_translated() {
let t = Transform::new(
Vec3::new(10.0, 0.0, 0.0),
Quat::from_axis_angle(Vec3::Z, Radians::from_degrees(90.0)).expect("axis"),
);
assert_vec(t.transform_point(Vec3::X), Vec3::new(10.0, 1.0, 0.0));
}
#[test]
fn vector_ignores_translation() {
let t = Transform::new(
Vec3::new(10.0, 0.0, 0.0),
Quat::from_axis_angle(Vec3::Z, Radians::from_degrees(90.0)).expect("axis"),
);
assert_vec(t.transform_vector(Vec3::X), Vec3::Y);
}
#[test]
fn compose_matches_sequential_application() {
let a = Transform::new(
Vec3::new(1.0, 0.0, 0.0),
Quat::from_axis_angle(Vec3::Z, Radians::from_degrees(90.0)).expect("axis"),
);
let b = Transform::new(
Vec3::new(0.0, 2.0, 0.0),
Quat::from_axis_angle(Vec3::X, Radians::from_degrees(45.0)).expect("axis"),
);
let p = Vec3::new(0.3, -0.4, 0.5);
assert_vec(
(a * b).transform_point(p),
a.transform_point(b.transform_point(p)),
);
}
#[test]
fn inverse_round_trip_of_the_transform() {
let t = Transform::new(
Vec3::new(1.0, -2.0, 3.0),
Quat::from_axis_angle(Vec3::new(1.0, 1.0, 1.0), Radians(0.9)).expect("axis"),
);
let p = Vec3::new(-0.5, 0.25, 2.0);
let back = t
.inverse()
.expect("unit rotation inverts")
.transform_point(t.transform_point(p));
assert_vec(back, p);
}

View file

@ -0,0 +1,59 @@
//! A rigid transform: rotation followed by translation.
use core::ops::Mul;
use super::{Quat, Vec3};
/// A position and an orientation; the canonical placement of a rigid body.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Transform {
pub position: Vec3,
pub rotation: Quat,
}
impl Transform {
/// The origin with no rotation.
pub const IDENTITY: Self = Self::new(Vec3::ZERO, Quat::IDENTITY);
/// Builds a transform from a position and an orientation.
#[inline]
#[must_use]
pub const fn new(position: Vec3, rotation: Quat) -> Self {
Self { position, rotation }
}
/// Maps a point from local space to the space this transform lives in.
#[inline]
#[must_use]
pub fn transform_point(self, point: Vec3) -> Vec3 {
self.rotation.rotate(point) + self.position
}
/// Rotates a direction; translation does not apply.
#[inline]
#[must_use]
pub fn transform_vector(self, vector: Vec3) -> Vec3 {
self.rotation.rotate(vector)
}
/// The inverse transform, or `None` for a zero rotation.
#[inline]
#[must_use]
pub fn inverse(self) -> Option<Self> {
let rotation = self.rotation.inverse()?;
Some(Self::new(-rotation.rotate(self.position), rotation))
}
}
impl Mul for Transform {
type Output = Self;
/// Composition: `(a * b).transform_point(p) == a.transform_point(b.transform_point(p))`.
#[inline]
fn mul(self, rhs: Self) -> Self {
Self::new(
self.transform_point(rhs.position),
self.rotation * rhs.rotation,
)
}
}

151
crates/core/src/vec/vec3.rs Normal file
View file

@ -0,0 +1,151 @@
//! A 3D vector on `f64`, deterministic by construction: no `std` transcendental
//! functions, only `fabrilis_core::math`.
use core::ops::{Add, AddAssign, Div, Mul, Neg, Sub, SubAssign};
use crate::math;
/// A point or direction in 3D space, metres unless stated otherwise.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct Vec3 {
pub x: f64,
pub y: f64,
pub z: f64,
}
impl Vec3 {
/// The zero vector.
pub const ZERO: Self = Self::new(0.0, 0.0, 0.0);
/// The unit vector along X.
pub const X: Self = Self::new(1.0, 0.0, 0.0);
/// The unit vector along Y.
pub const Y: Self = Self::new(0.0, 1.0, 0.0);
/// The unit vector along Z.
pub const Z: Self = Self::new(0.0, 0.0, 1.0);
/// Builds a vector from its components.
#[inline]
#[must_use]
pub const fn new(x: f64, y: f64, z: f64) -> Self {
Self { x, y, z }
}
/// The dot product.
#[inline]
#[must_use]
pub fn dot(self, rhs: Self) -> f64 {
self.x * rhs.x + self.y * rhs.y + self.z * rhs.z
}
/// The cross product; follows the right-hand rule.
#[inline]
#[must_use]
pub fn cross(self, rhs: Self) -> Self {
Self::new(
self.y * rhs.z - self.z * rhs.y,
self.z * rhs.x - self.x * rhs.z,
self.x * rhs.y - self.y * rhs.x,
)
}
/// The squared length, cheaper than `length` when only comparisons are needed.
#[inline]
#[must_use]
pub fn length_squared(self) -> f64 {
self.dot(self)
}
/// The Euclidean length.
#[inline]
#[must_use]
pub fn length(self) -> f64 {
math::sqrt(self.length_squared())
}
/// The unit vector, or `None` for the zero vector and non-finite input.
#[inline]
#[must_use]
pub fn normalized(self) -> Option<Self> {
let len = self.length();
if len > 0.0 && len.is_finite() {
Some(self / len)
} else {
None
}
}
/// True when every component is finite.
#[inline]
#[must_use]
pub fn is_finite(self) -> bool {
self.x.is_finite() && self.y.is_finite() && self.z.is_finite()
}
}
impl Add for Vec3 {
type Output = Self;
#[inline]
fn add(self, rhs: Self) -> Self {
Self::new(self.x + rhs.x, self.y + rhs.y, self.z + rhs.z)
}
}
impl Sub for Vec3 {
type Output = Self;
#[inline]
fn sub(self, rhs: Self) -> Self {
Self::new(self.x - rhs.x, self.y - rhs.y, self.z - rhs.z)
}
}
impl Neg for Vec3 {
type Output = Self;
#[inline]
fn neg(self) -> Self {
Self::new(-self.x, -self.y, -self.z)
}
}
impl Mul<f64> for Vec3 {
type Output = Self;
#[inline]
fn mul(self, rhs: f64) -> Self {
Self::new(self.x * rhs, self.y * rhs, self.z * rhs)
}
}
impl Mul<Vec3> for f64 {
type Output = Vec3;
#[inline]
fn mul(self, rhs: Vec3) -> Vec3 {
rhs * self
}
}
impl Div<f64> for Vec3 {
type Output = Self;
#[inline]
fn div(self, rhs: f64) -> Self {
Self::new(self.x / rhs, self.y / rhs, self.z / rhs)
}
}
impl AddAssign for Vec3 {
#[inline]
fn add_assign(&mut self, rhs: Self) {
*self = *self + rhs;
}
}
impl SubAssign for Vec3 {
#[inline]
fn sub_assign(&mut self, rhs: Self) {
*self = *self - rhs;
}
}

View file

@ -0,0 +1,69 @@
//! Determinism golden test: the trajectory hash must not change between runs,
//! operating systems or versions. If it changed on purpose, update GOLDEN and explain why in the commit.
#![allow(
clippy::unwrap_used,
reason = "test helper: a failure should abort the test"
)]
use std::cell::RefCell;
use std::rc::Rc;
use fabrilis_core::fidelity::{Fidelity, Mode};
use fabrilis_core::math;
use fabrilis_core::sched::{Scheduler, Subsystem};
use fabrilis_core::snapshot::hash::StateHasher;
use fabrilis_core::time::{SimDelta, SimTime};
const GOLDEN: u64 = 0xdd62_00fc_171e_65e1;
struct Oscillator {
id: u64,
phase: f64,
hasher: Rc<RefCell<StateHasher>>,
}
impl Subsystem for Oscillator {
fn name(&self) -> &'static str {
"oscillator"
}
fn step(&mut self, now: SimTime, dt: SimDelta) {
let dt = dt.as_seconds().get();
self.phase += dt * 50.0 * math::exp(-self.phase * 0.001);
let value = math::sin(self.phase) * math::cos(self.phase * 0.5);
let mut h = self.hasher.borrow_mut();
h.write_u64(self.id);
h.write_u64(now.nanos());
h.write_f64(value);
}
}
fn run(mode: Mode, epochs: u64) -> u64 {
let fidelity = Fidelity::for_mode(mode);
let hasher = Rc::new(RefCell::new(StateHasher::new()));
let mut s = Scheduler::new(fidelity.epoch()).unwrap();
for (id, period) in [(0, fidelity.physics_step), (1, fidelity.analog_step)] {
let sub = Oscillator {
id,
phase: 0.1,
hasher: Rc::clone(&hasher),
};
s.add(Box::new(sub), period).unwrap();
}
s.run_epochs(epochs);
hasher.borrow().finish()
}
#[test]
fn repeated_runs_are_identical() {
for mode in [Mode::Bench, Mode::Lab, Mode::World] {
assert_eq!(run(mode, 50), run(mode, 50), "{mode:?}");
}
}
#[test]
fn world_trajectory_matches_golden() {
let hash = run(Mode::World, 250);
assert_eq!(hash, GOLDEN, "новый хеш: {hash:#018x}");
}