1

I am coding an assignment in computer graphics where I have to use different light models (ambient, diffusion, specular) for an object consisting of N triangles. Given the coordinates of the three vertices of each triangle in 3-D space, I want to calculate the normal vectors for each vertex.

I have tried the following code using some help I found searching online but I really am not sure if I am doing this correctly.

function Normals = findVertNormals(R, F)

     number_of_triangles = length(F);
     number_of_vertices = length(R);
     A = zeros(3,number_of_triangles);
     Normals = zeros(3,number_of_vertices);

     for i = 1:number_of_triangles

         first_vertex = R(:,F(i,1));
         second_vertex = R(:,F(i,2));
         third_vertex = R(:,F(i,3));

         V =  second_vertex - first_vertex ;
         W = third_vertex - first_vertex;

         N = cross(V,W);
         A(:,i) = N ./ norm(N);

     end

     for i = 1:number_of_triangles

         for j = 1:3

             Normals(:,F(i,j)) = Normals(:,F(i,j)) + A(:,i);

         end
     end

     Normals = Normals ./ norm(Normals);

 end

where matrix F describes which vertices form each triangle and matrix R contains the coordinates of vertex in 3-D space.

Teo Protoulis
  • 203
  • 4
  • 12
  • Do you mean to calculate the normal vectors for each face and not each vertex? – John Jun 13 '19 at 21:25
  • No, I mean for each vertex. That is what the assignment asks for. – Teo Protoulis Jun 13 '19 at 21:30
  • There's some ambiguity around calculating a normal for a vertex since it is undefined. Your approach of averaging the normals of the adjacent faces is a potential way to do it but it doesn't seem very robust to non-uniform triangles. – John Jun 13 '19 at 21:33
  • 2
    A better way might be to do a weighted average with the weights proportional to the angle each face makes with the vertex. – John Jun 13 '19 at 21:34
  • You might also consider methods based on the edges connected to each vertex rather than the faces connected to each vertex which might be more efficient if that's something you care about. – John Jun 13 '19 at 21:37
  • Possible duplicate of [How to achieve smooth tangent space normals?](https://stackoverflow.com/questions/21766605/how-to-achieve-smooth-tangent-space-normals) – Spektre Jun 14 '19 at 09:24

0 Answers0