liquidwar7core 0.2.0

Liquidwar7 core logic library, low-level things which are game-engine agnostic.
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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
// Copyright (C) 2025 Christian Mauduit <ufoot@ufoot.org>

//! Game handler for timing and step execution.
//!
//! This module contains the [`GameHandler`] struct which wraps a [`GameState`]
//! and manages fixed timestep updates.

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

use crate::GameState;

const DEFAULT_STEPS_PER_SECOND: f64 = 25.0;

/// Maximum steps per process call to avoid spiral of death.
/// If we fall behind, we drop time rather than trying to catch up.
const MAX_STEPS_PER_PROCESS: u32 = 10;

/// Computes the odd_even value from a step count.
///
/// The base pattern alternates every step, but additional variations are
/// XORed in to prevent fighters from getting stuck in loops:
/// - Every 7 steps, the pattern inverts for a stretch
/// - Every 13 steps, the pattern inverts for a stretch
/// - Every 37 steps, the pattern inverts for a stretch
///
/// Using three prime-based inversions with stretches ensures the distribution
/// stays close to 50/50 while creating chaotic patterns with a very long period.
fn odd_even_from_steps_count(steps_count: u64) -> bool {
    let base = steps_count % 2 == 1;
    let invert_7 = (steps_count / 7) % 2 == 1;
    let invert_13 = (steps_count / 13) % 2 == 1;
    let invert_37 = (steps_count / 37) % 2 == 1;
    base ^ invert_7 ^ invert_13 ^ invert_37
}

/// Handles game timing and processing logic.
/// Wraps a GameState and manages fixed timestep updates.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct GameHandler<S: GameState> {
    state: S,
    elapsed_time: f64,
    accumulated_time: f64,
    steps_per_second: f64,
    steps_count: u64,
    /// True if time was dropped in the last process() call due to falling behind.
    lagging: bool,
}

impl<S: GameState> GameHandler<S> {
    pub fn new(state: S) -> Self {
        Self {
            state,
            elapsed_time: 0.0,
            accumulated_time: 0.0,
            steps_per_second: DEFAULT_STEPS_PER_SECOND,
            steps_count: 0,
            lagging: false,
        }
    }

    pub fn state(&self) -> &S {
        &self.state
    }

    pub fn state_mut(&mut self) -> &mut S {
        &mut self.state
    }

    pub fn elapsed_time(&self) -> f64 {
        self.elapsed_time
    }

    pub fn steps_per_second(&self) -> f64 {
        self.steps_per_second
    }

    pub fn set_steps_per_second(&mut self, steps_per_second: f64) {
        assert!(steps_per_second > 0.0, "steps_per_second must be positive");
        self.steps_per_second = steps_per_second;
    }

    pub fn steps_count(&self) -> u64 {
        self.steps_count
    }

    /// Returns true if time was dropped in the last `process()` call.
    ///
    /// This indicates the game is falling behind and cannot keep up with
    /// the requested steps per second at the current frame rate.
    pub fn is_lagging(&self) -> bool {
        self.lagging
    }

    /// Returns the interpolation factor between the last step and the next.
    ///
    /// This value ranges from 0.0 (just after a step) to ~1.0 (just before the next step).
    /// Use this to interpolate display positions between logic steps for smooth rendering
    /// when the display rate (e.g., 60fps) is higher than the logic rate (e.g., 25 steps/sec).
    ///
    /// # Example
    ///
    /// ```text
    /// displayed_position = lerp(previous_position, current_position, interpolation_factor())
    /// ```
    pub fn interpolation_factor(&self) -> f64 {
        let step_duration = 1.0 / self.steps_per_second;
        (self.accumulated_time / step_duration).clamp(0.0, 1.0)
    }

    /// Returns a boolean that varies over time to break symmetry and avoid cycling.
    ///
    /// The base pattern alternates every step (steps_count % 2), but additional
    /// variations are XORed in to prevent fighters from getting stuck in loops:
    /// - Every 7 steps, the pattern inverts for a stretch
    /// - Every 13 steps, the pattern inverts for a stretch
    /// - Every 37 steps, the pattern inverts for a stretch
    ///
    /// Using prime numbers ensures the combined pattern has a very long period
    /// (LCM of 2, 14, 26, 74 = 6734) before repeating, breaking short cycles.
    pub fn odd_even(&self) -> bool {
        odd_even_from_steps_count(self.steps_count)
    }

