Skip to main content

roxlap_formats/
material.rs

1//! Voxel materials — opacity + blend mode for transparent voxels (TV stage).
2//!
3//! Every voxel roxlap renders is opaque today: both backends are per-pixel
4//! front-to-back 3D-DDA raymarchers that stop at the first solid voxel. A
5//! *material* attaches an opacity and a blend mode to a voxel so the march
6//! can instead accumulate it front-to-back over what lies behind (the
7//! per-pixel DDA visits cells strictly front-to-back, so this is
8//! order-correct without any sorting — see `PORTING-TRANSPARENCY.md`).
9//!
10//! Materials are kept out of the `0x80RRGGBB` colour word: its high byte is
11//! voxlap's lightmode-1 *brightness*, not alpha (see [`crate::kv6`] and
12//! [`crate::vxl`]). Instead a voxel carries a one-byte **material id** that
13//! indexes a [`MaterialTable`] — a 256-entry global palette the renderer
14//! owns. Id `0` is permanently [`Material::OPAQUE`], so a model or grid that
15//! carries no material data resolves every voxel to id 0 and renders exactly
16//! as before.
17
18use crate::color::Rgb;
19
20/// How a voxel's colour combines with what is already behind it along a ray.
21#[repr(u8)]
22#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
23pub enum BlendMode {
24    /// Fully opaque: the first solid hit wins and occludes everything behind
25    /// it — the existing render path. A voxel's `alpha` is ignored.
26    #[default]
27    Opaque = 0,
28    /// Front-to-back `over` compositing; `alpha` is the voxel's opacity.
29    /// Glass, smoke, water.
30    AlphaBlend = 1,
31    /// Commutative additive glow: contributes `alpha`·colour to the pixel
32    /// without occluding what is behind it (order-independent). Spells,
33    /// fire, magic auras, muzzle flashes.
34    Additive = 2,
35    /// Thickness-aware Beer–Lambert absorption for **filled** volumes (true
36    /// smoke, fog, murky water). Unlike [`AlphaBlend`](BlendMode::AlphaBlend) (which composites one
37    /// alpha per surface run, so opacity is independent of thickness — ideal
38    /// for shells/glass), `Volumetric` weights each voxel's opacity by the
39    /// ray's path length through it: the per-cell effective opacity is
40    /// `1 − (1 − alpha)^seg_len` where `seg_len` is the traversed length in
41    /// voxel units. A boundary sliver contributes ≈0 (no voxel-grid dicing)
42    /// while opacity grows smoothly with depth. Occludes like `AlphaBlend`.
43    Volumetric = 3,
44}
45
46impl BlendMode {
47    /// Decode the on-wire `u8`. Returns `None` for an unknown discriminant.
48    #[must_use]
49    pub fn from_u8(v: u8) -> Option<Self> {
50        match v {
51            0 => Some(Self::Opaque),
52            1 => Some(Self::AlphaBlend),
53            2 => Some(Self::Additive),
54            3 => Some(Self::Volumetric),
55            _ => None,
56        }
57    }
58
59    /// The on-wire discriminant.
60    #[must_use]
61    pub fn as_u8(self) -> u8 {
62        self as u8
63    }
64}
65
66/// One material: an opacity and a blend mode, indexed out of a
67/// [`MaterialTable`] by a per-voxel material id.
68#[derive(Clone, Copy, Debug, PartialEq, Eq)]
69pub struct Material {
70    /// Opacity for [`BlendMode::AlphaBlend`] / intensity scale for
71    /// [`BlendMode::Additive`]; ignored for [`BlendMode::Opaque`].
72    /// `0` = fully transparent, `255` = fully opaque / full intensity.
73    pub alpha: u8,
74    /// How the voxel composites with what is behind it.
75    pub mode: BlendMode,
76}
77
78impl Material {
79    /// The reserved, fully-opaque material at table id `0` — the
80    /// back-compat default for every voxel without explicit material data.
81    pub const OPAQUE: Self = Self {
82        alpha: 255,
83        mode: BlendMode::Opaque,
84    };
85
86    /// An [`BlendMode::AlphaBlend`] material with opacity `alpha`.
87    #[must_use]
88    pub fn alpha_blend(alpha: u8) -> Self {
89        Self {
90            alpha,
91            mode: BlendMode::AlphaBlend,
92        }
93    }
94
95    /// An [`BlendMode::Additive`] glow material scaled by `alpha`.
96    #[must_use]
97    pub fn additive(alpha: u8) -> Self {
98        Self {
99            alpha,
100            mode: BlendMode::Additive,
101        }
102    }
103
104    /// A [`BlendMode::Volumetric`] (Beer–Lambert) material whose `alpha` is
105    /// the per-voxel-unit absorption — opacity accrues with the ray's path
106    /// length through filled volumes (smoke/fog/murky water).
107    #[must_use]
108    pub fn volumetric(alpha: u8) -> Self {
109        Self {
110            alpha,
111            mode: BlendMode::Volumetric,
112        }
113    }
114
115    /// True for [`BlendMode::Opaque`] — the first-hit, fully-occluding path.
116    #[must_use]
117    pub fn is_opaque(self) -> bool {
118        matches!(self.mode, BlendMode::Opaque)
119    }
120}
121
122impl Default for Material {
123    fn default() -> Self {
124        Self::OPAQUE
125    }
126}
127
128/// A 256-entry palette of [`Material`]s indexed by a per-voxel `u8` material
129/// id. The renderer owns one table (a global palette); voxels reference
130/// materials by id rather than embedding them.
131///
132/// Id `0` is permanently [`Material::OPAQUE`] and cannot be redefined —
133/// it is the value every material-free voxel resolves to, so the opaque
134/// world stays byte-for-byte unchanged. [`set`](Self::set) silently
135/// ignores id 0.
136#[derive(Clone, Debug)]
137pub struct MaterialTable {
138    materials: [Material; 256],
139}
140
141impl MaterialTable {
142    /// A fresh palette: every id is [`Material::OPAQUE`].
143    #[must_use]
144    pub fn new() -> Self {
145        Self {
146            materials: [Material::OPAQUE; 256],
147        }
148    }
149
150    /// Define material `id`. Id `0` is reserved as [`Material::OPAQUE`] and
151    /// cannot be overwritten — defining it is a no-op that returns `false`;
152    /// any other id returns `true`.
153    pub fn set(&mut self, id: u8, mat: Material) -> bool {
154        if id == 0 {
155            return false;
156        }
157        self.materials[id as usize] = mat;
158        true
159    }
160
161    /// The material at `id` ([`Material::OPAQUE`] for any never-set id).
162    #[must_use]
163    pub fn get(&self, id: u8) -> Material {
164        self.materials[id as usize]
165    }
166
167    /// True when every id is [`BlendMode::Opaque`] — lets a backend skip the
168    /// whole transparency path while nothing translucent is defined.
169    #[must_use]
170    pub fn all_opaque(&self) -> bool {
171        self.materials.iter().all(|m| m.is_opaque())
172    }
173
174    /// The backing 256-entry array, for backends that upload it wholesale.
175    #[must_use]
176    pub fn as_array(&self) -> &[Material; 256] {
177        &self.materials
178    }
179}
180
181impl Default for MaterialTable {
182    fn default() -> Self {
183        Self::new()
184    }
185}
186
187/// Resolve a voxel's **material id** from a colour→material map — the
188/// authoring bridge for mixed-material models (TV.3). A model is colour-coded
189/// (e.g. cyan voxels = glass, grey = an opaque frame); `map` pairs an RGB
190/// colour (`0xRRGGBB`, the brightness byte is ignored) with the material id
191/// it maps to. A voxel whose colour isn't in `map` resolves to `0`
192/// ([`Material::OPAQUE`]). Linear scan — `map` is tiny (a handful of material
193/// colours), so this stays cheap even called per voxel.
194#[must_use]
195pub fn material_for_color(map: &[(Rgb, u8)], col: u32) -> u8 {
196    let rgb = col & 0x00ff_ffff;
197    for &(c, id) in map {
198        if c.0 & 0x00ff_ffff == rgb {
199            return id;
200        }
201    }
202    0
203}
204
205#[cfg(test)]
206mod tests {
207    use super::*;
208
209    #[test]
210    fn blend_mode_round_trips() {
211        for m in [
212            BlendMode::Opaque,
213            BlendMode::AlphaBlend,
214            BlendMode::Additive,
215            BlendMode::Volumetric,
216        ] {
217            assert_eq!(BlendMode::from_u8(m.as_u8()), Some(m));
218        }
219        assert_eq!(BlendMode::from_u8(4), None);
220        assert_eq!(BlendMode::default(), BlendMode::Opaque);
221        // Volumetric is translucent (not the opaque first-hit path).
222        assert!(!Material::volumetric(128).is_opaque());
223    }
224
225    #[test]
226    fn material_defaults_opaque() {
227        assert_eq!(Material::default(), Material::OPAQUE);
228        assert!(Material::OPAQUE.is_opaque());
229        assert!(!Material::alpha_blend(128).is_opaque());
230        assert!(!Material::additive(200).is_opaque());
231    }
232
233    #[test]
234    fn table_starts_all_opaque() {
235        let t = MaterialTable::new();
236        assert!(t.all_opaque());
237        for id in 0..=255u8 {
238            assert_eq!(t.get(id), Material::OPAQUE);
239        }
240    }
241
242    #[test]
243    fn table_set_and_get() {
244        let mut t = MaterialTable::new();
245        assert!(t.set(1, Material::alpha_blend(64)));
246        assert_eq!(t.get(1), Material::alpha_blend(64));
247        assert!(!t.all_opaque());
248        assert!(t.set(255, Material::additive(255)));
249        assert_eq!(t.get(255), Material::additive(255));
250    }
251
252    #[test]
253    fn id_zero_is_locked_opaque() {
254        let mut t = MaterialTable::new();
255        assert!(!t.set(0, Material::alpha_blend(0)));
256        assert_eq!(t.get(0), Material::OPAQUE);
257        assert!(t.all_opaque());
258    }
259}