I am currently developing a custom mesh importer for my proprietary file format. The challenge I'm facing is that the format does not include normal data. As a result, I am exploring methods to calculate normals for enclosed shapes and then apply those normals to the mesh.
My approach involves computing a normal vector for each face of the geometry and casting a ray from the center of these faces in the direction of the normal vector. If the ray intersects with another plane, it indicates an inward direction. In such cases, I invert the normal; otherwise, I retain it as is.
However, despite implementing this logic in a function, I've encountered an issue where the normals remain unchanged.
function calculateNormals(object){
for (var i = 0; i < object.geometry.faces.length; i++) {
var vertices= object.geometry.vertices;
var face=object.geometry.faces[i];
var a=vertices[face.a];
var b=vertices[face.b];
var c=vertices[face.c];
console.log(face.a+" "+face.b+" "+face.c+" "+face.normal.z);
console.log(face);
console.log(face[4]);
var edge0=new THREE.Vector3(0,0,0);
edge0.subVectors(a,b);
var edge1=new THREE.Vector3(0,0,0);
edge1.subVectors(b,c);
var planeNormal=new THREE.Vector3(0,0,0)
planeNormal.crossVectors(edge0,edge1);
var midPoint=calculateMiddlePoint([a,b,c]);
var raycaster = new THREE.Raycaster(midPoint,planeNormal);
var intersects = raycaster.intersectObjects([object]);
if(intersects.length==0){
console.log("Normal is true");
face.normal=planeNormal;
}else{
console.log("Normal is wrong, you should flip normal direction, length: "+intersects.length);
console.log("Old face");
console.log(face.normal);
var newNormal=new THREE.Vector3(-1*planeNormal.x,-1*planeNormal.y,-1*planeNormal.z);
console.log(newNormal);
face.normal=newNormal;
console.log("new face");
console.log(face.normal);
console.log(face);
}
object.geometry.faces[i]=face;
};
return object;
}