Skip to main content

qualia_core_db/render/
lod_chain.rs

1//! P5.8 — LOD chain: author mesh → decimate N LODs → serialize to `.10d`
2//! → renderer parses each level → `plan_view` selects the expected LOD.
3//!
4//! This module is the serial integrator spine connecting P5.7 (`decimate_3`)
5//! to the `.10d` container format and the authoring planner (`authoring.rs`).
6//!
7//! ## Pipeline
8//!
9//! 1. **Author**: a source `Mesh` (the highest-LOD asset).
10//! 2. **Decimate**: produce N LOD levels by successive QEM decimation, each
11//!    targeting a fraction of the previous level's triangle count.
12//! 3. **Serialize**: encode each LOD as a `.10d` QuantizedMesh section
13//!    (`mesh_section.rs`), concatenated into a single buffer.
14//! 4. **Select**: at render time, `select_lod` picks the appropriate LOD index
15//!    based on `OperationalMode` (Full → LOD 0, Eco → LOD 1, Reserve → LOD 2).
16//! 5. **Parse**: the renderer decodes the selected section back to a `Mesh`.
17//!
18//! ## Determinism
19//!
20//! Decimation is deterministic (canonical vertex remap, sorted collapses).
21//! `.10d` encoding is deterministic (quantization is pure, section order is
22//! ascending). Two encodes of the same LOD chain produce byte-identical output.
23//!
24//! ## Budget rail
25//!
26//! The `plan_view` integration adds a `LodDisposition` that combines the
27//! existing governance/attestation gates with LOD selection. On a constrained
28//! tier (`Eco`/`Reserve`), a `Scene3D` view selects a coarser LOD rather than
29//! collapsing to 2D — *if* a coarser LOD is available. If no coarser LOD
30//! exists, the existing `Collapsed2D` fallback applies.
31
32use crate::container_10d::mesh_section::{
33    decode_mesh_section, encode_mesh_section, encoded_len, MeshSectionError,
34};
35use crate::gpu_context::OperationalMode;
36use crate::render::assets::Mesh;
37use crate::specialized_libs::computational_geometry::{
38    decimate_qem, DecimateError, DecimateOptions, DecimateReport, Point3,
39};
40
41// ───────────────────────────────────────────────────────────────────────────
42//  Errors
43// ───────────────────────────────────────────────────────────────────────────
44
45/// Failure modes for the LOD chain.
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub enum LodChainError {
48    /// Decimation failed at the given LOD level.
49    DecimateFailed { level: usize, cause: DecimateError },
50    /// `.10d` encoding failed at the given LOD level.
51    EncodeFailed {
52        level: usize,
53        cause: MeshSectionError,
54    },
55    /// `.10d` decoding failed at the given LOD level.
56    DecodeFailed {
57        level: usize,
58        cause: MeshSectionError,
59    },
60    /// Output buffer too small for the serialized LOD chain.
61    BufferTooSmall { needed: usize, have: usize },
62    /// No LOD levels were requested.
63    NoLodLevels,
64    /// The source mesh is empty (no vertices or triangles).
65    EmptySourceMesh,
66}
67
68impl core::fmt::Display for LodChainError {
69    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
70        match self {
71            Self::DecimateFailed { level, cause } => {
72                write!(
73                    f,
74                    "lod_chain: decimation failed at level {level}: {cause:?}"
75                )
76            }
77            Self::EncodeFailed { level, cause } => {
78                write!(f, "lod_chain: encode failed at level {level}: {cause}")
79            }
80            Self::DecodeFailed { level, cause } => {
81                write!(f, "lod_chain: decode failed at level {level}: {cause}")
82            }
83            Self::BufferTooSmall { needed, have } => {
84                write!(f, "lod_chain: buffer too small, need {needed}, have {have}")
85            }
86            Self::NoLodLevels => write!(f, "lod_chain: no LOD levels requested"),
87            Self::EmptySourceMesh => write!(f, "lod_chain: source mesh is empty"),
88        }
89    }
90}
91
92impl std::error::Error for LodChainError {}
93
94// ───────────────────────────────────────────────────────────────────────────
95//  LOD chain configuration
96// ───────────────────────────────────────────────────────────────────────────
97
98/// Maximum number of LOD levels supported (including LOD 0 = full resolution).
99pub const MAX_LOD_LEVELS: usize = 8;
100
101/// LOD chain configuration: how many levels and what fraction to decimate to
102/// at each level.
103#[derive(Debug, Clone, Copy)]
104pub struct LodChainOptions {
105    /// Number of LOD levels (including LOD 0 = the source mesh). Must be ≥ 1.
106    pub level_count: usize,
107    /// Triangle-count fraction at each successive LOD level. E.g. 0.5 means
108    /// each level has half the triangles of the previous. LOD 0 is always the
109    /// full mesh; LOD 1 targets `fraction * LOD0_faces`, etc.
110    pub fraction: f64,
111}
112
113impl Default for LodChainOptions {
114    fn default() -> Self {
115        Self {
116            level_count: 3,
117            fraction: 0.5,
118        }
119    }
120}
121
122impl LodChainOptions {
123    /// Create a configuration with `level_count` levels and the given fraction.
124    pub fn new(level_count: usize, fraction: f64) -> Self {
125        Self {
126            level_count: level_count.clamp(1, MAX_LOD_LEVELS),
127            fraction: fraction.clamp(0.01, 1.0),
128        }
129    }
130
131    /// 3 levels (Full / Eco / Reserve) at 50% per level.
132    pub fn default_3_tier() -> Self {
133        Self {
134            level_count: 3,
135            fraction: 0.5,
136        }
137    }
138}
139
140/// Report for one LOD level after building the chain.
141#[derive(Debug, Clone, Copy)]
142pub struct LodLevelReport {
143    /// LOD index (0 = full resolution).
144    pub level: usize,
145    /// Vertex count at this level.
146    pub vertices: usize,
147    /// Triangle count at this level.
148    pub triangles: usize,
149    /// Encoded `.10d` section byte length.
150    pub encoded_bytes: usize,
151    /// Decimation report (None for LOD 0).
152    pub decimate_report: Option<DecimateReport>,
153}
154
155/// Overall LOD chain build report.
156#[derive(Debug, Clone)]
157pub struct LodChainReport {
158    pub levels: Vec<LodLevelReport>,
159    /// Total serialized byte length (all sections concatenated).
160    pub total_bytes: usize,
161}
162
163// ───────────────────────────────────────────────────────────────────────────
164//  LOD chain builder
165// ───────────────────────────────────────────────────────────────────────────
166
167/// Build a LOD chain from a source mesh and serialize all levels as `.10d`
168/// QuantizedMesh sections into `out_buffer`.
169///
170/// Returns a report with per-level stats and the total bytes written.
171///
172/// This is a cold builder (uses `Vec` scratch for decimation and encoding).
173/// The output is caller-owned and deterministic.
174pub fn build_lod_chain(
175    source: &Mesh,
176    options: LodChainOptions,
177    out_buffer: &mut [u8],
178) -> Result<LodChainReport, LodChainError> {
179    if source.positions.is_empty() || source.triangles.is_empty() {
180        return Err(LodChainError::EmptySourceMesh);
181    }
182    if options.level_count == 0 {
183        return Err(LodChainError::NoLodLevels);
184    }
185
186    let mut levels: Vec<LodLevelReport> = Vec::with_capacity(options.level_count);
187    let mut offset = 0usize;
188
189    // LOD 0: encode the source mesh directly (no decimation).
190    let lod0_bytes = encoded_len(source.positions.len(), source.triangles.len());
191    if offset + lod0_bytes > out_buffer.len() {
192        return Err(LodChainError::BufferTooSmall {
193            needed: offset + lod0_bytes,
194            have: out_buffer.len(),
195        });
196    }
197    let written = encode_mesh_section(source, &mut out_buffer[offset..])
198        .map_err(|e| LodChainError::EncodeFailed { level: 0, cause: e })?;
199    levels.push(LodLevelReport {
200        level: 0,
201        vertices: source.positions.len(),
202        triangles: source.triangles.len(),
203        encoded_bytes: written,
204        decimate_report: None,
205    });
206    offset += written;
207
208    // Successive LOD levels: decimate the previous level.
209    let mut current_verts_f64: Vec<Point3> = source
210        .positions
211        .iter()
212        .map(|p| Point3::new(p[0] as f64, p[1] as f64, p[2] as f64))
213        .collect();
214    let mut current_tris: Vec<[u32; 3]> = source.triangles.clone();
215
216    for level in 1..options.level_count {
217        let target_faces = (current_tris.len() as f64 * options.fraction) as usize;
218        if target_faces < 4 {
219            // Can't decimate below 4 triangles; stop early.
220            break;
221        }
222
223        let decim_opts = DecimateOptions::to_faces(target_faces);
224        let mut out_v = vec![Point3::default(); current_verts_f64.len()];
225        let mut out_t = vec![[0u32; 3]; current_tris.len()];
226
227        let report = decimate_qem(
228            &current_verts_f64,
229            &current_tris,
230            decim_opts,
231            &mut out_v,
232            &mut out_t,
233        )
234        .map_err(|e| LodChainError::DecimateFailed { level, cause: e })?;
235
236        // Compact to actual counts.
237        let live_v = report.vertices;
238        let live_t = report.faces;
239        current_verts_f64 = out_v[..live_v].to_vec();
240        current_tris = out_t[..live_t].to_vec();
241
242        // Convert back to f32 for encoding.
243        let f32_positions: Vec<[f32; 3]> = current_verts_f64
244            .iter()
245            .map(|p| [p.x as f32, p.y as f32, p.z as f32])
246            .collect();
247
248        // Encode this LOD level.
249        let lod_mesh = Mesh {
250            positions: f32_positions.clone(),
251            triangles: current_tris.clone(),
252            min: [
253                f32_positions
254                    .iter()
255                    .map(|p| p[0])
256                    .fold(f32::INFINITY, f32::min),
257                f32_positions
258                    .iter()
259                    .map(|p| p[1])
260                    .fold(f32::INFINITY, f32::min),
261                f32_positions
262                    .iter()
263                    .map(|p| p[2])
264                    .fold(f32::INFINITY, f32::min),
265            ],
266            max: [
267                f32_positions
268                    .iter()
269                    .map(|p| p[0])
270                    .fold(f32::NEG_INFINITY, f32::max),
271                f32_positions
272                    .iter()
273                    .map(|p| p[1])
274                    .fold(f32::NEG_INFINITY, f32::max),
275                f32_positions
276                    .iter()
277                    .map(|p| p[2])
278                    .fold(f32::NEG_INFINITY, f32::max),
279            ],
280        };
281
282        let lod_bytes = encoded_len(live_v, live_t);
283        if offset + lod_bytes > out_buffer.len() {
284            return Err(LodChainError::BufferTooSmall {
285                needed: offset + lod_bytes,
286                have: out_buffer.len(),
287            });
288        }
289        let written = encode_mesh_section(&lod_mesh, &mut out_buffer[offset..])
290            .map_err(|e| LodChainError::EncodeFailed { level, cause: e })?;
291        levels.push(LodLevelReport {
292            level,
293            vertices: live_v,
294            triangles: live_t,
295            encoded_bytes: written,
296            decimate_report: Some(report),
297        });
298        offset += written;
299    }
300
301    Ok(LodChainReport {
302        levels,
303        total_bytes: offset,
304    })
305}
306
307/// Compute the total buffer size needed for a LOD chain with the given options
308/// and source mesh size. This is an upper bound (actual may be smaller if
309/// decimation stops early).
310pub fn required_lod_buffer_size(
311    source_vertices: usize,
312    source_triangles: usize,
313    options: LodChainOptions,
314) -> usize {
315    let mut total = 0usize;
316    let mut verts = source_vertices;
317    let mut tris = source_triangles;
318
319    for level in 0..options.level_count {
320        total += encoded_len(verts, tris);
321        if level > 0 {
322            let target = (tris as f64 * options.fraction) as usize;
323            if target < 4 {
324                break;
325            }
326            // Estimate vertex count reduction proportionally.
327            verts = (verts as f64 * options.fraction) as usize;
328            tris = target;
329        }
330    }
331    total
332}
333
334// ───────────────────────────────────────────────────────────────────────────
335//  LOD selection
336// ───────────────────────────────────────────────────────────────────────────
337
338/// Select the appropriate LOD index for a given `OperationalMode`.
339///
340/// - `Full` → LOD 0 (full resolution)
341/// - `Eco` → LOD 1 (half resolution, or the coarsest available if < 2 levels)
342/// - `Reserve` → LOD 2 (quarter resolution, or the coarsest available if < 3 levels)
343///
344/// Returns the LOD index clamped to `[0, level_count-1]`.
345#[inline]
346pub fn select_lod(mode: OperationalMode, level_count: usize) -> usize {
347    if level_count == 0 {
348        return 0;
349    }
350    let preferred = match mode {
351        OperationalMode::Full => 0,
352        OperationalMode::Eco => 1,
353        OperationalMode::Reserve => 2,
354    };
355    preferred.min(level_count - 1)
356}
357
358/// Runtime description of one renderable whose LOD state is retained by the
359/// caller between frames. `semantic_id` is the stable content identity while
360/// `source_index` addresses the caller's source array; selection never
361/// compacts or renumbers either identity.
362#[derive(Debug, Clone, Copy, PartialEq)]
363pub struct LodRuntimeInstance {
364    pub semantic_id: u64,
365    pub source_index: u32,
366    pub world_center: [f32; 3],
367    pub world_radius: f32,
368    pub last_lod: u8,
369}
370
371/// Per-frame choice for one input instance. Entries are written in source
372/// order, making the result deterministic and directly indexable by the caller.
373#[derive(Debug, Clone, Copy, PartialEq, Eq)]
374pub struct SelectedLod {
375    pub semantic_id: u64,
376    pub source_index: u32,
377    pub level: u8,
378}
379
380/// Camera parameters used to convert geometric error into pixel error.
381#[derive(Debug, Clone, Copy)]
382pub struct LodCamera {
383    pub position: [f32; 3],
384    /// Vertical field of view in radians.
385    pub vertical_fov_radians: f32,
386    pub viewport_height_pixels: u32,
387    /// Lower bound for the projected-distance denominator, in world units.
388    pub near_distance: f32,
389}
390
391/// Screen-space LOD policy. A coarser level is admitted below
392/// `max_pixel_error * (1 - hysteresis)`; an existing coarse level is retained
393/// until it exceeds `max_pixel_error * (1 + hysteresis)`. This dead band
394/// prevents threshold chatter as the camera moves around a boundary.
395#[derive(Debug, Clone, Copy)]
396pub struct ScreenSpaceLodPolicy {
397    pub max_pixel_error: f32,
398    /// Fraction in `[0, 0.5)`, e.g. `0.1` gives a 10% dead band.
399    pub hysteresis: f32,
400}
401
402/// Errors detected before writing runtime LOD output.
403#[derive(Debug, Clone, Copy, PartialEq, Eq)]
404pub enum LodSelectionError {
405    InvalidLevelErrors,
406    InvalidCamera,
407    InvalidPolicy,
408    OutputTooSmall { needed: usize, have: usize },
409}
410
411/// Select a level for every instance using projected geometric error.
412///
413/// `geometric_errors` is indexed by LOD and must be finite, nonnegative, and
414/// monotonically nondecreasing (LOD 0 is normally zero). The selector uses a
415/// perspective camera approximation, clamps near-plane distance, and retains
416/// each instance's previous level through a configurable hysteresis band.
417/// Invalid per-instance bounds fail open to LOD 0; malformed shared inputs
418/// return an error before any output or state is modified. This is a hot-path
419/// routine: it allocates no memory and preserves both identities verbatim.
420pub fn select_lods_screen_space(
421    instances: &mut [LodRuntimeInstance],
422    geometric_errors: &[f32],
423    camera: LodCamera,
424    policy: ScreenSpaceLodPolicy,
425    out: &mut [SelectedLod],
426) -> Result<usize, LodSelectionError> {
427    if geometric_errors.is_empty()
428        || geometric_errors.len() > MAX_LOD_LEVELS
429        || geometric_errors.iter().any(|e| !e.is_finite() || *e < 0.0)
430        || geometric_errors.windows(2).any(|pair| pair[1] < pair[0])
431    {
432        return Err(LodSelectionError::InvalidLevelErrors);
433    }
434    if camera.position.iter().any(|v| !v.is_finite())
435        || !camera.vertical_fov_radians.is_finite()
436        || camera.vertical_fov_radians <= 0.0
437        || camera.vertical_fov_radians >= core::f32::consts::PI
438        || camera.viewport_height_pixels == 0
439        || !camera.near_distance.is_finite()
440        || camera.near_distance <= 0.0
441    {
442        return Err(LodSelectionError::InvalidCamera);
443    }
444    if !policy.max_pixel_error.is_finite()
445        || policy.max_pixel_error <= 0.0
446        || !policy.hysteresis.is_finite()
447        || !(0.0..0.5).contains(&policy.hysteresis)
448    {
449        return Err(LodSelectionError::InvalidPolicy);
450    }
451    if out.len() < instances.len() {
452        return Err(LodSelectionError::OutputTooSmall {
453            needed: instances.len(),
454            have: out.len(),
455        });
456    }
457
458    let focal_pixels =
459        camera.viewport_height_pixels as f32 / (2.0 * (camera.vertical_fov_radians * 0.5).tan());
460    let coarsen_limit = policy.max_pixel_error * (1.0 - policy.hysteresis);
461    let refine_limit = policy.max_pixel_error * (1.0 + policy.hysteresis);
462
463    for (slot, instance) in instances.iter_mut().enumerate() {
464        let level_count = geometric_errors.len();
465        let mut level = (instance.last_lod as usize).min(level_count - 1);
466        let valid_bounds = instance.world_center.iter().all(|v| v.is_finite())
467            && instance.world_radius.is_finite()
468            && instance.world_radius >= 0.0;
469        if valid_bounds {
470            let dx = instance.world_center[0] - camera.position[0];
471            let dy = instance.world_center[1] - camera.position[1];
472            let dz = instance.world_center[2] - camera.position[2];
473            let distance = (dx * dx + dy * dy + dz * dz).sqrt();
474            let distance = (distance - instance.world_radius).max(camera.near_distance);
475            let projected_scale = focal_pixels / distance;
476            if projected_scale.is_finite() {
477                // Refine while the currently selected level exceeds the upper
478                // edge of the dead band.
479                while level > 0 && geometric_errors[level] * projected_scale > refine_limit {
480                    level -= 1;
481                }
482                // Coarsen while each next level stays below the lower edge.
483                while level + 1 < level_count
484                    && geometric_errors[level + 1] * projected_scale <= coarsen_limit
485                {
486                    level += 1;
487                }
488            } else {
489                level = 0;
490            }
491        } else {
492            level = 0;
493        }
494        instance.last_lod = level as u8;
495        out[slot] = SelectedLod {
496            semantic_id: instance.semantic_id,
497            source_index: instance.source_index,
498            level: level as u8,
499        };
500    }
501    Ok(instances.len())
502}
503
504// ───────────────────────────────────────────────────────────────────────────
505//  LOD section parsing
506// ───────────────────────────────────────────────────────────────────────────
507
508/// Parse a specific LOD level from a serialized LOD chain buffer.
509///
510/// The `level_offsets` are the byte offsets of each LOD section within the
511/// buffer (as reported by `LodChainReport`). Returns the decoded `Mesh`.
512pub fn parse_lod_level(
513    buffer: &[u8],
514    level_offsets: &[usize],
515    level: usize,
516) -> Result<Mesh, LodChainError> {
517    if level >= level_offsets.len() {
518        return Err(LodChainError::DecodeFailed {
519            level,
520            cause: MeshSectionError::PayloadTooShort { got: 0, need: 40 },
521        });
522    }
523    let offset = level_offsets[level];
524    let end = if level + 1 < level_offsets.len() {
525        level_offsets[level + 1]
526    } else {
527        buffer.len()
528    };
529    let section_bytes = &buffer[offset..end];
530    decode_mesh_section(section_bytes).map_err(|e| LodChainError::DecodeFailed { level, cause: e })
531}
532
533/// Extract the per-level byte offsets from a `LodChainReport`.
534pub fn level_offsets(report: &LodChainReport) -> Vec<usize> {
535    let mut offsets = Vec::with_capacity(report.levels.len());
536    let mut acc = 0;
537    for lvl in &report.levels {
538        offsets.push(acc);
539        acc += lvl.encoded_bytes;
540    }
541    offsets
542}
543
544// ───────────────────────────────────────────────────────────────────────────
545//  plan_view integration
546// ───────────────────────────────────────────────────────────────────────────
547
548/// The LOD-aware disposition for a view, extending `ViewDisposition` with
549/// LOD selection for 3D scenes that have a LOD chain available.
550#[derive(Debug, Clone, Copy, PartialEq, Eq)]
551pub enum LodViewDisposition {
552    /// Render the 3D scene at the given LOD level.
553    Render3dWithLod { lod: usize },
554    /// Render the 2D pane (no LOD needed).
555    Render2d,
556    /// A `Scene3D` view degraded to 2D under a constrained device budget with
557    /// no coarser LOD available.
558    Collapsed2D,
559    /// Attestation-gated and not yet attested — withheld.
560    WithheldUnattested,
561    /// Sensitive content in a shared/civic standpoint without consent — refused.
562    RefusedRightsBounded,
563}
564
565/// Plan a view with LOD awareness. Applies the same gate order as
566/// `authoring::plan_view` (attestation → rights → budget), but instead of
567/// collapsing 3D to 2D on constrained tiers, selects a coarser LOD if
568/// available.
569#[allow(clippy::too_many_arguments)]
570pub fn plan_view_with_lod(
571    view: &crate::render::authoring::QappView,
572    standpoint: &crate::render::authoring::RenderStandpoint,
573    mode: OperationalMode,
574    attestations: &[crate::NQuin],
575    gov_norms: &[crate::NQuin],
576    now_unix: u32,
577    lod_level_count: usize,
578) -> LodViewDisposition {
579    use crate::render::authoring::{has_attestation, Sensitivity, ViewKind};
580
581    // 1) Attestation gate.
582    if view.requires_attestation && !has_attestation(view, attestations) {
583        return LodViewDisposition::WithheldUnattested;
584    }
585
586    // 2) Rights-bounded context.
587    if matches!(view.sensitivity, Sensitivity::RightsBounded)
588        && !crate::render::authoring::rights_render_permitted(
589            standpoint,
590            view.manifold,
591            gov_norms,
592            now_unix,
593        )
594    {
595        return LodViewDisposition::RefusedRightsBounded;
596    }
597
598    // 3) Budget + LOD selection.
599    match view.kind {
600        ViewKind::Pane2D => LodViewDisposition::Render2d,
601        ViewKind::Scene3D => {
602            if mode.supports_3d() {
603                LodViewDisposition::Render3dWithLod {
604                    lod: select_lod(mode, lod_level_count),
605                }
606            } else if lod_level_count > 1 {
607                // Constrained tier but coarser LODs available → use the coarsest.
608                LodViewDisposition::Render3dWithLod {
609                    lod: select_lod(mode, lod_level_count),
610                }
611            } else {
612                // No coarser LOD → collapse to 2D.
613                LodViewDisposition::Collapsed2D
614            }
615        }
616    }
617}
618
619// ───────────────────────────────────────────────────────────────────────────
620//  Hash stability
621// ───────────────────────────────────────────────────────────────────────────
622
623/// Compute a simple FNV-1a hash over a byte slice (for determinism verification).
624pub fn lod_chain_hash(bytes: &[u8]) -> u64 {
625    let mut hash: u64 = 0xcbf29ce484222325;
626    for &b in bytes {
627        hash ^= b as u64;
628        hash = hash.wrapping_mul(0x100000001b3);
629    }
630    hash
631}
632
633// ───────────────────────────────────────────────────────────────────────────
634//  Tests
635// ───────────────────────────────────────────────────────────────────────────
636
637#[cfg(test)]
638mod tests {
639    use super::*;
640    use crate::q_hash;
641    use crate::render::authoring::{
642        attestation_quin, plan_view, QappView, RenderStandpoint, Sensitivity, ViewDisposition,
643        ViewKind,
644    };
645
646    fn unit_cube_mesh() -> Mesh {
647        let positions = vec![
648            [0.0f32, 0.0, 0.0],
649            [1.0, 0.0, 0.0],
650            [1.0, 1.0, 0.0],
651            [0.0, 1.0, 0.0],
652            [0.0, 0.0, 1.0],
653            [1.0, 0.0, 1.0],
654            [1.0, 1.0, 1.0],
655            [0.0, 1.0, 1.0],
656        ];
657        let triangles = vec![
658            [0, 3, 2],
659            [0, 2, 1],
660            [4, 5, 6],
661            [4, 6, 7],
662            [0, 1, 5],
663            [0, 5, 4],
664            [3, 7, 6],
665            [3, 6, 2],
666            [0, 4, 7],
667            [0, 7, 3],
668            [1, 2, 6],
669            [1, 6, 5],
670        ];
671        Mesh {
672            positions,
673            triangles,
674            min: [0.0, 0.0, 0.0],
675            max: [1.0, 1.0, 1.0],
676        }
677    }
678
679    fn subdivided_cube_mesh(subdivs: usize) -> Mesh {
680        let s = subdivs as f32;
681        let mut positions = Vec::new();
682        for i in 0..=subdivs {
683            for j in 0..=subdivs {
684                for k in 0..=subdivs {
685                    positions.push([i as f32 / s, j as f32 / s, k as f32 / s]);
686                }
687            }
688        }
689        // Build triangles for each face of the cube.
690        let mut triangles = Vec::new();
691        let idx = |i: usize, j: usize, k: usize| -> u32 {
692            (i * (subdivs + 1) * (subdivs + 1) + j * (subdivs + 1) + k) as u32
693        };
694        // Bottom (z=0, facing down)
695        for i in 0..subdivs {
696            for j in 0..subdivs {
697                triangles.push([idx(i, j, 0), idx(i, j + 1, 0), idx(i + 1, j + 1, 0)]);
698                triangles.push([idx(i, j, 0), idx(i + 1, j + 1, 0), idx(i + 1, j, 0)]);
699            }
700        }
701        // Top (z=1, facing up)
702        for i in 0..subdivs {
703            for j in 0..subdivs {
704                triangles.push([
705                    idx(i, j, subdivs),
706                    idx(i + 1, j + 1, subdivs),
707                    idx(i, j + 1, subdivs),
708                ]);
709                triangles.push([
710                    idx(i, j, subdivs),
711                    idx(i + 1, j, subdivs),
712                    idx(i + 1, j + 1, subdivs),
713                ]);
714            }
715        }
716        // Front (y=0, facing -y)
717        for i in 0..subdivs {
718            for k in 0..subdivs {
719                triangles.push([idx(i, 0, k), idx(i + 1, 0, k + 1), idx(i, 0, k + 1)]);
720                triangles.push([idx(i, 0, k), idx(i + 1, 0, k), idx(i + 1, 0, k + 1)]);
721            }
722        }
723        // Back (y=1, facing +y)
724        for i in 0..subdivs {
725            for k in 0..subdivs {
726                triangles.push([
727                    idx(i, subdivs, k),
728                    idx(i, subdivs, k + 1),
729                    idx(i + 1, subdivs, k + 1),
730                ]);
731                triangles.push([
732                    idx(i, subdivs, k),
733                    idx(i + 1, subdivs, k + 1),
734                    idx(i + 1, subdivs, k),
735                ]);
736            }
737        }
738        // Left (x=0, facing -x)
739        for j in 0..subdivs {
740            for k in 0..subdivs {
741                triangles.push([idx(0, j, k), idx(0, j, k + 1), idx(0, j + 1, k + 1)]);
742                triangles.push([idx(0, j, k), idx(0, j + 1, k + 1), idx(0, j + 1, k)]);
743            }
744        }
745        // Right (x=1, facing +x)
746        for j in 0..subdivs {
747            for k in 0..subdivs {
748                triangles.push([
749                    idx(subdivs, j, k),
750                    idx(subdivs, j + 1, k + 1),
751                    idx(subdivs, j, k + 1),
752                ]);
753                triangles.push([
754                    idx(subdivs, j, k),
755                    idx(subdivs, j + 1, k),
756                    idx(subdivs, j + 1, k + 1),
757                ]);
758            }
759        }
760        let min = [0.0f32; 3];
761        let max = [1.0f32; 3];
762        Mesh {
763            positions,
764            triangles,
765            min,
766            max,
767        }
768    }
769
770    #[test]
771    fn build_lod_chain_3_levels() {
772        let mesh = subdivided_cube_mesh(4); // 125 verts, 96 tris
773        let options = LodChainOptions::default_3_tier();
774        let buf_size =
775            required_lod_buffer_size(mesh.positions.len(), mesh.triangles.len(), options);
776        let mut buf = vec![0u8; buf_size];
777        let report = build_lod_chain(&mesh, options, &mut buf).unwrap();
778
779        assert!(
780            report.levels.len() >= 2,
781            "should produce at least 2 LOD levels"
782        );
783        assert_eq!(report.levels[0].level, 0);
784        assert_eq!(report.levels[0].vertices, mesh.positions.len());
785        assert_eq!(report.levels[0].triangles, mesh.triangles.len());
786        assert_eq!(
787            report.total_bytes,
788            report.levels.iter().map(|l| l.encoded_bytes).sum::<usize>()
789        );
790    }
791
792    #[test]
793    fn lod_chain_hash_stable() {
794        let mesh = subdivided_cube_mesh(3);
795        let options = LodChainOptions::default_3_tier();
796        let buf_size =
797            required_lod_buffer_size(mesh.positions.len(), mesh.triangles.len(), options);
798
799        let mut buf1 = vec![0u8; buf_size];
800        let mut buf2 = vec![0u8; buf_size];
801        let report1 = build_lod_chain(&mesh, options, &mut buf1).unwrap();
802        let report2 = build_lod_chain(&mesh, options, &mut buf2).unwrap();
803
804        assert_eq!(report1.total_bytes, report2.total_bytes);
805        let h1 = lod_chain_hash(&buf1[..report1.total_bytes]);
806        let h2 = lod_chain_hash(&buf2[..report2.total_bytes]);
807        assert_eq!(
808            h1, h2,
809            "LOD chain bytes must be hash-stable across two encodes"
810        );
811    }
812
813    #[test]
814    fn lod_chain_round_trip() {
815        let mesh = subdivided_cube_mesh(3);
816        let options = LodChainOptions::default_3_tier();
817        let buf_size =
818            required_lod_buffer_size(mesh.positions.len(), mesh.triangles.len(), options);
819        let mut buf = vec![0u8; buf_size];
820        let report = build_lod_chain(&mesh, options, &mut buf).unwrap();
821
822        let offsets = level_offsets(&report);
823
824        // Parse LOD 0 and verify it matches the source.
825        let lod0 = parse_lod_level(&buf, &offsets, 0).unwrap();
826        assert_eq!(lod0.positions.len(), mesh.positions.len());
827        assert_eq!(lod0.triangles.len(), mesh.triangles.len());
828
829        // Parse any additional LODs.
830        for (i, lvl) in report.levels.iter().enumerate() {
831            let decoded = parse_lod_level(&buf, &offsets, i).unwrap();
832            assert_eq!(
833                decoded.positions.len(),
834                lvl.vertices,
835                "LOD {i} vertex count mismatch"
836            );
837            assert_eq!(
838                decoded.triangles.len(),
839                lvl.triangles,
840                "LOD {i} triangle count mismatch"
841            );
842        }
843    }
844
845    #[test]
846    fn select_lod_by_mode() {
847        assert_eq!(select_lod(OperationalMode::Full, 3), 0);
848        assert_eq!(select_lod(OperationalMode::Eco, 3), 1);
849        assert_eq!(select_lod(OperationalMode::Reserve, 3), 2);
850        // Clamping: if only 2 levels, Reserve → LOD 1.
851        assert_eq!(select_lod(OperationalMode::Reserve, 2), 1);
852        // If only 1 level, all modes → LOD 0.
853        assert_eq!(select_lod(OperationalMode::Reserve, 1), 0);
854    }
855
856    #[test]
857    fn runtime_lod_uses_projected_error_and_preserves_identity() {
858        let mut instances = [LodRuntimeInstance {
859            semantic_id: 0xfeed_beef_1234_5678,
860            source_index: 37,
861            world_center: [0.0, 0.0, 50.0],
862            world_radius: 0.0,
863            last_lod: 0,
864        }];
865        let errors = [0.0, 0.1, 0.5];
866        let camera = LodCamera {
867            position: [0.0; 3],
868            vertical_fov_radians: core::f32::consts::FRAC_PI_2,
869            viewport_height_pixels: 1000,
870            near_distance: 0.1,
871        };
872        let policy = ScreenSpaceLodPolicy {
873            max_pixel_error: 2.0,
874            hysteresis: 0.1,
875        };
876        let mut out = [SelectedLod {
877            semantic_id: 0,
878            source_index: 0,
879            level: 0,
880        }];
881
882        assert_eq!(
883            select_lods_screen_space(&mut instances, &errors, camera, policy, &mut out),
884            Ok(1)
885        );
886        assert_eq!(out[0].level, 1); // LOD 2 is still above the pixel-error budget.
887        assert_eq!(out[0].semantic_id, 0xfeed_beef_1234_5678);
888        assert_eq!(out[0].source_index, 37);
889
890        // The current level remains selected inside the 10% hysteresis band.
891        instances[0].world_center[2] = 40.0;
892        select_lods_screen_space(&mut instances, &errors, camera, policy, &mut out).unwrap();
893        assert_eq!(out[0].level, 1);
894
895        // At close range, its projected error exceeds the upper edge and it refines.
896        instances[0].world_center[2] = 20.0;
897        select_lods_screen_space(&mut instances, &errors, camera, policy, &mut out).unwrap();
898        assert_eq!(out[0].level, 0);
899        assert_eq!(instances[0].last_lod, 0);
900    }
901
902    #[test]
903    fn runtime_lod_preflights_output_and_fails_open_bad_bounds() {
904        let mut instances = [
905            LodRuntimeInstance {
906                semantic_id: 11,
907                source_index: 5,
908                world_center: [f32::NAN, 0.0, 10.0],
909                world_radius: 1.0,
910                last_lod: 2,
911            },
912            LodRuntimeInstance {
913                semantic_id: 22,
914                source_index: 9,
915                world_center: [0.0, 0.0, 10.0],
916                world_radius: 1.0,
917                last_lod: 0,
918            },
919        ];
920        let errors = [0.0, 0.1, 0.5];
921        let camera = LodCamera {
922            position: [0.0; 3],
923            vertical_fov_radians: core::f32::consts::FRAC_PI_2,
924            viewport_height_pixels: 720,
925            near_distance: 0.1,
926        };
927        let policy = ScreenSpaceLodPolicy {
928            max_pixel_error: 2.0,
929            hysteresis: 0.1,
930        };
931        let mut too_small = [SelectedLod {
932            semantic_id: 99,
933            source_index: 99,
934            level: 99,
935        }];
936        assert_eq!(
937            select_lods_screen_space(&mut instances, &errors, camera, policy, &mut too_small),
938            Err(LodSelectionError::OutputTooSmall { needed: 2, have: 1 })
939        );
940        assert_eq!(instances[0].last_lod, 2); // Preflight does not mutate state.
941
942        let mut out = [too_small[0]; 2];
943        select_lods_screen_space(&mut instances, &errors, camera, policy, &mut out).unwrap();
944        assert_eq!(out[0].level, 0); // Invalid bounds render at highest detail.
945        assert_eq!(out[0].semantic_id, 11);
946        assert_eq!(out[0].source_index, 5);
947        assert_eq!(out[1].semantic_id, 22);
948        assert_eq!(out[1].source_index, 9);
949    }
950
951    #[test]
952    fn runtime_lod_rejects_invalid_shared_configuration_without_partial_output() {
953        let mut instances = [LodRuntimeInstance {
954            semantic_id: 1,
955            source_index: 0,
956            world_center: [0.0, 0.0, 1.0],
957            world_radius: 0.0,
958            last_lod: 1,
959        }];
960        let mut out = [SelectedLod {
961            semantic_id: 77,
962            source_index: 77,
963            level: 77,
964        }];
965        let invalid_errors = [0.2, 0.1];
966        let camera = LodCamera {
967            position: [0.0; 3],
968            vertical_fov_radians: core::f32::consts::FRAC_PI_2,
969            viewport_height_pixels: 720,
970            near_distance: 0.1,
971        };
972        let policy = ScreenSpaceLodPolicy {
973            max_pixel_error: 2.0,
974            hysteresis: 0.1,
975        };
976        assert_eq!(
977            select_lods_screen_space(&mut instances, &invalid_errors, camera, policy, &mut out),
978            Err(LodSelectionError::InvalidLevelErrors)
979        );
980        assert_eq!(out[0].semantic_id, 77);
981        assert_eq!(instances[0].last_lod, 1);
982    }
983
984    #[test]
985    fn lod_chain_decreasing_triangle_counts() {
986        let mesh = subdivided_cube_mesh(5);
987        let options = LodChainOptions::default_3_tier();
988        let buf_size =
989            required_lod_buffer_size(mesh.positions.len(), mesh.triangles.len(), options);
990        let mut buf = vec![0u8; buf_size];
991        let report = build_lod_chain(&mesh, options, &mut buf).unwrap();
992
993        for i in 1..report.levels.len() {
994            assert!(
995                report.levels[i].triangles <= report.levels[i - 1].triangles,
996                "LOD {i} should have ≤ triangles than LOD {}",
997                i - 1
998            );
999        }
1000    }
1001
1002    #[test]
1003    fn plan_view_with_lod_selects_coarser_on_eco() {
1004        let m = q_hash("urn:qualia:manifold:demo");
1005        let view = QappView::public(m, ViewKind::Scene3D);
1006        let standpoint = RenderStandpoint {
1007            id: q_hash("urn:qualia:standpoint:owner"),
1008            shared_civic: false,
1009        };
1010
1011        // Full → LOD 0.
1012        assert_eq!(
1013            plan_view_with_lod(&view, &standpoint, OperationalMode::Full, &[], &[], 100, 3),
1014            LodViewDisposition::Render3dWithLod { lod: 0 }
1015        );
1016        // Eco → LOD 1.
1017        assert_eq!(
1018            plan_view_with_lod(&view, &standpoint, OperationalMode::Eco, &[], &[], 100, 3),
1019            LodViewDisposition::Render3dWithLod { lod: 1 }
1020        );
1021        // Reserve → LOD 2.
1022        assert_eq!(
1023            plan_view_with_lod(
1024                &view,
1025                &standpoint,
1026                OperationalMode::Reserve,
1027                &[],
1028                &[],
1029                100,
1030                3
1031            ),
1032            LodViewDisposition::Render3dWithLod { lod: 2 }
1033        );
1034    }
1035
1036    #[test]
1037    fn plan_view_with_lod_collapses_when_no_coarser_lod() {
1038        let m = q_hash("urn:qualia:manifold:demo");
1039        let view = QappView::public(m, ViewKind::Scene3D);
1040        let standpoint = RenderStandpoint {
1041            id: q_hash("urn:qualia:standpoint:owner"),
1042            shared_civic: false,
1043        };
1044
1045        // Only 1 LOD level → Eco collapses to 2D.
1046        assert_eq!(
1047            plan_view_with_lod(&view, &standpoint, OperationalMode::Eco, &[], &[], 100, 1),
1048            LodViewDisposition::Collapsed2D
1049        );
1050    }
1051
1052    #[test]
1053    fn plan_view_with_lod_2d_pane_ignores_lod() {
1054        let m = q_hash("urn:qualia:manifold:demo");
1055        let view = QappView::public(m, ViewKind::Pane2D);
1056        let standpoint = RenderStandpoint {
1057            id: q_hash("urn:qualia:standpoint:owner"),
1058            shared_civic: false,
1059        };
1060
1061        assert_eq!(
1062            plan_view_with_lod(&view, &standpoint, OperationalMode::Full, &[], &[], 100, 3),
1063            LodViewDisposition::Render2d
1064        );
1065        assert_eq!(
1066            plan_view_with_lod(&view, &standpoint, OperationalMode::Eco, &[], &[], 100, 3),
1067            LodViewDisposition::Render2d
1068        );
1069    }
1070
1071    #[test]
1072    fn plan_view_with_lod_attestation_gate() {
1073        let m = q_hash("urn:qualia:manifold:demo");
1074        let view = QappView {
1075            manifold: m,
1076            kind: ViewKind::Scene3D,
1077            sensitivity: Sensitivity::Public,
1078            requires_attestation: true,
1079        };
1080        let standpoint = RenderStandpoint {
1081            id: q_hash("urn:qualia:standpoint:owner"),
1082            shared_civic: false,
1083        };
1084
1085        // No attestation → withheld.
1086        assert_eq!(
1087            plan_view_with_lod(&view, &standpoint, OperationalMode::Full, &[], &[], 100, 3),
1088            LodViewDisposition::WithheldUnattested
1089        );
1090
1091        // With attestation → rendered at LOD 0.
1092        let att = attestation_quin(
1093            q_hash("did:example:auditor"),
1094            m,
1095            q_hash("urn:qualia:frame:app"),
1096        );
1097        assert_eq!(
1098            plan_view_with_lod(
1099                &view,
1100                &standpoint,
1101                OperationalMode::Full,
1102                &[att],
1103                &[],
1104                100,
1105                3
1106            ),
1107            LodViewDisposition::Render3dWithLod { lod: 0 }
1108        );
1109    }
1110
1111    #[test]
1112    fn plan_view_with_lod_rights_bounded() {
1113        let m = q_hash("urn:qualia:manifold:demo");
1114        let view = QappView {
1115            manifold: m,
1116            kind: ViewKind::Scene3D,
1117            sensitivity: Sensitivity::RightsBounded,
1118            requires_attestation: false,
1119        };
1120        let civic = RenderStandpoint {
1121            id: q_hash("urn:qualia:standpoint:civic"),
1122            shared_civic: true,
1123        };
1124
1125        // Civic, no consent → refused.
1126        assert_eq!(
1127            plan_view_with_lod(&view, &civic, OperationalMode::Full, &[], &[], 100, 3),
1128            LodViewDisposition::RefusedRightsBounded
1129        );
1130    }
1131
1132    #[test]
1133    fn existing_authoring_tests_stay_green() {
1134        // Verify that the existing plan_view still works (no regression).
1135        let m = q_hash("urn:qualia:manifold:demo");
1136        let view = QappView::public(m, ViewKind::Scene3D);
1137        let standpoint = RenderStandpoint {
1138            id: q_hash("urn:qualia:standpoint:owner"),
1139            shared_civic: false,
1140        };
1141
1142        // Full tier → 3D scene rendered.
1143        assert_eq!(
1144            plan_view(&view, &standpoint, OperationalMode::Full, &[], &[], 100),
1145            ViewDisposition::Render(ViewKind::Scene3D)
1146        );
1147        // Eco tier → collapsed to 2D (existing behavior, no LOD).
1148        assert_eq!(
1149            plan_view(&view, &standpoint, OperationalMode::Eco, &[], &[], 100),
1150            ViewDisposition::Collapsed2D
1151        );
1152    }
1153
1154    #[test]
1155    fn empty_source_mesh_errors() {
1156        let mesh = Mesh {
1157            positions: vec![],
1158            triangles: vec![],
1159            min: [0.0; 3],
1160            max: [0.0; 3],
1161        };
1162        let options = LodChainOptions::default_3_tier();
1163        let mut buf = vec![0u8; 1024];
1164        assert!(matches!(
1165            build_lod_chain(&mesh, options, &mut buf),
1166            Err(LodChainError::EmptySourceMesh)
1167        ));
1168    }
1169
1170    #[test]
1171    fn buffer_too_small_errors() {
1172        let mesh = unit_cube_mesh();
1173        let options = LodChainOptions::default_3_tier();
1174        let mut buf = vec![0u8; 10]; // way too small
1175        assert!(matches!(
1176            build_lod_chain(&mesh, options, &mut buf),
1177            Err(LodChainError::BufferTooSmall { .. })
1178        ));
1179    }
1180
1181    #[test]
1182    fn single_level_lod_chain() {
1183        let mesh = unit_cube_mesh();
1184        let options = LodChainOptions::new(1, 0.5);
1185        let buf_size =
1186            required_lod_buffer_size(mesh.positions.len(), mesh.triangles.len(), options);
1187        let mut buf = vec![0u8; buf_size];
1188        let report = build_lod_chain(&mesh, options, &mut buf).unwrap();
1189        assert_eq!(report.levels.len(), 1);
1190        assert_eq!(report.levels[0].vertices, 8);
1191        assert_eq!(report.levels[0].triangles, 12);
1192    }
1193}