Skip to main content

openqmc/
state.rs

1//! Port of `oqmc/state.h` — the generic 8-byte sampler state shared by all
2//! sampler implementations. Small enough to pass by value; carries the
3//! pattern/sample/pixel identifiers and the domain-tree mutations.
4
5use crate::encode::{EncodeKey, encode_bits16};
6use crate::pcg;
7
8/// 2^16 sample-index upper limit (bit size).
9pub const MAX_INDEX_BIT_SIZE: u32 = 16;
10/// 2^16 sample-index upper limit.
11pub const MAX_INDEX_SIZE: usize = 1 << 16;
12/// Pixel-x encoding precision (256 pixels).
13pub const SPATIAL_ENCODE_BITS_X: u32 = 8;
14/// Pixel-y encoding precision (256 pixels).
15pub const SPATIAL_ENCODE_BITS_Y: u32 = 8;
16
17/// Top 16 bits of a sample index (the domain key for indices >= 2^16).
18#[inline]
19pub const fn compute_index_key(index: i32) -> i32 {
20    index >> MAX_INDEX_BIT_SIZE
21}
22
23/// Bottom 16 bits of a sample index.
24#[inline]
25pub const fn compute_index_id(index: i32) -> i32 {
26    index & (MAX_INDEX_SIZE as i32 - 1)
27}
28
29/// Generic sampler state.
30#[derive(Clone, Copy, Debug, PartialEq, Eq)]
31pub struct State64Bit {
32    /// Identifier for the domain pattern.
33    pub pattern_id: u32,
34    /// Identifier for the sample index.
35    pub sample_id: u16,
36    /// Identifier for the pixel position.
37    pub pixel_id: u16,
38}
39
40impl State64Bit {
41    /// Construct from pixel, frame and sample indices. Pixels are correlated by
42    /// default; call [`pixel_decorrelate`](Self::pixel_decorrelate) to separate
43    /// them.
44    #[inline]
45    pub fn new(x: i32, y: i32, frame: i32, index: i32) -> Self {
46        debug_assert!(index >= 0);
47
48        let index_key = compute_index_key(index);
49        let index_id = compute_index_id(index);
50
51        let pixel_id =
52            encode_bits16::<SPATIAL_ENCODE_BITS_X, SPATIAL_ENCODE_BITS_Y, 0>(EncodeKey {
53                x,
54                y,
55                z: 0,
56            });
57
58        Self {
59            pattern_id: pcg::init_seed((frame + index_key) as u32),
60            sample_id: index_id as u16,
61            pixel_id,
62        }
63    }
64
65    /// Decorrelate the state between pixels using the pixel identifier.
66    #[inline]
67    pub fn pixel_decorrelate(&self) -> Self {
68        self.new_domain(self.pixel_id as i32)
69    }
70
71    /// Derive a child domain with an independent 4D pattern.
72    #[inline]
73    pub fn new_domain(&self, key: i32) -> Self {
74        let mut ret = *self;
75        ret.pattern_id = pcg::state_transition(self.pattern_id.wrapping_add(key as u32));
76        ret
77    }
78
79    /// Derive a split domain with a fixed sample-rate multiplier (`size`).
80    #[inline]
81    pub fn new_domain_split(&self, key: i32, size: i32, index: i32) -> Self {
82        debug_assert!(size > 0 && index >= 0);
83
84        let combined = self.sample_id as i32 * size + index;
85        let index_key = compute_index_key(combined);
86        let index_id = compute_index_id(combined);
87
88        let mut ret = self.new_domain(key).new_domain(index_key);
89        ret.sample_id = index_id as u16;
90        ret
91    }
92
93    /// Derive a split domain with an adaptive (local) distribution.
94    #[inline]
95    pub fn new_domain_distrib(&self, key: i32, index: i32) -> Self {
96        debug_assert!(index >= 0);
97
98        let index_key = compute_index_key(index);
99        let index_id = compute_index_id(index);
100
101        let mut ret = self
102            .new_domain(key)
103            .new_domain(index_key)
104            .new_domain(self.sample_id as i32);
105        ret.sample_id = index_id as u16;
106        ret
107    }
108
109    /// Draw `N` low-quality pseudo-random values seeded from this state.
110    #[inline]
111    pub fn draw_rnd<const N: usize>(&self) -> [u32; N] {
112        let mut rng_state = self.pattern_id.wrapping_add(self.sample_id as u32);
113        let mut rnd = [0u32; N];
114        let mut i = 0;
115        while i < N {
116            rnd[i] = pcg::rng(&mut rng_state);
117            i += 1;
118        }
119        rnd
120    }
121
122    /// A sequential PRNG stream seeded from this state (the same seed
123    /// `pattern_id + sample_id` used by [`draw_rnd`](Self::draw_rnd)). Use it for
124    /// unbounded random streams — Russian roulette, delta tracking.
125    #[inline]
126    pub fn rng(&self) -> pcg::Rng {
127        pcg::Rng::new(self.pattern_id.wrapping_add(self.sample_id as u32))
128    }
129}
130
131#[cfg(test)]
132mod tests {
133    use super::*;
134
135    const FRAME: i32 = 2;
136    const INDEX: i32 = 3;
137    const PIXEL_X: i32 = 5;
138    const PIXEL_Y: i32 = 7;
139    const PRIMES: [i32; 20] = [
140        2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
141    ];
142
143    fn default_state() -> State64Bit {
144        State64Bit::new(PIXEL_X, PIXEL_Y, FRAME, INDEX)
145    }
146
147    #[test]
148    fn is_eight_bytes() {
149        assert_eq!(std::mem::size_of::<State64Bit>(), 8);
150    }
151
152    // Mirrors state.cpp:AlterSample.
153    #[test]
154    fn alter_sample() {
155        let d = default_state();
156        for prime in PRIMES {
157            let s = State64Bit::new(PIXEL_X, PIXEL_Y, FRAME, prime);
158            assert_eq!(s.pattern_id, d.pattern_id);
159            assert_eq!(s.pixel_id, d.pixel_id);
160            if prime == INDEX {
161                assert_eq!(s.sample_id, d.sample_id);
162            } else {
163                assert_ne!(s.sample_id, d.sample_id);
164            }
165        }
166
167        let a = State64Bit::new(PIXEL_X, PIXEL_Y, FRAME, MAX_INDEX_SIZE as i32);
168        let b = State64Bit::new(PIXEL_X, PIXEL_Y, FRAME, MAX_INDEX_SIZE as i32 - 1);
169        assert_eq!(a.sample_id, 0);
170        assert_eq!(b.sample_id, (MAX_INDEX_SIZE - 1) as u16);
171        assert_ne!(a.pattern_id, b.pattern_id);
172    }
173
174    // Mirrors state.cpp:AlterPixel — changing pixel changes only pixel_id, and
175    // decorrelation makes pattern_id distinct.
176    #[test]
177    fn alter_pixel() {
178        let base = State64Bit::new(0, 0, 0, INDEX);
179        let base_dec = base.pixel_decorrelate();
180        for x in 1..11 {
181            let s = State64Bit::new(x, 0, 0, INDEX);
182            assert_eq!(s.pattern_id, base.pattern_id);
183            assert_eq!(s.sample_id, base.sample_id);
184            assert_ne!(s.pixel_id, base.pixel_id);
185            assert_ne!(s.pixel_decorrelate().pattern_id, base_dec.pattern_id);
186        }
187    }
188
189    // Mirrors state.cpp:NewDomain — the three domain kinds produce distinct,
190    // non-colliding pattern ids while preserving the right sample/pixel ids.
191    #[test]
192    fn new_domain_distinct() {
193        let d = default_state();
194        let mut seen_state = Vec::new();
195        let mut seen_distr = Vec::new();
196        let mut seen_split = Vec::new();
197        for prime in PRIMES {
198            let state = d.new_domain(prime);
199            let distr = d.new_domain_distrib(prime, 0);
200            let split = d.new_domain_split(prime, 11, 0);
201
202            assert_ne!(state.pattern_id, d.pattern_id);
203            assert_ne!(distr.pattern_id, d.pattern_id);
204            assert_ne!(split.pattern_id, d.pattern_id);
205
206            assert_eq!(state.sample_id, d.sample_id);
207            assert_eq!(distr.sample_id, 0);
208            assert!(split.sample_id >= d.sample_id);
209
210            assert_eq!(state.pixel_id, d.pixel_id);
211            assert_ne!(state.pattern_id, distr.pattern_id);
212            assert_ne!(state.pattern_id, split.pattern_id);
213
214            assert!(!seen_state.contains(&state.pattern_id));
215            assert!(!seen_distr.contains(&distr.pattern_id));
216            assert!(!seen_split.contains(&split.pattern_id));
217            seen_state.push(state.pattern_id);
218            seen_distr.push(distr.pattern_id);
219            seen_split.push(split.pattern_id);
220        }
221    }
222}