moirai-for-games 0.1.0

A small deterministic no_std ECS for constrained and headless games
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
//! Monotonic clocks and fixed-timestep planning for [`crate::App`] and [`crate::world::World`].
//!
//! [`WorldTick`] advances once per successful Update pass. [`ChangeTick`] tags component and
//! resource mutation metadata. [`FixedConfig`] and [`FixedDebtPolicy`] control how overdue fixed
//! intervals are scheduled, dropped, preserved, or coalesced.

use core::fmt;
use core::time::Duration;

/// Monotonic frame counter advanced once per successful Update pass.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Default)]
pub struct WorldTick(u64);

#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub(crate) enum WorldTickError {
    Exhausted,
}

/// Fixed simulation substep identity while FixedUpdate runs.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct FixedStep {
    /// Index of the first fixed interval represented by this run.
    pub index: u64,
    /// Simulation time represented by this run.
    pub delta: Duration,
    /// Number of fixed intervals represented by this run.
    ///
    /// This is one for ordinary fixed updates. A coalesced update represents
    /// more than one interval and advances the next index by this amount.
    pub steps: u64,
}

#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub(crate) enum FixedStepError {
    Exhausted,
}

/// Host-provided fixed timestep: interval, substep cap, and debt policy.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct FixedConfig {
    delta: Duration,
    max_substeps: u32,
    debt_policy: FixedDebtPolicy,
}

/// Policy used when a frame contains more whole fixed intervals than [`FixedConfig::max_substeps`].
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum FixedDebtPolicy {
    /// Run up to the cap, discard remaining whole intervals, and emit diagnostics.
    DropWithDiagnostic,
    /// Run up to the cap and carry remaining whole intervals into future Update passes.
    Preserve,
    /// Run one FixedUpdate with all overdue whole intervals combined into its delta.
    Coalesce,
}

/// Invalid [`FixedConfig`] construction input.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum FixedConfigError {
    /// Fixed interval must be strictly positive.
    NonPositiveDelta,
    /// `max_substeps` must be nonzero.
    ZeroSubstepCap,
}

/// Debt-preserving fixed-step accumulator owned by `Schedule`.
#[derive(Clone, Debug)]
pub(crate) struct FixedAccumulator {
    remainder: Duration,
    next_index: u64,
}

/// Whole fixed intervals discarded when debt exceeds the substep cap.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct FixedDebtDropped {
    /// Number of whole intervals dropped this frame.
    pub steps: u128,
}

/// Whole fixed intervals represented by one coalesced FixedUpdate run.
/// Whole fixed intervals combined into one coalesced FixedUpdate run.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct FixedDebtCoalesced {
    /// Number of whole intervals represented by the coalesced run.
    pub steps: u128,
}

#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub(crate) enum FixedWork {
    Steps(u32),
    Coalesced { steps: u128, delta: Duration },
}

#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub(crate) struct FixedPlan {
    pub work: FixedWork,
    pub dropped: Option<FixedDebtDropped>,
    pub coalesced: Option<FixedDebtCoalesced>,
}

/// Monotonic world change counter for component/resource mutation metadata.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Default)]
pub struct ChangeTick(u64);

#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub(crate) enum ChangeTickError {
    Exhausted,
}

impl WorldTick {
    /// Initial world tick before the first Update pass.
    pub const ZERO: Self = Self(0);

    /// Returns the underlying counter value.
    pub fn raw(self) -> u64 {
        self.0
    }

    #[allow(dead_code)]
    pub(crate) fn set_raw(&mut self, raw: u64) {
        self.0 = raw;
    }

    pub(crate) fn advance(&mut self) -> Result<Self, WorldTickError> {
        self.0 = self.0.checked_add(1).ok_or(WorldTickError::Exhausted)?;
        Ok(Self(self.0))
    }
}

impl FixedConfig {
    /// Default substep cap used by [`FixedConfig::new`].
    pub const DEFAULT_MAX_SUBSTEPS: u32 = 8;

    /// Creates fixed configuration with [`Self::DEFAULT_MAX_SUBSTEPS`] and
    /// [`FixedDebtPolicy::DropWithDiagnostic`].
    pub fn new(delta: Duration) -> Result<Self, FixedConfigError> {
        if delta.as_nanos() == 0 {
            return Err(FixedConfigError::NonPositiveDelta);
        }
        Ok(Self {
            delta,
            max_substeps: Self::DEFAULT_MAX_SUBSTEPS,
            debt_policy: FixedDebtPolicy::DropWithDiagnostic,
        })
    }

