sim_logic/rendering/three_d/
mesh.rs1use 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#[derive(Debug, Clone)]
22pub struct MeshAsset3d {
23 mesh: Mesh3d,
24}
25
26impl MeshAsset3d {
27 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 pub fn mesh(&self) -> &Mesh3d {
42 &self.mesh
43 }
44
45 pub fn source_bytes(&self) -> usize {
47 self.mesh.recovery_memory_bytes()
48 }
49
50 pub fn shares_storage(&self, other: &Self) -> bool {
52 self.key() == other.key()
53 }
54
55 pub(crate) fn key(&self) -> usize {
56 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#[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 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 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 pub const fn asset(&self) -> &MeshAsset3d {
117 &self.asset
118 }
119
120 pub const fn transform(&self) -> Transform3d {
122 self.transform
123 }
124
125 pub const fn color(&self) -> Color {
127 self.surface.color()
128 }
129
130 pub const fn surface(&self) -> SurfaceStyle3d {
132 self.surface
133 }
134
135 pub const fn texture(&self) -> Option<&TextureVisual3d> {
137 self.texture.as_ref()
138 }
139
140 pub const fn visible(&self) -> bool {
142 self.visible
143 }
144
145 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 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 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 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 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 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 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#[derive(Debug, Clone, Copy, PartialEq)]
253pub enum MeshVisualError {
254 UnsupportedTopology,
256 Geometry(Pseudo3dError),
258 Style(Mesh3dStyleError),
260 CollapsedGeometry,
262 MissingNormals,
264 MissingTextureCoordinates,
266 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}