import { v3_length } from "../../vec3/v3_length.js";
import { compute_triangle_normal } from "../triangle/compute_triangle_normal.js";
//


const scratch_v3_0 = new Float32Array(3);

/**
 *
 * @param {number[]} result
 * @param {number} result_offset
 * @param {TopoVertex} vertex
 */
export function tm_vertex_compute_normal(result, result_offset, vertex) {
    const faces = vertex.faces;
    const face_length = faces.length;


    let _x = 0;
    let _y = 0;
    let _z = 0;

    for (let i = 0; i < face_length; i++) {
        const face = faces[i];

        compute_triangle_normal(scratch_v3_0, face.vertices[0], face.vertices[1], face.vertices[2]);

        _x += scratch_v3_0[0];
        _y += scratch_v3_0[1];
        _z += scratch_v3_0[2];
    }

    // re-normalize
    const len_inv = v3_length(_x,_y,_z);

    _x *= len_inv;
    _y *= len_inv;
    _z *= len_inv;

    result[result_offset] = _x;
    result[result_offset+1] = _y;
    result[result_offset+2] = _z;
}
