|
| 1 | +use bevy_math::{primitives::Cone, Vec3}; |
| 2 | +use wgpu::PrimitiveTopology; |
| 3 | + |
| 4 | +use crate::{ |
| 5 | + mesh::{Indices, Mesh, Meshable}, |
| 6 | + render_asset::RenderAssetUsages, |
| 7 | +}; |
| 8 | + |
| 9 | +/// A builder used for creating a [`Mesh`] with a [`Cone`] shape. |
| 10 | +#[derive(Clone, Copy, Debug)] |
| 11 | +pub struct ConeMeshBuilder { |
| 12 | + /// The [`Cone`] shape. |
| 13 | + pub cone: Cone, |
| 14 | + /// The number of vertices used for the base of the cone. |
| 15 | + /// |
| 16 | + /// The default is `32`. |
| 17 | + pub resolution: u32, |
| 18 | +} |
| 19 | + |
| 20 | +impl Default for ConeMeshBuilder { |
| 21 | + fn default() -> Self { |
| 22 | + Self { |
| 23 | + cone: Cone::default(), |
| 24 | + resolution: 32, |
| 25 | + } |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +impl ConeMeshBuilder { |
| 30 | + /// Creates a new [`ConeMeshBuilder`] from a given radius, height, |
| 31 | + /// and number of vertices used for the base of the cone. |
| 32 | + #[inline] |
| 33 | + pub const fn new(radius: f32, height: f32, resolution: u32) -> Self { |
| 34 | + Self { |
| 35 | + cone: Cone { radius, height }, |
| 36 | + resolution, |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + /// Sets the number of vertices used for the base of the cone. |
| 41 | + #[inline] |
| 42 | + pub const fn resolution(mut self, resolution: u32) -> Self { |
| 43 | + self.resolution = resolution; |
| 44 | + self |
| 45 | + } |
| 46 | + |
| 47 | + /// Builds a [`Mesh`] based on the configuration in `self`. |
| 48 | + pub fn build(&self) -> Mesh { |
| 49 | + let half_height = self.cone.height / 2.0; |
| 50 | + |
| 51 | + // `resolution` vertices for the base, `resolution` vertices for the bottom of the lateral surface, |
| 52 | + // and one vertex for the tip. |
| 53 | + let num_vertices = self.resolution as usize * 2 + 1; |
| 54 | + let num_indices = self.resolution as usize * 6 - 6; |
| 55 | + |
| 56 | + let mut positions = Vec::with_capacity(num_vertices); |
| 57 | + let mut normals = Vec::with_capacity(num_vertices); |
| 58 | + let mut uvs = Vec::with_capacity(num_vertices); |
| 59 | + let mut indices = Vec::with_capacity(num_indices); |
| 60 | + |
| 61 | + // Tip |
| 62 | + positions.push([0.0, half_height, 0.0]); |
| 63 | + |
| 64 | + // The tip doesn't have a singular normal that works correctly. |
| 65 | + // We use an invalid normal here so that it becomes NaN in the fragment shader |
| 66 | + // and doesn't affect the overall shading. This might seem hacky, but it's one of |
| 67 | + // the only ways to get perfectly smooth cones without creases or other shading artefacts. |
| 68 | + // |
| 69 | + // Note that this requires that normals are not normalized in the vertex shader, |
| 70 | + // as that would make the entire triangle invalid and make the cone appear as black. |
| 71 | + normals.push([0.0, 0.0, 0.0]); |
| 72 | + |
| 73 | + // The UVs of the cone are in polar coordinates, so it's like projecting a circle texture from above. |
| 74 | + // The center of the texture is at the center of the lateral surface, at the tip of the cone. |
| 75 | + uvs.push([0.5, 0.5]); |
| 76 | + |
| 77 | + // Now we build the lateral surface, the side of the cone. |
| 78 | + |
| 79 | + // The vertex normals will be perpendicular to the surface. |
| 80 | + // |
| 81 | + // Here we get the slope of a normal and use it for computing |
| 82 | + // the multiplicative inverse of the length of a vector in the direction |
| 83 | + // of the normal. This allows us to normalize vertex normals efficiently. |
| 84 | + let normal_slope = self.cone.radius / self.cone.height; |
| 85 | + // Equivalent to Vec2::new(1.0, slope).length().recip() |
| 86 | + let normalization_factor = (1.0 + normal_slope * normal_slope).sqrt().recip(); |
| 87 | + |
| 88 | + // How much the angle changes at each step |
| 89 | + let step_theta = std::f32::consts::TAU / self.resolution as f32; |
| 90 | + |
| 91 | + // Add vertices for the bottom of the lateral surface. |
| 92 | + for segment in 0..self.resolution { |
| 93 | + let theta = segment as f32 * step_theta; |
| 94 | + let (sin, cos) = theta.sin_cos(); |
| 95 | + |
| 96 | + // The vertex normal perpendicular to the side |
| 97 | + let normal = Vec3::new(cos, normal_slope, sin) * normalization_factor; |
| 98 | + |
| 99 | + positions.push([self.cone.radius * cos, -half_height, self.cone.radius * sin]); |
| 100 | + normals.push(normal.to_array()); |
| 101 | + uvs.push([0.5 + cos * 0.5, 0.5 + sin * 0.5]); |
| 102 | + } |
| 103 | + |
| 104 | + // Add indices for the lateral surface. Each triangle is formed by the tip |
| 105 | + // and two vertices at the base. |
| 106 | + for j in 1..self.resolution { |
| 107 | + indices.extend_from_slice(&[0, j + 1, j]); |
| 108 | + } |
| 109 | + |
| 110 | + // Close the surface with a triangle between the tip, first base vertex, and last base vertex. |
| 111 | + indices.extend_from_slice(&[0, 1, self.resolution]); |
| 112 | + |
| 113 | + // Now we build the actual base of the cone. |
| 114 | + |
| 115 | + let index_offset = positions.len() as u32; |
| 116 | + |
| 117 | + // Add base vertices. |
| 118 | + for i in 0..self.resolution { |
| 119 | + let theta = i as f32 * step_theta; |
| 120 | + let (sin, cos) = theta.sin_cos(); |
| 121 | + |
| 122 | + positions.push([cos * self.cone.radius, -half_height, sin * self.cone.radius]); |
| 123 | + normals.push([0.0, -1.0, 0.0]); |
| 124 | + uvs.push([0.5 * (cos + 1.0), 1.0 - 0.5 * (sin + 1.0)]); |
| 125 | + } |
| 126 | + |
| 127 | + // Add base indices. |
| 128 | + for i in 1..(self.resolution - 1) { |
| 129 | + indices.extend_from_slice(&[index_offset, index_offset + i, index_offset + i + 1]); |
| 130 | + } |
| 131 | + |
| 132 | + Mesh::new( |
| 133 | + PrimitiveTopology::TriangleList, |
| 134 | + RenderAssetUsages::default(), |
| 135 | + ) |
| 136 | + .with_inserted_indices(Indices::U32(indices)) |
| 137 | + .with_inserted_attribute(Mesh::ATTRIBUTE_POSITION, positions) |
| 138 | + .with_inserted_attribute(Mesh::ATTRIBUTE_NORMAL, normals) |
| 139 | + .with_inserted_attribute(Mesh::ATTRIBUTE_UV_0, uvs) |
| 140 | + } |
| 141 | +} |
| 142 | + |
| 143 | +impl Meshable for Cone { |
| 144 | + type Output = ConeMeshBuilder; |
| 145 | + |
| 146 | + fn mesh(&self) -> Self::Output { |
| 147 | + ConeMeshBuilder { |
| 148 | + cone: *self, |
| 149 | + ..Default::default() |
| 150 | + } |
| 151 | + } |
| 152 | +} |
| 153 | + |
| 154 | +impl From<Cone> for Mesh { |
| 155 | + fn from(cone: Cone) -> Self { |
| 156 | + cone.mesh().build() |
| 157 | + } |
| 158 | +} |
| 159 | + |
| 160 | +impl From<ConeMeshBuilder> for Mesh { |
| 161 | + fn from(cone: ConeMeshBuilder) -> Self { |
| 162 | + cone.build() |
| 163 | + } |
| 164 | +} |
| 165 | + |
| 166 | +#[cfg(test)] |
| 167 | +mod tests { |
| 168 | + use bevy_math::{primitives::Cone, Vec2}; |
| 169 | + |
| 170 | + use crate::mesh::{Mesh, Meshable, VertexAttributeValues}; |
| 171 | + |
| 172 | + /// Rounds floats to handle floating point error in tests. |
| 173 | + fn round_floats<const N: usize>(points: &mut [[f32; N]]) { |
| 174 | + for point in points.iter_mut() { |
| 175 | + for coord in point.iter_mut() { |
| 176 | + let round = (*coord * 100.0).round() / 100.0; |
| 177 | + if (*coord - round).abs() < 0.00001 { |
| 178 | + *coord = round; |
| 179 | + } |
| 180 | + } |
| 181 | + } |
| 182 | + } |
| 183 | + |
| 184 | + #[test] |
| 185 | + fn cone_mesh() { |
| 186 | + let mut mesh = Cone { |
| 187 | + radius: 0.5, |
| 188 | + height: 1.0, |
| 189 | + } |
| 190 | + .mesh() |
| 191 | + .resolution(4) |
| 192 | + .build(); |
| 193 | + |
| 194 | + let Some(VertexAttributeValues::Float32x3(mut positions)) = |
| 195 | + mesh.remove_attribute(Mesh::ATTRIBUTE_POSITION) |
| 196 | + else { |
| 197 | + panic!("Expected positions f32x3"); |
| 198 | + }; |
| 199 | + let Some(VertexAttributeValues::Float32x3(mut normals)) = |
| 200 | + mesh.remove_attribute(Mesh::ATTRIBUTE_NORMAL) |
| 201 | + else { |
| 202 | + panic!("Expected normals f32x3"); |
| 203 | + }; |
| 204 | + |
| 205 | + round_floats(&mut positions); |
| 206 | + round_floats(&mut normals); |
| 207 | + |
| 208 | + // Vertex positions |
| 209 | + assert_eq!( |
| 210 | + [ |
| 211 | + // Tip |
| 212 | + [0.0, 0.5, 0.0], |
| 213 | + // Lateral surface |
| 214 | + [0.5, -0.5, 0.0], |
| 215 | + [0.0, -0.5, 0.5], |
| 216 | + [-0.5, -0.5, 0.0], |
| 217 | + [0.0, -0.5, -0.5], |
| 218 | + // Base |
| 219 | + [0.5, -0.5, 0.0], |
| 220 | + [0.0, -0.5, 0.5], |
| 221 | + [-0.5, -0.5, 0.0], |
| 222 | + [0.0, -0.5, -0.5], |
| 223 | + ], |
| 224 | + &positions[..] |
| 225 | + ); |
| 226 | + |
| 227 | + // Vertex normals |
| 228 | + let [x, y] = Vec2::new(0.5, -1.0).perp().normalize().to_array(); |
| 229 | + assert_eq!( |
| 230 | + &[ |
| 231 | + // Tip |
| 232 | + [0.0, 0.0, 0.0], |
| 233 | + // Lateral surface |
| 234 | + [x, y, 0.0], |
| 235 | + [0.0, y, x], |
| 236 | + [-x, y, 0.0], |
| 237 | + [0.0, y, -x], |
| 238 | + // Base |
| 239 | + [0.0, -1.0, 0.0], |
| 240 | + [0.0, -1.0, 0.0], |
| 241 | + [0.0, -1.0, 0.0], |
| 242 | + [0.0, -1.0, 0.0], |
| 243 | + ], |
| 244 | + &normals[..] |
| 245 | + ); |
| 246 | + } |
| 247 | +} |
0 commit comments