calculate normal per vertex OpenGL

后端 未结 1 1946
逝去的感伤
逝去的感伤 2021-02-06 12:51

I am trying the calculate normal per vertex. But I do something wrong. When I run the code I see this:

\"enter

相关标签:
1条回答
  • 2021-02-06 13:41

    You are computing normals per triangle, not per vertex. In fact you can clearly see "solid" normals in the image you posted.

    In order to compute "smooth" normals, you need to assign to each vertex a normal which is an average of the normals of the triangles adjacent to that vertex.

    Here's some pseudocode, which computed the weighted average of the normals based on the angle between the two edges adjacent to the vertex. (Maybe someone uses the area of the triangle as weight, I don't know if there is an universally accepted way to do it).

    vector3D triangleNormalFromVertex(int face_id, int vertex_id) {
       //This assumes that A->B->C is a counter-clockwise ordering
       vector3D A = mesh.face[face_id].vertex[vertex_id];
       vector3D B = mesh.face[face_id].vertex[(vertex_id+1)%3];
       vector3D C = mesh.face[face_id].vertex[(vertex_id+2)%3];
    
    
       vector3D N = cross(B-A,C-A);
       float sin_alpha = length(N) / (length(B-A) * length(C-A) );
       return normalize(N) * asin(sin_alpha);
    }
    
    void computeNormals() {
        for (vertex v in mesh) {
            vector3D N (0,0,0);
            for (int i = 0;i < NumOfTriangles;++i) {
                if (mesh.face[i].contains(v) ) {
                    int VertexID = index_of_v_in_triangle(i,v); //Can be 0,1 or 2
                    N = N + triangleNormalFromVertex(i,VertexID);
                }
            }
            N = normalize(N);
            add_N_to_normals_for_vertex_v(N,v);
        }
    }
    
    0 讨论(0)
提交回复
热议问题