    /// Advances the game state by one step.
    fn step(&mut self) {
        self.steps_count += 1;
        self.state.do_step(self.odd_even(), self.steps_count);
    }

    /// Processes the game state based on elapsed time.
    /// Calls `step()` as many times as needed to match the configured steps per second.
    ///
    /// To avoid "spiral of death" when frames are slow, at most [`MAX_STEPS_PER_PROCESS`]
    /// steps are executed per call. If we fall behind, excess accumulated time is dropped
    /// and [`is_lagging`] returns true.
    ///
    /// # Arguments
    /// * `delta` - Time elapsed since last frame, in seconds (matches Godot's `_process(delta)`)
    pub fn process(&mut self, delta: f64) {
        self.elapsed_time += delta;
        self.accumulated_time += delta;

        let step_duration = 1.0 / self.steps_per_second;
        let mut steps_this_frame = 0u32;

        while self.accumulated_time >= step_duration && steps_this_frame < MAX_STEPS_PER_PROCESS {
            self.step();
            self.accumulated_time -= step_duration;
            steps_this_frame += 1;
        }

        // If still behind after max steps, drop the excess time to avoid spiral of death
        if self.accumulated_time >= step_duration {
            self.accumulated_time = self.accumulated_time.rem_euclid(step_duration);
            self.lagging = true;
        } else {
            self.lagging = false;
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[derive(Debug, Clone, Default)]
    struct DummyState {
        step_count: u64,
    }

    impl GameState for DummyState {
        fn do_step(&mut self, _odd_even: bool, _steps_count: u64) {
            self.step_count += 1;
        }
    }

    #[test]
    fn test_new_handler_defaults() {
        let handler = GameHandler::new(DummyState::default());

        assert_eq!(handler.elapsed_time(), 0.0);
        assert_eq!(handler.steps_per_second(), DEFAULT_STEPS_PER_SECOND);
        assert!(!handler.odd_even());
        assert_eq!(handler.steps_count(), 0);
    }

    #[test]
    fn test_set_steps_per_second() {
        let mut handler = GameHandler::new(DummyState::default());

        handler.set_steps_per_second(30.0);
        assert_eq!(handler.steps_per_second(), 30.0);

        handler.set_steps_per_second(120.0);
        assert_eq!(handler.steps_per_second(), 120.0);
    }

    #[test]
    #[should_panic(expected = "steps_per_second must be positive")]
    fn test_set_steps_per_second_zero_panics() {
        let mut handler = GameHandler::new(DummyState::default());
        handler.set_steps_per_second(0.0);
    }

    #[test]
    #[should_panic(expected = "steps_per_second must be positive")]
    fn test_set_steps_per_second_negative_panics() {
        let mut handler = GameHandler::new(DummyState::default());
        handler.set_steps_per_second(-1.0);
    }

    #[test]
    fn test_process_no_steps_when_delta_too_small() {
        let mut handler = GameHandler::new(DummyState::default());
        handler.set_steps_per_second(10.0); // 1 step per 0.1 seconds

        handler.process(0.05); // Only 0.05 seconds, not enough for a step

        assert_eq!(handler.steps_count(), 0);
        assert!(!handler.odd_even());
    }

    #[test]
    fn test_process_one_step() {
        let mut handler = GameHandler::new(DummyState::default());
        handler.set_steps_per_second(10.0); // 1 step per 0.1 seconds

        handler.process(0.1);

        assert_eq!(handler.steps_count(), 1);
        // At step 1: base=T, invert_7=F, invert_13=F -> T
        assert!(handler.odd_even());
    }

    #[test]
    fn test_process_multiple_steps() {
        let mut handler = GameHandler::new(DummyState::default());
        handler.set_steps_per_second(10.0); // 1 step per 0.1 seconds

        handler.process(0.35); // Should trigger 3 steps

        assert_eq!(handler.steps_count(), 3);
        // At step 3: base=T, invert_7=F, invert_13=F -> T
        assert!(handler.odd_even());
    }

    #[test]
    fn test_odd_even_pattern() {
        // Test the odd_even pattern which includes chaos to break cycles:
        // base = steps_count % 2 == 1
        // invert_7 = (steps_count / 7) % 2 == 1
        // invert_13 = (steps_count / 13) % 2 == 1
        // result = base ^ invert_7 ^ invert_13

        let mut handler = GameHandler::new(DummyState::default());
        handler.set_steps_per_second(1000.0); // Fast steps for testing

        // Collect first 30 values
        let mut pattern = vec![handler.odd_even()];
        for _ in 0..29 {
            handler.process(0.001);
            pattern.push(handler.odd_even());
        }

        // Expected pattern based on formula
        let expected: Vec<bool> = (0..30u64).map(odd_even_from_steps_count).collect();

        assert_eq!(pattern, expected, "odd_even pattern mismatch");

        // Verify the pattern is not just simple alternation
        // Count how many times consecutive values are the same
        let same_consecutive = pattern.windows(2).filter(|w| w[0] == w[1]).count();
        assert!(
            same_consecutive > 0,
            "Pattern should have some consecutive same values due to inversions"
        );
    }

    #[test]
    fn test_odd_even_breaks_simple_cycles() {
        // The point of the complex odd_even is to avoid 2-step cycles
        // where fighters oscillate between two positions.
        // With prime-based inversions, the pattern doesn't repeat for a while.

        let mut handler = GameHandler::new(DummyState::default());
        handler.set_steps_per_second(1000.0);

        // Collect 100 values and check cycle length
        let mut pattern = Vec::new();
        for _ in 0..100 {
            pattern.push(handler.odd_even());
            handler.process(0.001);
        }

        // Check that no short cycle exists (e.g., no repeating every 2 or 4 steps)
        // The pattern should not be simply [T,F,T,F,...] or [T,T,F,F,...]
        let simple_alternating: Vec<bool> = (0..100).map(|i| i % 2 == 1).collect();
        assert_ne!(
            pattern, simple_alternating,
            "Pattern should not be simple alternation"
        );
    }

    #[test]
    fn test_odd_even_balanced_distribution() {
        // Verify that over 100000 draws, odd_even produces roughly 50% true and 50% false.
        // This ensures the chaos doesn't bias toward one value.

        let total: u64 = 100000;
        let mut true_count: u64 = 0;

        for s in 0..total {
            if odd_even_from_steps_count(s) {
                true_count += 1;
            }
        }

        let true_ratio = true_count as f32 / total as f32;
        let false_ratio = 1.0 - true_ratio;

        // Allow 5% deviation from perfect 50/50
        assert!(
            (true_ratio - 0.5).abs() < 0.05,
            "true ratio should be ~0.5, got {} ({} true, {} false)",
            true_ratio,
            true_count,
            total - true_count
        );
        assert!(
            (false_ratio - 0.5).abs() < 0.05,
            "false ratio should be ~0.5, got {}",
            false_ratio
        );
    }

    #[test]
    fn test_elapsed_time_accumulates() {
        let mut handler = GameHandler::new(DummyState::default());

        handler.process(0.5);
        assert!((handler.elapsed_time() - 0.5).abs() < 1e-10);

        handler.process(0.3);
        assert!((handler.elapsed_time() - 0.8).abs() < 1e-10);

        handler.process(0.2);
        assert!((handler.elapsed_time() - 1.0).abs() < 1e-10);
    }

    #[test]
    fn test_accumulated_time_carries_over() {
        let mut handler = GameHandler::new(DummyState::default());
        handler.set_steps_per_second(10.0); // 1 step per 0.1 seconds

        handler.process(0.05); // 0.05 accumulated, no step
        assert_eq!(handler.steps_count(), 0);

        handler.process(0.05); // 0.10 accumulated, 1 step
        assert_eq!(handler.steps_count(), 1);

        handler.process(0.05); // 0.05 accumulated, no step
        assert_eq!(handler.steps_count(), 1);

        handler.process(0.06); // 0.11 accumulated, 1 step, 0.01 left over
        assert_eq!(handler.steps_count(), 2);
    }

    #[test]
    fn test_state_mut_access() {
        let mut handler = GameHandler::new(DummyState::default());

        handler.state_mut().step_count = 100;
        assert_eq!(handler.state().step_count, 100);
    }

    #[test]
    fn test_spiral_of_death_protection() {
        // Test that process() caps steps per frame to avoid spiral of death
        let mut handler = GameHandler::new(DummyState::default());
        handler.set_steps_per_second(10.0); // 1 step per 0.1 seconds

        // Request 50 steps worth of time (5.0 seconds at 10 steps/sec)
        // But MAX_STEPS_PER_PROCESS is 10, so only 10 should execute
        handler.process(5.0);

        assert_eq!(
            handler.steps_count(),
            MAX_STEPS_PER_PROCESS as u64,
            "Should cap at MAX_STEPS_PER_PROCESS"
        );

        // Accumulated time should have been reset to avoid catching up forever
        // After 10 steps at 0.1s each = 1.0s consumed, 4.0s excess should be dropped
        // The remaining accumulated_time should be < step_duration (0.1s)
        // We can verify by calling process(0) and checking no new steps run
        let steps_before = handler.steps_count();
        handler.process(0.0);
        assert_eq!(
            handler.steps_count(),
            steps_before,
            "No steps should run with 0 delta after time was dropped"
        );
    }

    #[test]
    fn test_spiral_of_death_drops_excess_time() {
        // More precise test: verify excess time is properly dropped
        let mut handler = GameHandler::new(DummyState::default());
        handler.set_steps_per_second(10.0); // 1 step per 0.1 seconds

        // Process a huge delta
        handler.process(100.0); // Would be 1000 steps without cap

        assert_eq!(handler.steps_count(), MAX_STEPS_PER_PROCESS as u64);

        // Now process a small delta that would NOT trigger a step on its own
        // If time wasn't dropped, we'd have ~99 seconds accumulated and get more steps
        handler.process(0.05);
        assert_eq!(
            handler.steps_count(),
            MAX_STEPS_PER_PROCESS as u64,
            "Excess time should have been dropped, no new steps from small delta"
        );

        // But if we add enough time for one more step, it should work
        handler.process(0.06); // 0.05 + 0.06 = 0.11 >= 0.1
        assert_eq!(
            handler.steps_count(),
            MAX_STEPS_PER_PROCESS as u64 + 1,
            "Should get one more step after accumulating enough time"
        );
    }

    #[test]
    fn test_is_lagging_reports_correctly() {
        let mut handler = GameHandler::new(DummyState::default());
        handler.set_steps_per_second(10.0); // 1 step per 0.1 seconds

        // Initially not lagging
        assert!(!handler.is_lagging());

        // Normal process - not lagging
        handler.process(0.1);
        assert!(!handler.is_lagging(), "Should not lag with normal delta");

        // Process with huge delta - should lag
        handler.process(100.0);
        assert!(handler.is_lagging(), "Should lag after huge delta");

        // Next normal process - should recover
        handler.process(0.1);
        assert!(!handler.is_lagging(), "Should recover after normal delta");
    }

    #[test]
    fn test_interpolation_factor() {
        let mut handler = GameHandler::new(DummyState::default());
        handler.set_steps_per_second(10.0); // 1 step per 0.1 seconds

        // Initially, interpolation factor should be 0
        assert!((handler.interpolation_factor() - 0.0).abs() < 1e-10);

        // After 0.05 seconds (half a step), factor should be ~0.5
        handler.process(0.05);
        assert!(
            (handler.interpolation_factor() - 0.5).abs() < 1e-10,
            "Expected 0.5, got {}",
            handler.interpolation_factor()
        );

        // After another 0.03 seconds (0.08 total), factor should be ~0.8
        handler.process(0.03);
        assert!(
            (handler.interpolation_factor() - 0.8).abs() < 1e-10,
            "Expected 0.8, got {}",
            handler.interpolation_factor()
        );

        // After 0.02 more (0.10 total), a step runs, factor resets to ~0.0
        handler.process(0.02);
        assert_eq!(handler.steps_count(), 1);
        assert!(
            handler.interpolation_factor() < 0.01,
            "Expected ~0.0 after step, got {}",
            handler.interpolation_factor()
        );
    }

    #[test]
    fn test_default_steps_per_second_is_25() {
        // Verify the default for documentation/architecture purposes
        assert_eq!(DEFAULT_STEPS_PER_SECOND, 25.0);
    }
}