Skip to main content

sim_logic/rendering/three_d/
mesh.rs

1//! Immutable host-built topology, without GPU ownership or a second renderer.
2
3use std::{error::Error, fmt};
4
5use bevy_ecs::prelude::Component;
6#[cfg(feature = "desktop")]
7use sim_engine::MeshStyle3d;
8use sim_engine::{
9    Color, Mesh3d, Mesh3dStyleError, Pseudo3dError, SurfaceAlphaMode3d, SurfaceLighting3d,
10    SurfaceStyle3d, Transform3d,
11};
12
13use super::TextureVisual3d;
14
15/// Shared immutable surface topology built by the application.
16///
17/// Cloning shares Engine's CPU allocation in constant time. Construct a new
18/// asset after editing geometry; unchanged clones reuse one retained desktop
19/// mesh. Asset identity is allocation identity, not content equality. The host
20/// owns mesh generation, including chunk boundaries and hidden-face removal.
21#[derive(Debug, Clone)]
22pub struct MeshAsset3d {
23    mesh: Mesh3d,
24}
25
26impl MeshAsset3d {
27    /// Accepts validated Engine topology without allocating GPU resources.
28    ///
29    /// UVs, colors and normals retain Engine's validated attribute contracts.
30    /// Edge-only meshes are not supported. Display edges may be present but are
31    /// not drawn. Caller-owned
32    /// assets are not application-budgeted until visible extraction uses them.
33    pub fn new(mesh: Mesh3d) -> Result<Self, MeshVisualError> {
34        if mesh.triangle_count() == 0 {
35            return Err(MeshVisualError::UnsupportedTopology);
36        }
37        Ok(Self { mesh })
38    }
39
40    /// Returns immutable Engine topology in caller-defined model-space units.
41    pub fn mesh(&self) -> &Mesh3d {
42        &self.mesh
43    }
44
45    /// Returns retained CPU topology capacities, using Engine's accounting.
46    pub fn source_bytes(&self) -> usize {
47        self.mesh.recovery_memory_bytes()
48    }
49
50    /// Returns whether both assets share the same immutable source allocation.
51    pub fn shares_storage(&self, other: &Self) -> bool {
52        self.key() == other.key()
53    }
54
55    pub(crate) fn key(&self) -> usize {
56        // Engine meshes have a nonempty immutable vertex allocation. Keep an
57        // owning mesh alongside every cached key so an address cannot be reused
58        // while it still names a live entry. No pointer is dereferenced here.
59        self.mesh.vertices().as_ptr() as usize
60    }
61}
62
63impl PartialEq for MeshAsset3d {
64    fn eq(&self, other: &Self) -> bool {
65        self.shares_storage(other)
66    }
67}
68
69impl Eq for MeshAsset3d {}
70
71/// One transformed instance of an immutable host-built surface mesh.
72///
73/// The constructor and geometry setters validate transformed vertices and
74/// triangles before changing state. Extraction then clones only shared handles;
75/// it does not rebuild topology or interpolate transforms. Engine remains
76/// responsible for view-dependent clipping and GPU validation.
77#[derive(Debug, Clone, PartialEq, Component)]
78pub struct MeshVisual3d {
79    asset: MeshAsset3d,
80    transform: Transform3d,
81    surface: SurfaceStyle3d,
82    texture: Option<TextureVisual3d>,
83    visible: bool,
84}
85
86impl MeshVisual3d {
87    /// Creates an opaque mesh instance after CPU geometry validation.
88    pub fn new(
89        asset: MeshAsset3d,
90        transform: Transform3d,
91        color: Color,
92    ) -> Result<Self, MeshVisualError> {
93        Self::with_surface(asset, transform, SurfaceStyle3d::opaque(color)?)
94    }
95
96    /// Creates an Opaque, Mask or Blend mesh with explicit Engine surface policy.
97    /// Lambert requires host-supplied normals. View-dependent arithmetic remains
98    /// Engine's responsibility; this constructor does not duplicate GPU proofs.
99    pub fn with_surface(
100        asset: MeshAsset3d,
101        transform: Transform3d,
102        surface: SurfaceStyle3d,
103    ) -> Result<Self, MeshVisualError> {
104        validate_transform(&asset, transform)?;
105        validate_attributes(&asset, surface, None)?;
106        Ok(Self {
107            asset,
108            transform,
109            surface,
110            texture: None,
111            visible: true,
112        })
113    }
114
115    /// Returns the shared immutable source topology.
116    pub const fn asset(&self) -> &MeshAsset3d {
117        &self.asset
118    }
119
120    /// Returns the current model-to-world transform.
121    pub const fn transform(&self) -> Transform3d {
122        self.transform
123    }
124
125    /// Returns normalized straight-linear surface tint, including surface alpha.
126    pub const fn color(&self) -> Color {
127        self.surface.color()
128    }
129
130    /// Returns alpha, sidedness, lighting and fog policy plus surface tint.
131    pub const fn surface(&self) -> SurfaceStyle3d {
132        self.surface
133    }
134
135    /// Returns optional immutable texture pixels and independent sampling state.
136    pub const fn texture(&self) -> Option<&TextureVisual3d> {
137        self.texture.as_ref()
138    }
139
140    /// Reports whether an enabled entity participates in 3D extraction.
141    pub const fn visible(&self) -> bool {
142        self.visible
143    }
144
145    /// Replaces topology atomically; invalid transformed geometry changes nothing.
146    pub fn set_asset(&mut self, asset: MeshAsset3d) -> Result<(), MeshVisualError> {
147        validate_transform(&asset, self.transform)?;
148        validate_attributes(&asset, self.surface, self.texture.as_ref())?;
149        self.asset = asset;
150        Ok(())
151    }
152
153    /// Replaces the model-to-world transform, or preserves the previous value.
154    pub fn set_transform(&mut self, transform: Transform3d) -> Result<(), MeshVisualError> {
155        validate_transform(&self.asset, transform)?;
156        self.transform = transform;
157        Ok(())
158    }
159
160    /// Replaces normalized surface tint while preserving alpha/lighting/fog policy.
161    /// Opaque surfaces still reject alpha other than one. Failure changes nothing.
162    pub fn set_color(&mut self, color: Color) -> Result<(), MeshVisualError> {
163        let surface = match self.surface.alpha_mode() {
164            SurfaceAlphaMode3d::Opaque => SurfaceStyle3d::opaque(color)?,
165            SurfaceAlphaMode3d::Mask => SurfaceStyle3d::mask(
166                color,
167                self.surface
168                    .mask_cutoff()
169                    .ok_or(MeshVisualError::UnsupportedSurface)?,
170            )?,
171            SurfaceAlphaMode3d::Blend => SurfaceStyle3d::blend(color)?,
172            _ => return Err(MeshVisualError::UnsupportedSurface),
173        }
174        .with_sidedness(self.surface.sidedness())
175        .with_lighting(self.surface.lighting())
176        .with_fog(self.surface.fog_enabled());
177        self.set_surface(surface)
178    }
179
180    /// Replaces the complete surface policy, preserving geometry and texture.
181    /// Enabling Lambert without model normals is rejected atomically.
182    pub fn set_surface(&mut self, surface: SurfaceStyle3d) -> Result<(), MeshVisualError> {
183        validate_attributes(&self.asset, surface, self.texture.as_ref())?;
184        self.surface = surface;
185        Ok(())
186    }
187
188    /// Attaches or removes a texture. Attaching requires one UV per mesh vertex.
189    /// Pixel snapshots are shared; no upload or image copying occurs here.
190    pub fn set_texture(&mut self, texture: Option<TextureVisual3d>) -> Result<(), MeshVisualError> {
191        validate_attributes(&self.asset, self.surface, texture.as_ref())?;
192        self.texture = texture;
193        Ok(())
194    }
195
196    /// Changes visibility without discarding the host's CPU asset.
197    pub fn set_visible(&mut self, visible: bool) {
198        self.visible = visible;
199    }
200
201    #[cfg(feature = "desktop")]
202    pub(crate) fn style(&self) -> Result<MeshStyle3d, MeshVisualError> {
203        Ok(MeshStyle3d::surface(self.surface))
204    }
205}
206
207fn validate_attributes(
208    asset: &MeshAsset3d,
209    surface: SurfaceStyle3d,
210    texture: Option<&TextureVisual3d>,
211) -> Result<(), MeshVisualError> {
212    if surface.lighting() == SurfaceLighting3d::Lambert && asset.mesh.normals().is_empty() {
213        return Err(MeshVisualError::MissingNormals);
214    }
215    if texture.is_some() && asset.mesh.texture_coordinates().is_empty() {
216        return Err(MeshVisualError::MissingTextureCoordinates);
217    }
218    Ok(())
219}
220
221fn validate_transform(asset: &MeshAsset3d, transform: Transform3d) -> Result<(), MeshVisualError> {
222    // Validate even unused vertices: Engine uploads the entire source array.
223    for vertex in asset.mesh.vertices() {
224        transform.transform_point(*vertex)?;
225    }
226    for indices in asset.mesh.triangle_indices().chunks_exact(3) {
227        let mut points = [[0.0_f64; 3]; 3];
228        for (point, index) in points.iter_mut().zip(indices) {
229            let vertex = transform.transform_point(asset.mesh.vertices()[*index as usize])?;
230            *point = [
231                f64::from(vertex.x()),
232                f64::from(vertex.y()),
233                f64::from(vertex.z()),
234            ];
235        }
236        let [a, b, c] = points;
237        let u = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
238        let v = [c[0] - a[0], c[1] - a[1], c[2] - a[2]];
239        if [
240            u[1] * v[2] - u[2] * v[1],
241            u[2] * v[0] - u[0] * v[2],
242            u[0] * v[1] - u[1] * v[0],
243        ] == [0.0; 3]
244        {
245            return Err(MeshVisualError::CollapsedGeometry);
246        }
247    }
248    Ok(())
249}
250
251/// A managed mesh could not represent its requested presentation.
252#[derive(Debug, Clone, Copy, PartialEq)]
253pub enum MeshVisualError {
254    /// Topology has no filled surface triangles.
255    UnsupportedTopology,
256    /// Invalid or overflowing model-to-world arithmetic.
257    Geometry(Pseudo3dError),
258    /// Surface color or alpha settings were invalid for their selected policy.
259    Style(Mesh3dStyleError),
260    /// A transformed filled triangle collapsed in floating-point coordinates.
261    CollapsedGeometry,
262    /// Lambert shading requires host-supplied model normals.
263    MissingNormals,
264    /// A texture requires host-supplied UVs on the mesh.
265    MissingTextureCoordinates,
266    /// An Engine surface mode is not understood by this Logic integration.
267    UnsupportedSurface,
268}
269
270impl From<Pseudo3dError> for MeshVisualError {
271    fn from(error: Pseudo3dError) -> Self {
272        Self::Geometry(error)
273    }
274}
275
276impl From<Mesh3dStyleError> for MeshVisualError {
277    fn from(error: Mesh3dStyleError) -> Self {
278        Self::Style(error)
279    }
280}
281
282impl fmt::Display for MeshVisualError {
283    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
284        match self {
285            Self::UnsupportedTopology => {
286                formatter.write_str("managed meshes require filled surface topology")
287            }
288            Self::Geometry(error) => write!(formatter, "invalid mesh transform: {error}"),
289            Self::Style(error) => write!(formatter, "invalid mesh style: {error}"),
290            Self::CollapsedGeometry => {
291                formatter.write_str("transformed mesh triangle collapses in f32")
292            }
293            Self::MissingNormals => {
294                formatter.write_str("Lambert mesh surface requires model normals")
295            }
296            Self::MissingTextureCoordinates => {
297                formatter.write_str("textured mesh surface requires UV coordinates")
298            }
299            Self::UnsupportedSurface => formatter.write_str("unsupported Engine surface policy"),
300        }
301    }
302}
303
304impl Error for MeshVisualError {
305    fn source(&self) -> Option<&(dyn Error + 'static)> {
306        match self {
307            Self::Geometry(error) => Some(error),
308            Self::Style(error) => Some(error),
309            _ => None,
310        }
311    }
312}