ferravex_render/
retained.rs

1//! Retained low-poly geometry and ordered instanced draw recording.
2use crate::{Mat4, Mesh, shaders::LitSettings};
3use std::{
4    cell::{Cell, RefCell},
5    rc::{Rc, Weak},
6};
7
8const MAX_MESHES: usize = 1024;
9const MAX_BYTES: usize = 64 * 1024 * 1024;
10const MAX_INSTANCES: usize = 65536;
11
12/// Retained CPU buffer capacities, in elements (not bytes or GPU allocations).
13///
14/// Buffers keep their allocations when a frame is cleared. Finalization swaps
15/// the active instance/draw buffers with their scratch buffers, so inspect both
16/// when planning memory use. See [`telemetry_snapshot`] for a usage example.
17#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
18pub struct RetainedBufferCapacities {
19    /// Registry slots, including space for expired weak mesh handles.
20    pub mesh_slots: usize,
21    /// Shared command buffer; includes immediate and effect commands too.
22    pub commands: usize,
23    /// Active instance records, each containing 28 floats.
24    pub instances: usize,
25    /// Active [`RetainedBatch`] records.
26    pub draws: usize,
27    /// Instance records reserved for finalization.
28    pub scratch_instances: usize,
29    /// Batch records reserved for finalization.
30    pub scratch_draws: usize,
31    /// Joint position matrices, each containing 16 floats.
32    pub skin_matrices: usize,
33    /// Joint normal matrices, each containing 9 floats.
34    pub skin_normals: usize,
35}
36
37/// Rejected retained operations since the last [`reset_telemetry`], on this thread.
38///
39/// Each failed mesh creation or retained draw validation increments exactly one
40/// category, selected by its first error. Counters saturate at `u64::MAX` and
41/// survive frame clears. Pure [`validate_mesh`] and [`validate_transform`] calls
42/// do not count. Culling and failures in host/skinning code before reaching the
43/// retained recorder do not count; [`draw_resident_checked`] also counts its
44/// preflight errors, including those for invisible objects. A failed
45/// [`draw_residents_checked`] group increments one category once, not once per
46/// rejected entry; its report contains the exact rejected entry count.
47#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
48pub struct RetainedRejections {
49    /// Invalid geometry or a mismatched skin vertex count.
50    pub mesh_validation: u64,
51    /// Individual mesh size, live mesh count, or total geometry byte limit.
52    pub mesh_capacity: u64,
53    /// Exhaustion of the monotonically increasing mesh identity space.
54    pub mesh_identity: u64,
55    /// Invalid model/camera transform or a mismatched skin palette.
56    pub draw_validation: u64,
57    /// Frame instance limit reached.
58    pub instance_capacity: u64,
59    /// Frame joint palette limit reached after attempting adjacent palette reuse.
60    pub skin_capacity: u64,
61}
62thread_local! {
63    static REJECTIONS: Cell<RetainedRejections> = Cell::new(RetainedRejections::default());
64}
65impl RetainedRejections {
66    fn mesh(error: MeshError) {
67        REJECTIONS.with(|cell| {
68            let mut counts = cell.get();
69            let count = match error {
70                MeshError::MeshTooLarge { .. } | MeshError::StorageCapacity { .. } => {
71                    &mut counts.mesh_capacity
72                }
73                MeshError::IdentityExhausted => &mut counts.mesh_identity,
74                _ => &mut counts.mesh_validation,
75            };
76            *count = count.saturating_add(1);
77            cell.set(counts);
78        });
79    }
80    fn draw(error: DrawError) {
81        REJECTIONS.with(|cell| {
82            let mut counts = cell.get();
83            let count = match error {
84                DrawError::InstanceCapacity { .. } => &mut counts.instance_capacity,
85                DrawError::SkinCapacity { .. } => &mut counts.skin_capacity,
86                _ => &mut counts.draw_validation,
87            };
88            *count = count.saturating_add(1);
89            cell.set(counts);
90        });
91    }
92}
93
94/// A copy of retained resource usage on the calling renderer thread.
95///
96/// Meshes include geometry kept alive by recorded draws, but exclude expired
97/// weak handles and do not double-count cloned handles. Instance, draw and joint
98/// usage describes the current frame buffers (the last completed frame until
99/// the next clear). This is CPU recording telemetry, not a GPU timing or actual
100/// driver draw-call count. See [`telemetry_snapshot`] for an example.
101#[derive(Clone, Copy, Debug, PartialEq, Eq)]
102pub struct RetainedTelemetry {
103    pub live_meshes: usize,
104    pub mesh_limit: usize,
105    /// Expanded vertex and skin payload bytes; excludes metadata and GPU copies.
106    pub mesh_bytes: usize,
107    pub mesh_byte_limit: usize,
108    /// Accepted instances, including shadow-only submissions.
109    pub instances: usize,
110    pub instance_limit: usize,
111    /// Retained batches after adjacent merging or the most recent finalization.
112    pub draws: usize,
113    /// Upper bound from the instance budget: each batch needs an instance.
114    /// There is no separate draw-batch rejection threshold.
115    pub draw_limit: usize,
116    /// Stored palette joints; adjacent equal palettes share their storage.
117    pub skin_joints: usize,
118    pub skin_joint_limit: usize,
119    pub buffers: RetainedBufferCapacities,
120    pub rejections: RetainedRejections,
121}
122
123/// Snapshot retained usage, limits, buffer capacities and rejection counters.
124///
125/// Does not clear counters, prune the registry, finalize draws, or change mesh
126/// lifetimes. After thread/renderer initialization this allocates nothing: it
127/// scans at most the mesh limit of registry entries and copies frame counters.
128///
129/// ```
130/// use ferravex_render::{mesh::Mesh3d, Mat4, Vec3, WHITE,
131///     retained::{ResidentMesh, draw_resident_checked, reset_telemetry,
132///                telemetry_snapshot}};
133/// reset_telemetry();
134/// let mesh = ResidentMesh::try_new(&Mesh3d::cuboid(Vec3::ONE, WHITE).mesh)?;
135/// draw_resident_checked(&mesh, Mat4::IDENTITY)?;
136/// assert!(draw_resident_checked(&mesh, Mat4::ZERO).is_err());
137/// let sample = telemetry_snapshot();
138/// assert_eq!(sample.instances, 1);
139/// assert_eq!(sample.draws, 1);
140/// assert!(sample.buffers.instances >= sample.instances);
141/// assert!(sample.mesh_bytes <= sample.mesh_byte_limit);
142/// assert_eq!(sample.rejections.draw_validation, 1);
143/// # Ok::<(), Box<dyn std::error::Error>>(())
144/// ```
145pub fn telemetry_snapshot() -> RetainedTelemetry {
146    let (live_meshes, mesh_bytes, mesh_slots) = REGISTRY.with(|registry| {
147        let registry = registry.borrow();
148        let (live, bytes) = registry.usage();
149        (live, bytes, registry.meshes.capacity())
150    });
151    crate::read(|s| {
152        let frame = &s.retained;
153        RetainedTelemetry {
154            live_meshes,
155            mesh_limit: MAX_MESHES,
156            mesh_bytes,
157            mesh_byte_limit: MAX_BYTES,
158            instances: frame.instances.len(),
159            instance_limit: MAX_INSTANCES,
160            draws: frame.batches.len(),
161            draw_limit: MAX_INSTANCES,
162            skin_joints: frame.skin_matrices.len(),
163            skin_joint_limit: crate::skinning::MAX_FRAME_SKIN_JOINTS,
164            buffers: RetainedBufferCapacities {
165                mesh_slots,
166                commands: frame.commands.capacity(),
167                instances: frame.instances.capacity(),
168                draws: frame.batches.capacity(),
169                scratch_instances: frame.scratch_instances.capacity(),
170                scratch_draws: frame.scratch_batches.capacity(),
171                skin_matrices: frame.skin_matrices.capacity(),
172                skin_normals: frame.skin_normals.capacity(),
173            },
174            rejections: REJECTIONS.with(Cell::get),
175        }
176    })
177}
178
179/// Return and zero rejection counters for this thread without allocating.
180///
181/// Leaves geometry, identities, recorded draws and all buffer allocations alone.
182/// Frame clears never implicitly reset these counters.
183///
184/// ```
185/// use ferravex_render::{Mesh, retained::{ResidentMesh, RetainedRejections,
186///                                      reset_telemetry, telemetry_snapshot}};
187/// reset_telemetry();
188/// assert!(ResidentMesh::try_new(&Mesh::default()).is_err());
189/// assert_eq!(reset_telemetry().mesh_validation, 1);
190/// assert_eq!(telemetry_snapshot().rejections, RetainedRejections::default());
191/// ```
192pub fn reset_telemetry() -> RetainedRejections {
193    REJECTIONS.with(Cell::take)
194}
195
196/// A retained mesh authoring or storage error. All offsets are zero-based.
197#[derive(Clone, Copy, Debug, PartialEq, Eq)]
198#[non_exhaustive]
199pub enum MeshError {
200    IncompleteTriangles {
201        index_count: usize,
202    },
203    IndexOutOfBounds {
204        index_position: usize,
205        index: u16,
206        vertex_count: usize,
207    },
208    NonFiniteVertex {
209        vertex: usize,
210        /// `position`, `uv`, or `normal`.
211        attribute: &'static str,
212        component: usize,
213    },
214    MeshTooLarge {
215        index_count: usize,
216        max_indices: usize,
217    },
218    StorageCapacity {
219        live_meshes: usize,
220        requested_bytes: usize,
221        available_bytes: usize,
222    },
223    IdentityExhausted,
224    SkinVertexCountMismatch {
225        expected: usize,
226        actual: usize,
227    },
228}
229impl std::fmt::Display for MeshError {
230    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
231        match *self {
232            Self::IncompleteTriangles { index_count } => write!(
233                f,
234                "mesh has {index_count} indices; supply a nonempty triangle list with a multiple of 3 indices"
235            ),
236            Self::IndexOutOfBounds {
237                index_position,
238                index,
239                vertex_count,
240            } => write!(
241                f,
242                "mesh index[{index_position}] is {index}, but there are {vertex_count} vertices; use an index below {vertex_count}"
243            ),
244            Self::NonFiniteVertex {
245                vertex,
246                attribute,
247                component,
248            } => write!(
249                f,
250                "mesh vertex[{vertex}].{attribute}[{component}] is not finite; replace NaN or infinity with a finite value"
251            ),
252            Self::MeshTooLarge {
253                index_count,
254                max_indices,
255            } => write!(
256                f,
257                "mesh has {index_count} indices; retained storage allows at most {max_indices} for this vertex layout; split or simplify the mesh"
258            ),
259            Self::StorageCapacity {
260                live_meshes,
261                requested_bytes,
262                available_bytes,
263            } => write!(
264                f,
265                "retained storage has {live_meshes}/{MAX_MESHES} live meshes and {available_bytes} bytes free; requested {requested_bytes} bytes; drop unused resident handles or simplify geometry"
266            ),
267            Self::IdentityExhausted => {
268                f.write_str("retained mesh identities exhausted; restart the renderer thread")
269            }
270            Self::SkinVertexCountMismatch { expected, actual } => write!(
271                f,
272                "mesh has {expected} vertices but {actual} skin records; supply one skin record per source vertex"
273            ),
274        }
275    }
276}
277impl std::error::Error for MeshError {}
278impl MeshError {
279    // Keep the original string-error API and its existing error categories.
280    fn legacy_message(self) -> &'static str {
281        match self {
282            Self::IncompleteTriangles { .. } => "mesh requires complete triangles",
283            Self::IndexOutOfBounds { .. } | Self::NonFiniteVertex { .. } => {
284                "invalid retained mesh geometry"
285            }
286            Self::MeshTooLarge { .. } => "mesh exceeds retained storage budget",
287            Self::StorageCapacity { .. } => "retained storage capacity exceeded",
288            Self::IdentityExhausted => "mesh identity exhausted",
289            Self::SkinVertexCountMismatch { .. } => "skin source vertex count mismatch",
290        }
291    }
292}
293
294/// Check source geometry without allocating, registering a mesh, or using a GPU.
295/// Checks every source vertex, including unused vertices and UVs. Zero normals,
296/// degenerate triangles, and UVs outside 0..1 remain valid. This checks the
297/// individual static-mesh budget, not currently available registry capacity.
298///
299/// ```
300/// use ferravex_render::{mesh::Mesh3d, retained::validate_mesh, Vec3, WHITE};
301/// let mesh = Mesh3d::cuboid(Vec3::ONE, WHITE).mesh;
302/// validate_mesh(&mesh)?;
303/// # Ok::<(), ferravex_render::retained::MeshError>(())
304/// ```
305pub fn validate_mesh(mesh: &Mesh) -> Result<(), MeshError> {
306    validate_mesh_layout(mesh, 40)
307}
308fn validate_mesh_layout(mesh: &Mesh, stride: usize) -> Result<(), MeshError> {
309    if mesh.indices.is_empty() || !mesh.indices.len().is_multiple_of(3) {
310        return Err(MeshError::IncompleteTriangles {
311            index_count: mesh.indices.len(),
312        });
313    }
314    if mesh.indices.len() > MAX_BYTES / stride {
315        return Err(MeshError::MeshTooLarge {
316            index_count: mesh.indices.len(),
317            max_indices: MAX_BYTES / stride,
318        });
319    }
320    for (index_position, &index) in mesh.indices.iter().enumerate() {
321        if index as usize >= mesh.vertices.len() {
322            return Err(MeshError::IndexOutOfBounds {
323                index_position,
324                index,
325                vertex_count: mesh.vertices.len(),
326            });
327        }
328    }
329    for (vertex, v) in mesh.vertices.iter().enumerate() {
330        let position = v.position.to_array();
331        let uv = v.uv.to_array();
332        let normal = v.normal.to_array();
333        for (attribute, values) in [
334            ("position", position.as_slice()),
335            ("uv", uv.as_slice()),
336            ("normal", normal.as_slice()),
337        ] {
338            if let Some(component) = values.iter().position(|v| !v.is_finite()) {
339                return Err(MeshError::NonFiniteVertex {
340                    vertex,
341                    attribute,
342                    component,
343                });
344            }
345        }
346    }
347    Ok(())
348}
349
350/// Why a retained draw cannot be submitted. Matrix coordinates are zero-based.
351#[derive(Clone, Copy, Debug, PartialEq, Eq)]
352#[non_exhaustive]
353pub enum DrawError {
354    NonFiniteModel {
355        column: usize,
356        row: usize,
357    },
358    NonAffineModel {
359        column: usize,
360    },
361    /// Singular, or its inverse cannot be represented with finite f32 values.
362    NonInvertibleModel,
363    NonFiniteCamera {
364        column: usize,
365        row: usize,
366    },
367    InstanceCapacity {
368        limit: usize,
369    },
370    SkinPaletteMismatch {
371        expected: usize,
372        actual: usize,
373    },
374    SkinCapacity {
375        limit: usize,
376    },
377}
378impl std::fmt::Display for DrawError {
379    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
380        match *self {
381            Self::NonFiniteModel { column, row } => write!(f,
382                "model matrix column {column}, row {row} is not finite; use a finite translation, rotation, and scale"),
383            Self::NonAffineModel { column } => write!(f,
384                "model matrix column {column}, row 3 is not affine; its last row must be [0, 0, 0, 1]; put projection in the camera matrix"),
385            Self::NonInvertibleModel => f.write_str(
386                "model matrix is singular or its inverse exceeds finite f32 range; use nonzero scales and independent transform axes"),
387            Self::NonFiniteCamera { column, row } => write!(f,
388                "camera matrix column {column}, row {row} is not finite; check the viewport, projection, and camera pose"),
389            Self::InstanceCapacity { limit } => write!(f,
390                "retained frame is full ({limit} instances); submit fewer instances or begin a new frame"),
391            Self::SkinPaletteMismatch { expected, actual } => write!(f,
392                "mesh needs {expected} skin joints, but draw supplied {actual}; draw skinned geometry with a matching SkinPalette"),
393            Self::SkinCapacity { limit } => write!(f,
394                "retained frame skin storage is full ({limit} joints); reuse palettes or begin a new frame"),
395        }
396    }
397}
398impl std::error::Error for DrawError {}
399
400/// Check a finite affine model matrix and its inverse-transpose normal matrix.
401/// Uses only stack storage. Reflections, shear, and nonuniform scale are valid;
402/// projection belongs in the camera matrix. Does not evaluate shader arithmetic
403/// or guarantee that extreme finite vertex/transform products cannot overflow.
404///
405/// ```
406/// use ferravex_render::{Mat4, Vec3, retained::{validate_transform, DrawError}};
407/// validate_transform(Mat4::from_scale(Vec3::new(-2., 3., 4.)))?;
408/// assert_eq!(validate_transform(Mat4::from_scale(Vec3::ZERO)),
409///            Err(DrawError::NonInvertibleModel));
410/// # Ok::<(), DrawError>(())
411/// ```
412pub fn validate_transform(model: Mat4) -> Result<(), DrawError> {
413    prepare_instance(model).map(|_| ())
414}
415fn prepare_instance(model: Mat4) -> Result<[f32; 28], DrawError> {
416    let columns = model.to_cols_array();
417    if let Some(i) = columns.iter().position(|v| !v.is_finite()) {
418        return Err(DrawError::NonFiniteModel {
419            column: i / 4,
420            row: i % 4,
421        });
422    }
423    for column in 0..4 {
424        if columns[column * 4 + 3] != if column == 3 { 1. } else { 0. } {
425            return Err(DrawError::NonAffineModel { column });
426        }
427    }
428    let normal = model
429        .try_inverse()
430        .ok_or(DrawError::NonInvertibleModel)?
431        .transpose()
432        .to_cols_array();
433    let mut instance = [0.; 28];
434    instance[..16].copy_from_slice(&columns);
435    for i in 0..3 {
436        instance[16 + i * 4..19 + i * 4].copy_from_slice(&normal[i * 4..i * 4 + 3]);
437    }
438    Ok(instance)
439}
440
441/// Checked counterpart of [`crate::draw_resident`], using the current camera and
442/// material. Returns `Ok(true)` for a visible recorded draw and `Ok(false)` when
443/// culled (a shadow-only instance may still be recorded). Validation runs even
444/// for culled draws; an error records nothing. Skinned geometry requires
445/// [`crate::draw_skinned`] with its palette.
446///
447/// Shares the existing resident buffers and frame recording path. Validation
448/// uses stack storage; frame buffers retain their capacity across frames.
449///
450/// ```
451/// use ferravex_render::{mesh::Mesh3d, Mat4, Vec3, WHITE,
452///     retained::{ResidentMesh, draw_resident_checked}};
453/// let mesh = ResidentMesh::try_new(&Mesh3d::cuboid(Vec3::ONE, WHITE).mesh)?;
454/// // After selecting your camera/material, in the frame loop:
455/// let visible = draw_resident_checked(&mesh, Mat4::IDENTITY)?;
456/// # let _ = visible;
457/// # Ok::<(), Box<dyn std::error::Error>>(())
458/// ```
459pub fn draw_resident_checked(mesh: &ResidentMesh, model: Mat4) -> Result<bool, DrawError> {
460    crate::edit(|s| {
461        s.retained
462            .prepare_draw(mesh, model, s.matrix, None)
463            .inspect_err(|error| RetainedRejections::draw(*error))?;
464        let bounds = s
465            .shader
466            .as_ref()
467            .map_or(mesh.bounds(), |m| m.padded(mesh.bounds()));
468        Ok(s.submit(mesh, model, bounds, None))
469    })
470}
471
472/// Outcome of one atomic [`draw_residents_checked`] call.
473///
474/// Counts are exact `usize` entry counts, not saturating activity counters.
475/// `accepted + culled + rejected` equals the input slice length. See the
476/// function's runnable recipe for handling both success and whole-group failure.
477#[must_use]
478#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
479pub struct InstanceGroupReport {
480    /// Recorded instances, including shadow-only instances.
481    pub accepted: usize,
482    /// All input entries on failure; zero on success, including complete culls.
483    pub rejected: usize,
484    /// Valid entries omitted from both the visible and shadow passes.
485    pub culled: usize,
486    /// Visible recorded instances; a subset of `accepted`.
487    pub visible: usize,
488    /// First validation error, or the first entry exceeding aggregate capacity.
489    pub error: Option<InstanceGroupError>,
490}
491
492/// A group's failure location and existing retained-draw diagnostic.
493///
494/// No entries were recorded. The index is zero-based in the caller slice.
495/// See [`draw_residents_checked`] for validation/capacity precedence and usage.
496#[derive(Clone, Copy, Debug, PartialEq, Eq)]
497pub struct InstanceGroupError {
498    pub index: usize,
499    pub source: DrawError,
500}
501impl std::fmt::Display for InstanceGroupError {
502    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
503        write!(
504            f,
505            "retained instance group entry[{}]: {}",
506            self.index, self.source
507        )
508    }
509}
510impl std::error::Error for InstanceGroupError {
511    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
512        Some(&self.source)
513    }
514}
515
516/// Atomically submit a caller slice of resident mesh/model pairs using the
517/// current camera, material, lighting, visibility and shadow settings.
518///
519/// All entries are validated before recording, including invisible entries.
520/// The first validation error in input order wins over aggregate capacity.
521/// Otherwise capacity counts only instances that would actually be recorded
522/// (visible or shadow-only); its error index is the first entry that would
523/// exceed the remaining frame budget. Empty input succeeds without validation.
524/// Skinned residents require palettes and are rejected, as by
525/// [`draw_resident_checked`]. Borrowed [`ResidentMesh`] handles guarantee live,
526/// already-validated geometry; cloned/duplicate handles are valid and each pair
527/// is a separate instance. No raw identity lookup or new geometry is needed.
528///
529/// Failure leaves every frame buffer's contents, length, capacity, mesh/material
530/// lifetimes and visibility counters unchanged. It increments exactly one
531/// saturating [`RetainedRejections`] activity counter; `report.rejected` is the
532/// entire slice length. Success records in caller order through the existing
533/// single-instance path, with its adjacent batching and later opaque regrouping.
534/// Valid complete culls are reported separately and are not rejections.
535///
536/// Preflight uses O(n) work and O(1) stack storage, with no scratch allocation.
537/// Commit repeats preparation/classification; the caller bounds work by slice
538/// length. Buffers grow normally on success and retain warmed capacity across
539/// frames. Atomicity covers reported validation/capacity errors, not allocation
540/// failures or unwinding/destructor panics; no panic rollback is promised.
541///
542/// # Runnable composition recipe
543///
544/// Retain authored geometry once, then submit each frame's caller-owned model
545/// array as a group. This headless recipe uses the same recorder as game hosts;
546/// it does not require a window or replace their rendering implementation.
547///
548/// ```rust
549/// use ferravex_math::affine::PreparedAffine3D;
550/// use ferravex_render::{Mat4, Vec3, WHITE, BLACK, clear_background,
551///     set_default_camera, mesh::Mesh3d,
552///     retained::{ResidentMesh, draw_residents_checked, telemetry_snapshot}};
553///
554/// fn main() -> Result<(), Box<dyn std::error::Error>> {
555///     let resident = ResidentMesh::try_new(&Mesh3d::cuboid(Vec3::ONE, WHITE).mesh)?;
556///     let clone = resident.clone(); // shares the validated geometry
557///     let authored = PreparedAffine3D::try_new(Mat4::from_scale(
558///         Vec3::new(-2.0, 3.0, 1.0)))?;
559///     clear_background(BLACK);
560///     set_default_camera();
561///     let instances = [(&resident, authored.model()), (&clone, Mat4::IDENTITY)];
562///     let report = draw_residents_checked(&instances);
563///     assert_eq!((report.accepted, report.rejected, report.visible), (2, 0, 2));
564///     assert_eq!(report.culled, 0);
565///     assert!(report.error.is_none());
566///     let before = telemetry_snapshot();
567///     let failed = draw_residents_checked(&[
568///         (&resident, Mat4::IDENTITY), (&resident, Mat4::ZERO)]);
569///     assert_eq!((failed.accepted, failed.rejected), (0, 2));
570///     assert_eq!(failed.error.unwrap().index, 1);
571///     assert_eq!(telemetry_snapshot().instances, before.instances);
572///     clear_background(BLACK); // frame reset reuses recording storage
573///     let next = draw_residents_checked(&instances);
574///     if let Some(error) = next.error { return Err(error.into()); }
575///     assert_eq!(next.accepted, 2);
576///     Ok(())
577/// }
578/// ```
579pub fn draw_residents_checked(instances: &[(&ResidentMesh, Mat4)]) -> InstanceGroupReport {
580    if instances.is_empty() {
581        return InstanceGroupReport::default();
582    }
583    crate::edit(|s| {
584        let reject = |index, source| {
585            RetainedRejections::draw(source);
586            InstanceGroupReport {
587                rejected: instances.len(),
588                error: Some(InstanceGroupError { index, source }),
589                ..Default::default()
590            }
591        };
592        let available = MAX_INSTANCES - s.retained.instances.len();
593        let mut required = 0;
594        let mut overflow = None;
595        for (index, &(mesh, model)) in instances.iter().enumerate() {
596            // A hypothetical empty instance buffer bypasses only the per-draw
597            // capacity check; the group checks its actual aggregate demand below.
598            if let Err(error) = s.retained.prepare_draw_at(mesh, model, s.matrix, None, 0) {
599                return reject(index, error);
600            }
601            let bounds = s
602                .shader
603                .as_ref()
604                .map_or(mesh.bounds(), |m| m.padded(mesh.bounds()));
605            let visible =
606                crate::visibility::classify(bounds, model, s.frustum, s.eye, s.visibility)
607                    == crate::visibility::Visibility::Visible;
608            // Mirror State::submit's shadow admission without recording or
609            // touching visibility telemetry. Commit still uses State::submit.
610            let casts = s.depth
611                && mesh.is_opaque()
612                && s.shader.as_ref().is_none_or(|m| {
613                    m.0.options.blend == crate::material::BlendMode::Opaque
614                        && m.0.options.casts_shadows
615                })
616                && s.shadow_frustum
617                    .is_some_and(|f| f.intersects_bounds(bounds, model));
618            if visible || casts {
619                required += 1;
620                if required > available && overflow.is_none() {
621                    overflow = Some(index);
622                }
623            }
624        }
625        if let Some(index) = overflow {
626            return reject(
627                index,
628                DrawError::InstanceCapacity {
629                    limit: MAX_INSTANCES,
630                },
631            );
632        }
633        let before = s.retained.instances.len();
634        let mut visible = 0;
635        for &(mesh, model) in instances {
636            let bounds = s
637                .shader
638                .as_ref()
639                .map_or(mesh.bounds(), |m| m.padded(mesh.bounds()));
640            visible += usize::from(s.submit(mesh, model, bounds, None));
641        }
642        let accepted = s.retained.instances.len() - before;
643        debug_assert_eq!(accepted, required);
644        InstanceGroupReport {
645            accepted,
646            culled: instances.len() - accepted,
647            visible,
648            ..Default::default()
649        }
650    })
651}
652
653#[derive(Clone)]
654pub struct ResidentMesh(Rc<Geometry>);
655pub(crate) struct Geometry {
656    pub id: u32,
657    pub vertices: Vec<[f32; 10]>,
658    pub skin: Option<Vec<[f32; 8]>>,
659    pub joint_count: usize,
660    opaque: bool,
661    bounds: ferravex_graphics::Bounds,
662}
663#[derive(Default)]
664struct Registry {
665    next: u32,
666    meshes: Vec<(u32, Weak<Geometry>)>,
667}
668impl Registry {
669    fn usage(&self) -> (usize, usize) {
670        self.meshes
671            .iter()
672            .filter_map(|(_, mesh)| mesh.upgrade())
673            .fold((0, 0), |(live, bytes), mesh| {
674                (
675                    live + 1,
676                    bytes + mesh.vertices.len() * if mesh.skin.is_some() { 72 } else { 40 },
677                )
678            })
679    }
680}
681thread_local! {static REGISTRY: RefCell<Registry> = RefCell::new(Registry::default());}
682impl ResidentMesh {
683    /// Snapshot validated geometry. Changes to the source Mesh require a new snapshot.
684    /// Use [`Self::try_new`] for structured errors with source locations.
685    pub fn new(mesh: &Mesh) -> Result<Self, &'static str> {
686        Self::try_new(mesh).map_err(MeshError::legacy_message)
687    }
688    /// Snapshot geometry after validating all source vertices and triangle indices.
689    /// Validation failure neither registers geometry nor consumes a mesh identity.
690    /// Cloning the returned handle shares the snapshot and its GPU buffers.
691    ///
692    /// ```
693    /// use ferravex_render::{mesh::Mesh3d, retained::ResidentMesh, Vec3, WHITE};
694    /// let source = Mesh3d::cuboid(Vec3::ONE, WHITE).mesh;
695    /// let resident = ResidentMesh::try_new(&source)?;
696    /// assert_eq!(resident.vertex_count(), source.indices.len());
697    /// # Ok::<(), ferravex_render::retained::MeshError>(())
698    /// ```
699    pub fn try_new(mesh: &Mesh) -> Result<Self, MeshError> {
700        Self::with_skin_checked(mesh, None).inspect_err(|error| RetainedRejections::mesh(*error))
701    }
702    pub(crate) fn with_skin(
703        mesh: &Mesh,
704        skin: Option<(&[[f32; 8]], usize)>,
705    ) -> Result<Self, &'static str> {
706        Self::with_skin_checked(mesh, skin)
707            .inspect_err(|error| RetainedRejections::mesh(*error))
708            .map_err(MeshError::legacy_message)
709    }
710    fn with_skin_checked(
711        mesh: &Mesh,
712        skin: Option<(&[[f32; 8]], usize)>,
713    ) -> Result<Self, MeshError> {
714        if let Some((weights, _)) = skin.filter(|(weights, _)| weights.len() != mesh.vertices.len())
715        {
716            return Err(MeshError::SkinVertexCountMismatch {
717                expected: mesh.vertices.len(),
718                actual: weights.len(),
719            });
720        }
721        let stride = if skin.is_some() { 72 } else { 40 };
722        validate_mesh_layout(mesh, stride)?;
723        REGISTRY.with(|registry| {
724            let mut r = registry.borrow_mut();
725            r.meshes.retain(|(_, mesh)| mesh.strong_count() > 0);
726            let (_, bytes) = r.usage();
727            if r.meshes.len() >= MAX_MESHES || bytes + mesh.indices.len() * stride > MAX_BYTES {
728                return Err(MeshError::StorageCapacity {
729                    live_meshes: r.meshes.len(),
730                    requested_bytes: mesh.indices.len() * stride,
731                    available_bytes: MAX_BYTES - bytes,
732                });
733            }
734            r.next = r.next.checked_add(1).ok_or(MeshError::IdentityExhausted)?;
735            let data = Rc::new(Geometry {
736                id: r.next,
737                skin: skin.map(|(weights, _)| {
738                    mesh.indices.iter().map(|i| weights[*i as usize]).collect()
739                }),
740                joint_count: skin.map_or(0, |(_, joints)| joints),
741                bounds: mesh
742                    .indices
743                    .iter()
744                    .map(|i| mesh.vertices[*i as usize].position)
745                    .fold(
746                        ferravex_graphics::Bounds {
747                            min: crate::Vec3::splat(f32::INFINITY),
748                            max: crate::Vec3::splat(f32::NEG_INFINITY),
749                        },
750                        |b, p| ferravex_graphics::Bounds {
751                            min: b.min.min(p),
752                            max: b.max.max(p),
753                        },
754                    ),
755                opaque: mesh
756                    .indices
757                    .iter()
758                    .all(|i| mesh.vertices[*i as usize].color[3] == 255),
759                vertices: mesh
760                    .indices
761                    .iter()
762                    .map(|i| {
763                        let v = mesh.vertices[*i as usize];
764                        [
765                            v.position.x,
766                            v.position.y,
767                            v.position.z,
768                            v.normal.x,
769                            v.normal.y,
770                            v.normal.z,
771                            v.color[0] as f32 / 255.,
772                            v.color[1] as f32 / 255.,
773                            v.color[2] as f32 / 255.,
774                            v.color[3] as f32 / 255.,
775                        ]
776                    })
777                    .collect(),
778            });
779            r.meshes.push((data.id, Rc::downgrade(&data)));
780            Ok(Self(data))
781        })
782    }
783    pub fn id(&self) -> u32 {
784        self.0.id
785    }
786    pub fn vertex_count(&self) -> usize {
787        self.0.vertices.len()
788    }
789    pub(crate) fn is_opaque(&self) -> bool {
790        self.0.opaque
791    }
792    pub fn bounds(&self) -> ferravex_graphics::Bounds {
793        self.0.bounds
794    }
795}
796// IDs increase monotonically and pruning retains order. Binary search avoids
797// walking/upgrading every earlier mesh during each host liveness check.
798pub(crate) fn geometry(id: u32) -> Option<Rc<Geometry>> {
799    REGISTRY.with(|r| {
800        let r = r.borrow();
801        let index = r.meshes.binary_search_by_key(&id, |(id, _)| *id).ok()?;
802        r.meshes[index].1.upgrade()
803    })
804}
805#[cfg(not(target_arch = "wasm32"))]
806pub(crate) fn is_live(id: u32) -> bool {
807    REGISTRY.with(|r| {
808        let r = r.borrow();
809        r.meshes
810            .binary_search_by_key(&id, |(id, _)| *id)
811            .is_ok_and(|index| r.meshes[index].1.strong_count() > 0)
812    })
813}
814/// ABI: kind 0 = immediate, kind 1 = retained, kind 2 = flagged triangles, kind 3 = instanced sprites,
815/// kind 4 = post-processing world/HUD boundary (index 0; see `post`). Preserves transparency/UI order.
816/// Hosts skip unknown kinds.
817#[repr(C)]
818#[derive(Clone, Copy, Debug)]
819pub struct Command {
820    pub kind: u32,
821    pub index: u32,
822}
823/// ABI: 224 bytes. Lighting: direction.xyz/enabled, eye.xyz/ambient, fog.rgba, start/end/padding.
824#[repr(C)]
825#[derive(Clone, Copy, Debug, PartialEq)]
826pub struct RetainedBatch {
827    pub mesh: u32,
828    pub first: u32,
829    pub count: u32,
830    /// Bit 0: depth test; bit 1: suppress depth writes; bit 2: additive blend.
831    pub depth: u32,
832    pub camera: [f32; 16],
833    pub light: [f32; 16],
834    pub params: [f32; 16],
835    pub material: u32,
836    pub revision: u32,
837    /// Skin palette first joint / joint count; count zero disables skinning.
838    pub reserved: [u32; 2],
839}
840#[derive(Default)]
841pub(crate) struct Frame {
842    pub commands: Vec<Command>,
843    pub effects: Vec<crate::effects::EffectBatch>,
844    pub sprite_batches: Vec<crate::effects::SpriteBatch>,
845    pub sprites: Vec<[f32; 16]>,
846    pub batches: Vec<RetainedBatch>,
847    pub instances: Vec<[f32; 28]>,
848    pub skin_matrices: Vec<[f32; 16]>,
849    pub skin_normals: Vec<[f32; 9]>,
850    pub environment: crate::lighting::Environment,
851    /// Resolved post-processing host block for this frame; index 0 is the tier.
852    pub post: [f32; crate::post::POST_FRAME_FLOATS],
853    scratch_instances: Vec<[f32; 28]>,
854    scratch_batches: Vec<RetainedBatch>,
855    keep_alive: Vec<ResidentMesh>,
856    keep_materials: Vec<crate::material::ShaderMaterial>,
857}
858#[derive(Default, Clone, Copy)]
859pub(crate) struct DrawStyle<'a> {
860    pub look: crate::Look,
861    pub light: Option<LitSettings>,
862    pub material: Option<&'a crate::material::ShaderMaterial>,
863    pub params: [f32; 16],
864    pub shadow_only: bool,
865    pub skip_shadow: bool,
866    pub skin: Option<&'a crate::skinning::SkinPalette>,
867}
868impl RetainedBatch {
869    fn same_pass(&self, other: &Self) -> bool {
870        self.camera == other.camera
871            && self.light == other.light
872            && self.params == other.params
873            && self.material == other.material
874            && self.revision == other.revision
875            && self.depth & 7 == other.depth & 7
876    }
877    fn compatible(&self, other: &Self) -> bool {
878        self.mesh == other.mesh
879            && self.depth == other.depth
880            && self.reserved == other.reserved
881            && self.same_pass(other)
882    }
883}
884impl Frame {
885    pub fn clear(&mut self) {
886        self.commands.clear();
887        self.effects.clear();
888        self.sprite_batches.clear();
889        self.sprites.clear();
890        self.batches.clear();
891        self.instances.clear();
892        self.skin_matrices.clear();
893        self.skin_normals.clear();
894        self.keep_alive.clear();
895        self.keep_materials.clear();
896    }
897    #[cfg(test)]
898    pub fn record(
899        &mut self,
900        mesh: &ResidentMesh,
901        model: Mat4,
902        camera: Mat4,
903        depth: bool,
904        light: Option<LitSettings>,
905    ) -> bool {
906        self.record_style(
907            mesh,
908            model,
909            camera,
910            depth,
911            DrawStyle {
912                light,
913                ..Default::default()
914            },
915        )
916    }
917    pub fn record_style(
918        &mut self,
919        mesh: &ResidentMesh,
920        model: Mat4,
921        camera: Mat4,
922        depth: bool,
923        style: DrawStyle<'_>,
924    ) -> bool {
925        let (instance, skin_at) = match self.prepare_draw(mesh, model, camera, style.skin) {
926            Ok(prepared) => prepared,
927            Err(error) => {
928                RetainedRejections::draw(error);
929                return false;
930            }
931        };
932        let light = style.light;
933        let bones = style.skin.map_or(0, |skin| skin.count);
934        let l = light.unwrap_or_default().sanitized();
935        let lighting = [
936            l.light_direction.x,
937            l.light_direction.y,
938            l.light_direction.z,
939            if light.is_some() { 1. } else { 0. },
940            l.camera_position.x,
941            l.camera_position.y,
942            l.camera_position.z,
943            l.ambient,
944            l.fog_color.r,
945            l.fog_color.g,
946            l.fog_color.b,
947            l.fog_color.a,
948            l.fog_start,
949            l.fog_end,
950            style.look as u32 as f32,
951            if mesh.0.opaque
952                && style
953                    .material
954                    .is_none_or(|m| m.0.options.blend == crate::material::BlendMode::Opaque)
955            {
956                1.
957            } else {
958                0.
959            },
960        ];
961        let mut depth_flags = depth as u32;
962        if !depth {
963            depth_flags |= 16;
964        }
965        if let Some(m) = style.material {
966            if m.0.options.blend != crate::material::BlendMode::Opaque {
967                depth_flags |= 2;
968            }
969            if m.0.options.blend == crate::material::BlendMode::Additive {
970                depth_flags |= 4;
971            }
972            if !m.0.options.casts_shadows {
973                depth_flags |= 8;
974            }
975            if !m.0.options.receives_shadows {
976                depth_flags |= 16;
977            }
978        }
979        if style.skip_shadow {
980            depth_flags |= 8;
981        }
982        if style.shadow_only {
983            depth_flags |= 32;
984        }
985        if let Some(skin) = style.skin.filter(|_| skin_at == self.skin_matrices.len()) {
986            self.skin_matrices
987                .extend_from_slice(&skin.matrices[..bones]);
988            self.skin_normals.extend_from_slice(&skin.normals[..bones]);
989        }
990        let batch = RetainedBatch {
991            mesh: mesh.id(),
992            first: self.instances.len() as u32,
993            count: 1,
994            depth: depth_flags,
995            camera: camera.to_cols_array(),
996            light: lighting,
997            params: style.params,
998            material: style.material.map_or(0, |m| m.id()),
999            revision: style.material.map_or(0, |m| m.0.revision.get()),
1000            reserved: if bones == 0 {
1001                [0; 2]
1002            } else {
1003                [skin_at as u32, bones as u32]
1004            },
1005        };
1006        if let Some(last) = self.batches.last_mut().filter(|last| {
1007            self.commands.last().is_some_and(|c| c.kind == 1) && last.compatible(&batch)
1008        }) {
1009            last.count += 1;
1010        } else {
1011            self.commands.push(Command {
1012                kind: 1,
1013                index: self.batches.len() as u32,
1014            });
1015            self.batches.push(batch);
1016            self.keep_alive.push(mesh.clone());
1017            if let Some(material) = style.material {
1018                self.keep_materials.push(material.clone());
1019            }
1020        }
1021        self.instances.push(instance);
1022        true
1023    }
1024    // No writes or allocation until every draw validation succeeds. The checked
1025    // public entry point also uses this before visibility can hide author errors.
1026    fn prepare_draw(
1027        &self,
1028        mesh: &ResidentMesh,
1029        model: Mat4,
1030        camera: Mat4,
1031        skin: Option<&crate::skinning::SkinPalette>,
1032    ) -> Result<([f32; 28], usize), DrawError> {
1033        self.prepare_draw_at(mesh, model, camera, skin, self.instances.len())
1034    }
1035    fn prepare_draw_at(
1036        &self,
1037        mesh: &ResidentMesh,
1038        model: Mat4,
1039        camera: Mat4,
1040        skin: Option<&crate::skinning::SkinPalette>,
1041        instance_count: usize,
1042    ) -> Result<([f32; 28], usize), DrawError> {
1043        let instance = prepare_instance(model)?;
1044        if let Some(i) = camera.to_cols_array().iter().position(|v| !v.is_finite()) {
1045            return Err(DrawError::NonFiniteCamera {
1046                column: i / 4,
1047                row: i % 4,
1048            });
1049        }
1050        if instance_count >= MAX_INSTANCES {
1051            return Err(DrawError::InstanceCapacity {
1052                limit: MAX_INSTANCES,
1053            });
1054        }
1055        let bones = skin.map_or(0, |skin| skin.count);
1056        if bones != mesh.0.joint_count {
1057            return Err(DrawError::SkinPaletteMismatch {
1058                expected: mesh.0.joint_count,
1059                actual: bones,
1060            });
1061        }
1062        let skin_at = if skin.is_some_and(|skin| {
1063            self.skin_matrices.len() >= bones
1064                && self.skin_matrices[self.skin_matrices.len() - bones..] == skin.matrices[..bones]
1065                && self.skin_normals[self.skin_normals.len() - bones..] == skin.normals[..bones]
1066        }) {
1067            self.skin_matrices.len() - bones
1068        } else {
1069            self.skin_matrices.len()
1070        };
1071        if skin_at + bones > crate::skinning::MAX_FRAME_SKIN_JOINTS {
1072            return Err(DrawError::SkinCapacity {
1073                limit: crate::skinning::MAX_FRAME_SKIN_JOINTS,
1074            });
1075        }
1076        Ok((instance, skin_at))
1077    }
1078    /// Group opaque depth-tested draws within an uninterrupted camera/material pass.
1079    /// Transparent draws and every immediate command are strict ordering barriers.
1080    pub fn finalize(&mut self) {
1081        let opaque = |c: &Command| {
1082            c.kind == 1
1083                && self.batches[c.index as usize].depth & 7 == 1
1084                && self.batches[c.index as usize].light[15] > 0.5
1085        };
1086        let mut begin = 0;
1087        while begin < self.commands.len() {
1088            if !opaque(&self.commands[begin]) {
1089                begin += 1;
1090                continue;
1091            }
1092            let first = self.batches[self.commands[begin].index as usize];
1093            let mut end = begin + 1;
1094            while end < self.commands.len() && opaque(&self.commands[end]) {
1095                let b = self.batches[self.commands[end].index as usize];
1096                if !b.same_pass(&first) {
1097                    break;
1098                }
1099                end += 1;
1100            }
1101            self.commands[begin..end].sort_unstable_by_key(|c| {
1102                let b = self.batches[c.index as usize];
1103                (b.mesh, b.depth)
1104            });
1105            begin = end;
1106        }
1107        self.scratch_instances.clear();
1108        self.scratch_batches.clear();
1109        let mut written = 0;
1110        let mut previous_retained = false;
1111        for i in 0..self.commands.len() {
1112            let c = self.commands[i];
1113            if c.kind != 1 {
1114                self.commands[written] = c;
1115                written += 1;
1116                previous_retained = false;
1117                continue;
1118            }
1119            let mut batch = self.batches[c.index as usize];
1120            let source =
1121                &self.instances[batch.first as usize..(batch.first + batch.count) as usize];
1122            batch.first = self.scratch_instances.len() as u32;
1123            self.scratch_instances.extend_from_slice(source);
1124            if let Some(last) = self
1125                .scratch_batches
1126                .last_mut()
1127                .filter(|last| previous_retained && last.compatible(&batch))
1128            {
1129                last.count += batch.count;
1130            } else {
1131                self.commands[written] = Command {
1132                    kind: 1,
1133                    index: self.scratch_batches.len() as u32,
1134                };
1135                written += 1;
1136                self.scratch_batches.push(batch);
1137            }
1138            previous_retained = true;
1139        }
1140        self.commands.truncate(written);
1141        std::mem::swap(&mut self.instances, &mut self.scratch_instances);
1142        std::mem::swap(&mut self.batches, &mut self.scratch_batches);
1143    }
1144}
1145
1146/// Same vertex-lighting/fog equations as the CPU immediate path, evaluated by the GPU.
1147pub const VERTEX_BODY: &str = r#"
1148attribute vec3 a_position;
1149attribute vec3 a_normal;
1150attribute vec4 a_color;
1151attribute vec4 a_joints; attribute vec4 a_weights;
1152uniform int u_skin_count;
1153uniform mat4 u_bones[32];
1154uniform mat3 u_bone_normals[32];
1155attribute vec4 a_model0; attribute vec4 a_model1; attribute vec4 a_model2; attribute vec4 a_model3;
1156attribute vec4 a_normal0; attribute vec4 a_normal1; attribute vec4 a_normal2;
1157uniform mat4 u_camera;
1158uniform vec4 u_light[4];
1159uniform vec4 u_params[4];
1160varying vec4 v_color;
1161varying vec3 v_world;
1162varying vec3 v_normal;
1163vec3 ferravex_vertex(vec3 position);
1164vec3 ferravex_normal(vec3 normal);
1165void main(){
1166 mat4 model=mat4(a_model0,a_model1,a_model2,a_model3);
1167 vec3 position=a_position;vec3 posed_normal=a_normal;
1168 if(u_skin_count>0){
1169  position=vec3(0.0);posed_normal=vec3(0.0);
1170  for(int i=0;i<4;i++){int joint=int(a_joints[i]);position+=(u_bones[joint]*vec4(a_position,1.0)).xyz*a_weights[i];posed_normal+=u_bone_normals[joint]*a_normal*a_weights[i];}
1171 }
1172 vec4 world=model*vec4(ferravex_vertex(position),1.0);
1173 vec3 normal=mat3(a_normal0.xyz,a_normal1.xyz,a_normal2.xyz)*ferravex_normal(posed_normal);
1174 float n=length(normal);normal=n>0.0?normal/n:vec3(0.0);
1175 gl_Position=u_camera*world;v_color=a_color;v_world=world.xyz;v_normal=normal;
1176}
1177"#;
1178#[cfg(test)]
1179mod tests {
1180    use super::*;
1181    use crate::{Color, Vec3, mesh::Mesh3d};
1182    fn mesh() -> ResidentMesh {
1183        ResidentMesh::new(&Mesh3d::cuboid(Vec3::ONE, Color::new(1., 1., 1., 1.)).mesh).unwrap()
1184    }
1185    #[test]
1186    fn telemetry_tracks_live_geometry_without_counting_clones_or_expired_entries() {
1187        reset_telemetry();
1188        let source = Mesh3d::cuboid(Vec3::ONE, crate::WHITE).mesh;
1189        let resident = ResidentMesh::try_new(&source).unwrap();
1190        let clone = resident.clone();
1191        let packed = vec![[0.; 8]; source.vertices.len()];
1192        let skin = ResidentMesh::with_skin(&source, Some((&packed, 1))).unwrap();
1193        let snapshot = telemetry_snapshot();
1194        assert_eq!(snapshot.live_meshes, 2);
1195        assert_eq!(snapshot.mesh_bytes, source.indices.len() * (40 + 72));
1196        assert_eq!(snapshot.mesh_limit, MAX_MESHES);
1197        assert_eq!(snapshot.mesh_byte_limit, MAX_BYTES);
1198        assert!(snapshot.buffers.mesh_slots >= snapshot.live_meshes);
1199        assert_eq!(telemetry_snapshot(), snapshot);
1200
1201        crate::input::host_frame(0., 800, 600, || {
1202            assert_eq!(draw_resident_checked(&resident, Mat4::IDENTITY), Ok(true));
1203        });
1204        drop((resident, clone, skin));
1205        let kept = telemetry_snapshot();
1206        assert_eq!(kept.live_meshes, 1); // Recorded batches keep geometry alive.
1207        assert_eq!(kept.mesh_bytes, source.indices.len() * 40);
1208        assert_eq!(kept.instances, 1);
1209        assert_eq!(kept.draws, 1);
1210        assert_eq!(reset_telemetry(), RetainedRejections::default());
1211        assert_eq!(telemetry_snapshot(), kept);
1212
1213        crate::clear_background(crate::BLACK);
1214        let cleared = telemetry_snapshot();
1215        assert_eq!(cleared.live_meshes, 0);
1216        assert_eq!(cleared.mesh_bytes, 0);
1217        assert_eq!(cleared.instances, 0);
1218        assert_eq!(cleared.draws, 0);
1219        assert_eq!(cleared.buffers, kept.buffers);
1220        // Snapshotting does not prune expired weak handles.
1221        REGISTRY.with(|r| assert_eq!(r.borrow().meshes.len(), 2));
1222    }
1223    #[test]
1224    fn telemetry_counts_creation_errors_once_and_does_not_count_pure_validation() {
1225        reset_telemetry();
1226        let source = Mesh::default();
1227        assert!(validate_mesh(&source).is_err());
1228        assert!(validate_transform(Mat4::ZERO).is_err());
1229        assert_eq!(
1230            telemetry_snapshot().rejections,
1231            RetainedRejections::default()
1232        );
1233        assert!(ResidentMesh::try_new(&source).is_err());
1234        assert!(ResidentMesh::new(&source).is_err());
1235        let source = Mesh3d::cuboid(Vec3::ONE, crate::WHITE).mesh;
1236        assert!(ResidentMesh::with_skin(&source, Some((&[], 1))).is_err());
1237        let counts = telemetry_snapshot().rejections;
1238        assert_eq!(counts.mesh_validation, 3);
1239        assert_eq!(counts.mesh_capacity, 0);
1240        assert_eq!(reset_telemetry(), counts);
1241        assert_eq!(reset_telemetry(), RetainedRejections::default());
1242    }
1243    #[test]
1244    fn telemetry_reports_mesh_count_limit_and_recovery_without_consuming_identity() {
1245        reset_telemetry();
1246        let mut source = Mesh3d::cuboid(Vec3::ONE, crate::WHITE).mesh;
1247        source.indices.truncate(3);
1248        let mut meshes: Vec<_> = (0..MAX_MESHES)
1249            .map(|_| ResidentMesh::try_new(&source).unwrap())
1250            .collect();
1251        let before = telemetry_snapshot();
1252        assert_eq!(before.live_meshes, before.mesh_limit);
1253        assert_eq!(before.mesh_bytes, MAX_MESHES * 3 * 40);
1254        assert!(matches!(
1255            ResidentMesh::try_new(&source),
1256            Err(MeshError::StorageCapacity {
1257                live_meshes: MAX_MESHES,
1258                ..
1259            })
1260        ));
1261        assert_eq!(telemetry_snapshot().rejections.mesh_capacity, 1);
1262        let last_id = meshes.pop().unwrap().id();
1263        let next = ResidentMesh::try_new(&source).unwrap();
1264        assert_eq!(next.id(), last_id + 1);
1265        assert_eq!(telemetry_snapshot().live_meshes, MAX_MESHES);
1266    }
1267    #[test]
1268    fn telemetry_distinguishes_mesh_byte_limits_from_invalid_geometry() {
1269        reset_telemetry();
1270        let mut source = Mesh3d::cuboid(Vec3::ONE, crate::WHITE).mesh;
1271        let count = (MAX_BYTES / 40 / 3) * 3;
1272        source.indices = vec![0; count + 3];
1273        assert!(matches!(
1274            ResidentMesh::try_new(&source),
1275            Err(MeshError::MeshTooLarge { .. })
1276        ));
1277        source.indices.truncate(count);
1278        let large = ResidentMesh::try_new(&source).unwrap();
1279        let full = telemetry_snapshot();
1280        assert_eq!(full.live_meshes, 1);
1281        assert_eq!(full.mesh_bytes, count * 40);
1282        source.indices.truncate(3);
1283        assert!(matches!(
1284            ResidentMesh::try_new(&source),
1285            Err(MeshError::StorageCapacity { live_meshes: 1, available_bytes, .. })
1286                if available_bytes == MAX_BYTES - full.mesh_bytes
1287        ));
1288        let counts = telemetry_snapshot().rejections;
1289        assert_eq!(counts.mesh_capacity, 2);
1290        assert_eq!(counts.mesh_validation, 0);
1291        let id = large.id();
1292        drop(large);
1293        assert_eq!(telemetry_snapshot().mesh_bytes, 0);
1294        assert_eq!(ResidentMesh::try_new(&source).unwrap().id(), id + 1);
1295    }
1296    #[test]
1297    fn telemetry_tracks_batch_merging_and_buffer_swaps_without_resetting_counters() {
1298        struct IdentityCamera;
1299        impl crate::Camera for IdentityCamera {
1300            fn matrix(&self, _: f32, _: f32) -> Mat4 {
1301                Mat4::IDENTITY
1302            }
1303            fn depth(&self) -> bool {
1304                true
1305            }
1306        }
1307        reset_telemetry();
1308        let a = mesh();
1309        let b = mesh();
1310        crate::input::host_frame(0., 800, 600, || {
1311            crate::set_camera(&IdentityCamera);
1312            for mesh in [&a, &b, &a] {
1313                assert_eq!(draw_resident_checked(mesh, Mat4::IDENTITY), Ok(true));
1314            }
1315            let sample = telemetry_snapshot();
1316            assert_eq!((sample.instances, sample.draws), (3, 3));
1317            assert_eq!(sample.instance_limit, MAX_INSTANCES);
1318            assert_eq!(sample.draw_limit, sample.instance_limit);
1319            let outside = Mat4::from_translation(Vec3::X * 100.);
1320            assert_eq!(draw_resident_checked(&a, outside), Ok(false));
1321            assert_eq!(telemetry_snapshot(), sample);
1322            assert!(draw_resident_checked(&a, outside * Mat4::ZERO).is_err());
1323            assert_eq!(telemetry_snapshot().rejections.draw_validation, 1);
1324        });
1325        let finalized = telemetry_snapshot();
1326        assert_eq!((finalized.instances, finalized.draws), (3, 2));
1327        assert!(finalized.buffers.instances >= 3);
1328        assert!(finalized.buffers.scratch_instances >= 3);
1329        assert!(finalized.buffers.draws >= 2);
1330        assert!(finalized.buffers.scratch_draws >= 3);
1331        crate::input::host_frame(0., 800, 600, || {
1332            let cleared = telemetry_snapshot();
1333            assert_eq!((cleared.instances, cleared.draws), (0, 0));
1334            assert_eq!(cleared.buffers, finalized.buffers);
1335            assert_eq!(cleared.rejections.draw_validation, 1);
1336            assert_eq!(reset_telemetry(), cleared.rejections);
1337            let reset = telemetry_snapshot();
1338            assert_eq!(reset.rejections, RetainedRejections::default());
1339            assert_eq!(
1340                RetainedTelemetry {
1341                    rejections: cleared.rejections,
1342                    ..reset
1343                },
1344                cleared
1345            );
1346        });
1347    }
1348    #[test]
1349    fn telemetry_counts_checked_and_legacy_instance_rejections_once_each() {
1350        reset_telemetry();
1351        let mesh = mesh();
1352        crate::input::host_frame(0., 800, 600, || {
1353            for _ in 0..MAX_INSTANCES {
1354                assert!(crate::draw_resident(&mesh, Mat4::IDENTITY));
1355            }
1356            let full = telemetry_snapshot();
1357            assert_eq!(full.instances, full.instance_limit);
1358            assert_eq!(full.draws, 1); // An instance budget, not a batch budget.
1359            assert_eq!(
1360                draw_resident_checked(&mesh, Mat4::IDENTITY),
1361                Err(DrawError::InstanceCapacity {
1362                    limit: MAX_INSTANCES
1363                })
1364            );
1365            assert!(!crate::draw_resident(&mesh, Mat4::IDENTITY));
1366            let rejected = telemetry_snapshot();
1367            assert_eq!(rejected.rejections.instance_capacity, 2);
1368            assert_eq!(
1369                RetainedTelemetry {
1370                    rejections: full.rejections,
1371                    ..rejected
1372                },
1373                full
1374            );
1375            crate::clear_background(crate::BLACK);
1376            assert_eq!(draw_resident_checked(&mesh, Mat4::IDENTITY), Ok(true));
1377            assert_eq!(telemetry_snapshot().buffers, full.buffers);
1378            assert_eq!(telemetry_snapshot().rejections.instance_capacity, 2);
1379        });
1380    }
1381    #[test]
1382    fn telemetry_counts_skin_capacity_after_palette_reuse_and_preserves_storage() {
1383        use crate::skinning::{MAX_FRAME_SKIN_JOINTS, MAX_SKIN_JOINTS, SkinPalette};
1384        reset_telemetry();
1385        let source = Mesh3d::cuboid(Vec3::ONE, crate::WHITE).mesh;
1386        let packed = vec![[0.; 8]; source.vertices.len()];
1387        let mesh = ResidentMesh::with_skin(&source, Some((&packed, MAX_SKIN_JOINTS))).unwrap();
1388        let a = SkinPalette::new(&[Mat4::IDENTITY.to_cols_array(); MAX_SKIN_JOINTS]).unwrap();
1389        let b =
1390            SkinPalette::new(&[Mat4::from_translation(Vec3::X).to_cols_array(); MAX_SKIN_JOINTS])
1391                .unwrap();
1392        crate::edit(|s| {
1393            for i in 0..MAX_FRAME_SKIN_JOINTS / MAX_SKIN_JOINTS {
1394                assert!(s.retained.record_style(
1395                    &mesh,
1396                    Mat4::IDENTITY,
1397                    Mat4::IDENTITY,
1398                    true,
1399                    DrawStyle {
1400                        skin: Some(if i % 2 == 0 { &a } else { &b }),
1401                        ..Default::default()
1402                    }
1403                ));
1404            }
1405            // The last palette can still be reused when joint storage is full.
1406            assert!(s.retained.record_style(
1407                &mesh,
1408                Mat4::IDENTITY,
1409                Mat4::IDENTITY,
1410                true,
1411                DrawStyle {
1412                    skin: Some(&b),
1413                    ..Default::default()
1414                }
1415            ));
1416        });
1417        let full = telemetry_snapshot();
1418        assert_eq!(full.skin_joints, full.skin_joint_limit);
1419        assert_eq!(full.rejections, RetainedRejections::default());
1420        crate::edit(|s| {
1421            assert!(!s.retained.record_style(
1422                &mesh,
1423                Mat4::IDENTITY,
1424                Mat4::IDENTITY,
1425                true,
1426                DrawStyle {
1427                    skin: Some(&a),
1428                    ..Default::default()
1429                }
1430            ));
1431        });
1432        let rejected = telemetry_snapshot();
1433        assert_eq!(rejected.rejections.skin_capacity, 1);
1434        assert_eq!(
1435            RetainedTelemetry {
1436                rejections: full.rejections,
1437                ..rejected
1438            },
1439            full
1440        );
1441        assert!(matches!(
1442            draw_resident_checked(&mesh, Mat4::IDENTITY),
1443            Err(DrawError::SkinPaletteMismatch { .. })
1444        ));
1445        assert_eq!(telemetry_snapshot().rejections.draw_validation, 1);
1446        crate::clear_background(crate::BLACK);
1447        assert_eq!(telemetry_snapshot().skin_joints, 0);
1448        assert_eq!(telemetry_snapshot().buffers, full.buffers);
1449    }
1450    #[test]
1451    fn telemetry_identity_rejection_and_saturating_counters_are_independent_of_reset() {
1452        reset_telemetry();
1453        let source = Mesh3d::cuboid(Vec3::ONE, crate::WHITE).mesh;
1454        REGISTRY.with(|r| r.borrow_mut().next = u32::MAX);
1455        assert!(matches!(
1456            ResidentMesh::try_new(&source),
1457            Err(MeshError::IdentityExhausted)
1458        ));
1459        assert_eq!(reset_telemetry().mesh_identity, 1);
1460        assert!(matches!(
1461            ResidentMesh::try_new(&source),
1462            Err(MeshError::IdentityExhausted)
1463        ));
1464        assert_eq!(reset_telemetry().mesh_identity, 1); // Reset never recycles IDs.
1465        REGISTRY.with(|r| r.borrow_mut().next = 0);
1466        let mesh = ResidentMesh::try_new(&source).unwrap();
1467        REJECTIONS.with(|r| {
1468            r.set(RetainedRejections {
1469                mesh_validation: u64::MAX,
1470                draw_validation: u64::MAX,
1471                ..Default::default()
1472            })
1473        });
1474        assert!(ResidentMesh::try_new(&Mesh::default()).is_err());
1475        assert!(draw_resident_checked(&mesh, Mat4::ZERO).is_err());
1476        assert_eq!(
1477            reset_telemetry(),
1478            RetainedRejections {
1479                mesh_validation: u64::MAX,
1480                draw_validation: u64::MAX,
1481                ..Default::default()
1482            }
1483        );
1484    }
1485    #[test]
1486    fn telemetry_is_thread_local() {
1487        reset_telemetry();
1488        let _resident = mesh();
1489        assert!(ResidentMesh::try_new(&Mesh::default()).is_err());
1490        std::thread::spawn(|| {
1491            let sample = telemetry_snapshot();
1492            assert_eq!(sample.live_meshes, 0);
1493            assert_eq!(sample.rejections, RetainedRejections::default());
1494            reset_telemetry();
1495        })
1496        .join()
1497        .unwrap();
1498        assert_eq!(telemetry_snapshot().live_meshes, 1);
1499        assert_eq!(reset_telemetry().mesh_validation, 1);
1500    }
1501    #[test]
1502    fn malformed_geometry_is_rejected_before_identity_or_storage_changes() {
1503        let mut source = Mesh3d::cuboid(Vec3::ONE, crate::WHITE).mesh;
1504        let before = mesh();
1505        source.indices[4] = u16::MAX;
1506        assert!(matches!(
1507            ResidentMesh::try_new(&source),
1508            Err(MeshError::IndexOutOfBounds {
1509                index_position: 4,
1510                index: u16::MAX,
1511                ..
1512            })
1513        ));
1514        assert_eq!(
1515            ResidentMesh::new(&source).err(),
1516            Some("invalid retained mesh geometry")
1517        );
1518        let after = mesh();
1519        assert_eq!(after.id(), before.id() + 1);
1520        assert!(geometry(before.id()).is_some());
1521    }
1522    #[test]
1523    fn all_vertex_attributes_and_unused_vertices_must_be_finite() {
1524        let mut source = Mesh3d::cuboid(Vec3::ONE, crate::WHITE).mesh;
1525        let unused = source.vertices.len();
1526        source.vertices.push(source.vertices[0]);
1527        for value in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
1528            for (attribute, count) in [("position", 3), ("uv", 2), ("normal", 4)] {
1529                for component in 0..count {
1530                    source.vertices[unused] = source.vertices[0];
1531                    let vertex = &mut source.vertices[unused];
1532                    match attribute {
1533                        "position" => vertex.position[component] = value,
1534                        "uv" => vertex.uv[component] = value,
1535                        _ => vertex.normal[component] = value,
1536                    }
1537                    let expected = MeshError::NonFiniteVertex {
1538                        vertex: unused,
1539                        attribute,
1540                        component,
1541                    };
1542                    assert_eq!(validate_mesh(&source), Err(expected));
1543                    assert!(
1544                        matches!(ResidentMesh::try_new(&source), Err(error) if error == expected)
1545                    );
1546                    assert!(ResidentMesh::new(&source).is_err());
1547                }
1548            }
1549        }
1550        source.vertices[unused] = source.vertices[0];
1551        assert!(ResidentMesh::try_new(&source).is_ok());
1552    }
1553    #[test]
1554    fn triangle_lists_and_individual_storage_budget_are_checked() {
1555        let mut source = Mesh3d::cuboid(Vec3::ONE, crate::WHITE).mesh;
1556        for count in [0, 1, 2, 4] {
1557            source.indices = vec![0; count];
1558            assert_eq!(
1559                validate_mesh(&source),
1560                Err(MeshError::IncompleteTriangles { index_count: count })
1561            );
1562        }
1563        let count = (MAX_BYTES / 40 / 3 + 1) * 3;
1564        source.indices = vec![0; count];
1565        assert_eq!(
1566            validate_mesh(&source),
1567            Err(MeshError::MeshTooLarge {
1568                index_count: count,
1569                max_indices: MAX_BYTES / 40,
1570            })
1571        );
1572        source.indices = vec![0, 0, 0]; // Degenerate authored triangles remain supported.
1573        assert_eq!(validate_mesh(&source), Ok(()));
1574    }
1575    #[test]
1576    fn invalid_draws_do_not_change_recorded_batches_or_skin_storage() {
1577        use crate::skinning::{SkinPalette, SkinWeights, SkinnedMesh};
1578        let source = Mesh3d::cuboid(Vec3::ONE, crate::WHITE).mesh;
1579        let skin = SkinnedMesh::new(
1580            &source,
1581            &vec![SkinWeights::rigid(0); source.vertices.len()],
1582            1,
1583        )
1584        .unwrap();
1585        let palette = SkinPalette::new(&[Mat4::IDENTITY.to_cols_array()]).unwrap();
1586        let changed_palette =
1587            SkinPalette::new(&[Mat4::from_translation(Vec3::X).to_cols_array()]).unwrap();
1588        let mut f = Frame::default();
1589        assert!(f.record_style(
1590            skin.resident(),
1591            Mat4::IDENTITY,
1592            Mat4::IDENTITY,
1593            true,
1594            DrawStyle {
1595                skin: Some(&palette),
1596                ..Default::default()
1597            }
1598        ));
1599        let instances = f.instances.clone();
1600        let batches = f.batches.clone();
1601        let matrices = f.skin_matrices.clone();
1602        let normals = f.skin_normals.clone();
1603        let mut perspective_model = Mat4::IDENTITY;
1604        perspective_model.x_axis.w = 0.25;
1605        for (model, camera) in [
1606            (Mat4::NAN, Mat4::IDENTITY),
1607            (Mat4::from_scale(Vec3::ZERO), Mat4::IDENTITY),
1608            (perspective_model, Mat4::IDENTITY),
1609            (Mat4::IDENTITY, Mat4::NAN),
1610            (
1611                Mat4::from_scale(Vec3::new(f32::from_bits(1), 1., 1.)),
1612                Mat4::IDENTITY,
1613            ),
1614        ] {
1615            assert!(
1616                f.prepare_draw(skin.resident(), model, camera, Some(&changed_palette))
1617                    .is_err()
1618            );
1619            assert!(!f.record_style(
1620                skin.resident(),
1621                model,
1622                camera,
1623                true,
1624                DrawStyle {
1625                    skin: Some(&changed_palette),
1626                    ..Default::default()
1627                }
1628            ));
1629            assert_eq!(f.instances, instances);
1630            assert_eq!(f.batches, batches);
1631            assert_eq!(f.skin_matrices, matrices);
1632            assert_eq!(f.skin_normals, normals);
1633            assert_eq!(f.commands.len(), 1);
1634            assert_eq!(f.keep_alive.len(), 1);
1635        }
1636        assert!(f.record_style(
1637            skin.resident(),
1638            Mat4::IDENTITY,
1639            Mat4::IDENTITY,
1640            true,
1641            DrawStyle {
1642                skin: Some(&palette),
1643                ..Default::default()
1644            }
1645        ));
1646        assert_eq!(f.skin_matrices.len(), 1); // Palette reuse survives rejected draws.
1647        assert_eq!(f.batches[0].count, 2);
1648    }
1649    #[test]
1650    fn frame_limits_are_reported_and_rejection_is_transactional() {
1651        let mesh = mesh();
1652        let mut f = Frame::default();
1653        f.instances.resize(MAX_INSTANCES, [0.; 28]);
1654        let capacity = f.instances.capacity();
1655        assert_eq!(
1656            f.prepare_draw(&mesh, Mat4::IDENTITY, Mat4::IDENTITY, None),
1657            Err(DrawError::InstanceCapacity {
1658                limit: MAX_INSTANCES
1659            })
1660        );
1661        assert!(!f.record(&mesh, Mat4::IDENTITY, Mat4::IDENTITY, true, None));
1662        assert_eq!(f.instances.len(), MAX_INSTANCES);
1663        assert!(f.commands.is_empty());
1664        f.clear();
1665        assert!(f.record(&mesh, Mat4::IDENTITY, Mat4::IDENTITY, true, None));
1666        assert_eq!(f.instances.capacity(), capacity);
1667    }
1668    #[test]
1669    fn resident_snapshot_and_shared_handle_survive_source_edits() {
1670        let mut source = Mesh3d::cuboid(Vec3::ONE, crate::WHITE).mesh;
1671        let mesh = ResidentMesh::try_new(&source).unwrap();
1672        let shared = mesh.clone();
1673        let snapshot = geometry(mesh.id()).unwrap();
1674        source.vertices[0].position.x = f32::NAN;
1675        assert!(ResidentMesh::try_new(&source).is_err());
1676        assert_eq!(shared.id(), mesh.id());
1677        assert_eq!(shared.bounds(), mesh.bounds());
1678        assert!(Rc::ptr_eq(&snapshot, &geometry(shared.id()).unwrap()));
1679        assert!(snapshot.vertices.iter().flatten().all(|v| v.is_finite()));
1680    }
1681    #[test]
1682    fn compatible_instances_merge_but_camera_and_order_are_preserved() {
1683        let mesh = mesh();
1684        let mut f = Frame::default();
1685        assert!(f.record(&mesh, Mat4::IDENTITY, Mat4::IDENTITY, true, None));
1686        f.record(
1687            &mesh,
1688            Mat4::from_translation(Vec3::X),
1689            Mat4::IDENTITY,
1690            true,
1691            None,
1692        );
1693        assert_eq!(f.batches.len(), 1);
1694        assert_eq!(f.batches[0].count, 2);
1695        f.commands.push(Command { kind: 0, index: 0 });
1696        f.record(&mesh, Mat4::IDENTITY, Mat4::IDENTITY, true, None);
1697        f.record(
1698            &mesh,
1699            Mat4::IDENTITY,
1700            Mat4::from_translation(Vec3::X),
1701            true,
1702            None,
1703        );
1704        assert_eq!(f.batches.len(), 3);
1705        assert_eq!(f.commands.len(), 4);
1706        assert!(!f.record(
1707            &mesh,
1708            Mat4::from_scale(Vec3::ZERO),
1709            Mat4::IDENTITY,
1710            true,
1711            None
1712        ));
1713    }
1714    #[test]
1715    fn lifetime_keeps_draws_valid_and_ids_never_recycle() {
1716        let mut f = Frame::default();
1717        let id;
1718        {
1719            let mesh = mesh();
1720            id = mesh.id();
1721            f.record(&mesh, Mat4::IDENTITY, Mat4::IDENTITY, true, None);
1722        }
1723        assert!(is_live(id));
1724        f.clear();
1725        assert!(!is_live(id));
1726        assert_ne!(id, mesh().id());
1727    }
1728    #[test]
1729    fn lookup_survives_dead_entries_and_registry_pruning() {
1730        let meshes: Vec<_> = (0..64).map(|_| mesh()).collect();
1731        let ids: Vec<_> = meshes.iter().map(ResidentMesh::id).collect();
1732        let live: Vec<_> = meshes
1733            .into_iter()
1734            .enumerate()
1735            .filter_map(|(i, mesh)| (i % 3 == 0).then_some(mesh))
1736            .collect();
1737        for (i, &id) in ids.iter().enumerate() {
1738            assert_eq!(geometry(id).is_some(), i % 3 == 0);
1739            assert_eq!(is_live(id), i % 3 == 0);
1740        }
1741        let next = mesh(); // Removes expired weak entries without recycling IDs.
1742        assert!(next.id() > *ids.last().unwrap());
1743        for mesh in &live {
1744            assert_eq!(geometry(mesh.id()).unwrap().id, mesh.id());
1745        }
1746        for (i, &id) in ids.iter().enumerate() {
1747            assert_eq!(is_live(id), i % 3 == 0);
1748        }
1749        assert!(geometry(0).is_none());
1750        assert!(geometry(u32::MAX).is_none());
1751    }
1752    #[test]
1753    fn wire_layout_and_normal_matrix_are_defined() {
1754        assert_eq!(std::mem::size_of::<Command>(), 8);
1755        assert_eq!(std::mem::size_of::<RetainedBatch>(), 224);
1756        assert_eq!(std::mem::offset_of!(RetainedBatch, camera), 16);
1757        assert_eq!(std::mem::offset_of!(RetainedBatch, light), 80);
1758        assert_eq!(std::mem::offset_of!(RetainedBatch, params), 144);
1759        assert_eq!(std::mem::offset_of!(RetainedBatch, material), 208);
1760        let mut f = Frame::default();
1761        f.record(
1762            &mesh(),
1763            Mat4::from_scale(Vec3::new(2., 4., 8.)),
1764            Mat4::IDENTITY,
1765            true,
1766            None,
1767        );
1768        assert_eq!(f.instances[0][16], 0.5);
1769        assert_eq!(f.instances[0][21], 0.25);
1770        assert_eq!(f.instances[0][26], 0.125);
1771    }
1772    #[test]
1773    fn material_and_parameter_changes_cannot_be_merged() {
1774        use crate::material::{MaterialOptions, ShaderMaterial};
1775        let mesh = mesh();
1776        let a = ShaderMaterial::new(
1777            Default::default(),
1778            MaterialOptions {
1779                blend: crate::material::BlendMode::Opaque,
1780                ..Default::default()
1781            },
1782        )
1783        .unwrap();
1784        let b = ShaderMaterial::new(
1785            Default::default(),
1786            MaterialOptions {
1787                blend: crate::material::BlendMode::Opaque,
1788                ..Default::default()
1789            },
1790        )
1791        .unwrap();
1792        let mut f = Frame::default();
1793        for (m, v) in [(&a, 1.), (&b, 1.), (&b, 2.)] {
1794            f.record_style(
1795                &mesh,
1796                Mat4::IDENTITY,
1797                Mat4::IDENTITY,
1798                true,
1799                DrawStyle {
1800                    material: Some(m),
1801                    params: [v; 16],
1802                    ..Default::default()
1803                },
1804            );
1805        }
1806        f.finalize();
1807        assert_eq!(f.batches.len(), 3);
1808        assert_eq!(
1809            f.batches
1810                .iter()
1811                .map(|b| (b.material, b.params[0]))
1812                .collect::<Vec<_>>(),
1813            [(a.id(), 1.), (b.id(), 1.), (b.id(), 2.)]
1814        );
1815    }
1816    #[test]
1817    fn opaque_reordering_copies_instances_and_stops_at_ui_barriers() {
1818        let a = mesh();
1819        let b = mesh();
1820        let mut f = Frame::default();
1821        for (i, m) in [&a, &b, &a].into_iter().enumerate() {
1822            f.record(
1823                m,
1824                Mat4::from_translation(Vec3::X * i as f32),
1825                Mat4::IDENTITY,
1826                true,
1827                None,
1828            );
1829        }
1830        f.commands.push(Command { kind: 0, index: 0 });
1831        f.record(&a, Mat4::IDENTITY, Mat4::IDENTITY, true, None);
1832        f.finalize();
1833        assert_eq!(f.commands.len(), 4);
1834        assert_eq!(f.batches[0].count, 2);
1835        assert_eq!(
1836            f.instances.iter().map(|i| i[12]).collect::<Vec<_>>(),
1837            [0., 2., 1., 0.]
1838        );
1839    }
1840}
1841
1842#[cfg(test)]
1843mod journey400_284 {
1844    use super::*;
1845    use crate::{Vec3, mesh::Mesh3d};
1846
1847    fn mesh() -> ResidentMesh {
1848        ResidentMesh::try_new(&Mesh3d::cuboid(Vec3::ONE, crate::WHITE).mesh).unwrap()
1849    }
1850
1851    #[derive(Debug, PartialEq, Eq)]
1852    struct BatchBits {
1853        integers: [u32; 8],
1854        floats: [[u32; 16]; 3],
1855    }
1856    fn batches(values: &[RetainedBatch]) -> Vec<BatchBits> {
1857        values
1858            .iter()
1859            .map(|b| BatchBits {
1860                integers: [
1861                    b.mesh,
1862                    b.first,
1863                    b.count,
1864                    b.depth,
1865                    b.material,
1866                    b.revision,
1867                    b.reserved[0],
1868                    b.reserved[1],
1869                ],
1870                floats: [
1871                    b.camera.map(f32::to_bits),
1872                    b.light.map(f32::to_bits),
1873                    b.params.map(f32::to_bits),
1874                ],
1875            })
1876            .collect()
1877    }
1878    #[derive(Debug, PartialEq, Eq)]
1879    struct MeshBits {
1880        id: u32,
1881        strong: usize,
1882        vertices: Vec<[u32; 10]>,
1883        skin: Option<Vec<[u32; 8]>>,
1884    }
1885    #[derive(Debug, PartialEq, Eq)]
1886    struct FrameBits {
1887        commands: Vec<[u32; 2]>,
1888        batches: Vec<BatchBits>,
1889        instances: Vec<[u32; 28]>,
1890        scratch_batches: Vec<BatchBits>,
1891        scratch_instances: Vec<[u32; 28]>,
1892        skin_matrices: Vec<[u32; 16]>,
1893        skin_normals: Vec<[u32; 9]>,
1894        effects: Vec<crate::effects::EffectBatch>,
1895        sprite_batches: Vec<crate::effects::SpriteBatch>,
1896        sprites: Vec<[u32; 16]>,
1897        meshes: Vec<MeshBits>,
1898        materials: Vec<(u32, usize)>,
1899        // Length, capacity and allocation address of every frame Vec.
1900        storage: Vec<(usize, usize, usize)>,
1901    }
1902    fn storage<T>(values: &Vec<T>) -> (usize, usize, usize) {
1903        (values.len(), values.capacity(), values.as_ptr() as usize)
1904    }
1905    fn snapshot() -> FrameBits {
1906        crate::read(|s| {
1907            let f = &s.retained;
1908            FrameBits {
1909                commands: f.commands.iter().map(|c| [c.kind, c.index]).collect(),
1910                batches: batches(&f.batches),
1911                instances: f.instances.iter().map(|v| v.map(f32::to_bits)).collect(),
1912                scratch_batches: batches(&f.scratch_batches),
1913                scratch_instances: f
1914                    .scratch_instances
1915                    .iter()
1916                    .map(|v| v.map(f32::to_bits))
1917                    .collect(),
1918                skin_matrices: f
1919                    .skin_matrices
1920                    .iter()
1921                    .map(|v| v.map(f32::to_bits))
1922                    .collect(),
1923                skin_normals: f.skin_normals.iter().map(|v| v.map(f32::to_bits)).collect(),
1924                effects: f.effects.clone(),
1925                sprite_batches: f.sprite_batches.clone(),
1926                sprites: f.sprites.iter().map(|v| v.map(f32::to_bits)).collect(),
1927                meshes: f
1928                    .keep_alive
1929                    .iter()
1930                    .map(|m| MeshBits {
1931                        id: m.id(),
1932                        strong: Rc::strong_count(&m.0),
1933                        vertices: m.0.vertices.iter().map(|v| v.map(f32::to_bits)).collect(),
1934                        skin: m
1935                            .0
1936                            .skin
1937                            .as_ref()
1938                            .map(|skin| skin.iter().map(|v| v.map(f32::to_bits)).collect()),
1939                    })
1940                    .collect(),
1941                materials: f
1942                    .keep_materials
1943                    .iter()
1944                    .map(|m| (m.id(), Rc::strong_count(&m.0)))
1945                    .collect(),
1946                storage: vec![
1947                    storage(&f.commands),
1948                    storage(&f.batches),
1949                    storage(&f.instances),
1950                    storage(&f.scratch_batches),
1951                    storage(&f.scratch_instances),
1952                    storage(&f.skin_matrices),
1953                    storage(&f.skin_normals),
1954                    storage(&f.effects),
1955                    storage(&f.sprite_batches),
1956                    storage(&f.sprites),
1957                    storage(&f.keep_alive),
1958                    storage(&f.keep_materials),
1959                ],
1960            }
1961        })
1962    }
1963    fn assert_rejected(input: &[(&ResidentMesh, Mat4)], index: usize, source: DrawError) {
1964        let before = snapshot();
1965        let telemetry = telemetry_snapshot();
1966        let visibility = crate::visibility_stats();
1967        let result = draw_residents_checked(input);
1968        assert_eq!(
1969            result,
1970            InstanceGroupReport {
1971                rejected: input.len(),
1972                error: Some(InstanceGroupError { index, source }),
1973                ..Default::default()
1974            }
1975        );
1976        assert_eq!(snapshot(), before);
1977        assert_eq!(crate::visibility_stats(), visibility);
1978        let after = telemetry_snapshot();
1979        assert_eq!(
1980            RetainedTelemetry {
1981                rejections: telemetry.rejections,
1982                ..after
1983            },
1984            telemetry
1985        );
1986        let mut expected = telemetry.rejections;
1987        let counter = if matches!(source, DrawError::InstanceCapacity { .. }) {
1988            &mut expected.instance_capacity
1989        } else {
1990            &mut expected.draw_validation
1991        };
1992        *counter = counter.saturating_add(1);
1993        assert_eq!(after.rejections, expected);
1994    }
1995
1996    #[test]
1997    fn group_uses_existing_adjacent_batches_and_immediate_order_barriers() {
1998        let a = mesh();
1999        let b = mesh();
2000        assert_eq!(draw_resident_checked(&a, Mat4::IDENTITY), Ok(true));
2001        crate::draw_triangle(
2002            crate::Vec2::ZERO,
2003            crate::Vec2::X,
2004            crate::Vec2::Y,
2005            crate::WHITE,
2006        );
2007        let model = Mat4::from_scale(Vec3::new(-2., 4., 8.));
2008        let report = draw_residents_checked(&[
2009            (&a, model),
2010            (&a, Mat4::IDENTITY),
2011            (&b, Mat4::from_translation(Vec3::Y)),
2012            (&a, Mat4::IDENTITY),
2013        ]);
2014        assert_eq!(
2015            report,
2016            InstanceGroupReport {
2017                accepted: 4,
2018                visible: 4,
2019                ..Default::default()
2020            }
2021        );
2022        crate::read(|s| {
2023            assert_eq!(
2024                s.retained
2025                    .commands
2026                    .iter()
2027                    .map(|c| c.kind)
2028                    .collect::<Vec<_>>(),
2029                [1, 0, 1, 1, 1]
2030            );
2031            assert_eq!(
2032                s.retained
2033                    .batches
2034                    .iter()
2035                    .map(|b| (b.first, b.count))
2036                    .collect::<Vec<_>>(),
2037                [(0, 1), (1, 2), (3, 1), (4, 1)]
2038            );
2039            let packed = &s.retained.instances[1];
2040            assert_eq!(&packed[..16], &model.to_cols_array());
2041            assert_eq!(
2042                &packed[16..],
2043                &[-0.5, 0., 0., 0., 0., 0.25, 0., 0., 0., 0., 0.125, 0.]
2044            );
2045            assert_eq!(std::mem::size_of::<RetainedBatch>(), 224);
2046            assert_eq!(std::mem::size_of_val(packed), 112);
2047        });
2048        crate::edit(|s| s.retained.finalize());
2049        crate::read(|s| {
2050            assert_eq!(
2051                s.retained
2052                    .commands
2053                    .iter()
2054                    .map(|c| c.kind)
2055                    .collect::<Vec<_>>(),
2056                [1, 0, 1, 1, 1]
2057            )
2058        });
2059    }
2060
2061    #[test]
2062    fn group_late_errors_preserve_all_buffers_bits_lifetimes_and_visibility() {
2063        let mesh = mesh();
2064        let source = Mesh3d::cuboid(Vec3::ONE, crate::WHITE).mesh;
2065        let skin =
2066            ResidentMesh::with_skin(&source, Some((&vec![[0.; 8]; source.vertices.len()], 1)))
2067                .unwrap();
2068        let palette = crate::skinning::SkinPalette::new(&[Mat4::IDENTITY.to_cols_array()]).unwrap();
2069        let material =
2070            crate::material::ShaderMaterial::new(Default::default(), Default::default()).unwrap();
2071        crate::edit(|s| {
2072            assert!(s.retained.record_style(
2073                &skin,
2074                Mat4::IDENTITY,
2075                s.matrix,
2076                false,
2077                DrawStyle {
2078                    material: Some(&material),
2079                    skin: Some(&palette),
2080                    ..Default::default()
2081                }
2082            ));
2083            s.retained.finalize(); // Leave genuine prior content in scratch buffers.
2084            assert!(s.retained.record(
2085                &mesh,
2086                Mat4::from_scale(Vec3::new(-2., 4., 8.)),
2087                s.matrix,
2088                false,
2089                None
2090            ));
2091            // Unrelated buffers and NaN/signed-zero payloads must also survive.
2092            s.retained.effects.push(crate::effects::EffectBatch {
2093                start: 0,
2094                count: 3,
2095                flags: 5,
2096            });
2097            s.retained.sprite_batches.push(crate::effects::SpriteBatch {
2098                first: 0,
2099                count: 1,
2100                flags: 5,
2101                triangles: 2,
2102            });
2103            let mut sprite = [-0.; 16];
2104            sprite[0] = f32::from_bits(0x7fc0_0284);
2105            s.retained.sprites.push(sprite);
2106            s.retained.batches[0].params[0] = f32::from_bits(0x7fc0_0184);
2107        });
2108        for (model, error) in [
2109            (Mat4::ZERO, DrawError::NonAffineModel { column: 3 }),
2110            (Mat4::from_scale(Vec3::ZERO), DrawError::NonInvertibleModel),
2111        ] {
2112            assert_rejected(
2113                &[
2114                    (&mesh, Mat4::IDENTITY),
2115                    (&mesh, Mat4::IDENTITY),
2116                    (&mesh, model),
2117                ],
2118                2,
2119                error,
2120            );
2121        }
2122        let mut nonfinite = Mat4::IDENTITY;
2123        nonfinite[2][1] = f32::NAN;
2124        assert_rejected(
2125            &[
2126                (&mesh, Mat4::IDENTITY),
2127                (&mesh, nonfinite),
2128                (&mesh, Mat4::ZERO),
2129            ],
2130            1,
2131            DrawError::NonFiniteModel { column: 2, row: 1 },
2132        );
2133        assert_rejected(
2134            &[(&mesh, Mat4::IDENTITY), (&skin, Mat4::IDENTITY)],
2135            1,
2136            DrawError::SkinPaletteMismatch {
2137                expected: 1,
2138                actual: 0,
2139            },
2140        );
2141        crate::edit(|s| s.matrix[3][2] = f32::INFINITY);
2142        assert_rejected(
2143            &[(&mesh, Mat4::IDENTITY)],
2144            0,
2145            DrawError::NonFiniteCamera { column: 3, row: 2 },
2146        );
2147    }
2148
2149    #[test]
2150    fn group_capacity_is_aggregate_atomic_and_recovers_after_clear() {
2151        let mesh = mesh();
2152        let other = mesh.clone();
2153        let input = vec![(&mesh, Mat4::IDENTITY); MAX_INSTANCES - 1];
2154        let result = draw_residents_checked(&input);
2155        assert_eq!(result.accepted, MAX_INSTANCES - 1);
2156        assert!(result.error.is_none());
2157        assert_eq!(telemetry_snapshot().draws, 1);
2158        // The first pair could merge into the previous batch; it must not do so.
2159        assert_rejected(
2160            &[(&mesh, Mat4::IDENTITY), (&other, Mat4::IDENTITY)],
2161            1,
2162            DrawError::InstanceCapacity {
2163                limit: MAX_INSTANCES,
2164            },
2165        );
2166        // Validation wins even after the capacity preflight observed overflow.
2167        assert_rejected(
2168            &[
2169                (&mesh, Mat4::IDENTITY),
2170                (&other, Mat4::IDENTITY),
2171                (&mesh, Mat4::ZERO),
2172            ],
2173            2,
2174            DrawError::NonAffineModel { column: 3 },
2175        );
2176        assert_eq!(draw_residents_checked(&input[..1]).accepted, 1);
2177        assert_rejected(
2178            &input[..1],
2179            0,
2180            DrawError::InstanceCapacity {
2181                limit: MAX_INSTANCES,
2182            },
2183        );
2184        let full = telemetry_snapshot();
2185        assert_eq!(full.instances, MAX_INSTANCES);
2186        crate::clear_background(crate::BLACK);
2187        assert_eq!(telemetry_snapshot().buffers, full.buffers);
2188        assert_eq!(telemetry_snapshot().rejections, full.rejections);
2189        assert_eq!(draw_residents_checked(&input[..2]).accepted, 2);
2190        assert_eq!(reset_telemetry(), full.rejections);
2191        assert_eq!(
2192            telemetry_snapshot().rejections,
2193            RetainedRejections::default()
2194        );
2195        crate::clear_background(crate::BLACK);
2196        let oversized = vec![(&mesh, Mat4::IDENTITY); MAX_INSTANCES + 1];
2197        assert_rejected(
2198            &oversized,
2199            MAX_INSTANCES,
2200            DrawError::InstanceCapacity {
2201                limit: MAX_INSTANCES,
2202            },
2203        );
2204    }
2205
2206    #[test]
2207    fn group_empty_and_saturated_activity_counters_keep_exact_entry_counts() {
2208        let mesh = mesh();
2209        REJECTIONS.with(|r| {
2210            r.set(RetainedRejections {
2211                draw_validation: u64::MAX,
2212                ..Default::default()
2213            })
2214        });
2215        assert_rejected(
2216            &[
2217                (&mesh, Mat4::IDENTITY),
2218                (&mesh, Mat4::ZERO),
2219                (&mesh, Mat4::ZERO),
2220            ],
2221            1,
2222            DrawError::NonAffineModel { column: 3 },
2223        );
2224        crate::edit(|s| s.matrix = Mat4::ZERO * f32::NAN);
2225        let before = snapshot();
2226        let telemetry = telemetry_snapshot();
2227        assert_eq!(draw_residents_checked(&[]), InstanceGroupReport::default());
2228        assert_eq!(snapshot(), before);
2229        assert_eq!(telemetry_snapshot(), telemetry);
2230        let error = InstanceGroupError {
2231            index: 7,
2232            source: DrawError::NonInvertibleModel,
2233        };
2234        assert!(error.to_string().contains("entry[7]"));
2235        assert_eq!(
2236            std::error::Error::source(&error).unwrap().to_string(),
2237            error.source.to_string()
2238        );
2239    }
2240
2241    #[test]
2242    fn group_preserves_resident_snapshots_duplicates_and_recorded_lifetimes() {
2243        let mut source = Mesh3d::cuboid(Vec3::ONE, crate::WHITE).mesh;
2244        let resident = ResidentMesh::try_new(&source).unwrap();
2245        let clone = resident.clone();
2246        let id = resident.id();
2247        let expected = resident.0.vertices.clone();
2248        source.vertices[0].position.x = f32::NAN;
2249        source.indices.clear();
2250        drop(resident);
2251        let dead = mesh();
2252        let dead_id = dead.id();
2253        drop(dead);
2254        assert!(geometry(dead_id).is_none());
2255        let before = telemetry_snapshot();
2256        let result = draw_residents_checked(&[
2257            (&clone, Mat4::IDENTITY),
2258            (&clone, Mat4::from_translation(Vec3::X)),
2259        ]);
2260        assert_eq!(
2261            (
2262                result.accepted,
2263                result.rejected,
2264                result.culled,
2265                result.visible
2266            ),
2267            (2, 0, 0, 2)
2268        );
2269        assert_eq!(telemetry_snapshot().live_meshes, before.live_meshes);
2270        assert_eq!(telemetry_snapshot().mesh_bytes, before.mesh_bytes);
2271        crate::read(|s| {
2272            assert_eq!(s.retained.keep_alive.len(), 1);
2273            assert_eq!(s.retained.batches[0].count, 2);
2274            assert_eq!(s.retained.instances[1][12], 1.);
2275            assert_eq!(s.retained.keep_alive[0].0.vertices, expected);
2276        });
2277        let rejected = mesh();
2278        let rejected_id = rejected.id();
2279        assert_rejected(
2280            &[(&rejected, Mat4::IDENTITY), (&clone, Mat4::ZERO)],
2281            1,
2282            DrawError::NonAffineModel { column: 3 },
2283        );
2284        drop(rejected);
2285        assert!(geometry(rejected_id).is_none());
2286        drop(clone);
2287        assert_eq!(geometry(id).unwrap().vertices, expected);
2288        crate::clear_background(crate::BLACK);
2289        assert!(geometry(id).is_none());
2290        assert!(mesh().id() > rejected_id);
2291    }
2292
2293    #[test]
2294    fn group_retains_legacy_full_inverse_validation_boundary() {
2295        let resident = mesh();
2296        let mut model = Mat4::from_scale(Vec3::new(1e-20, 1., 1.));
2297        model.w_axis.x = f32::MAX;
2298        assert!(ferravex_math::affine::PreparedAffine3D::try_new(model).is_ok());
2299        assert_eq!(
2300            validate_transform(model),
2301            Err(DrawError::NonInvertibleModel)
2302        );
2303        assert_rejected(
2304            &[(&resident, Mat4::IDENTITY), (&resident, model)],
2305            1,
2306            DrawError::NonInvertibleModel,
2307        );
2308    }
2309
2310    #[test]
2311    fn group_matches_single_draw_recording_culling_shadows_materials_and_finalization() {
2312        use crate::material::{BlendMode, MaterialOptions, ShaderMaterial};
2313        let opaque = mesh();
2314        let transparent = ResidentMesh::try_new(
2315            &Mesh3d::cuboid(Vec3::ONE, crate::Color::new(1., 1., 1., 0.5)).mesh,
2316        )
2317        .unwrap();
2318        let mut reflected_shear = Mat4::from_scale(Vec3::new(-0.5, 0.25, 0.5));
2319        reflected_shear.y_axis.x = 0.125;
2320        for depth in [false, true] {
2321            for mesh in [&opaque, &transparent] {
2322                for blend in [BlendMode::Opaque, BlendMode::Alpha, BlendMode::Additive] {
2323                    for casts_shadows in [false, true] {
2324                        for bounds_padding in [0., 4.] {
2325                            for max_distance in [None, Some(1.)] {
2326                                let material = ShaderMaterial::new(
2327                                    Default::default(),
2328                                    MaterialOptions {
2329                                        blend,
2330                                        bounds_padding,
2331                                        casts_shadows,
2332                                        receives_shadows: false,
2333                                    },
2334                                )
2335                                .unwrap();
2336                                crate::edit(|s| {
2337                                    s.retained.clear();
2338                                    s.visibility_stats = Default::default();
2339                                    s.matrix = Mat4::IDENTITY;
2340                                    s.depth = depth;
2341                                    s.frustum = depth.then(|| {
2342                                        ferravex_graphics::Frustum::from_matrix(
2343                                            Mat4::IDENTITY,
2344                                            ferravex_graphics::ClipDepth::NegativeOneToOne,
2345                                        )
2346                                        .unwrap()
2347                                    });
2348                                    s.shadow_frustum = ferravex_graphics::Frustum::from_matrix(
2349                                        Mat4::from_scale(Vec3::splat(0.1)),
2350                                        ferravex_graphics::ClipDepth::NegativeOneToOne,
2351                                    );
2352                                    s.eye = Some(Vec3::ZERO);
2353                                    s.visibility = crate::visibility::VisibilitySettings {
2354                                        frustum_culling: true,
2355                                        max_distance,
2356                                    };
2357                                    s.shader = Some(material.clone());
2358                                    s.shader_params = [0.25; 16];
2359                                    s.lighting = Some(Default::default());
2360                                });
2361                                let input = [
2362                                    (mesh, reflected_shear),
2363                                    (mesh, Mat4::IDENTITY),
2364                                    (&opaque, Mat4::from_translation(Vec3::X * 4.)),
2365                                    (mesh, Mat4::from_translation(Vec3::X * 100.)),
2366                                ];
2367                                let mut visible = 0;
2368                                for &(m, model) in &input {
2369                                    visible +=
2370                                        usize::from(draw_resident_checked(m, model).unwrap());
2371                                }
2372                                let expected = snapshot();
2373                                let stats = crate::visibility_stats();
2374                                let accepted = expected.instances.len();
2375                                crate::edit(|s| {
2376                                    s.retained.finalize();
2377                                });
2378                                let finalized = snapshot();
2379                                crate::edit(|s| {
2380                                    s.retained.clear();
2381                                    s.visibility_stats = Default::default();
2382                                });
2383                                let group = draw_residents_checked(&input);
2384                                assert_eq!(
2385                                    group,
2386                                    InstanceGroupReport {
2387                                        accepted,
2388                                        visible,
2389                                        culled: input.len() - accepted,
2390                                        ..Default::default()
2391                                    }
2392                                );
2393                                assert_eq!(crate::visibility_stats(), stats);
2394                                let actual = snapshot();
2395                                assert_eq!(actual.commands, expected.commands);
2396                                assert_eq!(actual.batches, expected.batches);
2397                                assert_eq!(actual.instances, expected.instances);
2398                                assert_eq!(actual.meshes, expected.meshes);
2399                                assert_eq!(actual.materials, expected.materials);
2400                                crate::edit(|s| {
2401                                    s.retained.finalize();
2402                                });
2403                                let actual = snapshot();
2404                                assert_eq!(actual.commands, finalized.commands);
2405                                assert_eq!(actual.batches, finalized.batches);
2406                                assert_eq!(actual.instances, finalized.instances);
2407                            }
2408                        }
2409                    }
2410                }
2411            }
2412        }
2413    }
2414
2415    #[test]
2416    fn group_capacity_counts_visible_and_shadow_instances_but_not_complete_culls() {
2417        let mesh = mesh();
2418        let input = vec![(&mesh, Mat4::IDENTITY); MAX_INSTANCES - 1];
2419        assert_eq!(draw_residents_checked(&input).accepted, input.len());
2420        crate::edit(|s| {
2421            s.depth = true;
2422            s.frustum = ferravex_graphics::Frustum::from_matrix(
2423                Mat4::IDENTITY,
2424                ferravex_graphics::ClipDepth::NegativeOneToOne,
2425            );
2426            s.shadow_frustum = ferravex_graphics::Frustum::from_matrix(
2427                Mat4::from_scale(Vec3::splat(0.1)),
2428                ferravex_graphics::ClipDepth::NegativeOneToOne,
2429            );
2430        });
2431        let outside = Mat4::from_translation(Vec3::X * 100.);
2432        let shadow = Mat4::from_translation(Vec3::X * 4.);
2433        assert_rejected(
2434            &[(&mesh, outside), (&mesh, shadow), (&mesh, Mat4::IDENTITY)],
2435            2,
2436            DrawError::InstanceCapacity {
2437                limit: MAX_INSTANCES,
2438            },
2439        );
2440        let report = draw_residents_checked(&[(&mesh, outside), (&mesh, shadow)]);
2441        assert_eq!(
2442            report,
2443            InstanceGroupReport {
2444                accepted: 1,
2445                culled: 1,
2446                ..Default::default()
2447            }
2448        );
2449        crate::read(|s| assert_eq!(s.retained.batches.last().unwrap().depth & 32, 32));
2450        let full = telemetry_snapshot();
2451        assert_eq!(full.instances, MAX_INSTANCES);
2452        // Even a full frame may process a group needing no instance storage.
2453        assert_eq!(
2454            draw_residents_checked(&[(&mesh, outside)]),
2455            InstanceGroupReport {
2456                culled: 1,
2457                ..Default::default()
2458            }
2459        );
2460        assert_eq!(telemetry_snapshot(), full);
2461        assert_rejected(
2462            &[(&mesh, outside), (&mesh, Mat4::IDENTITY)],
2463            1,
2464            DrawError::InstanceCapacity {
2465                limit: MAX_INSTANCES,
2466            },
2467        );
2468    }
2469}