Skip to main content

euv_core/game/algorithms/procgen/
impl.rs

1use super::*;
2
3/// Deterministic pseudo-random generation helpers for `DeterministicRng`.
4impl DeterministicRng {
5    /// Creates a new `DeterministicRng` seeded via four SplitMix64 mixing rounds.
6    ///
7    /// # Arguments
8    ///
9    /// - `u64` - Arbitrary 64-bit seed value.
10    ///
11    /// # Returns
12    ///
13    /// - `Self` - Seeded deterministic generator.
14    #[must_use]
15    pub fn new(seed: u64) -> Self {
16        let mut sm: u64 = seed;
17        let s0: u64 = splitmix64_next(&mut sm);
18        let s1: u64 = splitmix64_next(&mut sm);
19        let s2: u64 = splitmix64_next(&mut sm);
20        let s3: u64 = splitmix64_next(&mut sm);
21        Self {
22            state: [s0, s1, s2, s3],
23        }
24    }
25
26    /// Generates the next uniform 64-bit unsigned integer.
27    ///
28    /// # Returns
29    ///
30    /// - `u64` - Pseudo-random 64-bit integer.
31    pub fn next_u64(&mut self) -> u64 {
32        let mut s: [u64; 4] = self.get_state();
33        let result: u64 = s[1].wrapping_mul(5).rotate_left(7).wrapping_mul(9);
34        let t: u64 = s[1] << 17;
35        s[2] ^= s[0];
36        s[3] ^= s[1];
37        s[1] ^= s[2];
38        s[0] ^= s[3];
39        s[2] ^= t;
40        s[3] = s[3].rotate_left(45);
41        self.set_state(s);
42        result
43    }
44
45    /// Generates the next uniform 32-bit unsigned integer.
46    ///
47    /// # Returns
48    ///
49    /// - `u32` - Pseudo-random 32-bit integer.
50    pub fn next_u32(&mut self) -> u32 {
51        (self.next_u64() >> 32) as u32
52    }
53
54    /// Generates a uniform floating-point scalar in `[0.0, 1.0)`.
55    ///
56    /// # Returns
57    ///
58    /// - `f32` - Uniform scalar in `[0.0, 1.0)`.
59    pub fn next_f32(&mut self) -> f32 {
60        let bits: u32 = (self.next_u64() >> 40) as u32;
61        (bits as f32) * (1.0 / 16_777_216.0)
62    }
63
64    /// Generates a uniform floating-point scalar in `[min, max)`.
65    ///
66    /// # Arguments
67    ///
68    /// - `f32` - Lower bound.
69    /// - `f32` - Upper bound.
70    ///
71    /// # Returns
72    ///
73    /// - `f32` - Uniform scalar within `[min, max]`.
74    pub fn next_range_f32(&mut self, min: f32, max: f32) -> f32 {
75        if !min.is_finite() || !max.is_finite() {
76            return 0.0;
77        }
78        let lo: f32 = min.min(max);
79        let hi: f32 = min.max(max);
80        lo + (hi - lo) * self.next_f32()
81    }
82
83    /// Generates a uniform integer in `[min, max_exclusive)`.
84    ///
85    /// # Arguments
86    ///
87    /// - `usize` - Inclusive lower bound.
88    /// - `usize` - Exclusive upper bound.
89    ///
90    /// # Returns
91    ///
92    /// - `usize` - Uniform integer in range (or `min` when `max_exclusive <= min`).
93    pub fn next_range_usize(&mut self, min: usize, max_exclusive: usize) -> usize {
94        if max_exclusive <= min {
95            return min;
96        }
97        let span: u64 = (max_exclusive - min) as u64;
98        min + (self.next_u64() % span) as usize
99    }
100}
101
102/// Seeded Perlin, Simplex, Worley, fBm, Ridged Multifractal, and Curl noise evaluation for `NoiseField`.
103impl NoiseField {
104    /// Builds a deterministic `NoiseField` from `seed`.
105    ///
106    /// # Arguments
107    ///
108    /// - `u64` - Deterministic seed controlling the permutation table and cellular hashes.
109    ///
110    /// # Returns
111    ///
112    /// - `Self` - Seeded noise evaluator.
113    #[must_use]
114    pub fn new(seed: u64) -> Self {
115        let mut base: [u8; 256] = [0; 256];
116        for (idx, slot) in base.iter_mut().enumerate() {
117            *slot = idx as u8;
118        }
119        let mut rng: DeterministicRng = DeterministicRng::new(seed);
120        let mut i: usize = 255;
121        while i > 0 {
122            let j: usize = rng.next_range_usize(0, i + 1);
123            base.swap(i, j);
124            i -= 1;
125        }
126        let mut perm: [u8; 512] = [0; 512];
127        perm[..256].copy_from_slice(&base);
128        perm[256..512].copy_from_slice(&base);
129        Self { seed, perm }
130    }
131
132    /// Evaluates classic improved 2D Perlin gradient noise in `[-1.0, 1.0]`.
133    ///
134    /// # Arguments
135    ///
136    /// - `f32` - World X coordinate.
137    /// - `f32` - World Y coordinate.
138    ///
139    /// # Returns
140    ///
141    /// - `f32` - Smooth deterministic Perlin value bounded in `[-1.0, 1.0]`.
142    #[must_use]
143    pub fn perlin_2d(&self, x: f32, y: f32) -> f32 {
144        if !x.is_finite() || !y.is_finite() {
145            return 0.0;
146        }
147        let perm: &[u8; 512] = self.get_perm();
148        let fx: f32 = x.floor();
149        let fy: f32 = y.floor();
150        let xi: usize = (fx as i32 & 255) as usize;
151        let yi: usize = (fy as i32 & 255) as usize;
152        let xf: f32 = x - fx;
153        let yf: f32 = y - fy;
154        let u: f32 = noise_fade(xf);
155        let v: f32 = noise_fade(yf);
156        let aa: u8 = perm[perm[xi] as usize + yi];
157        let ab: u8 = perm[perm[xi] as usize + yi + 1];
158        let ba: u8 = perm[perm[xi + 1] as usize + yi];
159        let bb: u8 = perm[perm[xi + 1] as usize + yi + 1];
160        let x1: f32 = noise_lerp(grad_2d(aa, xf, yf), grad_2d(ba, xf - 1.0, yf), u);
161        let x2: f32 = noise_lerp(
162            grad_2d(ab, xf, yf - 1.0),
163            grad_2d(bb, xf - 1.0, yf - 1.0),
164            u,
165        );
166        noise_lerp(x1, x2, v).clamp(-1.0, 1.0)
167    }
168
169    /// Evaluates classic improved 3D Perlin gradient noise in `[-1.0, 1.0]`.
170    ///
171    /// # Arguments
172    ///
173    /// - `f32` - World X coordinate.
174    /// - `f32` - World Y coordinate.
175    /// - `f32` - World Z coordinate.
176    ///
177    /// # Returns
178    ///
179    /// - `f32` - Smooth deterministic 3D Perlin value bounded in `[-1.0, 1.0]`.
180    #[must_use]
181    pub fn perlin_3d(&self, x: f32, y: f32, z: f32) -> f32 {
182        if !x.is_finite() || !y.is_finite() || !z.is_finite() {
183            return 0.0;
184        }
185        let perm: &[u8; 512] = self.get_perm();
186        let fx: f32 = x.floor();
187        let fy: f32 = y.floor();
188        let fz: f32 = z.floor();
189        let xi: usize = (fx as i32 & 255) as usize;
190        let yi: usize = (fy as i32 & 255) as usize;
191        let zi: usize = (fz as i32 & 255) as usize;
192        let xf: f32 = x - fx;
193        let yf: f32 = y - fy;
194        let zf: f32 = z - fz;
195        let u: f32 = noise_fade(xf);
196        let v: f32 = noise_fade(yf);
197        let w: f32 = noise_fade(zf);
198        let a: usize = perm[xi] as usize + yi;
199        let aa: usize = perm[a] as usize + zi;
200        let ab: usize = perm[a + 1] as usize + zi;
201        let b: usize = perm[xi + 1] as usize + yi;
202        let ba: usize = perm[b] as usize + zi;
203        let bb: usize = perm[b + 1] as usize + zi;
204        let x1: f32 = noise_lerp(
205            grad_3d(perm[aa], xf, yf, zf),
206            grad_3d(perm[ba], xf - 1.0, yf, zf),
207            u,
208        );
209        let x2: f32 = noise_lerp(
210            grad_3d(perm[ab], xf, yf - 1.0, zf),
211            grad_3d(perm[bb], xf - 1.0, yf - 1.0, zf),
212            u,
213        );
214        let y1: f32 = noise_lerp(x1, x2, v);
215        let x3: f32 = noise_lerp(
216            grad_3d(perm[aa + 1], xf, yf, zf - 1.0),
217            grad_3d(perm[ba + 1], xf - 1.0, yf, zf - 1.0),
218            u,
219        );
220        let x4: f32 = noise_lerp(
221            grad_3d(perm[ab + 1], xf, yf - 1.0, zf - 1.0),
222            grad_3d(perm[bb + 1], xf - 1.0, yf - 1.0, zf - 1.0),
223            u,
224        );
225        let y2: f32 = noise_lerp(x3, x4, v);
226        noise_lerp(y1, y2, w).clamp(-1.0, 1.0)
227    }
228
229    /// Evaluates 2D Simplex gradient noise in `[-1.0, 1.0]`.
230    ///
231    /// # Arguments
232    ///
233    /// - `f32` - World X coordinate.
234    /// - `f32` - World Y coordinate.
235    ///
236    /// # Returns
237    ///
238    /// - `f32` - Isotropic 2D Simplex value bounded in `[-1.0, 1.0]`.
239    #[must_use]
240    pub fn simplex_2d(&self, x: f32, y: f32) -> f32 {
241        if !x.is_finite() || !y.is_finite() {
242            return 0.0;
243        }
244        let perm: &[u8; 512] = self.get_perm();
245        let s: f32 = (x + y) * SIMPLEX_F2;
246        let i: i32 = (x + s).floor() as i32;
247        let j: i32 = (y + s).floor() as i32;
248        let t: f32 = ((i + j) as f32) * SIMPLEX_G2;
249        let x0: f32 = x - ((i as f32) - t);
250        let y0: f32 = y - ((j as f32) - t);
251        let (i1, j1): (i32, i32) = if x0 > y0 { (1, 0) } else { (0, 1) };
252        let x1: f32 = x0 - (i1 as f32) + SIMPLEX_G2;
253        let y1: f32 = y0 - (j1 as f32) + SIMPLEX_G2;
254        let x2: f32 = x0 - 1.0 + 2.0 * SIMPLEX_G2;
255        let y2: f32 = y0 - 1.0 + 2.0 * SIMPLEX_G2;
256        let ii: usize = (i & 255) as usize;
257        let jj: usize = (j & 255) as usize;
258        let gi0: u8 = perm[ii + perm[jj] as usize];
259        let gi1: u8 = perm[ii + (i1 as usize) + perm[jj + (j1 as usize)] as usize];
260        let gi2: u8 = perm[ii + 1 + perm[jj + 1] as usize];
261        let t0: f32 = 0.5 - x0 * x0 - y0 * y0;
262        let n0: f32 = if t0 < 0.0 {
263            0.0
264        } else {
265            let t0_sq: f32 = t0 * t0;
266            t0_sq * t0_sq * grad_2d(gi0, x0, y0)
267        };
268        let t1: f32 = 0.5 - x1 * x1 - y1 * y1;
269        let n1: f32 = if t1 < 0.0 {
270            0.0
271        } else {
272            let t1_sq: f32 = t1 * t1;
273            t1_sq * t1_sq * grad_2d(gi1, x1, y1)
274        };
275        let t2: f32 = 0.5 - x2 * x2 - y2 * y2;
276        let n2: f32 = if t2 < 0.0 {
277            0.0
278        } else {
279            let t2_sq: f32 = t2 * t2;
280            t2_sq * t2_sq * grad_2d(gi2, x2, y2)
281        };
282        (70.0 * (n0 + n1 + n2)).clamp(-1.0, 1.0)
283    }
284
285    /// Evaluates 3D Simplex gradient noise in `[-1.0, 1.0]`.
286    ///
287    /// # Arguments
288    ///
289    /// - `f32` - World X coordinate.
290    /// - `f32` - World Y coordinate.
291    /// - `f32` - World Z coordinate.
292    ///
293    /// # Returns
294    ///
295    /// - `f32` - Isotropic 3D Simplex value bounded in `[-1.0, 1.0]`.
296    #[must_use]
297    pub fn simplex_3d(&self, x: f32, y: f32, z: f32) -> f32 {
298        if !x.is_finite() || !y.is_finite() || !z.is_finite() {
299            return 0.0;
300        }
301        let perm: &[u8; 512] = self.get_perm();
302        let s: f32 = (x + y + z) * SIMPLEX_F3;
303        let i: i32 = (x + s).floor() as i32;
304        let j: i32 = (y + s).floor() as i32;
305        let k: i32 = (z + s).floor() as i32;
306        let t: f32 = ((i + j + k) as f32) * SIMPLEX_G3;
307        let x0: f32 = x - ((i as f32) - t);
308        let y0: f32 = y - ((j as f32) - t);
309        let z0: f32 = z - ((k as f32) - t);
310        let (i1, j1, k1, i2, j2, k2): (usize, usize, usize, usize, usize, usize) = if x0 >= y0 {
311            if y0 >= z0 {
312                (1, 0, 0, 1, 1, 0)
313            } else if x0 >= z0 {
314                (1, 0, 0, 1, 0, 1)
315            } else {
316                (0, 0, 1, 1, 0, 1)
317            }
318        } else if y0 < z0 {
319            (0, 0, 1, 0, 1, 1)
320        } else if x0 < z0 {
321            (0, 1, 0, 0, 1, 1)
322        } else {
323            (0, 1, 0, 1, 1, 0)
324        };
325        let x1: f32 = x0 - (i1 as f32) + SIMPLEX_G3;
326        let y1: f32 = y0 - (j1 as f32) + SIMPLEX_G3;
327        let z1: f32 = z0 - (k1 as f32) + SIMPLEX_G3;
328        let x2: f32 = x0 - (i2 as f32) + 2.0 * SIMPLEX_G3;
329        let y2: f32 = y0 - (j2 as f32) + 2.0 * SIMPLEX_G3;
330        let z2: f32 = z0 - (k2 as f32) + 2.0 * SIMPLEX_G3;
331        let x3: f32 = x0 - 1.0 + 3.0 * SIMPLEX_G3;
332        let y3: f32 = y0 - 1.0 + 3.0 * SIMPLEX_G3;
333        let z3: f32 = z0 - 1.0 + 3.0 * SIMPLEX_G3;
334        let ii: usize = (i & 255) as usize;
335        let jj: usize = (j & 255) as usize;
336        let kk: usize = (k & 255) as usize;
337        let gi0: u8 = perm[ii + perm[jj + perm[kk] as usize] as usize];
338        let gi1: u8 = perm[ii + i1 + perm[jj + j1 + perm[kk + k1] as usize] as usize];
339        let gi2: u8 = perm[ii + i2 + perm[jj + j2 + perm[kk + k2] as usize] as usize];
340        let gi3: u8 = perm[ii + 1 + perm[jj + 1 + perm[kk + 1] as usize] as usize];
341        let corners: [(f32, f32, f32, u8); 4] = [
342            (x0, y0, z0, gi0),
343            (x1, y1, z1, gi1),
344            (x2, y2, z2, gi2),
345            (x3, y3, z3, gi3),
346        ];
347        let mut sum: f32 = 0.0;
348        for &(cx, cy, cz, gi) in &corners {
349            let term: f32 = 0.6 - cx * cx - cy * cy - cz * cz;
350            if term > 0.0 {
351                let term_sq: f32 = term * term;
352                sum += term_sq * term_sq * grad_3d(gi, cx, cy, cz);
353            }
354        }
355        (32.0 * sum).clamp(-1.0, 1.0)
356    }
357
358    /// Evaluates 2D Worley / cellular noise returning `F1`, `F2`, or `F2 - F1`.
359    ///
360    /// # Arguments
361    ///
362    /// - `f32` - World X coordinate.
363    /// - `f32` - World Y coordinate.
364    /// - `WorleyMetric` - Distance norm (`Euclidean`, `Manhattan`, or `Chebyshev`).
365    /// - `WorleyOutput` - Feature distance selector (`F1`, `F2`, or `F2MinusF1`).
366    ///
367    /// # Returns
368    ///
369    /// - `f32` - Non-negative cellular distance value.
370    #[must_use]
371    pub fn worley_2d(&self, x: f32, y: f32, metric: WorleyMetric, output: WorleyOutput) -> f32 {
372        if !x.is_finite() || !y.is_finite() {
373            return 0.0;
374        }
375        let seed: u64 = self.get_seed();
376        let ix: i32 = x.floor() as i32;
377        let iy: i32 = y.floor() as i32;
378        let mut f1: f32 = f32::INFINITY;
379        let mut f2: f32 = f32::INFINITY;
380        for dy in -1..=1 {
381            for dx in -1..=1 {
382                let cx: i32 = ix + dx;
383                let cy: i32 = iy + dy;
384                let (ox, oy): (f32, f32) = worley_hash_2d(cx, cy, seed);
385                let dist: f32 = worley_dist_2d((cx as f32) + ox - x, (cy as f32) + oy - y, metric);
386                if dist < f1 {
387                    f2 = f1;
388                    f1 = dist;
389                } else if dist < f2 {
390                    f2 = dist;
391                }
392            }
393        }
394        match output {
395            WorleyOutput::F1 => f1,
396            WorleyOutput::F2 => f2,
397            WorleyOutput::F2MinusF1 => (f2 - f1).max(0.0),
398        }
399    }
400
401    /// Evaluates 3D Worley / cellular noise returning `F1`, `F2`, or `F2 - F1`.
402    ///
403    /// # Arguments
404    ///
405    /// - `f32` - World X coordinate.
406    /// - `f32` - World Y coordinate.
407    /// - `f32` - World Z coordinate.
408    /// - `WorleyMetric` - Distance norm.
409    /// - `WorleyOutput` - Feature distance selector.
410    ///
411    /// # Returns
412    ///
413    /// - `f32` - Non-negative cellular distance value.
414    #[must_use]
415    pub fn worley_3d(
416        &self,
417        x: f32,
418        y: f32,
419        z: f32,
420        metric: WorleyMetric,
421        output: WorleyOutput,
422    ) -> f32 {
423        if !x.is_finite() || !y.is_finite() || !z.is_finite() {
424            return 0.0;
425        }
426        let seed: u64 = self.get_seed();
427        let ix: i32 = x.floor() as i32;
428        let iy: i32 = y.floor() as i32;
429        let iz: i32 = z.floor() as i32;
430        let mut f1: f32 = f32::INFINITY;
431        let mut f2: f32 = f32::INFINITY;
432        for dz in -1..=1 {
433            for dy in -1..=1 {
434                for dx in -1..=1 {
435                    let cx: i32 = ix + dx;
436                    let cy: i32 = iy + dy;
437                    let cz: i32 = iz + dz;
438                    let (ox, oy, oz): (f32, f32, f32) = worley_hash_3d(cx, cy, cz, seed);
439                    let dist: f32 = worley_dist_3d(
440                        (cx as f32) + ox - x,
441                        (cy as f32) + oy - y,
442                        (cz as f32) + oz - z,
443                        metric,
444                    );
445                    if dist < f1 {
446                        f2 = f1;
447                        f1 = dist;
448                    } else if dist < f2 {
449                        f2 = dist;
450                    }
451                }
452            }
453        }
454        match output {
455            WorleyOutput::F1 => f1,
456            WorleyOutput::F2 => f2,
457            WorleyOutput::F2MinusF1 => (f2 - f1).max(0.0),
458        }
459    }
460
461    /// Evaluates normalized 2D Fractional Brownian Motion (fBm) bounded in `[-1.0, 1.0]`.
462    ///
463    /// # Arguments
464    ///
465    /// - `f32` - World X coordinate.
466    /// - `f32` - World Y coordinate.
467    /// - `u32` - Number of octaves (clamped to `[1, 12]`).
468    /// - `f32` - Frequency multiplier per octave (e.g. `2.0`).
469    /// - `f32` - Amplitude persistence per octave (e.g. `0.5`).
470    ///
471    /// # Returns
472    ///
473    /// - `f32` - Normalized fBm scalar in `[-1.0, 1.0]`.
474    #[must_use]
475    pub fn fbm_2d(&self, x: f32, y: f32, octaves: u32, lacunarity: f32, gain: f32) -> f32 {
476        let count: u32 = octaves.clamp(1, 12);
477        let safe_lac: f32 = if lacunarity.is_finite() && lacunarity > 0.0 {
478            lacunarity
479        } else {
480            2.0
481        };
482        let safe_gain: f32 = if gain.is_finite() && gain > 0.0 {
483            gain
484        } else {
485            0.5
486        };
487        let mut amp: f32 = 1.0;
488        let mut freq: f32 = 1.0;
489        let mut sum: f32 = 0.0;
490        let mut norm: f32 = 0.0;
491        for _ in 0..count {
492            sum += amp * self.perlin_2d(x * freq, y * freq);
493            norm += amp;
494            freq *= safe_lac;
495            amp *= safe_gain;
496        }
497        if norm > 1e-6 {
498            (sum / norm).clamp(-1.0, 1.0)
499        } else {
500            0.0
501        }
502    }
503
504    /// Evaluates normalized 3D Fractional Brownian Motion (fBm) bounded in `[-1.0, 1.0]`.
505    ///
506    /// # Arguments
507    ///
508    /// - `f32` - World X coordinate.
509    /// - `f32` - World Y coordinate.
510    /// - `f32` - World Z coordinate.
511    /// - `u32` - Number of octaves (clamped to `[1, 12]`).
512    /// - `f32` - Frequency multiplier per octave.
513    /// - `f32` - Amplitude persistence per octave.
514    ///
515    /// # Returns
516    ///
517    /// - `f32` - Normalized fBm scalar in `[-1.0, 1.0]`.
518    #[must_use]
519    pub fn fbm_3d(&self, x: f32, y: f32, z: f32, octaves: u32, lacunarity: f32, gain: f32) -> f32 {
520        let count: u32 = octaves.clamp(1, 12);
521        let safe_lac: f32 = if lacunarity.is_finite() && lacunarity > 0.0 {
522            lacunarity
523        } else {
524            2.0
525        };
526        let safe_gain: f32 = if gain.is_finite() && gain > 0.0 {
527            gain
528        } else {
529            0.5
530        };
531        let mut amp: f32 = 1.0;
532        let mut freq: f32 = 1.0;
533        let mut sum: f32 = 0.0;
534        let mut norm: f32 = 0.0;
535        for _ in 0..count {
536            sum += amp * self.perlin_3d(x * freq, y * freq, z * freq);
537            norm += amp;
538            freq *= safe_lac;
539            amp *= safe_gain;
540        }
541        if norm > 1e-6 {
542            (sum / norm).clamp(-1.0, 1.0)
543        } else {
544            0.0
545        }
546    }
547
548    /// Evaluates normalized 2D Ridged Multifractal noise bounded in `[0.0, 1.0]`.
549    ///
550    /// # Arguments
551    ///
552    /// - `f32` - World X coordinate.
553    /// - `f32` - World Y coordinate.
554    /// - `u32` - Octave count (clamped to `[1, 12]`).
555    /// - `f32` - Frequency multiplier per octave.
556    /// - `f32` - Amplitude gain per octave.
557    ///
558    /// # Returns
559    ///
560    /// - `f32` - Sharp mountain-ridge scalar in `[0.0, 1.0]`.
561    #[must_use]
562    pub fn ridged_2d(&self, x: f32, y: f32, octaves: u32, lacunarity: f32, gain: f32) -> f32 {
563        let count: u32 = octaves.clamp(1, 12);
564        let safe_lac: f32 = if lacunarity.is_finite() && lacunarity > 0.0 {
565            lacunarity
566        } else {
567            2.0
568        };
569        let safe_gain: f32 = if gain.is_finite() && gain > 0.0 {
570            gain
571        } else {
572            0.5
573        };
574        let mut amp: f32 = 1.0;
575        let mut freq: f32 = 1.0;
576        let mut weight: f32 = 1.0;
577        let mut sum: f32 = 0.0;
578        let mut norm: f32 = 0.0;
579        for _ in 0..count {
580            let signal_raw: f32 = 1.0 - self.simplex_2d(x * freq, y * freq).abs();
581            let signal: f32 = signal_raw * signal_raw * weight;
582            weight = (signal * 2.0).clamp(0.0, 1.0);
583            sum += signal * amp;
584            norm += amp;
585            freq *= safe_lac;
586            amp *= safe_gain;
587        }
588        if norm > 1e-6 {
589            (sum / norm).clamp(0.0, 1.0)
590        } else {
591            0.0
592        }
593    }
594
595    /// Evaluates normalized 3D Ridged Multifractal noise bounded in `[0.0, 1.0]`.
596    ///
597    /// # Arguments
598    ///
599    /// - `f32` - World X coordinate.
600    /// - `f32` - World Y coordinate.
601    /// - `f32` - World Z coordinate.
602    /// - `u32` - Octave count (clamped to `[1, 12]`).
603    /// - `f32` - Frequency multiplier per octave.
604    /// - `f32` - Amplitude gain per octave.
605    ///
606    /// # Returns
607    ///
608    /// - `f32` - Sharp 3D ridge scalar in `[0.0, 1.0]`.
609    #[must_use]
610    pub fn ridged_3d(
611        &self,
612        x: f32,
613        y: f32,
614        z: f32,
615        octaves: u32,
616        lacunarity: f32,
617        gain: f32,
618    ) -> f32 {
619        let count: u32 = octaves.clamp(1, 12);
620        let safe_lac: f32 = if lacunarity.is_finite() && lacunarity > 0.0 {
621            lacunarity
622        } else {
623            2.0
624        };
625        let safe_gain: f32 = if gain.is_finite() && gain > 0.0 {
626            gain
627        } else {
628            0.5
629        };
630        let mut amp: f32 = 1.0;
631        let mut freq: f32 = 1.0;
632        let mut weight: f32 = 1.0;
633        let mut sum: f32 = 0.0;
634        let mut norm: f32 = 0.0;
635        for _ in 0..count {
636            let signal_raw: f32 = 1.0 - self.simplex_3d(x * freq, y * freq, z * freq).abs();
637            let signal: f32 = signal_raw * signal_raw * weight;
638            weight = (signal * 2.0).clamp(0.0, 1.0);
639            sum += signal * amp;
640            norm += amp;
641            freq *= safe_lac;
642            amp *= safe_gain;
643        }
644        if norm > 1e-6 {
645            (sum / norm).clamp(0.0, 1.0)
646        } else {
647            0.0
648        }
649    }
650
651    /// Evaluates divergence-free 2D Curl Noise `(dPsi/dy, -dPsi/dx)` for swirling flow fields.
652    ///
653    /// # Arguments
654    ///
655    /// - `f32` - World X coordinate.
656    /// - `f32` - World Y coordinate.
657    /// - `f32` - Central difference step size (defaults to `1e-3` when non-positive).
658    ///
659    /// # Returns
660    ///
661    /// - `Vec2` - Divergence-free 2D velocity vector.
662    #[must_use]
663    pub fn curl_2d(&self, x: f32, y: f32, epsilon: f32) -> Vec2 {
664        let eps: f32 = if epsilon.is_finite() && epsilon > 1e-5 {
665            epsilon
666        } else {
667            CURL_DEFAULT_EPS
668        };
669        let inv_2e: f32 = 0.5 / eps;
670        let dpsi_dy: f32 = (self.perlin_2d(x, y + eps) - self.perlin_2d(x, y - eps)) * inv_2e;
671        let dpsi_dx: f32 = (self.perlin_2d(x + eps, y) - self.perlin_2d(x - eps, y)) * inv_2e;
672        Vec2::new(dpsi_dy, -dpsi_dx)
673    }
674
675    /// Evaluates divergence-free 3D Curl Noise `curl(Px, Py, Pz)` for turbulent incompressible fields.
676    ///
677    /// # Arguments
678    ///
679    /// - `f32` - World X coordinate.
680    /// - `f32` - World Y coordinate.
681    /// - `f32` - World Z coordinate.
682    /// - `f32` - Central difference step size (defaults to `1e-3` when non-positive).
683    ///
684    /// # Returns
685    ///
686    /// - `Vec3` - Divergence-free 3D velocity vector.
687    #[must_use]
688    pub fn curl_3d(&self, x: f32, y: f32, z: f32, epsilon: f32) -> Vec3 {
689        let eps: f32 = if epsilon.is_finite() && epsilon > 1e-5 {
690            epsilon
691        } else {
692            CURL_DEFAULT_EPS
693        };
694        let inv_2e: f32 = 0.5 / eps;
695        let px_dy_pos: f32 = self.perlin_3d(x, y + eps, z);
696        let px_dy_neg: f32 = self.perlin_3d(x, y - eps, z);
697        let px_dz_pos: f32 = self.perlin_3d(x, y, z + eps);
698        let px_dz_neg: f32 = self.perlin_3d(x, y, z - eps);
699        let py_x: f32 = x + 31.416;
700        let py_y: f32 = y + 47.853;
701        let py_z: f32 = z + 12.793;
702        let py_dx_pos: f32 = self.perlin_3d(py_x + eps, py_y, py_z);
703        let py_dx_neg: f32 = self.perlin_3d(py_x - eps, py_y, py_z);
704        let py_dz_pos: f32 = self.perlin_3d(py_x, py_y, py_z + eps);
705        let py_dz_neg: f32 = self.perlin_3d(py_x, py_y, py_z - eps);
706        let pz_x: f32 = x - 19.191;
707        let pz_y: f32 = y + 73.219;
708        let pz_z: f32 = z - 54.321;
709        let pz_dx_pos: f32 = self.perlin_3d(pz_x + eps, pz_y, pz_z);
710        let pz_dx_neg: f32 = self.perlin_3d(pz_x - eps, pz_y, pz_z);
711        let pz_dy_pos: f32 = self.perlin_3d(pz_x, pz_y + eps, pz_z);
712        let pz_dy_neg: f32 = self.perlin_3d(pz_x, pz_y - eps, pz_z);
713        let vx: f32 = ((pz_dy_pos - pz_dy_neg) - (py_dz_pos - py_dz_neg)) * inv_2e;
714        let vy: f32 = ((px_dz_pos - px_dz_neg) - (pz_dx_pos - pz_dx_neg)) * inv_2e;
715        let vz: f32 = ((py_dx_pos - py_dx_neg) - (px_dy_pos - px_dy_neg)) * inv_2e;
716        Vec3::new(vx, vy, vz)
717    }
718}
719
720/// Direction indexing and inversion helpers for `WfcDirection`.
721impl WfcDirection {
722    /// Returns the array index `0..4` corresponding to this direction.
723    ///
724    /// # Returns
725    ///
726    /// - `usize` - Direction slot index.
727    #[must_use]
728    pub const fn index(self) -> usize {
729        match self {
730            Self::North => 0,
731            Self::East => 1,
732            Self::South => 2,
733            Self::West => 3,
734        }
735    }
736
737    /// Returns the opposite cardinal direction (`North <-> South`, `East <-> West`).
738    ///
739    /// # Returns
740    ///
741    /// - `Self` - Opposite direction.
742    #[must_use]
743    pub const fn opposite(self) -> Self {
744        match self {
745            Self::North => Self::South,
746            Self::East => Self::West,
747            Self::South => Self::North,
748            Self::West => Self::East,
749        }
750    }
751
752    /// Returns the signed grid offset `(dx, dy)` for stepping in this direction.
753    ///
754    /// # Returns
755    ///
756    /// - `(isize, isize)` - Neighbor offset `(dx, dy)`.
757    #[must_use]
758    pub const fn offset(self) -> (isize, isize) {
759        match self {
760            Self::North => (0, -1),
761            Self::East => (1, 0),
762            Self::South => (0, 1),
763            Self::West => (-1, 0),
764        }
765    }
766}
767
768/// Bitwise domain operations for 128-bit `WfcMask`.
769impl WfcMask {
770    /// Returns an empty bitmask with zero enabled tiles.
771    ///
772    /// # Returns
773    ///
774    /// - `Self` - Empty bitmask.
775    pub(crate) const fn empty() -> Self {
776        Self { words: [0, 0] }
777    }
778
779    /// Returns a bitmask with all tiles `0..tile_count` enabled.
780    ///
781    /// # Arguments
782    ///
783    /// - `usize` - Number of valid tiles (`<= 128`).
784    ///
785    /// # Returns
786    ///
787    /// - `Self` - Full domain mask.
788    pub(crate) fn full(tile_count: usize) -> Self {
789        let clamped: usize = tile_count.min(WFC_MAX_TILES);
790        let lo: u64 = if clamped >= 64 {
791            u64::MAX
792        } else if clamped == 0 {
793            0
794        } else {
795            (1_u64 << clamped) - 1
796        };
797        let hi: u64 = if clamped <= 64 {
798            0
799        } else if clamped >= 128 {
800            u64::MAX
801        } else {
802            (1_u64 << (clamped - 64)) - 1
803        };
804        Self { words: [lo, hi] }
805    }
806
807    /// Returns a bitmask with only tile `tile_idx` enabled.
808    ///
809    /// # Arguments
810    ///
811    /// - `usize` - Tile index in `0..128`.
812    ///
813    /// # Returns
814    ///
815    /// - `Self` - Single-bit mask.
816    pub(crate) fn single(tile_idx: usize) -> Self {
817        if tile_idx < 64 {
818            Self {
819                words: [1_u64 << tile_idx, 0],
820            }
821        } else if tile_idx < WFC_MAX_TILES {
822            Self {
823                words: [0, 1_u64 << (tile_idx - 64)],
824            }
825        } else {
826            Self::empty()
827        }
828    }
829
830    /// Tests whether tile `tile_idx` is enabled in this mask.
831    ///
832    /// # Arguments
833    ///
834    /// - `usize` - Tile index.
835    ///
836    /// # Returns
837    ///
838    /// - `bool` - `true` when bit `tile_idx` is set.
839    pub(crate) fn contains(self, tile_idx: usize) -> bool {
840        let words: [u64; 2] = self.get_words();
841        if tile_idx < 64 {
842            (words[0] & (1_u64 << tile_idx)) != 0
843        } else if tile_idx < WFC_MAX_TILES {
844            (words[1] & (1_u64 << (tile_idx - 64))) != 0
845        } else {
846            false
847        }
848    }
849
850    /// Returns the union `self | other`.
851    ///
852    /// # Arguments
853    ///
854    /// - `Self` - Right-hand bitmask.
855    ///
856    /// # Returns
857    ///
858    /// - `Self` - Bitwise OR union.
859    pub(crate) fn union(self, other: Self) -> Self {
860        let lhs: [u64; 2] = self.get_words();
861        let rhs: [u64; 2] = other.get_words();
862        let w0: u64 = lhs[0] | rhs[0];
863        let w1: u64 = lhs[1] | rhs[1];
864        Self { words: [w0, w1] }
865    }
866
867    /// Returns the intersection `self & other`.
868    ///
869    /// # Arguments
870    ///
871    /// - `Self` - Right-hand bitmask.
872    ///
873    /// # Returns
874    ///
875    /// - `Self` - Bitwise AND intersection.
876    pub(crate) fn intersect(self, other: Self) -> Self {
877        let lhs: [u64; 2] = self.get_words();
878        let rhs: [u64; 2] = other.get_words();
879        Self {
880            words: [lhs[0] & rhs[0], lhs[1] & rhs[1]],
881        }
882    }
883
884    /// Returns `self` with bit `tile_idx` cleared.
885    ///
886    /// # Arguments
887    ///
888    /// - `usize` - Tile index to clear.
889    ///
890    /// # Returns
891    ///
892    /// - `Self` - Updated bitmask.
893    pub(crate) fn without(self, tile_idx: usize) -> Self {
894        let lhs: [u64; 2] = self.get_words();
895        let single: [u64; 2] = Self::single(tile_idx).get_words();
896        Self {
897            words: [lhs[0] & !single[0], lhs[1] & !single[1]],
898        }
899    }
900
901    /// Returns the number of enabled tiles in this domain mask.
902    ///
903    /// # Returns
904    ///
905    /// - `u32` - Popcount of set bits.
906    pub(crate) fn count(self) -> u32 {
907        let words: [u64; 2] = self.get_words();
908        words[0].count_ones() + words[1].count_ones()
909    }
910
911    /// Returns the index of the lowest set tile bit, if non-empty.
912    ///
913    /// # Returns
914    ///
915    /// - `Option<usize>` - Lowest enabled tile index.
916    pub(crate) fn first_tile(self) -> Option<usize> {
917        let words: [u64; 2] = self.get_words();
918        if words[0] != 0 {
919            Some(words[0].trailing_zeros() as usize)
920        } else if words[1] != 0 {
921            Some(64 + words[1].trailing_zeros() as usize)
922        } else {
923            None
924        }
925    }
926}
927
928/// Rule-set construction and symmetric adjacency registration for `WfcRuleSet`.
929impl WfcRuleSet {
930    /// Creates an empty `WfcRuleSet` for `tile_count` tiles (clamped to `[1, 128]`), all weighted `1.0`.
931    ///
932    /// # Arguments
933    ///
934    /// - `usize` - Number of tile types in `1..=128`.
935    ///
936    /// # Returns
937    ///
938    /// - `Self` - Rule set ready for adjacency registration.
939    #[must_use]
940    pub fn new(tile_count: usize) -> Self {
941        let clamped: usize = tile_count.clamp(1, WFC_MAX_TILES);
942        Self {
943            tile_count: clamped,
944            weights: vec![1.0; clamped],
945            compat: vec![[WfcMask::empty(); 4]; clamped],
946        }
947    }
948
949    /// Sets the relative selection weight for `tile_index` (clamped to `>= 1e-4`).
950    ///
951    /// # Arguments
952    ///
953    /// - `usize` - Tile index.
954    /// - `f32` - Positive tile weight.
955    pub fn set_weight(&mut self, tile_index: usize, weight: f32) {
956        if tile_index < self.get_tile_count() {
957            let safe: f32 = if weight.is_finite() && weight > 1e-4 {
958                weight
959            } else {
960                1e-4
961            };
962            self.get_mut_weights()[tile_index] = safe;
963        }
964    }
965
966    /// Allows `tile_b` to sit directly in direction `dir` from `tile_a` (and registers the symmetric opposite).
967    ///
968    /// # Arguments
969    ///
970    /// - `usize` - Source tile index.
971    /// - `WfcDirection` - Cardinal direction from `tile_a` to `tile_b`.
972    /// - `usize` - Neighbor tile index.
973    pub fn allow_adjacency(&mut self, tile_a: usize, dir: WfcDirection, tile_b: usize) {
974        let count: usize = self.get_tile_count();
975        if tile_a >= count || tile_b >= count {
976            return;
977        }
978        let d_idx: usize = dir.index();
979        let opp_idx: usize = dir.opposite().index();
980        let compat: &mut Vec<[WfcMask; 4]> = self.get_mut_compat();
981        compat[tile_a][d_idx] = compat[tile_a][d_idx].union(WfcMask::single(tile_b));
982        compat[tile_b][opp_idx] = compat[tile_b][opp_idx].union(WfcMask::single(tile_a));
983    }
984
985    /// Allows `tile_a` and `tile_b` to sit adjacent in all four cardinal directions.
986    ///
987    /// # Arguments
988    ///
989    /// - `usize` - First tile index.
990    /// - `usize` - Second tile index.
991    pub fn allow_all_directions(&mut self, tile_a: usize, tile_b: usize) {
992        self.allow_adjacency(tile_a, WfcDirection::North, tile_b);
993        self.allow_adjacency(tile_a, WfcDirection::East, tile_b);
994        self.allow_adjacency(tile_a, WfcDirection::South, tile_b);
995        self.allow_adjacency(tile_a, WfcDirection::West, tile_b);
996    }
997
998    /// Returns whether `tile_b` is permitted immediately in direction `dir` from `tile_a`.
999    ///
1000    /// # Arguments
1001    ///
1002    /// - `usize` - Source tile index.
1003    /// - `WfcDirection` - Cardinal direction to neighbor.
1004    /// - `usize` - Neighbor tile index.
1005    ///
1006    /// # Returns
1007    ///
1008    /// - `bool` - `true` if compatible.
1009    #[must_use]
1010    pub fn is_compatible(&self, tile_a: usize, dir: WfcDirection, tile_b: usize) -> bool {
1011        let count: usize = self.get_tile_count();
1012        if tile_a >= count || tile_b >= count {
1013            return false;
1014        }
1015        self.get_compat()[tile_a][dir.index()].contains(tile_b)
1016    }
1017}
1018
1019/// Validation helpers for `WfcResult2D`.
1020impl WfcResult2D {
1021    /// Returns the collapsed tile index at `(x, y)` if inside bounds.
1022    ///
1023    /// # Arguments
1024    ///
1025    /// - `usize` - Column index.
1026    /// - `usize` - Row index.
1027    ///
1028    /// # Returns
1029    ///
1030    /// - `Option<usize>` - Tile index at `(x, y)`.
1031    #[must_use]
1032    pub fn tile_at(&self, x: usize, y: usize) -> Option<usize> {
1033        if x < self.get_width() && y < self.get_height() {
1034            Some(self.get_tiles()[y * self.get_width() + x])
1035        } else {
1036            None
1037        }
1038    }
1039
1040    /// Verifies that every adjacent tile pair in the solved grid satisfies `rules`.
1041    ///
1042    /// # Arguments
1043    ///
1044    /// - `&WfcRuleSet` - Adjacency rule set to verify against.
1045    ///
1046    /// # Returns
1047    ///
1048    /// - `bool` - `true` when 100% of adjacent pairs are compatible.
1049    #[must_use]
1050    pub fn is_valid(&self, rules: &WfcRuleSet) -> bool {
1051        let width: usize = self.get_width();
1052        let height: usize = self.get_height();
1053        let tiles: &[usize] = self.get_tiles();
1054        if tiles.len() != width * height {
1055            return false;
1056        }
1057        for y in 0..height {
1058            for x in 0..width {
1059                let tile: usize = tiles[y * width + x];
1060                if tile >= rules.get_tile_count() {
1061                    return false;
1062                }
1063                if x + 1 < width {
1064                    let east: usize = tiles[y * width + (x + 1)];
1065                    if !rules.is_compatible(tile, WfcDirection::East, east) {
1066                        return false;
1067                    }
1068                }
1069                if y + 1 < height {
1070                    let south: usize = tiles[(y + 1) * width + x];
1071                    if !rules.is_compatible(tile, WfcDirection::South, south) {
1072                        return false;
1073                    }
1074                }
1075            }
1076        }
1077        true
1078    }
1079}
1080
1081/// Wave Function Collapse solver with Shannon-entropy selection, propagation, and backtracking.
1082impl WfcSolver2D {
1083    /// Creates a `WfcSolver2D` from `rules` with the default backtracking budget (`4096`).
1084    ///
1085    /// # Arguments
1086    ///
1087    /// - `WfcRuleSet` - Tile weights and adjacency compatibility rules.
1088    ///
1089    /// # Returns
1090    ///
1091    /// - `Self` - Configured WFC solver.
1092    #[must_use]
1093    pub fn new(rules: WfcRuleSet) -> Self {
1094        Self {
1095            rules,
1096            max_backtracks: WFC_DEFAULT_BACKTRACKS,
1097        }
1098    }
1099
1100    /// Computes the Shannon entropy of a cell's candidate tile mask.
1101    ///
1102    /// # Arguments
1103    ///
1104    /// - `WfcMask` - Candidate tile bitmask.
1105    /// - `&[f32]` - Tile weights slice.
1106    ///
1107    /// # Returns
1108    ///
1109    /// - `f32` - Shannon entropy value `ln(sum_w) - sum(w * ln(w)) / sum_w`.
1110    fn shannon_entropy(mask: WfcMask, weights: &[f32]) -> f32 {
1111        let mut sum_w: f32 = 0.0;
1112        let mut sum_w_log_w: f32 = 0.0;
1113        for (tile_idx, &weight) in weights.iter().enumerate() {
1114            if mask.contains(tile_idx) {
1115                sum_w += weight;
1116                sum_w_log_w += weight * weight.ln();
1117            }
1118        }
1119        if sum_w <= 1e-8 {
1120            return 0.0;
1121        }
1122        sum_w.ln() - (sum_w_log_w / sum_w)
1123    }
1124
1125    /// Selects a tile index from `mask` weighted by `weights` using deterministic `rng`.
1126    ///
1127    /// # Arguments
1128    ///
1129    /// - `WfcMask` - Non-empty candidate bitmask.
1130    /// - `&[f32]` - Tile weight slice.
1131    /// - `&mut DeterministicRng` - Deterministic PRNG.
1132    ///
1133    /// # Returns
1134    ///
1135    /// - `Option<usize>` - Selected tile index.
1136    fn pick_weighted_tile(
1137        mask: WfcMask,
1138        weights: &[f32],
1139        rng: &mut DeterministicRng,
1140    ) -> Option<usize> {
1141        let mut total_w: f32 = 0.0;
1142        let mut fallback: Option<usize> = None;
1143        for (tile_idx, &weight) in weights.iter().enumerate() {
1144            if mask.contains(tile_idx) {
1145                total_w += weight;
1146                fallback = Some(tile_idx);
1147            }
1148        }
1149        if total_w <= 0.0 {
1150            return fallback;
1151        }
1152        let mut target: f32 = rng.next_f32() * total_w;
1153        for (tile_idx, &weight) in weights.iter().enumerate() {
1154            if mask.contains(tile_idx) {
1155                if target <= weight {
1156                    return Some(tile_idx);
1157                }
1158                target -= weight;
1159            }
1160        }
1161        fallback
1162    }
1163
1164    /// Propagates adjacency constraints from `prop_stack`; returns `false` on contradiction.
1165    ///
1166    /// # Arguments
1167    ///
1168    /// - `&mut [WfcMask]` - Grid of tile domain masks.
1169    /// - `usize` - Grid width.
1170    /// - `usize` - Grid height.
1171    /// - `&[[WfcMask; 4]]` - Compatibility table indexed by `[tile][dir]`.
1172    /// - `&mut Vec<usize>` - Reusable cell index propagation stack.
1173    ///
1174    /// # Returns
1175    ///
1176    /// - `bool` - `true` when consistent, `false` if any cell domain becomes empty.
1177    fn propagate(
1178        cells: &mut [WfcMask],
1179        width: usize,
1180        height: usize,
1181        compat: &[[WfcMask; 4]],
1182        prop_stack: &mut Vec<usize>,
1183    ) -> bool {
1184        let dirs: [WfcDirection; 4] = [
1185            WfcDirection::North,
1186            WfcDirection::East,
1187            WfcDirection::South,
1188            WfcDirection::West,
1189        ];
1190        while let Some(cell_idx) = prop_stack.pop() {
1191            let cur_mask: WfcMask = cells[cell_idx];
1192            if cur_mask.count() == 0 {
1193                return false;
1194            }
1195            let cx: isize = (cell_idx % width) as isize;
1196            let cy: isize = (cell_idx / width) as isize;
1197            for dir in dirs {
1198                let (dx, dy): (isize, isize) = dir.offset();
1199                let nx: isize = cx + dx;
1200                let ny: isize = cy + dy;
1201                let in_x: bool = nx >= 0 && nx < width as isize;
1202                let in_y: bool = ny >= 0 && ny < height as isize;
1203                if !in_x || !in_y {
1204                    continue;
1205                }
1206                let n_idx: usize = (ny as usize) * width + (nx as usize);
1207                let mut allowed: WfcMask = WfcMask::empty();
1208                let d_slot: usize = dir.index();
1209                for (tile_idx, row) in compat.iter().enumerate() {
1210                    if cur_mask.contains(tile_idx) {
1211                        allowed = allowed.union(row[d_slot]);
1212                    }
1213                }
1214                let prev_n: WfcMask = cells[n_idx];
1215                let next_n: WfcMask = prev_n.intersect(allowed);
1216                if next_n != prev_n {
1217                    if next_n.count() == 0 {
1218                        return false;
1219                    }
1220                    cells[n_idx] = next_n;
1221                    prop_stack.push(n_idx);
1222                }
1223            }
1224        }
1225        true
1226    }
1227
1228    /// Solves a `width x height` 2D tile grid deterministically with Shannon entropy and backtracking.
1229    ///
1230    /// # Arguments
1231    ///
1232    /// - `usize` - Grid width in tiles.
1233    /// - `usize` - Grid height in tiles.
1234    /// - `u64` - Deterministic seed.
1235    ///
1236    /// # Returns
1237    ///
1238    /// - `Option<WfcResult2D>` - Valid solved grid if satisfiable within the backtrack budget.
1239    #[must_use]
1240    pub fn solve(&self, width: usize, height: usize, seed: u64) -> Option<WfcResult2D> {
1241        let total: usize = width.saturating_mul(height);
1242        if total == 0 {
1243            return None;
1244        }
1245        let tile_count: usize = self.get_rules().get_tile_count();
1246        let weights: &[f32] = self.get_rules().get_weights();
1247        let compat: &[[WfcMask; 4]] = self.get_rules().get_compat();
1248        let max_backtracks: usize = self.get_max_backtracks();
1249        let mut rng: DeterministicRng = DeterministicRng::new(seed);
1250        let mut cells: Vec<WfcMask> = vec![WfcMask::full(tile_count); total];
1251        let mut prop_stack: Vec<usize> = Vec::with_capacity(total);
1252        let mut history: Vec<WfcBacktrackFrame> = Vec::with_capacity(total);
1253        let mut backtracks: usize = 0;
1254        loop {
1255            let mut best_cell: Option<usize> = None;
1256            let mut best_entropy: f32 = f32::INFINITY;
1257            let mut contradiction: bool = false;
1258            for (idx, &mask) in cells.iter().enumerate() {
1259                let cnt: u32 = mask.count();
1260                if cnt == 0 {
1261                    contradiction = true;
1262                    break;
1263                }
1264                if cnt > 1 {
1265                    let jitter: f32 = rng.next_f32() * 1e-4;
1266                    let entropy: f32 = Self::shannon_entropy(mask, weights) + jitter;
1267                    if entropy < best_entropy {
1268                        best_entropy = entropy;
1269                        best_cell = Some(idx);
1270                    }
1271                }
1272            }
1273            if !contradiction {
1274                let Some(chosen_cell) = best_cell else {
1275                    let mut tiles: Vec<usize> = Vec::with_capacity(total);
1276                    for &mask in &cells {
1277                        tiles.push(mask.first_tile().unwrap_or(0));
1278                    }
1279                    return Some(WfcResult2D {
1280                        width,
1281                        height,
1282                        tiles,
1283                        backtracks,
1284                    });
1285                };
1286                let mask: WfcMask = cells[chosen_cell];
1287                let chosen_tile: usize = Self::pick_weighted_tile(mask, weights, &mut rng)?;
1288                let remaining: WfcMask = mask.without(chosen_tile);
1289                if remaining.count() > 0 {
1290                    history.push(WfcBacktrackFrame {
1291                        cells: cells.clone(),
1292                        cell_index: chosen_cell,
1293                        remaining,
1294                    });
1295                }
1296                cells[chosen_cell] = WfcMask::single(chosen_tile);
1297                prop_stack.clear();
1298                prop_stack.push(chosen_cell);
1299                if Self::propagate(&mut cells, width, height, compat, &mut prop_stack) {
1300                    continue;
1301                }
1302            }
1303            let mut recovered: bool = false;
1304            while let Some(frame) = history.pop() {
1305                if backtracks >= max_backtracks {
1306                    return None;
1307                }
1308                backtracks += 1;
1309                cells = frame.cells;
1310                let Some(next_tile) = Self::pick_weighted_tile(frame.remaining, weights, &mut rng)
1311                else {
1312                    continue;
1313                };
1314                let rest: WfcMask = frame.remaining.without(next_tile);
1315                if rest.count() > 0 {
1316                    history.push(WfcBacktrackFrame {
1317                        cells: cells.clone(),
1318                        cell_index: frame.cell_index,
1319                        remaining: rest,
1320                    });
1321                }
1322                cells[frame.cell_index] = WfcMask::single(next_tile);
1323                prop_stack.clear();
1324                prop_stack.push(frame.cell_index);
1325                if Self::propagate(&mut cells, width, height, compat, &mut prop_stack) {
1326                    recovered = true;
1327                    break;
1328                }
1329            }
1330            if !recovered {
1331                return None;
1332            }
1333        }
1334    }
1335}
1336
1337/// Bridson's fast O(N) Poisson-disk sampling in 2D and 3D for `PoissonDiskSampler`.
1338impl PoissonDiskSampler {
1339    /// Generates blue-noise 2D samples inside `bounds` with exact minimum separation `min_distance`.
1340    ///
1341    /// # Arguments
1342    ///
1343    /// - `Bounds2D` - Sampling domain rectangle.
1344    /// - `f32` - Minimum Euclidean distance guaranteed between every sample pair.
1345    /// - `u64` - Deterministic RNG seed.
1346    ///
1347    /// # Returns
1348    ///
1349    /// - `Vec<Vec2>` - Well-spaced 2D sample positions.
1350    #[must_use]
1351    pub fn sample_2d(&self, bounds: Bounds2D, min_distance: f32, seed: u64) -> Vec<Vec2> {
1352        let size: Vec2 = bounds.size();
1353        if !min_distance.is_finite()
1354            || min_distance <= 1e-5
1355            || size.get_x() <= 0.0
1356            || size.get_y() <= 0.0
1357        {
1358            return Vec::new();
1359        }
1360        let max_attempts: usize = if self.get_max_attempts() == 0 {
1361            POISSON_DEFAULT_K
1362        } else {
1363            self.get_max_attempts()
1364        };
1365        let cell_size: f32 = min_distance / SQRT_2;
1366        let inv_cell: f32 = 1.0 / cell_size;
1367        let grid_w: usize = ((size.get_x() * inv_cell).ceil() as usize).max(1);
1368        let grid_h: usize = ((size.get_y() * inv_cell).ceil() as usize).max(1);
1369        let mut grid: Vec<usize> = vec![usize::MAX; grid_w * grid_h];
1370        let mut points: Vec<Vec2> = Vec::with_capacity((grid_w * grid_h) / 2);
1371        let mut active: Vec<usize> = Vec::with_capacity(64);
1372        let mut rng: DeterministicRng = DeterministicRng::new(seed);
1373        let mn: Vec2 = bounds.get_min();
1374        let first: Vec2 = Vec2::new(
1375            rng.next_range_f32(mn.get_x(), bounds.get_max().get_x()),
1376            rng.next_range_f32(mn.get_y(), bounds.get_max().get_y()),
1377        );
1378        let f_gx: usize =
1379            (((first.get_x() - mn.get_x()) * inv_cell).floor() as usize).min(grid_w - 1);
1380        let f_gy: usize =
1381            (((first.get_y() - mn.get_y()) * inv_cell).floor() as usize).min(grid_h - 1);
1382        points.push(first);
1383        grid[f_gy * grid_w + f_gx] = 0;
1384        active.push(0);
1385        let min_dist_sq: f32 = min_distance * min_distance;
1386        while !active.is_empty() {
1387            let act_slot: usize = rng.next_range_usize(0, active.len());
1388            let base: Vec2 = points[active[act_slot]];
1389            let mut accepted: bool = false;
1390            for _ in 0..max_attempts {
1391                let rad: f32 = min_distance * (1.0 + 3.0 * rng.next_f32()).sqrt();
1392                let angle: f32 = rng.next_f32() * TAU;
1393                let cand: Vec2 = Vec2::new(
1394                    base.get_x() + rad * angle.cos(),
1395                    base.get_y() + rad * angle.sin(),
1396                );
1397                if !bounds.contains_point(cand) {
1398                    continue;
1399                }
1400                let gx: isize = (((cand.get_x() - mn.get_x()) * inv_cell).floor() as isize)
1401                    .clamp(0, (grid_w as isize) - 1);
1402                let gy: isize = (((cand.get_y() - mn.get_y()) * inv_cell).floor() as isize)
1403                    .clamp(0, (grid_h as isize) - 1);
1404                let mut valid: bool = true;
1405                let y0: usize = (gy - 2).max(0) as usize;
1406                let y1: usize = (gy + 2).min((grid_h as isize) - 1) as usize;
1407                let x0: usize = (gx - 2).max(0) as usize;
1408                let x1: usize = (gx + 2).min((grid_w as isize) - 1) as usize;
1409                for ny in y0..=y1 {
1410                    for nx in x0..=x1 {
1411                        let existing_idx: usize = grid[ny * grid_w + nx];
1412                        if existing_idx != usize::MAX {
1413                            let existing: Vec2 = points[existing_idx];
1414                            let dx: f32 = cand.get_x() - existing.get_x();
1415                            let dy: f32 = cand.get_y() - existing.get_y();
1416                            if dx * dx + dy * dy < min_dist_sq {
1417                                valid = false;
1418                                break;
1419                            }
1420                        }
1421                    }
1422                    if !valid {
1423                        break;
1424                    }
1425                }
1426                if valid {
1427                    let new_idx: usize = points.len();
1428                    points.push(cand);
1429                    grid[(gy as usize) * grid_w + (gx as usize)] = new_idx;
1430                    active.push(new_idx);
1431                    accepted = true;
1432                    break;
1433                }
1434            }
1435            if !accepted {
1436                let _: usize = active.swap_remove(act_slot);
1437            }
1438        }
1439        points
1440    }
1441
1442    /// Generates blue-noise 3D samples inside `bounds` with exact minimum separation `min_distance`.
1443    ///
1444    /// # Arguments
1445    ///
1446    /// - `AxisAlignedBox3D` - Sampling volume bounds.
1447    /// - `f32` - Minimum Euclidean 3D distance guaranteed between every sample pair.
1448    /// - `u64` - Deterministic RNG seed.
1449    ///
1450    /// # Returns
1451    ///
1452    /// - `Vec<Vec3>` - Well-spaced 3D sample positions.
1453    #[must_use]
1454    pub fn sample_3d(&self, bounds: AxisAlignedBox3D, min_distance: f32, seed: u64) -> Vec<Vec3> {
1455        let mn: Vec3 = bounds.get_min();
1456        let mx: Vec3 = bounds.get_max();
1457        let ext: Vec3 = mx.sub(mn);
1458        if !min_distance.is_finite()
1459            || min_distance <= 1e-5
1460            || ext.get_x() <= 0.0
1461            || ext.get_y() <= 0.0
1462            || ext.get_z() <= 0.0
1463        {
1464            return Vec::new();
1465        }
1466        let max_attempts: usize = if self.get_max_attempts() == 0 {
1467            POISSON_DEFAULT_K
1468        } else {
1469            self.get_max_attempts()
1470        };
1471        let cell_size: f32 = min_distance / 3.0_f32.sqrt();
1472        let inv_cell: f32 = 1.0 / cell_size;
1473        let grid_w: usize = ((ext.get_x() * inv_cell).ceil() as usize).max(1);
1474        let grid_h: usize = ((ext.get_y() * inv_cell).ceil() as usize).max(1);
1475        let grid_d: usize = ((ext.get_z() * inv_cell).ceil() as usize).max(1);
1476        let mut grid: Vec<usize> = vec![usize::MAX; grid_w * grid_h * grid_d];
1477        let mut points: Vec<Vec3> = Vec::with_capacity(64);
1478        let mut active: Vec<usize> = Vec::with_capacity(64);
1479        let mut rng: DeterministicRng = DeterministicRng::new(seed);
1480        let first: Vec3 = Vec3::new(
1481            rng.next_range_f32(mn.get_x(), mx.get_x()),
1482            rng.next_range_f32(mn.get_y(), mx.get_y()),
1483            rng.next_range_f32(mn.get_z(), mx.get_z()),
1484        );
1485        let fgx: usize =
1486            (((first.get_x() - mn.get_x()) * inv_cell).floor() as usize).min(grid_w - 1);
1487        let fgy: usize =
1488            (((first.get_y() - mn.get_y()) * inv_cell).floor() as usize).min(grid_h - 1);
1489        let fgz: usize =
1490            (((first.get_z() - mn.get_z()) * inv_cell).floor() as usize).min(grid_d - 1);
1491        points.push(first);
1492        grid[(fgz * grid_h + fgy) * grid_w + fgx] = 0;
1493        active.push(0);
1494        let min_dist_sq: f32 = min_distance * min_distance;
1495        while !active.is_empty() {
1496            let act_slot: usize = rng.next_range_usize(0, active.len());
1497            let base: Vec3 = points[active[act_slot]];
1498            let mut accepted: bool = false;
1499            for _ in 0..max_attempts {
1500                let rad: f32 = min_distance * (1.0 + 7.0 * rng.next_f32()).cbrt();
1501                let z_dir: f32 = 2.0 * rng.next_f32() - 1.0;
1502                let phi: f32 = rng.next_f32() * TAU;
1503                let xy_ring: f32 = (1.0 - z_dir * z_dir).max(0.0).sqrt();
1504                let cand: Vec3 = Vec3::new(
1505                    base.get_x() + rad * xy_ring * phi.cos(),
1506                    base.get_y() + rad * xy_ring * phi.sin(),
1507                    base.get_z() + rad * z_dir,
1508                );
1509                if cand.get_x() < mn.get_x()
1510                    || cand.get_x() > mx.get_x()
1511                    || cand.get_y() < mn.get_y()
1512                    || cand.get_y() > mx.get_y()
1513                    || cand.get_z() < mn.get_z()
1514                    || cand.get_z() > mx.get_z()
1515                {
1516                    continue;
1517                }
1518                let gx: isize = (((cand.get_x() - mn.get_x()) * inv_cell).floor() as isize)
1519                    .clamp(0, (grid_w as isize) - 1);
1520                let gy: isize = (((cand.get_y() - mn.get_y()) * inv_cell).floor() as isize)
1521                    .clamp(0, (grid_h as isize) - 1);
1522                let gz: isize = (((cand.get_z() - mn.get_z()) * inv_cell).floor() as isize)
1523                    .clamp(0, (grid_d as isize) - 1);
1524                let mut valid: bool = true;
1525                let z0: usize = (gz - 2).max(0) as usize;
1526                let z1: usize = (gz + 2).min((grid_d as isize) - 1) as usize;
1527                let y0: usize = (gy - 2).max(0) as usize;
1528                let y1: usize = (gy + 2).min((grid_h as isize) - 1) as usize;
1529                let x0: usize = (gx - 2).max(0) as usize;
1530                let x1: usize = (gx + 2).min((grid_w as isize) - 1) as usize;
1531                for nz in z0..=z1 {
1532                    for ny in y0..=y1 {
1533                        for nx in x0..=x1 {
1534                            let existing_idx: usize = grid[(nz * grid_h + ny) * grid_w + nx];
1535                            if existing_idx != usize::MAX
1536                                && cand.sub(points[existing_idx]).length_sq() < min_dist_sq
1537                            {
1538                                valid = false;
1539                                break;
1540                            }
1541                        }
1542                        if !valid {
1543                            break;
1544                        }
1545                    }
1546                    if !valid {
1547                        break;
1548                    }
1549                }
1550                if valid {
1551                    let new_idx: usize = points.len();
1552                    points.push(cand);
1553                    grid[((gz as usize) * grid_h + (gy as usize)) * grid_w + (gx as usize)] =
1554                        new_idx;
1555                    active.push(new_idx);
1556                    accepted = true;
1557                    break;
1558                }
1559            }
1560            if !accepted {
1561                let _: usize = active.swap_remove(act_slot);
1562            }
1563        }
1564        points
1565    }
1566}
1567
1568/// Default configuration for `BspDungeonConfig`.
1569impl Default for BspDungeonConfig {
1570    /// Returns a balanced 64x64 dungeon layout configuration.
1571    ///
1572    /// # Returns
1573    ///
1574    /// - `Self` - Default BSP dungeon parameters.
1575    fn default() -> Self {
1576        Self {
1577            width: 64,
1578            height: 64,
1579            min_leaf_size: 10,
1580            max_leaf_size: 20,
1581            min_room_size: 4,
1582            room_padding: 1,
1583            corridor_width: 1,
1584        }
1585    }
1586}
1587
1588/// Geometric helpers for `BspRoomRect`.
1589impl BspRoomRect {
1590    /// Returns the integer center coordinate of this room.
1591    ///
1592    /// # Returns
1593    ///
1594    /// - `GridCoord` - Center tile inside the room.
1595    #[must_use]
1596    pub fn center(&self) -> GridCoord {
1597        GridCoord::new(
1598            self.get_x() + self.get_width() / 2,
1599            self.get_y() + self.get_height() / 2,
1600        )
1601    }
1602
1603    /// Tests whether `(tx, ty)` lies strictly inside this room's floor area.
1604    ///
1605    /// # Arguments
1606    ///
1607    /// - `usize` - Tile X coordinate.
1608    /// - `usize` - Tile Y coordinate.
1609    ///
1610    /// # Returns
1611    ///
1612    /// - `bool` - `true` when `(tx, ty)` belongs to this room.
1613    #[must_use]
1614    pub fn contains(&self, tx: usize, ty: usize) -> bool {
1615        tx >= self.get_x()
1616            && tx < self.get_x() + self.get_width()
1617            && ty >= self.get_y()
1618            && ty < self.get_y() + self.get_height()
1619    }
1620}
1621
1622/// Tile query helpers for `BspDungeonMap`.
1623impl BspDungeonMap {
1624    /// Returns the semantic tile at `(x, y)` (`Wall` if out of bounds).
1625    ///
1626    /// # Arguments
1627    ///
1628    /// - `usize` - Column index.
1629    /// - `usize` - Row index.
1630    ///
1631    /// # Returns
1632    ///
1633    /// - `BspTileKind` - Tile classification.
1634    #[must_use]
1635    pub fn tile_at(&self, x: usize, y: usize) -> BspTileKind {
1636        if x < self.get_width() && y < self.get_height() {
1637            self.get_tiles()[y * self.get_width() + x]
1638        } else {
1639            BspTileKind::Wall
1640        }
1641    }
1642
1643    /// Returns whether `(x, y)` is a walkable floor, corridor, or doorway tile.
1644    ///
1645    /// # Arguments
1646    ///
1647    /// - `usize` - Column index.
1648    /// - `usize` - Row index.
1649    ///
1650    /// # Returns
1651    ///
1652    /// - `bool` - `true` when walkable.
1653    #[must_use]
1654    pub fn is_walkable(&self, x: usize, y: usize) -> bool {
1655        self.tile_at(x, y) != BspTileKind::Wall
1656    }
1657}
1658
1659/// Binary Space Partitioning procedural room, corridor, and doorway generator for `BspDungeonGenerator`.
1660impl BspDungeonGenerator {
1661    /// Recursively splits `node_idx` into child BSP partitions when larger than limits.
1662    ///
1663    /// # Arguments
1664    ///
1665    /// - `&mut Vec<BspLeafNode>` - BSP node arena.
1666    /// - `usize` - Active node index to split.
1667    /// - `BspDungeonConfig` - Partition sizing rules.
1668    /// - `&mut DeterministicRng` - Deterministic PRNG.
1669    fn split_node(
1670        nodes: &mut Vec<BspLeafNode>,
1671        node_idx: usize,
1672        cfg: BspDungeonConfig,
1673        rng: &mut DeterministicRng,
1674    ) {
1675        let min_leaf: usize = cfg
1676            .get_min_leaf_size()
1677            .max(cfg.get_min_room_size() + cfg.get_room_padding() * 2);
1678        let max_leaf: usize = cfg.get_max_leaf_size().max(min_leaf * 2);
1679        let w: usize = nodes[node_idx].width;
1680        let h: usize = nodes[node_idx].height;
1681        let can_split_h: bool = h >= min_leaf * 2;
1682        let can_split_v: bool = w >= min_leaf * 2;
1683        if !can_split_h && !can_split_v {
1684            return;
1685        }
1686        let must_split: bool = w > max_leaf || h > max_leaf;
1687        if !must_split && rng.next_f32() < 0.2 {
1688            return;
1689        }
1690        let split_horizontal: bool = if can_split_h && can_split_v {
1691            if (w as f32) > (h as f32) * 1.25 {
1692                false
1693            } else if (h as f32) > (w as f32) * 1.25 {
1694                true
1695            } else {
1696                rng.next_f32() < 0.5
1697            }
1698        } else {
1699            can_split_h
1700        };
1701        let nx: usize = nodes[node_idx].x;
1702        let ny: usize = nodes[node_idx].y;
1703        let (left_node, right_node): (BspLeafNode, BspLeafNode) = if split_horizontal {
1704            let split: usize = rng.next_range_usize(min_leaf, h - min_leaf + 1);
1705            (
1706                BspLeafNode {
1707                    x: nx,
1708                    y: ny,
1709                    width: w,
1710                    height: split,
1711                    left: usize::MAX,
1712                    right: usize::MAX,
1713                    room_index: usize::MAX,
1714                },
1715                BspLeafNode {
1716                    x: nx,
1717                    y: ny + split,
1718                    width: w,
1719                    height: h - split,
1720                    left: usize::MAX,
1721                    right: usize::MAX,
1722                    room_index: usize::MAX,
1723                },
1724            )
1725        } else {
1726            let split: usize = rng.next_range_usize(min_leaf, w - min_leaf + 1);
1727            (
1728                BspLeafNode {
1729                    x: nx,
1730                    y: ny,
1731                    width: split,
1732                    height: h,
1733                    left: usize::MAX,
1734                    right: usize::MAX,
1735                    room_index: usize::MAX,
1736                },
1737                BspLeafNode {
1738                    x: nx + split,
1739                    y: ny,
1740                    width: w - split,
1741                    height: h,
1742                    left: usize::MAX,
1743                    right: usize::MAX,
1744                    room_index: usize::MAX,
1745                },
1746            )
1747        };
1748        let left_idx: usize = nodes.len();
1749        nodes.push(left_node);
1750        let right_idx: usize = nodes.len();
1751        nodes.push(right_node);
1752        nodes[node_idx].left = left_idx;
1753        nodes[node_idx].right = right_idx;
1754        Self::split_node(nodes, left_idx, cfg, rng);
1755        Self::split_node(nodes, right_idx, cfg, rng);
1756    }
1757
1758    /// Collects all carved room indices beneath BSP subtree `node_idx`.
1759    ///
1760    /// # Arguments
1761    ///
1762    /// - `&[BspLeafNode]` - BSP node arena slice.
1763    /// - `usize` - Subtree root index.
1764    /// - `&mut Vec<usize>` - Output room index accumulator.
1765    fn collect_subtree_rooms(nodes: &[BspLeafNode], node_idx: usize, out: &mut Vec<usize>) {
1766        let node: &BspLeafNode = &nodes[node_idx];
1767        if node.room_index != usize::MAX {
1768            out.push(node.room_index);
1769            return;
1770        }
1771        if node.left != usize::MAX {
1772            Self::collect_subtree_rooms(nodes, node.left, out);
1773        }
1774        if node.right != usize::MAX {
1775            Self::collect_subtree_rooms(nodes, node.right, out);
1776        }
1777    }
1778
1779    /// Carves an orthogonal corridor segment onto `tiles` without overwriting interior room floors.
1780    ///
1781    /// # Arguments
1782    ///
1783    /// - `&mut [BspTileKind]` - Row-major tile buffer.
1784    /// - `usize` - Grid width.
1785    /// - `usize` - Grid height.
1786    /// - `GridCoord` - Segment start tile.
1787    /// - `GridCoord` - Segment end tile.
1788    /// - `usize` - Corridor tile width.
1789    fn carve_segment(
1790        tiles: &mut [BspTileKind],
1791        width: usize,
1792        height: usize,
1793        start: GridCoord,
1794        end: GridCoord,
1795        corridor_width: usize,
1796    ) {
1797        let half: isize = (corridor_width.max(1) / 2) as isize;
1798        let span: isize = corridor_width.max(1) as isize;
1799        let x0: usize = start.get_x().min(end.get_x());
1800        let x1: usize = start.get_x().max(end.get_x());
1801        let y0: usize = start.get_y().min(end.get_y());
1802        let y1: usize = start.get_y().max(end.get_y());
1803        for ty in y0..=y1 {
1804            for tx in x0..=x1 {
1805                for dy in 0..span {
1806                    for dx in 0..span {
1807                        let px: isize = (tx as isize) + dx - half;
1808                        let py: isize = (ty as isize) + dy - half;
1809                        if px >= 1
1810                            && py >= 1
1811                            && px < (width as isize) - 1
1812                            && py < (height as isize) - 1
1813                        {
1814                            let idx: usize = (py as usize) * width + (px as usize);
1815                            if tiles[idx] == BspTileKind::Wall {
1816                                tiles[idx] = BspTileKind::Corridor;
1817                            }
1818                        }
1819                    }
1820                }
1821            }
1822        }
1823    }
1824
1825    /// Generates a fully connected procedural BSP dungeon with rooms, corridors, and doorways.
1826    ///
1827    /// # Arguments
1828    ///
1829    /// - `u64` - Deterministic generation seed.
1830    ///
1831    /// # Returns
1832    ///
1833    /// - `BspDungeonMap` - Generated dungeon layout with guaranteed room-to-room connectivity.
1834    #[must_use]
1835    pub fn generate(&self, seed: u64) -> BspDungeonMap {
1836        let cfg: BspDungeonConfig = self.get_config();
1837        let width: usize = cfg.get_width().max(8);
1838        let height: usize = cfg.get_height().max(8);
1839        let pad: usize = cfg.get_room_padding().max(1);
1840        let min_room: usize = cfg.get_min_room_size().max(2);
1841        let corr_w: usize = cfg.get_corridor_width().max(1);
1842        let mut rng: DeterministicRng = DeterministicRng::new(seed);
1843        let mut nodes: Vec<BspLeafNode> = vec![BspLeafNode {
1844            x: 1,
1845            y: 1,
1846            width: width - 2,
1847            height: height - 2,
1848            left: usize::MAX,
1849            right: usize::MAX,
1850            room_index: usize::MAX,
1851        }];
1852        Self::split_node(&mut nodes, 0, cfg, &mut rng);
1853        let mut tiles: Vec<BspTileKind> = vec![BspTileKind::Wall; width * height];
1854        let mut rooms: Vec<BspRoomRect> = Vec::new();
1855        for node in &mut nodes {
1856            if node.left != usize::MAX || node.right != usize::MAX {
1857                continue;
1858            }
1859            let max_rw: usize = node
1860                .width
1861                .saturating_sub(pad * 2)
1862                .max(min_room)
1863                .min(node.width);
1864            let max_rh: usize = node
1865                .height
1866                .saturating_sub(pad * 2)
1867                .max(min_room)
1868                .min(node.height);
1869            let min_rw: usize = min_room.min(max_rw);
1870            let min_rh: usize = min_room.min(max_rh);
1871            let rw: usize = rng.next_range_usize(min_rw, max_rw + 1).max(1);
1872            let rh: usize = rng.next_range_usize(min_rh, max_rh + 1).max(1);
1873            let max_ox: usize = node.width.saturating_sub(rw);
1874            let max_oy: usize = node.height.saturating_sub(rh);
1875            let ox: usize = rng.next_range_usize(0, max_ox + 1);
1876            let oy: usize = rng.next_range_usize(0, max_oy + 1);
1877            let room: BspRoomRect = BspRoomRect::new(node.x + ox, node.y + oy, rw, rh);
1878            let room_idx: usize = rooms.len();
1879            rooms.push(room);
1880            node.room_index = room_idx;
1881            for ry in room.get_y()..(room.get_y() + room.get_height()) {
1882                for rx in room.get_x()..(room.get_x() + room.get_width()) {
1883                    if rx < width && ry < height {
1884                        tiles[ry * width + rx] = BspTileKind::Floor;
1885                    }
1886                }
1887            }
1888        }
1889        let mut corridors: Vec<BspCorridorSegment> = Vec::new();
1890        let mut left_rooms: Vec<usize> = Vec::new();
1891        let mut right_rooms: Vec<usize> = Vec::new();
1892        for node_idx in (0..nodes.len()).rev() {
1893            let left: usize = nodes[node_idx].left;
1894            let right: usize = nodes[node_idx].right;
1895            if left == usize::MAX || right == usize::MAX {
1896                continue;
1897            }
1898            left_rooms.clear();
1899            right_rooms.clear();
1900            Self::collect_subtree_rooms(&nodes, left, &mut left_rooms);
1901            Self::collect_subtree_rooms(&nodes, right, &mut right_rooms);
1902            if left_rooms.is_empty() || right_rooms.is_empty() {
1903                continue;
1904            }
1905            let mut best_pair: (usize, usize) = (left_rooms[0], right_rooms[0]);
1906            let mut best_dist: usize = usize::MAX;
1907            for &lr in &left_rooms {
1908                let lc: GridCoord = rooms[lr].center();
1909                for &rr in &right_rooms {
1910                    let rc: GridCoord = rooms[rr].center();
1911                    let d: usize =
1912                        lc.get_x().abs_diff(rc.get_x()) + lc.get_y().abs_diff(rc.get_y());
1913                    if d < best_dist {
1914                        best_dist = d;
1915                        best_pair = (lr, rr);
1916                    }
1917                }
1918            }
1919            let c_a: GridCoord = rooms[best_pair.0].center();
1920            let c_b: GridCoord = rooms[best_pair.1].center();
1921            let elbow: GridCoord = if rng.next_f32() < 0.5 {
1922                GridCoord::new(c_b.get_x(), c_a.get_y())
1923            } else {
1924                GridCoord::new(c_a.get_x(), c_b.get_y())
1925            };
1926            Self::carve_segment(&mut tiles, width, height, c_a, elbow, corr_w);
1927            Self::carve_segment(&mut tiles, width, height, elbow, c_b, corr_w);
1928            corridors.push(BspCorridorSegment::new(c_a, elbow, corr_w));
1929            corridors.push(BspCorridorSegment::new(elbow, c_b, corr_w));
1930        }
1931        let mut doors: Vec<BspDoorway> = Vec::new();
1932        let dirs: [(isize, isize); 4] = [(1, 0), (-1, 0), (0, 1), (0, -1)];
1933        for y in 1..(height - 1) {
1934            for x in 1..(width - 1) {
1935                if tiles[y * width + x] != BspTileKind::Corridor {
1936                    continue;
1937                }
1938                let mut touched_room: Option<usize> = None;
1939                for &(dx, dy) in &dirs {
1940                    let nx: usize = ((x as isize) + dx) as usize;
1941                    let ny: usize = ((y as isize) + dy) as usize;
1942                    if tiles[ny * width + nx] == BspTileKind::Floor {
1943                        for (r_idx, room) in rooms.iter().enumerate() {
1944                            if room.contains(nx, ny) {
1945                                touched_room = Some(r_idx);
1946                                break;
1947                            }
1948                        }
1949                    }
1950                    if touched_room.is_some() {
1951                        break;
1952                    }
1953                }
1954                if let Some(r_idx) = touched_room {
1955                    tiles[y * width + x] = BspTileKind::Door;
1956                    doors.push(BspDoorway::new(GridCoord::new(x, y), r_idx));
1957                }
1958            }
1959        }
1960        BspDungeonMap {
1961            width,
1962            height,
1963            tiles,
1964            rooms,
1965            corridors,
1966            doors,
1967        }
1968    }
1969}