Skip to main content

qualia_core_db/container_10d/
impostor_section.rs

1//! Section 19 (`IMPO`): Directional Octahedral Impostor Atlas for `.10d` Living Containers.
2//!
3//! Provides the runtime data container and projection mathematics for Tier 3 rendering
4//! (Screen-Space Radius: 8–64 px). At this distance, drawing full geometry or even dense meshlets
5//! triggers the GPU 2x2 quad-overdraw penalty. An octahedral impostor replaces the entire geometry
6//! with a single camera-facing quad (2 triangles) that samples an offline-baked atlas of directional
7//! views.
8//!
9//! # Mathematical Foundations
10//!
11//! 1. **Hemi-Octahedral Projection**: Maps upper-hemisphere directional rays $V \in S^2$ ($z \ge 0$)
12//!    onto a unit square UV coordinate $[0, 1]^2$:
13//!    $$u = \frac{x}{2(|x| + |y| + z)} + 0.5, \quad v = \frac{y}{2(|x| + |y| + z)} + 0.5$$
14//!    This provides uniform solid-angle texel distribution with minimal distortion compared to
15//!    equirectangular maps.
16//!
17//! 2. **Barycentric View Interpolation**: At runtime, a camera view vector falls between grid cells.
18//!    The runtime determines the 3 closest discrete camera angle viewpoints on the octahedral grid
19//!    and blends them with barycentric weights, providing parallax-free rotation without popping.
20//!
21//! 3. **Packed Channels**:
22//!    - Slice 0: Albedo RGB + Radial Depth A (for depth-buffer reconstruction and soft intersections).
23//!    - Slice 1: Octahedral normal map + Metallic/Roughness.
24
25use bytemuck::{Pod, Zeroable};
26
27pub const IMPOSTOR_SECTION_VERSION: u16 = 1;
28pub const IMPOSTOR_MINI_HEADER_SIZE: usize = 64;
29pub const MAGIC_IMPO: [u8; 4] = *b"IMPO";
30
31pub const FLAG_HEMI_OCTAHEDRAL: u16 = 1 << 0;
32pub const FLAG_DEPTH_IN_ALPHA: u16 = 1 << 1;
33pub const FLAG_OCT32_NORMALS: u16 = 1 << 2;
34pub const FLAG_PBR_METALLIC_ROUGHNESS: u16 = 1 << 3;
35
36/// 64-byte POD header encoding octahedral impostor atlas in SectionType::ImpostorAtlas (19).
37#[repr(C)]
38#[derive(Debug, Clone, Copy, PartialEq, Pod, Zeroable)]
39pub struct ImpostorAtlasMiniHeader {
40    pub magic: [u8; 4],
41    pub version: u16,
42    pub flags: u16,
43    /// Grid dimension along one axis (e.g., 8 for an 8x8 grid = 64 views, 16 for 16x16 = 256 views).
44    pub grid_dimension: u16,
45    /// Resolution in texels per view (e.g., 64 for 64x64 or 128 for 128x128).
46    pub view_resolution: u16,
47    /// Local-space bounding sphere center.
48    pub sphere_center: [f32; 3],
49    /// Local-space bounding sphere radius.
50    pub sphere_radius: f32,
51    /// Total byte length of the texture payload following this header.
52    pub atlas_byte_size: u32,
53    /// 0 = RGBA8_UNORM, 1 = BC7, 2 = ASTC_4x4.
54    pub channel_format: u8,
55    pub reserved: [u8; 31],
56}
57const _: [(); IMPOSTOR_MINI_HEADER_SIZE] = [(); core::mem::size_of::<ImpostorAtlasMiniHeader>()];
58
59#[derive(Debug, Clone, PartialEq, Eq)]
60pub enum ImpostorSectionError {
61    PayloadTooShort { need: usize, have: usize },
62    BadMagic([u8; 4]),
63    UnsupportedVersion(u16),
64    BufferTooSmall { need: usize, have: usize },
65    InvalidGridDimension(u16),
66    PayloadLengthMismatch { declared: usize, actual: usize },
67}
68
69impl std::fmt::Display for ImpostorSectionError {
70    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
71        match self {
72            Self::PayloadTooShort { need, have } => {
73                write!(
74                    f,
75                    "impostor section payload too short: have {have}, need {need}"
76                )
77            }
78            Self::BadMagic(m) => write!(f, "bad impostor section magic: {m:?}"),
79            Self::UnsupportedVersion(v) => write!(f, "unsupported impostor section version {v}"),
80            Self::BufferTooSmall { need, have } => {
81                write!(f, "buffer too small: have {have}, need {need}")
82            }
83            Self::InvalidGridDimension(d) => write!(f, "invalid impostor grid dimension: {d}"),
84            Self::PayloadLengthMismatch { declared, actual } => {
85                write!(
86                    f,
87                    "impostor payload length mismatch: declared {declared}, actual {actual}"
88                )
89            }
90        }
91    }
92}
93
94impl std::error::Error for ImpostorSectionError {}
95
96/// Encode impostor header and binary atlas payload into caller-supplied buffer. Zero heap.
97pub fn encode_impostor_section(
98    header: &ImpostorAtlasMiniHeader,
99    payload: &[u8],
100    out: &mut [u8],
101) -> Result<usize, ImpostorSectionError> {
102    let total_len = IMPOSTOR_MINI_HEADER_SIZE + payload.len();
103    if out.len() < total_len {
104        return Err(ImpostorSectionError::BufferTooSmall {
105            need: total_len,
106            have: out.len(),
107        });
108    }
109    let header_bytes = bytemuck::bytes_of(header);
110    out[..IMPOSTOR_MINI_HEADER_SIZE].copy_from_slice(header_bytes);
111    out[IMPOSTOR_MINI_HEADER_SIZE..total_len].copy_from_slice(payload);
112    Ok(total_len)
113}
114
115/// Decode impostor header and extract zero-copy slice of atlas payload. Zero heap.
116pub fn decode_impostor_section<'a>(
117    payload: &'a [u8],
118) -> Result<(ImpostorAtlasMiniHeader, &'a [u8]), ImpostorSectionError> {
119    if payload.len() < IMPOSTOR_MINI_HEADER_SIZE {
120        return Err(ImpostorSectionError::PayloadTooShort {
121            need: IMPOSTOR_MINI_HEADER_SIZE,
122            have: payload.len(),
123        });
124    }
125    let header: ImpostorAtlasMiniHeader =
126        bytemuck::pod_read_unaligned(&payload[..IMPOSTOR_MINI_HEADER_SIZE]);
127    if header.magic != MAGIC_IMPO {
128        return Err(ImpostorSectionError::BadMagic(header.magic));
129    }
130    if header.version != IMPOSTOR_SECTION_VERSION {
131        return Err(ImpostorSectionError::UnsupportedVersion(header.version));
132    }
133    if header.grid_dimension == 0 || header.grid_dimension > 64 {
134        return Err(ImpostorSectionError::InvalidGridDimension(
135            header.grid_dimension,
136        ));
137    }
138    let data_len = payload.len() - IMPOSTOR_MINI_HEADER_SIZE;
139    if header.atlas_byte_size as usize != data_len {
140        return Err(ImpostorSectionError::PayloadLengthMismatch {
141            declared: header.atlas_byte_size as usize,
142            actual: data_len,
143        });
144    }
145    Ok((header, &payload[IMPOSTOR_MINI_HEADER_SIZE..]))
146}
147
148// ───────────────────────────────────────────────────────────────────────────
149//  Hemi-Octahedral Projection Mathematics (Zero-Heap Hot-Path Helpers)
150// ───────────────────────────────────────────────────────────────────────────
151
152/// Project a normalized 3D direction vector $V = (x, y, z)$ on the upper hemisphere
153/// ($z \ge 0$) onto 2D octahedral UV coordinates $[0.0, 1.0]^2$.
154#[inline]
155pub fn hemi_octahedral_encode(dir: [f32; 3]) -> [f32; 2] {
156    let l1_norm = dir[0].abs() + dir[1].abs() + dir[2].max(0.0);
157    if l1_norm < 1e-7 {
158        return [0.5, 0.5];
159    }
160    let inv_l1 = 1.0 / l1_norm;
161    let u = (dir[0] - dir[1]) * inv_l1 * 0.5 + 0.5;
162    let v = (dir[0] + dir[1]) * inv_l1 * 0.5 + 0.5;
163    [u.clamp(0.0, 1.0), v.clamp(0.0, 1.0)]
164}
165
166/// Unproject 2D octahedral UV coordinates $[0.0, 1.0]^2$ back to a normalized
167/// 3D directional vector on the upper hemisphere.
168#[inline]
169pub fn hemi_octahedral_decode(uv: [f32; 2]) -> [f32; 3] {
170    // Map UV from [0, 1] to [-1, 1]
171    let u = uv[0] * 2.0 - 1.0;
172    let v = uv[1] * 2.0 - 1.0;
173    let x = (u + v) * 0.5;
174    let y = (v - u) * 0.5;
175    let z = 1.0 - x.abs() - y.abs();
176    let len = (x * x + y * y + z * z).sqrt();
177    if len < 1e-7 {
178        [0.0, 0.0, 1.0]
179    } else {
180        [x / len, y / len, (z / len).max(0.0)]
181    }
182}
183
184/// Viewpoint blending information for smooth camera interpolation.
185#[derive(Debug, Clone, Copy, PartialEq)]
186pub struct ImpostorBlendSample {
187    /// 3 nearest view grid indices (row * grid_dimension + col).
188    pub view_indices: [u16; 3],
189    /// Barycentric weights summing to 1.0.
190    pub weights: [f32; 3],
191}
192
193/// Calculate the 3 closest discrete camera viewpoints on the octahedral grid and their
194/// barycentric blending weights.
195pub fn sample_impostor_blend_weights(view_dir: [f32; 3], grid_dim: u16) -> ImpostorBlendSample {
196    if grid_dim < 2 {
197        return ImpostorBlendSample {
198            view_indices: [0, 0, 0],
199            weights: [1.0, 0.0, 0.0],
200        };
201    }
202    let uv = hemi_octahedral_encode(view_dir);
203    let n = (grid_dim - 1) as f32;
204    let gx = (uv[0] * n).clamp(0.0, n);
205    let gy = (uv[1] * n).clamp(0.0, n);
206
207    let x0 = gx.floor() as u16;
208    let y0 = gy.floor() as u16;
209    let x1 = (x0 + 1).min(grid_dim - 1);
210    let y1 = (y0 + 1).min(grid_dim - 1);
211
212    let fx = gx - x0 as f32;
213    let fy = gy - y0 as f32;
214
215    let idx00 = y0 * grid_dim + x0;
216    let idx10 = y0 * grid_dim + x1;
217    let idx01 = y1 * grid_dim + x0;
218    let idx11 = y1 * grid_dim + x1;
219
220    // Split quad into two triangles along diagonal
221    if fx + fy <= 1.0 {
222        ImpostorBlendSample {
223            view_indices: [idx00, idx10, idx01],
224            weights: [1.0 - fx - fy, fx, fy],
225        }
226    } else {
227        ImpostorBlendSample {
228            view_indices: [idx11, idx10, idx01],
229            weights: [fx + fy - 1.0, 1.0 - fy, 1.0 - fx],
230        }
231    }
232}
233
234#[cfg(test)]
235mod tests {
236    use super::*;
237
238    #[test]
239    fn test_impostor_header_roundtrip() {
240        let header = ImpostorAtlasMiniHeader {
241            magic: MAGIC_IMPO,
242            version: IMPOSTOR_SECTION_VERSION,
243            flags: FLAG_HEMI_OCTAHEDRAL | FLAG_DEPTH_IN_ALPHA,
244            grid_dimension: 16,
245            view_resolution: 64,
246            sphere_center: [0.0, 1.5, 0.0],
247            sphere_radius: 2.2,
248            atlas_byte_size: 16,
249            channel_format: 0,
250            reserved: [0; 31],
251        };
252        let dummy_payload = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
253        let mut buffer = [0u8; 128];
254
255        let written = encode_impostor_section(&header, &dummy_payload, &mut buffer).unwrap();
256        assert_eq!(written, 64 + 16);
257
258        let (decoded_hdr, decoded_data) = decode_impostor_section(&buffer[..written]).unwrap();
259        assert_eq!(decoded_hdr, header);
260        assert_eq!(decoded_data, &dummy_payload);
261        let mut unaligned = [0u8; 129];
262        unaligned[1..1 + written].copy_from_slice(&buffer[..written]);
263        assert_eq!(
264            decode_impostor_section(&unaligned[1..1 + written])
265                .unwrap()
266                .0,
267            header
268        );
269    }
270
271    #[test]
272    fn test_hemi_octahedral_projection_cardinal() {
273        // Up direction (0, 0, 1) should map to center (0.5, 0.5)
274        let uv = hemi_octahedral_encode([0.0, 0.0, 1.0]);
275        assert!((uv[0] - 0.5).abs() < 1e-4);
276        assert!((uv[1] - 0.5).abs() < 1e-4);
277
278        let recovered = hemi_octahedral_decode(uv);
279        assert!((recovered[0] - 0.0).abs() < 1e-4);
280        assert!((recovered[1] - 0.0).abs() < 1e-4);
281        assert!((recovered[2] - 1.0).abs() < 1e-4);
282    }
283
284    #[test]
285    fn test_barycentric_blend_weights() {
286        let sample = sample_impostor_blend_weights([0.0, 0.0, 1.0], 8);
287        let sum = sample.weights[0] + sample.weights[1] + sample.weights[2];
288        assert!((sum - 1.0).abs() < 1e-5);
289    }
290}