Skip to content

Commit ed41f48

Browse files
pmhpereiraawesomekling
authored andcommitted
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.
1 parent 5fd58a2 commit ed41f48

File tree

2 files changed

+26
-4
lines changed

2 files changed

+26
-4
lines changed

Userland/Applications/3DFileViewer/Mesh.cpp

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -58,10 +58,30 @@ void Mesh::draw(float uv_scale)
5858
m_vertex_list.at(triangle.c).y,
5959
m_vertex_list.at(triangle.c).z);
6060

61-
// Compute the triangle normal
62-
const FloatVector3 vec_ab = vertex_b - vertex_a;
63-
const FloatVector3 vec_ac = vertex_c - vertex_a;
64-
const FloatVector3 normal = vec_ab.cross(vec_ac).normalized();
61+
FloatVector3 normal;
62+
if (has_normals()) {
63+
const FloatVector3 normal_a(
64+
m_normal_list.at(triangle.normal_index0).x,
65+
m_normal_list.at(triangle.normal_index0).y,
66+
m_normal_list.at(triangle.normal_index0).z);
67+
68+
const FloatVector3 normal_b(
69+
m_normal_list.at(triangle.normal_index1).x,
70+
m_normal_list.at(triangle.normal_index1).y,
71+
m_normal_list.at(triangle.normal_index1).z);
72+
73+
const FloatVector3 normal_c(
74+
m_normal_list.at(triangle.normal_index2).x,
75+
m_normal_list.at(triangle.normal_index2).y,
76+
m_normal_list.at(triangle.normal_index2).z);
77+
78+
normal = (normal_a + normal_b + normal_c).normalized();
79+
} else {
80+
// Compute the triangle normal
81+
const FloatVector3 vec_ab = vertex_b - vertex_a;
82+
const FloatVector3 vec_ac = vertex_c - vertex_a;
83+
normal = vec_ab.cross(vec_ac).normalized();
84+
}
6585

6686
// Compute lighting with a Lambertian color model
6787
const auto light_intensity = max(light_direction.dot(normal), 0.f);

Userland/Applications/3DFileViewer/Mesh.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@ class Mesh : public RefCounted<Mesh> {
2727

2828
bool is_textured() const { return m_tex_coords.size() > 0; }
2929

30+
bool has_normals() const { return m_normal_list.size() > 0; }
31+
3032
private:
3133
Vector<Vertex> m_vertex_list;
3234
Vector<TexCoord> m_tex_coords;

0 commit comments

Comments
 (0)