Skip to main content

sim_logic/rendering/three_d/
extraction.rs

1use std::{error::Error, fmt, mem::size_of};
2
3use sim_engine::{Color, Transform3d};
4
5use crate::identity::{LogicEntity, WorldGeneration};
6
7use super::{CuboidVisual3d, CuboidVisualError, MeshSource, ResolvedMesh3d, View3d, View3dError};
8
9/// Frozen opt-in limits for geometry, textures and the desktop 3D passes.
10///
11/// Defaults are all zero. Every visible cuboid consumes twelve triangles and
12/// at most twenty-four edge segments when both wireframe modes are selected.
13/// Target pixels include one color and one depth attachment; mesh upload and
14/// prepass work are separate from the final FrameBudget. The final composition
15/// additionally consumes one target pass and its color texture byte allowance.
16#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
17pub struct ThreeDRenderLimits {
18    max_cuboids: usize,
19    max_triangles: usize,
20    max_target_pixels: u64,
21    max_meshes: usize,
22    max_mesh_source_bytes: usize,
23    max_texture_source_bytes: usize,
24    max_texture_gpu_bytes: usize,
25}
26
27impl ThreeDRenderLimits {
28    /// Sets exact inclusive object, surface-triangle, and physical-pixel caps.
29    pub const fn new(max_cuboids: usize, max_triangles: usize, max_target_pixels: u64) -> Self {
30        Self {
31            max_cuboids,
32            max_triangles,
33            max_target_pixels,
34            max_meshes: 0,
35            max_mesh_source_bytes: 0,
36            max_texture_source_bytes: 0,
37            max_texture_gpu_bytes: 0,
38        }
39    }
40
41    /// Returns the maximum visible cuboid count and retained scene slot count.
42    pub const fn max_cuboids(self) -> usize {
43        self.max_cuboids
44    }
45
46    /// Returns the maximum submitted surface triangle count.
47    pub const fn max_triangles(self) -> usize {
48        self.max_triangles
49    }
50
51    /// Returns the maximum physical width times height of the depth target.
52    pub const fn max_target_pixels(self) -> u64 {
53        self.max_target_pixels
54    }
55
56    /// Enables custom meshes with inclusive instance and CPU-source caps.
57    ///
58    /// Source capacities are conservatively charged once per visible instance,
59    /// even when instances share an asset. Triangle limits include both cuboids
60    /// and custom meshes. Hidden/disabled meshes consume none of these limits.
61    /// Engine's additional finite GPU/upload/scene-memory limits still apply.
62    pub const fn with_mesh_limits(mut self, max_meshes: usize, max_source_bytes: usize) -> Self {
63        self.max_meshes = max_meshes;
64        self.max_mesh_source_bytes = max_source_bytes;
65        self
66    }
67
68    /// Returns the maximum visible custom-mesh instance count.
69    pub const fn max_meshes(self) -> usize {
70        self.max_meshes
71    }
72
73    /// Returns the summed per-instance topology-capacity allowance.
74    pub const fn max_mesh_source_bytes(self) -> usize {
75        self.max_mesh_source_bytes
76    }
77
78    /// Enables textures with inclusive base-source and complete-mip texel caps.
79    /// Both are conservatively charged per visible instance, including shared
80    /// images. Engine additionally bounds its CPU mip storage, GPU resources and
81    /// transient updates; these caps do not claim to measure driver allocations.
82    pub const fn with_texture_limits(
83        mut self,
84        max_source_bytes: usize,
85        max_gpu_bytes: usize,
86    ) -> Self {
87        self.max_texture_source_bytes = max_source_bytes;
88        self.max_texture_gpu_bytes = max_gpu_bytes;
89        self
90    }
91
92    /// Returns the per-visible-instance summed base-pixel capacity allowance.
93    pub const fn max_texture_source_bytes(self) -> usize {
94        self.max_texture_source_bytes
95    }
96
97    /// Returns the per-visible-instance summed nominal full-mip texel allowance.
98    pub const fn max_texture_gpu_bytes(self) -> usize {
99        self.max_texture_gpu_bytes
100    }
101}
102
103/// Identifies which independent 3D work limit was exceeded.
104#[derive(Debug, Clone, Copy, PartialEq, Eq)]
105pub enum ThreeDLimitResource {
106    /// Visible extracted cuboids and retained desktop scene slots.
107    Cuboids,
108    /// Visible custom-mesh instances.
109    Meshes,
110    /// CPU topology capacities charged once per visible custom-mesh instance.
111    MeshSourceBytes,
112    /// Base texture pixel capacities charged per visible textured mesh instance.
113    TextureSourceBytes,
114    /// Nominal complete-chain texture bytes charged per visible instance.
115    TextureGpuBytes,
116    /// Filled surface triangles from cuboids and custom meshes.
117    Triangles,
118    /// Physical pixels in the color/depth target pair.
119    TargetPixels,
120}
121
122/// One validated current-value cuboid, retaining its managed source identity.
123#[derive(Debug, Clone, Copy, PartialEq)]
124pub struct ResolvedCuboid3d {
125    source: LogicEntity,
126    visual: CuboidVisual3d,
127}
128
129impl ResolvedCuboid3d {
130    /// Returns the managed entity that produced this cuboid.
131    pub const fn source(self) -> LogicEntity {
132        self.source
133    }
134
135    /// Returns the complete validated presentation value.
136    pub const fn visual(self) -> CuboidVisual3d {
137        self.visual
138    }
139
140    /// Returns the sampled world transform, with no interpolation.
141    pub const fn transform(self) -> Transform3d {
142        self.visual.transform()
143    }
144
145    /// Returns the normalized opaque surface color.
146    pub const fn color(self) -> Color {
147        self.visual.color()
148    }
149}
150
151/// Borrowed complete enabled 3D view from a published CPU frame.
152///
153/// A view may be enabled with no objects, in which case its background still
154/// renders. Missing or disabled views have no snapshot and require no prepass.
155#[derive(Debug, Clone, Copy)]
156pub struct ThreeDSnapshot<'a> {
157    view: View3d,
158    cuboids: &'a [ResolvedCuboid3d],
159    meshes: &'a [ResolvedMesh3d],
160}
161
162impl<'a> ThreeDSnapshot<'a> {
163    /// Returns the enabled camera, environment and normalized RGBA clear descriptor.
164    pub const fn view(self) -> View3d {
165        self.view
166    }
167
168    /// Returns visible cuboids in stable managed-identity extraction order.
169    pub const fn cuboids(self) -> &'a [ResolvedCuboid3d] {
170        self.cuboids
171    }
172
173    /// Returns surface meshes in stable managed-identity extraction order.
174    pub const fn meshes(self) -> &'a [ResolvedMesh3d] {
175        self.meshes
176    }
177
178    /// Returns original surface triangles before Engine's view-dependent clipping.
179    pub fn source_triangle_count(self) -> usize {
180        self.meshes
181            .iter()
182            .fold(self.cuboids.len().saturating_mul(12), |sum, mesh| {
183                sum.saturating_add(mesh.visual().asset().mesh().triangle_count())
184            })
185    }
186}
187
188#[derive(Debug, Clone, Copy)]
189pub(crate) struct CuboidSource {
190    entity: LogicEntity,
191    visual: CuboidVisual3d,
192}
193
194impl CuboidSource {
195    pub(crate) const fn new(entity: LogicEntity, visual: &CuboidVisual3d) -> Self {
196        Self {
197            entity,
198            visual: *visual,
199        }
200    }
201}
202
203pub(crate) struct ThreeDExtractionBuffer {
204    view: Option<View3d>,
205    resolved: Vec<ResolvedCuboid3d>,
206    pub(super) meshes: Vec<ResolvedMesh3d>,
207}
208
209impl ThreeDExtractionBuffer {
210    pub(crate) const fn new() -> Self {
211        Self {
212            view: None,
213            resolved: Vec::new(),
214            meshes: Vec::new(),
215        }
216    }
217
218    pub(crate) fn clear(&mut self) {
219        self.view = None;
220        self.resolved.clear();
221        self.meshes.clear();
222    }
223
224    pub(crate) fn extract(
225        &mut self,
226        generation: WorldGeneration,
227        limits: ThreeDRenderLimits,
228        view: Option<View3d>,
229        sources: impl IntoIterator<Item = CuboidSource>,
230    ) -> Result<(), ThreeDExtractionError> {
231        self.clear();
232        let Some(view) = view.filter(|view| view.enabled()) else {
233            return Ok(());
234        };
235        view.validate().map_err(ThreeDExtractionError::View)?;
236        for source in sources {
237            if !source.visual.visible() {
238                continue;
239            }
240            if source.entity.world_generation() != generation {
241                return Err(ThreeDExtractionError::StaleEntity {
242                    source: source.entity,
243                });
244            }
245            let count = self.resolved.len().saturating_add(1);
246            check_limit(ThreeDLimitResource::Cuboids, count, limits.max_cuboids)?;
247            let triangles = count
248                .checked_mul(12)
249                .ok_or(ThreeDExtractionError::LimitExceeded {
250                    resource: ThreeDLimitResource::Triangles,
251                    requested: u64::MAX,
252                    limit: limits.max_triangles as u64,
253                })?;
254            check_limit(
255                ThreeDLimitResource::Triangles,
256                triangles,
257                limits.max_triangles,
258            )?;
259            source
260                .visual
261                .validate()
262                .map_err(|error| ThreeDExtractionError::Cuboid {
263                    source: source.entity,
264                    error,
265                })?;
266            if self.resolved.len() == self.resolved.capacity() {
267                self.resolved.try_reserve_exact(1).map_err(|_| {
268                    ThreeDExtractionError::AllocationFailed {
269                        requested_bytes: size_of::<ResolvedCuboid3d>(),
270                    }
271                })?;
272            }
273            self.resolved.push(ResolvedCuboid3d {
274                source: source.entity,
275                visual: source.visual,
276            });
277        }
278        self.resolved
279            .sort_unstable_by_key(|record| record.source.stable_bits());
280        self.view = Some(view);
281        Ok(())
282    }
283
284    pub(crate) fn snapshot(&self) -> Option<ThreeDSnapshot<'_>> {
285        self.view.map(|view| ThreeDSnapshot {
286            view,
287            cuboids: &self.resolved,
288            meshes: &self.meshes,
289        })
290    }
291
292    pub(crate) fn resolved(&self) -> &[ResolvedCuboid3d] {
293        &self.resolved
294    }
295
296    pub(crate) fn extract_meshes(
297        &mut self,
298        generation: WorldGeneration,
299        limits: ThreeDRenderLimits,
300        sources: impl IntoIterator<Item = MeshSource>,
301    ) -> Result<(), ThreeDExtractionError> {
302        if self.view.is_none() {
303            return Ok(());
304        }
305        if let Err(error) = super::mesh_extraction::extract_meshes(
306            &mut self.meshes,
307            generation,
308            limits,
309            self.resolved.len().saturating_mul(12),
310            sources,
311        ) {
312            self.view = None;
313            return Err(error);
314        }
315        Ok(())
316    }
317}
318
319pub(super) fn check_limit(
320    resource: ThreeDLimitResource,
321    requested: usize,
322    limit: usize,
323) -> Result<(), ThreeDExtractionError> {
324    if requested > limit {
325        return Err(ThreeDExtractionError::LimitExceeded {
326            resource,
327            requested: requested as u64,
328            limit: limit as u64,
329        });
330    }
331    Ok(())
332}
333
334/// A complete 3D CPU snapshot could not be produced within its frozen contract.
335#[derive(Debug, Clone, Copy, PartialEq)]
336pub enum ThreeDExtractionError {
337    /// A visible cuboid belonged to a different World or application.
338    StaleEntity {
339        /// Rejected managed source identity.
340        source: LogicEntity,
341    },
342    /// A configured independent 3D work cap was exceeded.
343    LimitExceeded {
344        /// Resource that would exceed its cap.
345        resource: ThreeDLimitResource,
346        /// Work requested by this snapshot.
347        requested: u64,
348        /// Frozen application cap.
349        limit: u64,
350    },
351    /// The camera or opaque clear descriptor was invalid.
352    View(View3dError),
353    /// A visible cuboid could not be represented by portable CPU geometry.
354    Cuboid {
355        /// Managed source whose geometry failed validation.
356        source: LogicEntity,
357        /// Concrete value failure.
358        error: CuboidVisualError,
359    },
360    /// Bounded CPU metadata storage could not be reserved.
361    AllocationFailed {
362        /// Minimum additional requested allocation bytes.
363        requested_bytes: usize,
364    },
365}
366
367impl fmt::Display for ThreeDExtractionError {
368    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
369        match self {
370            Self::StaleEntity { source } => {
371                write!(formatter, "3D source {source:?} is from a stale World")
372            }
373            Self::LimitExceeded {
374                resource,
375                requested,
376                limit,
377            } => write!(
378                formatter,
379                "3D {resource:?} requested {requested}, exceeding {limit}"
380            ),
381            Self::View(error) => write!(formatter, "3D view extraction failed: {error}"),
382            Self::Cuboid { source, error } => {
383                write!(formatter, "3D cuboid {source:?} extraction failed: {error}")
384            }
385            Self::AllocationFailed { requested_bytes } => write!(
386                formatter,
387                "3D extraction could not reserve {requested_bytes} additional bytes"
388            ),
389        }
390    }
391}
392
393impl Error for ThreeDExtractionError {
394    fn source(&self) -> Option<&(dyn Error + 'static)> {
395        match self {
396            Self::View(error) => Some(error),
397            Self::Cuboid { error, .. } => Some(error),
398            _ => None,
399        }
400    }
401}