    /// Sets the maximum fixed substeps executed per Update pass.
    pub fn with_max_substeps(mut self, max_substeps: u32) -> Result<Self, FixedConfigError> {
        if max_substeps == 0 {
            return Err(FixedConfigError::ZeroSubstepCap);
        }
        self.max_substeps = max_substeps;
        Ok(self)
    }

    /// Fixed simulation interval.
    pub fn delta(&self) -> Duration {
        self.delta
    }

    /// Maximum fixed substeps scheduled per Update pass.
    pub fn max_substeps(&self) -> u32 {
        self.max_substeps
    }

    /// Selects how overdue whole intervals are handled beyond the substep cap.
    pub fn with_debt_policy(mut self, debt_policy: FixedDebtPolicy) -> Self {
        self.debt_policy = debt_policy;
        self
    }

    /// Active debt policy for overdue fixed intervals.
    pub fn debt_policy(&self) -> FixedDebtPolicy {
        self.debt_policy
    }
}

impl FixedAccumulator {
    pub fn new() -> Self {
        Self {
            remainder: Duration::ZERO,
            next_index: 0,
        }
    }

    #[cfg(test)]
    pub(crate) fn set_next_index_for_test(&mut self, next_index: u64) {
        self.next_index = next_index;
    }

    pub fn peek_plan(&self, frame_delta: Duration, config: &FixedConfig) -> FixedPlan {
        Self::substep_plan(self.remainder.saturating_add(frame_delta), config).0
    }

    pub fn plan(&mut self, frame_delta: Duration, config: &FixedConfig) -> FixedPlan {
        let total = self.remainder.saturating_add(frame_delta);
        let (plan, remainder) = Self::substep_plan(total, config);
        self.remainder = remainder;
        plan
    }

    pub fn preflight_steps(&self, steps: u128) -> Result<(), FixedStepError> {
        if steps == 0 {
            return Ok(());
        }
        let steps = u64::try_from(steps).map_err(|_| FixedStepError::Exhausted)?;
        let last = self
            .next_index
            .checked_add(steps - 1)
            .ok_or(FixedStepError::Exhausted)?;
        last.checked_add(1).ok_or(FixedStepError::Exhausted)?;
        Ok(())
    }

    fn substep_plan(total: Duration, config: &FixedConfig) -> (FixedPlan, Duration) {
        let delta_nanos = config.delta().as_nanos();
        let total_nanos = total.as_nanos();
        let due = total_nanos / delta_nanos;
        let run = due.min(config.max_substeps() as u128) as u32;
        let ordinary = FixedPlan {
            work: FixedWork::Steps(run),
            dropped: None,
            coalesced: None,
        };
        if due <= config.max_substeps() as u128 {
            return (ordinary, duration_from_nanos(total_nanos % delta_nanos));
        }

        match config.debt_policy() {
            FixedDebtPolicy::DropWithDiagnostic => (
                FixedPlan {
                    dropped: Some(FixedDebtDropped {
                        steps: due - run as u128,
                    }),
                    ..ordinary
                },
                duration_from_nanos(total_nanos % delta_nanos),
            ),
            FixedDebtPolicy::Preserve => {
                let consumed = delta_nanos.saturating_mul(run as u128);
                (ordinary, duration_from_nanos(total_nanos - consumed))
            }
            FixedDebtPolicy::Coalesce => {
                let delta = duration_from_nanos(delta_nanos.saturating_mul(due));
                (
                    FixedPlan {
                        work: FixedWork::Coalesced { steps: due, delta },
                        dropped: None,
                        coalesced: Some(FixedDebtCoalesced { steps: due }),
                    },
                    duration_from_nanos(total_nanos % delta_nanos),
                )
            }
        }
    }

    pub fn next_step(&mut self, config: &FixedConfig) -> FixedStep {
        let step = FixedStep {
            index: self.next_index,
            delta: config.delta(),
            steps: 1,
        };
        self.next_index = self.next_index.saturating_add(step.steps);
        step
    }

    pub fn next_coalesced(&mut self, steps: u64, delta: Duration) -> FixedStep {
        let step = FixedStep {
            index: self.next_index,
            delta,
            steps,
        };
        self.next_index = self.next_index.saturating_add(steps);
        step
    }
}

fn duration_from_nanos(nanos: u128) -> Duration {
    const NANOS_PER_SECOND: u128 = 1_000_000_000;
    Duration::new(
        (nanos / NANOS_PER_SECOND) as u64,
        (nanos % NANOS_PER_SECOND) as u32,
    )
}

impl Default for FixedAccumulator {
    fn default() -> Self {
        Self::new()
    }
}

impl fmt::Display for WorldTick {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

impl ChangeTick {
    /// Initial change tick before any mutation metadata is issued.
    pub const ZERO: Self = Self(0);

