compute_normals functions
@@ -26,11 +26,6 @@ impl CPUMesh {
Ok(CPUMesh {magic_number: 61, version: 2, indices: indices.to_owned(), positions: positions.to_owned(), normals: normals.to_owned(), uvs: uvs.to_owned()})
}
- pub fn new_with_computed_normals(indices: &[u32], positions: &[f32], uvs: &[f32]) -> Result<Self, objects::Error>
- {
- Self::new(indices, positions, &compute_normals(indices, positions), uvs)
- }
-
pub fn from_bytes(bytes: &[u8]) -> Result<CPUMesh, bincode::Error>
{
let decoded = bincode::deserialize::<CPUMesh>(bytes)
@@ -124,7 +119,7 @@ struct CPUMeshV1 {
pub normals: Vec<f32>
}
-fn compute_normals(indices: &[u32], positions: &[f32]) -> Vec<f32> {
+pub fn compute_normals_with_indices(indices: &[u32], positions: &[f32]) -> Vec<f32> {
let mut normals = vec![0.0f32; positions.len() * 3];
for face in 0..indices.len()/3 {
let index0 = indices[face*3] as usize;
@@ -154,3 +149,35 @@ fn compute_normals(indices: &[u32], positions: &[f32]) -> Vec<f32> {
}
normals
}
+
+
+pub fn compute_normals(positions: &[f32]) -> Vec<f32> {
+ let mut normals = vec![0.0f32; positions.len()];
+ for face in 0..positions.len()/9 {
+ let index0 = face*3 as usize;
+ let p0 = vec3(positions[index0*3], positions[index0*3+1], positions[index0*3+2]);
+ let index1 = face*3 + 1 as usize;
+ let p1 = vec3(positions[index1*3], positions[index1*3+1], positions[index1*3+2]);
+ let index2 = face*3 + 2 as usize;
+ let p2 = vec3(positions[index2*3], positions[index2*3+1], positions[index2*3+2]);
+
+ let normal = (p1 - p0).cross(p2 - p0);
+ normals[index0*3] += normal.x;
+ normals[index0*3+1] += normal.y;
+ normals[index0*3+2] += normal.z;
+ normals[index1*3] += normal.x;
+ normals[index1*3+1] += normal.y;
+ normals[index1*3+2] += normal.z;
+ normals[index2*3] += normal.x;
+ normals[index2*3+1] += normal.y;
+ normals[index2*3+2] += normal.z;
+ }
+
+ for i in 0..normals.len()/3 {
+ let normal = vec3(normals[3*i], normals[3*i+1], normals[3*i+2]).normalize();
+ normals[3*i] = normal.x;
+ normals[3*i+1] = normal.y;
+ normals[3*i+2] = normal.z;
+ }
+ normals
+}
\ No newline at end of file
