//! Mesh objects. use std::f32::consts::PI; use std::{io, mem}; use ombre::bytes::encoding::{Decode, Encode}; use ombre::derive::Packed; use ombre::prelude::*; /// File extension for XYZW meshes. #[allow(dead_code)] pub const FILE_EXTENSION: &str = "xyzw"; /// File header magic. pub const MAGIC: [u8; 4] = [b'X', b'Y', b'Z', b'W']; /// Mesh vertex. #[derive(Debug, Clone, PartialEq, Packed)] #[repr(C)] pub struct Vertex { pub position: Vector3D, pub color: Rgba, pub normal: Vector3D, pub uv: Vector2D, pub opacity: f32, pub polygon: u32, } impl Vertex { /// Create a new vertex. pub const fn new(x: f32, y: f32, z: f32, nx: f32, ny: f32, nz: f32, u: f32, v: f32) -> Self { Self { position: Vector3D::new(x, y, z), color: Rgba::WHITE, normal: Vector3D::new(nx, ny, nz), uv: Vector2D::new(u, v), opacity: 1.0, polygon: 0, } } /// Stride used in buffer layout calculations. #[allow(dead_code)] pub fn stride() -> usize { mem::size_of::() } } impl Encode for Vertex { fn encode(&self, writer: &mut W) -> Result { let mut n = 0; n += self.position.encode(writer)?; n += self.color.encode(writer)?; n += self.normal.encode(writer)?; n += self.uv.encode(writer)?; n += self.opacity.encode(writer)?; n += self.polygon.encode(writer)?; Ok(n) } } impl Decode for Vertex { fn decode(reader: &mut R) -> Result { Ok(Self { position: Decode::decode(reader)?, color: Decode::decode(reader)?, normal: Decode::decode(reader)?, uv: Decode::decode(reader)?, opacity: Decode::decode(reader)?, polygon: Decode::decode(reader)?, }) } } /// A mesh with vertices and optional indices. /// /// When encoded, uses the following format: /// /// .------------. /// | MAGIC | "XYZW" (4 bytes) /// +------------+ /// | NVERTICES | (4 bytes) (Big Endian) Number of vertices /// +------------+ /// | NINDICES | (4 bytes) (Big Endian) Number of indices /// +------------+ /// | VERTICES | (NVERTICES * N bytes) Vertex data /// | .... | /// +------------+ /// | INDICES | (NINDICES * 4 bytes) Index data /// | .... | /// '------------' /// #[derive(Debug, PartialEq)] pub struct Mesh { /// Mesh vertices. Used as vertex buffer. pub vertices: Vec, /// Mesh indices. Used as index buffer. pub indices: Option>, } impl Mesh { /// Create a "cube" mesh. pub fn cube(size: f32) -> Self { let s = size / 2.0; #[rustfmt::skip] let mut vertices = vec![ // Front face. Vertex::new(-s, -s, s, 0.0, 0.0, 1.0, 0.0, 0.0), Vertex::new( s, -s, s, 0.0, 0.0, 1.0, 1.0, 0.0), Vertex::new( s, s, s, 0.0, 0.0, 1.0, 1.0, 1.0), Vertex::new(-s, s, s, 0.0, 0.0, 1.0, 0.0, 1.0), // Back face. Vertex::new(-s, -s, -s, 0.0, 0.0, -1.0, 1.0, 0.0), Vertex::new(-s, s, -s, 0.0, 0.0, -1.0, 1.0, 1.0), Vertex::new( s, s, -s, 0.0, 0.0, -1.0, 0.0, 1.0), Vertex::new( s, -s, -s, 0.0, 0.0, -1.0, 0.0, 0.0), // Left face. Vertex::new(-s, -s, -s, -1.0, 0.0, 0.0, 0.0, 0.0), Vertex::new(-s, -s, s, -1.0, 0.0, 0.0, 1.0, 0.0), Vertex::new(-s, s, s, -1.0, 0.0, 0.0, 1.0, 1.0), Vertex::new(-s, s, -s, -1.0, 0.0, 0.0, 0.0, 1.0), // Right face. Vertex::new( s, -s, s, 1.0, 0.0, 0.0, 0.0, 0.0), Vertex::new( s, -s, -s, 1.0, 0.0, 0.0, 1.0, 0.0), Vertex::new( s, s, -s, 1.0, 0.0, 0.0, 1.0, 1.0), Vertex::new( s, s, s, 1.0, 0.0, 0.0, 0.0, 1.0), // Top face. Vertex::new(-s, s, s, 0.0, 1.0, 0.0, 0.0, 0.0), Vertex::new(-s, s, -s, 0.0, 1.0, 0.0, 0.0, 1.0), Vertex::new( s, s, -s, 0.0, 1.0, 0.0, 1.0, 1.0), Vertex::new( s, s, s, 0.0, 1.0, 0.0, 1.0, 0.0), // Bottom face. Vertex::new(-s, -s, -s, 0.0, -1.0, 0.0, 1.0, 1.0), Vertex::new( s, -s, -s, 0.0, -1.0, 0.0, 0.0, 1.0), Vertex::new( s, -s, s, 0.0, -1.0, 0.0, 0.0, 0.0), Vertex::new(-s, -s, s, 0.0, -1.0, 0.0, 1.0, 0.0), ]; // Assign polygon IDs, starting from `1`. for (i, quad) in vertices.chunks_exact_mut(4).enumerate() { for v in quad { v.polygon = i as u32 + 1; } } Mesh { vertices, #[rustfmt::skip] indices: Some(vec![ 0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7, 8, 9, 10, 8, 10, 11, 12, 13, 14, 12, 14, 15, 16, 17, 18, 16, 18, 19, 20, 21, 22, 20, 22, 23, ]), } } /// Create a "sphere" mesh. pub fn sphere(color: Rgba8, radius: f32, segments: usize, rings: usize) -> Self { let mut vertices = Vec::new(); let mut indices = Vec::new(); // Vertices. for i in 0..=rings { let phi = i as f32 / rings as f32 * PI; for j in 0..=segments { let theta = j as f32 / segments as f32 * 2. * PI; let position = Vector3D::new( radius * phi.sin() * theta.cos(), radius * phi.cos(), radius * phi.sin() * theta.sin(), ); vertices.push(Vertex { position, color: color.into(), normal: position.normalize(), uv: Vector2D::default(), opacity: 1., polygon: 0, // TODO }); } } // Indices. for i in 0..rings { for j in 0..segments { let first = (i * (segments + 1)) + j; let second = first + segments + 1; // Create the first triangle (upper) indices.push((first + 1) as u16); indices.push(second as u16); indices.push(first as u16); // Create the second triangle (lower) indices.push((first + 1) as u16); indices.push((second + 1) as u16); indices.push(second as u16); } } Mesh { vertices, indices: Some(indices), } } /// Number of elements to render for this mesh. pub fn elements(&self) -> usize { self.indices.as_ref().map(|i| i.len()).unwrap_or(self.vertices.len()) } } impl Encode for Mesh { fn encode(&self, w: &mut W) -> Result { let mut n = 0; n += MAGIC.encode(w)?; let vertices = &self.vertices; let indices = &self.indices.as_deref().unwrap_or(&[]); assert!(vertices.len() <= u32::MAX as usize); assert!(indices.len() <= u32::MAX as usize); n += (vertices.len() as u32).encode(w)?; n += (indices.len() as u32).encode(w)?; for v in vertices { n += v.encode(w)?; } for i in indices.iter() { n += i.encode(w)?; } Ok(n) } } impl Decode for Mesh { fn decode(reader: &mut R) -> Result { let magic: [u8; 4] = Decode::decode(reader)?; if magic != MAGIC { return Err(io::ErrorKind::InvalidData.into()); } let nvertices = u32::decode(reader)? as usize; let nindices = u32::decode(reader)? as usize; let mut vertices = Vec::with_capacity(nvertices); while vertices.len() < nvertices { let v = Vertex::decode(reader)?; vertices.push(v); } let mut indices = Vec::::with_capacity(nindices); while indices.len() < nindices { let ix = I::decode(reader)?; indices.push(ix); } Ok(Self { vertices, indices: (!indices.is_empty()).then_some(indices), }) } } impl TryFrom<&[u8]> for Mesh { type Error = io::Error; fn try_from(bytes: &[u8]) -> Result { let mut cursor = io::Cursor::new(bytes); let mesh = Mesh::::decode(&mut cursor)?; Ok(mesh) } } #[cfg(test)] mod tests { #![allow(clippy::unwrap_used)] use super::*; #[test] fn test_encode_sphere() { let sphere = Mesh::::sphere(Rgba8::GREEN, 32.0, 16, 32); let mut out = Vec::new(); sphere.encode(&mut out).unwrap(); let decoded = Mesh::::try_from(out.as_slice()).unwrap(); assert_eq!(sphere, decoded); } #[test] fn test_encode_cube() { let cube = Mesh::::cube(16.0); let mut out = Vec::new(); cube.encode(&mut out).unwrap(); let decoded = Mesh::::try_from(out.as_slice()).unwrap(); assert_eq!(cube, decoded); } }