//! Lantern law: per-cell light levels with leak and dirty-flag recompute. //! //! Implements docs/03 §3.3 law 1 ("Light & darkness"): lantern glow, //! carried/dropped glow, muzzle flash, and phosphor flora all resolve to a //! 0–24 level per voxel. Stealth, accuracy, monster courage, and plant //! growth key off it. Light leaks under doors and through grates (open or //! glass cells) but never through solid rock (docs/04 §4.2 phase 8 `Light`, //! docs/05 §5.1 "Light as truth": brightness = light level × material × //! distance fog). //! //! Wiring contract for the parent `State` phase: mark edited or //! source-moved cells with [`FLAG_LIGHT_DIRTY`] and call //! [`propagate_light`] with `dirty_only = true` each tick; run a full pass //! (`dirty_only = false`) after structural edits. Only loaded chunks are //! read or written — the parent owns the 3×3×3 active set (docs/04 §4.3). //! //! Determinism: `BTreeMap`-ordered BFS, integer Manhattan falloff, no //! `HashMap`, no I/O, no threads, no wall-clock. This module emits no //! cause-links (light alone never kills); the parent logs first-sight lines //! per docs/04 §4.10 hard rule 5. use std::collections::{BTreeMap, VecDeque}; use crate::voxel::{material, ChunkedGrid, CHUNK}; /// Top of the 24-step brightness scale (docs/05 §5.1). pub const MAX_LIGHT: u8 = 24; /// Effective source-radius clamp: one chunk edge. Bounds the BFS box so a /// single call stays inside the tick budget (docs/04 §4.2); wider light /// (e.g. a shaft of daylight) is re-applied over successive ticks. pub const MAX_LIGHT_RADIUS: u8 = 32; /// Voxel `flags` bit for dirty light cells (shared voxel protocol: bit 0x08). /// [`propagate_light`] clears it on every cell it writes. pub const FLAG_LIGHT_DIRTY: u8 = 0x08; /// Cell-write budget per call (docs/04 §4.2: light shares the 4k /// updates/tick contract). Overflow is reported as spillover by /// [`propagate_light_capped`], never silently dropped. pub const MAX_LIGHT_UPDATES: usize = 4_000; /// A point glow: lantern, dropped torch, muzzle flash, phosphor bloom /// (docs/03 §3.3.1). `warm` selects the renderer palette fork (warm `+*` /// core vs cold blue falloff, docs/05 §5.1); falloff itself is identical. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct LightSource { /// Voxel-space position of the glow. pub x: i32, /// Voxel-space position of the glow. pub y: i32, /// Voxel-space position of the glow (up). pub z: i32, /// Flood radius in voxels; levels decay from 24 at the source to 0 at /// this distance. Clamped to [`MAX_LIGHT_RADIUS`]. pub radius: u8, /// Warm (lantern/oil) vs cold (phosphor/aether) tint hint for render. pub warm: bool, } /// Six-neighbour flood order. Fixed array ⇒ deterministic BFS expansion. const DIRS: [(i32, i32, i32); 6] = [ (1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, -1, 0), (0, 0, 1), (0, 0, -1), ]; /// Chunk coordinate containing voxel coordinate `c`. fn chunk_of(c: i32) -> i32 { c.div_euclid(CHUNK as i32) } /// Leak rule (docs/03 §3.3.1): light passes through open cells (`occ == 0`, /// which is how under-door gaps and grates are modelled) and through glass, /// never through solid. Unloaded cells read as default air and are treated /// as passable here; callers additionally gate on loaded chunks. fn passable(grid: &ChunkedGrid, x: i32, y: i32, z: i32) -> bool { let v = grid.get_world(x, y, z); v.occ == 0 || v.material == material::GLASS } /// Zero the light field over the loaded portion of a source box so doused /// lamps actually darken (docs/03 §3.3.1: "Douse the lamp = invisible but /// blind"). Unloaded chunks are skipped, never materialised. /// /// The flood in [`propagate_light_capped`] only visits cells reachable from /// the *current* sources, so a removed or moved lamp would otherwise leave /// stale light behind. The parent `State` phase owns the lamp list: when a /// lamp is removed, moved, or doused, it calls this with the lamp's *old* /// box before the next propagate. Zeroed cells are flagged /// [`FLAG_LIGHT_DIRTY`] so the renderer re-reads them. pub fn clear_light_box(grid: &mut ChunkedGrid, cx: i32, cy: i32, cz: i32, r: i32) { let edge = CHUNK as i32; for cxx in chunk_of(cx - r)..=chunk_of(cx + r) { for cyy in chunk_of(cy - r)..=chunk_of(cy + r) { for czz in chunk_of(cz - r)..=chunk_of(cz + r) { if !grid.is_loaded(cxx, cyy, czz) { continue; } let x0 = (cx - r).max(cxx * edge); let x1 = (cx + r).min(cxx * edge + edge - 1); let y0 = (cy - r).max(cyy * edge); let y1 = (cy + r).min(cyy * edge + edge - 1); let z0 = (cz - r).max(czz * edge); let z1 = (cz + r).min(czz * edge + edge - 1); for z in z0..=z1 { for y in y0..=y1 { for x in x0..=x1 { let mut v = grid.get_world(x, y, z); if v.light != 0 { v.light = 0; v.flags |= FLAG_LIGHT_DIRTY; grid.set_world(x, y, z, v); } } } } } } } } /// Recompute light from `sources` (docs/03 §3.3.1, docs/04 §4.2 phase 8). /// /// Multi-source Manhattan BFS: 24 at each source, integer falloff to 0 at /// `radius`, per-cell maximum across sources. Writes `Voxel.light` and /// clears [`FLAG_LIGHT_DIRTY`] on written cells. /// /// When `dirty_only` is true only cells already flagged dirty are written /// (clean cells keep their levels, so unrelated rooms cost nothing); the /// flood still traverses through them. A full pass first clears the loaded /// boxes of the *current* sources; a removed or moved lamp's old box is not /// visited, so the parent must call [`clear_light_box`] with the old box /// first (docs/03 §3.3.1: "Douse the lamp"). Traversal and writes never /// touch unloaded chunks. Returns the number of cells updated; use /// [`propagate_light_capped`] for the spillover count. pub fn propagate_light(grid: &mut ChunkedGrid, sources: &[LightSource], dirty_only: bool) -> usize { propagate_light_capped(grid, sources, dirty_only).0 } /// Bounded variant returning `(updated, spillover)`: `spillover` is the /// number of flood cells left unwritten because the [`MAX_LIGHT_UPDATES`] /// budget ran out — the parent re-runs the pass next tick (docs/04 §4.2). /// A wide-radius flood reaches tens of thousands of cells against the 4k /// shared-contract budget, so writes are always truncated here, never /// dropped silently. `spillover` is 0 whenever the flood fits the budget. pub fn propagate_light_capped( grid: &mut ChunkedGrid, sources: &[LightSource], dirty_only: bool, ) -> (usize, usize) { if sources.is_empty() { return (0, 0); } if !dirty_only { for s in sources { let r = s.radius.min(MAX_LIGHT_RADIUS) as i32; clear_light_box(grid, s.x, s.y, s.z, r); } } let levels = sample_light_field(grid, sources); let budget = levels.len().min(MAX_LIGHT_UPDATES); let spillover = levels.len() - budget; let mut touched = 0usize; for ((x, y, z), lvl) in levels.iter().take(budget) { let mut v = grid.get_world(*x, *y, *z); let dirty = (v.flags & FLAG_LIGHT_DIRTY) != 0; if dirty_only && !dirty { continue; } if v.light != *lvl || dirty { v.light = *lvl; v.flags &= !FLAG_LIGHT_DIRTY; grid.set_world(*x, *y, *z, v); touched += 1; } } (touched, spillover) } /// Read-only lantern field for presentation, including the initial frame before /// any simulation ticks. Uses the same loaded-cell, occlusion and radius rules /// as propagation, without changing authoritative voxels or spending a turn. pub fn sample_light_field( grid: &ChunkedGrid, sources: &[LightSource], ) -> BTreeMap<(i32, i32, i32), u8> { // Best level per cell, BTreeMap-ordered for determinism. let mut levels: BTreeMap<(i32, i32, i32), u8> = BTreeMap::new(); // (x, y, z, manhattan-dist, falloff-step, range). let mut queue: VecDeque<(i32, i32, i32, i32, i32, i32)> = VecDeque::new(); for s in sources { if !grid.is_loaded(chunk_of(s.x), chunk_of(s.y), chunk_of(s.z)) { continue; } let range = s.radius.min(MAX_LIGHT_RADIUS) as i32; let step = if range == 0 { MAX_LIGHT as i32 } else { (MAX_LIGHT / (range as u8)) as i32 } .max(1); levels.insert((s.x, s.y, s.z), MAX_LIGHT); queue.push_back((s.x, s.y, s.z, 0, step, range)); } while let Some((x, y, z, dist, step, range)) = queue.pop_front() { if dist >= range { continue; } for (dx, dy, dz) in DIRS { let (nx, ny, nz) = (x + dx, y + dy, z + dz); let lvl = MAX_LIGHT as i32 - (dist + 1) * step; if lvl <= 0 { continue; } if !grid.is_loaded(chunk_of(nx), chunk_of(ny), chunk_of(nz)) { continue; } if !passable(grid, nx, ny, nz) { continue; } let key = (nx, ny, nz); let lvl = lvl as u8; if levels.get(&key).copied().unwrap_or(0) < lvl { levels.insert(key, lvl); queue.push_back((nx, ny, nz, dist + 1, step, range)); } } } levels } /// Renderer helper for the visible lantern cone (docs/05 §5.1: "Lantern cone /// is visibly a cone"). Simple 60° flood out to 12 m around `dir`; the true /// occluding cone lands with the renderer, so this stub ignores voxels. /// Deterministic nested-loop order; a zero `dir` defaults to +x. pub fn lantern_cone(origin: [f32; 3], dir: [f32; 3]) -> Vec<(i32, i32, i32)> { const RANGE: f32 = 12.0; /// tan(30°): half-angle of the 60° flood. const TAN_HALF: f32 = 0.577_350_3; let len = (dir[0] * dir[0] + dir[1] * dir[1] + dir[2] * dir[2]).sqrt(); let (dx, dy, dz) = if len < 1e-6 { (1.0, 0.0, 0.0) } else { (dir[0] / len, dir[1] / len, dir[2] / len) }; let r = RANGE as i32 + 1; let (ox, oy, oz) = ( origin[0].round() as i32, origin[1].round() as i32, origin[2].round() as i32, ); let mut out = Vec::new(); for cz in (oz - r)..=(oz + r) { for cy in (oy - r)..=(oy + r) { for cx in (ox - r)..=(ox + r) { let px = cx as f32 - origin[0]; let py = cy as f32 - origin[1]; let pz = cz as f32 - origin[2]; let t = px * dx + py * dy + pz * dz; if !(0.5..=RANGE).contains(&t) { continue; } let perp2 = px * px + py * py + pz * pz - t * t; let allow = t * TAN_HALF + 0.5; if perp2 <= allow * allow { out.push((cx, cy, cz)); } } } } out } #[cfg(test)] mod tests { use super::*; use crate::voxel::{material, Voxel}; /// Build a stone wall plane at x=1 spanning the flood box, optionally /// leaving the (1,0,0) cell open as an under-door gap / grate. fn wall_with_gap(grid: &mut ChunkedGrid, gap: bool) { for z in -4..=4 { for y in -4..=4 { if gap && y == 0 && z == 0 { continue; } let v = Voxel { material: material::STONE, occ: 1, ..Voxel::default() }; grid.set_world(1, y, z, v); } } } fn source() -> LightSource { LightSource { x: 0, y: 0, z: 0, radius: 4, warm: true, } } #[test] fn leak_through_grate() { let mut grid = ChunkedGrid::new(); wall_with_gap(&mut grid, true); let n = propagate_light(&mut grid, &[source()], false); assert!(n > 0); // dist 2 through the gap, step 24/4=6 → level 12. assert_eq!(grid.get_world(2, 0, 0).light, 12); // Solid part of the wall stays dark. assert_eq!(grid.get_world(1, 1, 0).light, 0); } #[test] fn no_leak_through_stone() { let mut grid = ChunkedGrid::new(); wall_with_gap(&mut grid, false); propagate_light(&mut grid, &[source()], false); assert_eq!(grid.get_world(2, 0, 0).light, 0); assert_eq!(grid.get_world(1, 0, 0).light, 0); // The source cell itself still glows. assert_eq!(grid.get_world(0, 0, 0).light, MAX_LIGHT); } #[test] fn dirty_only_skips_clean() { let mut grid = ChunkedGrid::new(); // radius 3 → step 8: (1,0,0) recomputes to 16, (2,0,0) to 8. let s = LightSource { x: 0, y: 0, z: 0, radius: 3, warm: false, }; let dirty = Voxel { flags: FLAG_LIGHT_DIRTY, ..Voxel::default() }; grid.set_world(2, 0, 0, dirty); let stale = Voxel { light: 3, ..Voxel::default() }; grid.set_world(1, 0, 0, stale); let n = propagate_light(&mut grid, &[s], true); assert_eq!(n, 1); let fixed = grid.get_world(2, 0, 0); assert_eq!(fixed.light, 8); assert_eq!(fixed.flags & FLAG_LIGHT_DIRTY, 0); // Clean cell keeps its stale level even though the flood disagrees. assert_eq!(grid.get_world(1, 0, 0).light, 3); } #[test] fn capped_large_radius_truncates_with_spillover() { let mut grid = ChunkedGrid::new(); // Materialise the chunk; centre the source so the whole flood lands // in loaded cells. grid.set_world(24, 24, 24, Voxel::default()); let big = LightSource { x: 24, y: 24, z: 24, radius: MAX_LIGHT_RADIUS, warm: true, }; let (updated, spill) = propagate_light_capped(&mut grid, &[big], false); // r=32 Manhattan flood (~17k lit cells) overflows the 4k budget. assert!(updated <= MAX_LIGHT_UPDATES); assert_eq!(updated, MAX_LIGHT_UPDATES); assert!(spill > 0); } #[test] fn capped_small_source_has_no_spillover_and_matches_wrapper() { let s = LightSource { x: 24, y: 24, z: 24, radius: 4, warm: true, }; let mut a = ChunkedGrid::new(); a.set_world(24, 24, 24, Voxel::default()); let mut b = ChunkedGrid::new(); b.set_world(24, 24, 24, Voxel::default()); let (updated, spill) = propagate_light_capped(&mut a, &[s], false); let n = propagate_light(&mut b, &[s], false); // Small flood fits the budget: nothing truncated, wrapper agrees. assert_eq!(spill, 0); assert_eq!(updated, n); assert_eq!(a.get_world(25, 24, 24).light, b.get_world(25, 24, 24).light); } #[test] fn doused_lamp_darkens_via_clear_light_box() { let mut grid = ChunkedGrid::new(); grid.set_world(24, 24, 24, Voxel::default()); let s = LightSource { x: 24, y: 24, z: 24, radius: 4, warm: true, }; let n = propagate_light(&mut grid, &[s], false); assert!(n > 0); assert_eq!(grid.get_world(24, 24, 24).light, MAX_LIGHT); assert_eq!(grid.get_world(25, 24, 24).light, 18); // Lamp removed: parent clears the old box before the next pass. let r = s.radius.min(MAX_LIGHT_RADIUS) as i32; clear_light_box(&mut grid, s.x, s.y, s.z, r); for (x, y, z) in [(24, 24, 24), (25, 24, 24), (26, 24, 24)] { let v = grid.get_world(x, y, z); assert_eq!(v.light, 0); assert_ne!(v.flags & FLAG_LIGHT_DIRTY, 0); } // Clearing never materialises unloaded chunks. let before = grid.loaded_count(); clear_light_box(&mut grid, 500, 500, 500, 4); assert_eq!(grid.loaded_count(), before); } #[test] fn lantern_cone_is_bounded_flood() { let a = lantern_cone([0.0, 0.0, 0.0], [1.0, 0.0, 0.0]); assert!(!a.is_empty()); // Deterministic across calls. assert_eq!(a, lantern_cone([0.0, 0.0, 0.0], [1.0, 0.0, 0.0])); for (x, y, z) in &a { let (px, py, pz) = (*x as f32, *y as f32, *z as f32); // Forward reach is 12 m; true distance is longer at the rim. assert!( (0.0..=12.5).contains(&px), "cone cell out of reach: {x},{y},{z}" ); // Within the 60° flood (half-angle 30° + half-cell slack). assert!(*x as f32 >= 0.0, "cone cell behind origin: {x},{y},{z}"); let perp = (py * py + pz * pz).sqrt(); assert!(perp <= px * 0.58 + 0.51, "cone cell too wide: {x},{y},{z}"); } } }