Skip to main content

unbanished_core/
random.rs

1//! The game's random number generator: a Mersenne Twister (MT19937).
2//!
3//! The whole simulation draws from one [`Random`], seeded with the map seed. A port must draw the
4//! same numbers in the same order as the original, so every call here matches one call of the
5//! engine's `System::Random`.
6//!
7//! The state is the same as the engine object's: a `u32` index and 624 state words. A save stores
8//! the index, then the words ([`Random::from_parts`] restores them).
9//!
10//! Measured: `tools/emu/random_calls.py` replays 18,000 calls of every kind on 300 seeds (edge
11//! arguments among them: `Rand(0)`, reversed and wide ranges, negative tolerances), and every
12//! result matches the original's.
13//!
14//! ```
15//! use unbanished_core::random::Random;
16//!
17//! let mut rng = Random::new(1234);
18//! let die = rng.rand_range(1, 6);
19//! assert!((1..=6).contains(&die));
20//! ```
21//!
22//! Original: `System::Random`, Runtime `0x1800ca560` to `0x1800ca8b0`.
23
24/// An optional log of draws, to compare the port's draws with the original's.
25///
26/// The original's draws are recorded in the emulator (`tools/emu/rng_trace.py`), and
27/// `tools/triage/rngdiff.py` finds the first draw that differs. Only the outermost draw of a call
28/// is recorded (`rand_float` calling `rand` logs once), with the location of the Rust caller.
29pub mod trace {
30    use std::cell::{Cell, RefCell};
31    use std::panic::Location;
32
33    #[derive(Debug, Clone, PartialEq, Eq)]
34    /// One recorded draw.
35    pub struct Draw {
36        /// `Rand`, `Rand(n)`, `Rand(lo,hi)`, `RandTol(t)`, `RandFloat`, `RandFloatTol`.
37        pub kind: String,
38        /// The Rust code that made the draw.
39        pub at: &'static Location<'static>,
40    }
41
42    thread_local! {
43        static LOG: RefCell<Option<Vec<Draw>>> = const { RefCell::new(None) };
44        static DEPTH: Cell<u32> = const { Cell::new(0) };
45        static REPLAY: RefCell<std::collections::VecDeque<u32>> =
46            const { RefCell::new(std::collections::VecDeque::new()) };
47    }
48
49    /// While recording, make `skips[k]` plain draws before the `k`-th recorded draw. They stand
50    /// for draws the original made from the same generator outside the code being compared (its
51    /// sounds), so both generators give the same numbers to the rest.
52    pub fn replay(skips: impl IntoIterator<Item = u32>) {
53        REPLAY.with(|r| *r.borrow_mut() = skips.into_iter().collect());
54    }
55
56    /// Start recording on this thread (clears any previous log).
57    pub fn start() {
58        LOG.with(|l| *l.borrow_mut() = Some(Vec::new()));
59    }
60
61    /// Stop recording and return the draws.
62    pub fn take() -> Vec<Draw> {
63        LOG.with(|l| l.borrow_mut().take()).unwrap_or_default()
64    }
65
66    /// Write draws as `kind<TAB>caller` lines (the format `rngdiff.py` reads).
67    pub fn write(path: &std::path::Path, draws: &[Draw]) -> std::io::Result<()> {
68        let text: String = draws
69            .iter()
70            .map(|d| format!("{}\t{}:{}\n", d.kind, d.at.file(), d.at.line()))
71            .collect();
72        std::fs::write(path, text)
73    }
74
75    pub(super) struct Guard {
76        /// Plain draws to make first ([`replay`]).
77        pub(super) skip: u32,
78    }
79
80    impl Drop for Guard {
81        fn drop(&mut self) {
82            DEPTH.with(|d| d.set(d.get() - 1));
83        }
84    }
85
86    /// Record one draw unless already inside another draw.
87    #[track_caller]
88    pub(super) fn enter(kind: impl FnOnce() -> String) -> Guard {
89        let at = Location::caller();
90        let outer = DEPTH.with(|d| {
91            let v = d.get();
92            d.set(v + 1);
93            v == 0
94        });
95        let mut skip = 0;
96        if outer {
97            LOG.with(|l| {
98                if let Some(log) = l.borrow_mut().as_mut() {
99                    log.push(Draw { kind: kind(), at });
100                    skip = REPLAY.with(|r| r.borrow_mut().pop_front()).unwrap_or(0);
101                }
102            });
103        }
104        Guard { skip }
105    }
106}
107
108const N: usize = 624;
109const M: usize = 397;
110
111/// The game's random number generator. See the [module documentation](self).
112#[derive(Clone, PartialEq, Eq)]
113pub struct Random {
114    index: u32,
115    state: [u32; N],
116}
117
118impl std::fmt::Debug for Random {
119    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
120        f.debug_struct("Random")
121            .field("index", &self.index)
122            .finish_non_exhaustive()
123    }
124}
125
126impl Random {
127    /// A generator seeded with `seed`, as the engine seeds one.
128    ///
129    /// Original: `Random::Random(unsigned int)`, Runtime `0x1800ca740`.
130    pub fn new(seed: u32) -> Random {
131        let mut state = [0u32; N];
132        state[0] = seed;
133        for i in 1..N {
134            let prev = state[i - 1];
135            state[i] = (prev ^ (prev >> 30))
136                .wrapping_mul(0x6c07_8965)
137                .wrapping_add(i as u32);
138        }
139        Random { index: 0, state }
140    }
141
142    /// A generator restored from a save: its index, then its 624 state words.
143    pub fn from_parts(index: u32, state: [u32; N]) -> Random {
144        Random { index, state }
145    }
146
147    /// The position of the next word in the state.
148    pub fn index(&self) -> u32 {
149        self.index
150    }
151
152    /// The 624 state words.
153    pub fn state(&self) -> &[u32; N] {
154        &self.state
155    }
156
157    /// `NextGroup` (0x1800ca640).
158    fn next_group(&mut self) {
159        for i in 0..N {
160            let y = (self.state[i] & 0x8000_0000) | (self.state[(i + 1) % N] & 0x7fff_ffff);
161            let mut v = self.state[(i + M) % N] ^ (y >> 1);
162            if y & 1 != 0 {
163                v ^= 0x9908_b0df;
164            }
165            self.state[i] = v;
166        }
167    }
168
169    /// Plain draws standing for the original's draws outside the compared code
170    /// ([`trace::replay`]).
171    fn skip(&mut self, n: u32) {
172        for _ in 0..n {
173            self.rand();
174        }
175    }
176
177    /// The next number, any `u32`.
178    ///
179    /// Original: `Rand()`, Runtime `0x1800ca800`.
180    #[track_caller]
181    pub fn rand(&mut self) -> u32 {
182        let g = trace::enter(|| "Rand".into());
183        self.skip(g.skip);
184        if self.index == 0 {
185            self.next_group();
186        }
187        let mut y = self.state[self.index as usize];
188        y ^= y >> 11;
189        y ^= (y & 0xff3a_58ad) << 7;
190        y ^= (y & 0xffff_df8c) << 15;
191        self.index = if self.index + 1 == N as u32 {
192            0
193        } else {
194            self.index + 1
195        };
196        y ^ (y >> 18)
197    }
198
199    /// A number from 0 to `n - 1`. When `n` is 0, it returns 0 and draws nothing.
200    ///
201    /// Original: `Rand(unsigned int)`, Runtime `0x1800ca8b0`.
202    #[track_caller]
203    pub fn rand_below(&mut self, n: u32) -> u32 {
204        let g = trace::enter(|| format!("Rand({n})"));
205        self.skip(g.skip);
206        if n == 0 {
207            return 0;
208        }
209        self.rand() % n
210    }
211
212    /// A number from `lo` to `hi`, both included.
213    ///
214    /// Original: `Rand(int, int)`, Runtime `0x1800ca5e0`.
215    #[track_caller]
216    pub fn rand_range(&mut self, lo: i32, hi: i32) -> i32 {
217        let g = trace::enter(|| format!("Rand({lo},{hi})"));
218        self.skip(g.skip);
219        let r = self.rand();
220        lo.wrapping_add((r % ((hi.wrapping_sub(lo) as u32).wrapping_add(1))) as i32)
221    }
222
223    /// A number from `-t` to `t`, both included.
224    ///
225    /// Original: `RandTol(int)`, Runtime `0x1800ca610`.
226    #[track_caller]
227    pub fn rand_tol(&mut self, t: i32) -> i32 {
228        let g = trace::enter(|| format!("RandTol({t})"));
229        self.skip(g.skip);
230        let r = self.rand();
231        (r % ((t as u32).wrapping_mul(2).wrapping_add(1))) as i32 - t
232    }
233
234    /// A float from 0 to 1, 1 not included: `(float)u × 2⁻³²`.
235    ///
236    /// Original: `RandFloat()`, Runtime `0x1800ca5b0`.
237    #[track_caller]
238    pub fn rand_float(&mut self) -> f32 {
239        let g = trace::enter(|| "RandFloat".into());
240        self.skip(g.skip);
241        self.rand() as f32 * 2.328_306_4e-10
242    }
243
244    /// A float from -1 to 1, -1 not included: `1 − (float)u × 2⁻³² × 2`.
245    ///
246    /// Original: `RandFloatTol()`, Runtime `0x1800ca870`.
247    #[track_caller]
248    pub fn rand_float_tol(&mut self) -> f32 {
249        let g = trace::enter(|| "RandFloatTol".into());
250        self.skip(g.skip);
251        1.0 - self.rand() as f32 * 2.328_306_4e-10 * 2.0
252    }
253}
254
255#[cfg(test)]
256mod tests {
257    use super::*;
258
259    #[test]
260    fn trace_records_outermost_draws_only() {
261        let mut r = Random::new(1);
262        trace::start();
263        r.rand_float();
264        r.rand_below(7);
265        let log = trace::take();
266        assert_eq!(
267            log.iter().map(|d| d.kind.as_str()).collect::<Vec<_>>(),
268            ["RandFloat", "Rand(7)"]
269        );
270        assert!(log[0].at.file().ends_with("random.rs"));
271        r.rand();
272        assert!(trace::take().is_empty());
273    }
274
275    #[test]
276    fn replay_draws_before_recorded_draws() {
277        let mut expected = Random::new(1);
278        expected.rand();
279        let a = expected.rand_float();
280        expected.rand();
281        expected.rand();
282        let b = expected.rand_below(7);
283        let mut r = Random::new(1);
284        trace::start();
285        trace::replay([1, 2]);
286        assert_eq!(r.rand_float(), a);
287        assert_eq!(r.rand_below(7), b);
288        assert_eq!(trace::take().len(), 2);
289    }
290
291    #[test]
292    fn matches_reference_mt19937() {
293        // Reference MT19937 outputs for the canonical default seed 5489.
294        let mut r = Random::new(5489);
295        assert_eq!(r.rand(), 3_499_211_612);
296        assert_eq!(r.rand(), 581_869_302);
297        assert_eq!(r.rand(), 3_890_346_734);
298        for _ in 3..9999 {
299            r.rand();
300        }
301        assert_eq!(r.rand(), 4_123_659_995); // 10000th output
302    }
303}
304
305#[cfg(test)]
306mod golden {
307    //! Values produced by the original Runtime DLL under emulation (tools/emu/check_random.py).
308    use super::*;
309
310    #[test]
311    fn matches_original_engine() {
312        let mut r = Random::new(290);
313        let v: Vec<u32> = (0..5).map(|_| r.rand()).collect();
314        assert_eq!(
315            v,
316            [1174298092, 3342169725, 1127261350, 2332665128, 3191663389]
317        );
318        assert_eq!(
319            [r.rand_tol(0xffffff), r.rand_tol(0xffffff)],
320            [11962091, -9300278]
321        );
322        assert_eq!(
323            r.rand_float_tol().to_bits(),
324            0.20040464401245117f32.to_bits()
325        );
326        assert_eq!(
327            r.rand_float_tol().to_bits(),
328            0.34909939765930176f32.to_bits()
329        );
330    }
331}