    /// Constructs a tick from a raw counter value.
    pub const fn from_raw(raw: u64) -> Self {
        Self(raw)
    }

    /// Returns the underlying counter value.
    pub fn raw(self) -> u64 {
        self.0
    }

    pub(crate) fn advance(&mut self) -> Result<Self, ChangeTickError> {
        self.0 = self.0.checked_add(1).ok_or(ChangeTickError::Exhausted)?;
        Ok(Self(self.0))
    }

    pub(crate) fn issue(&mut self) -> Result<Self, ChangeTickError> {
        self.advance()
    }

    pub(crate) fn can_advance_n(&self, count: usize) -> bool {
        let count = count as u64;
        self.0.checked_add(count).is_some()
    }
}

impl fmt::Display for ChangeTick {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

#[cfg(test)]
mod tests {
    use super::{FixedAccumulator, FixedConfig, FixedDebtPolicy, FixedWork};
    use core::time::Duration;

    use alloc::format;

    use super::{ChangeTick, FixedConfigError, FixedStepError, WorldTick};

    #[test]
    fn fixed_config_rejects_non_positive_delta() {
        assert!(matches!(
            FixedConfig::new(Duration::ZERO),
            Err(FixedConfigError::NonPositiveDelta)
        ));
    }

    #[test]
    fn fixed_config_rejects_zero_substep_cap() {
        let config = FixedConfig::new(Duration::from_millis(1)).expect("delta");
        assert!(matches!(
            config.with_max_substeps(0),
            Err(FixedConfigError::ZeroSubstepCap)
        ));
    }

    #[test]
    fn preflight_steps_zero_is_ok() {
        let accumulator = FixedAccumulator::new();
        accumulator.preflight_steps(0).expect("zero steps");
    }

    #[test]
    fn preflight_steps_reports_exhaustion_near_u64_max() {
        let mut accumulator = FixedAccumulator::new();
        accumulator.set_next_index_for_test(u64::MAX);
        assert!(matches!(
            accumulator.preflight_steps(1),
            Err(FixedStepError::Exhausted)
        ));
    }

    #[test]
    fn world_tick_and_change_tick_display_format_raw_values() {
        assert_eq!(format!("{}", WorldTick::ZERO), "0");
        assert_eq!(format!("{}", ChangeTick::from_raw(9)), "9");
    }

    #[test]
    fn default_accumulator_matches_new() {
        assert_eq!(
            FixedAccumulator::default().peek_plan(
                Duration::from_millis(1),
                &FixedConfig::new(Duration::from_millis(1)).expect("delta")
            ),
            FixedAccumulator::new().peek_plan(
                Duration::from_millis(1),
                &FixedConfig::new(Duration::from_millis(1)).expect("delta")
            )
        );
    }

    #[test]
    fn huge_deltas_drop_debt_without_iterating_or_preserving_whole_steps() {
        let config = FixedConfig::new(Duration::from_millis(1))
            .expect("positive delta")
            .with_max_substeps(8)
            .expect("cap");
        let mut accumulator = FixedAccumulator::new();

        let plan = accumulator.plan(Duration::MAX, &config);

        assert_eq!(plan.work, FixedWork::Steps(8));
        assert_eq!(
            plan.dropped.expect("debt").steps,
            Duration::MAX.as_nanos() / config.delta().as_nanos() - 8
        );
        assert!(accumulator.remainder < config.delta());
    }

    #[test]
    fn preserve_debt_keeps_unrun_whole_steps() {
        let config = FixedConfig::new(Duration::from_millis(10))
            .expect("positive delta")
            .with_max_substeps(2)
            .expect("cap")
            .with_debt_policy(FixedDebtPolicy::Preserve);
        let mut accumulator = FixedAccumulator::new();

        let first = accumulator.plan(Duration::from_millis(50), &config);
        assert_eq!(first.work, FixedWork::Steps(2));
        assert!(first.dropped.is_none());
        let second = accumulator.plan(Duration::ZERO, &config);
        assert_eq!(second.work, FixedWork::Steps(2));
    }

    #[test]
    fn coalesce_represents_all_overdue_intervals_once() {
        let config = FixedConfig::new(Duration::from_millis(10))
            .expect("positive delta")
            .with_max_substeps(2)
            .expect("cap")
            .with_debt_policy(FixedDebtPolicy::Coalesce);
        let mut accumulator = FixedAccumulator::new();

        let plan = accumulator.plan(Duration::from_millis(55), &config);
        assert_eq!(
            plan.work,
            FixedWork::Coalesced {
                steps: 5,
                delta: Duration::from_millis(50),
            }
        );
        assert_eq!(plan.coalesced.expect("coalesced").steps, 5);
        assert_eq!(accumulator.remainder, Duration::from_millis(5));
    }
}