From ed41f48ea403c05b10c280986534cee8163802b6 Mon Sep 17 00:00:00 2001 From: Pedro Pereira Date: Fri, 5 Nov 2021 01:35:06 +0000 Subject: [PATCH] 3DFileViewer: Calculate face-normal from vertex-normals of the triangle This change calculates the face-normal of the triangle by adding the three vertex-normals and then normalizing. This results in an average of the three vertex-normals. --- Userland/Applications/3DFileViewer/Mesh.cpp | 28 ++++++++++++++++++--- Userland/Applications/3DFileViewer/Mesh.h | 2 ++ 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/Userland/Applications/3DFileViewer/Mesh.cpp b/Userland/Applications/3DFileViewer/Mesh.cpp index 335962bb64..d4970281bb 100644 --- a/Userland/Applications/3DFileViewer/Mesh.cpp +++ b/Userland/Applications/3DFileViewer/Mesh.cpp @@ -58,10 +58,30 @@ void Mesh::draw(float uv_scale) m_vertex_list.at(triangle.c).y, m_vertex_list.at(triangle.c).z); - // Compute the triangle normal - const FloatVector3 vec_ab = vertex_b - vertex_a; - const FloatVector3 vec_ac = vertex_c - vertex_a; - const FloatVector3 normal = vec_ab.cross(vec_ac).normalized(); + FloatVector3 normal; + if (has_normals()) { + const FloatVector3 normal_a( + m_normal_list.at(triangle.normal_index0).x, + m_normal_list.at(triangle.normal_index0).y, + m_normal_list.at(triangle.normal_index0).z); + + const FloatVector3 normal_b( + m_normal_list.at(triangle.normal_index1).x, + m_normal_list.at(triangle.normal_index1).y, + m_normal_list.at(triangle.normal_index1).z); + + const FloatVector3 normal_c( + m_normal_list.at(triangle.normal_index2).x, + m_normal_list.at(triangle.normal_index2).y, + m_normal_list.at(triangle.normal_index2).z); + + normal = (normal_a + normal_b + normal_c).normalized(); + } else { + // Compute the triangle normal + const FloatVector3 vec_ab = vertex_b - vertex_a; + const FloatVector3 vec_ac = vertex_c - vertex_a; + normal = vec_ab.cross(vec_ac).normalized(); + } // Compute lighting with a Lambertian color model const auto light_intensity = max(light_direction.dot(normal), 0.f); diff --git a/Userland/Applications/3DFileViewer/Mesh.h b/Userland/Applications/3DFileViewer/Mesh.h index abd280f4b4..3654a2234f 100644 --- a/Userland/Applications/3DFileViewer/Mesh.h +++ b/Userland/Applications/3DFileViewer/Mesh.h @@ -27,6 +27,8 @@ public: bool is_textured() const { return m_tex_coords.size() > 0; } + bool has_normals() const { return m_normal_list.size() > 0; } + private: Vector m_vertex_list; Vector m_tex_coords;