So I'm programming a game engine with LWJGL and I'm making a method that generates vertex normals using an indices array and a vertices array. My idea was to have a list of normals, add the face normals to them with a loop, and then average the variables. However when I tried that I get really odd effects with the lighting. This is my code:
public static Vector3f calculateNormal(Vector3f a, Vector3f b, Vector3f c)
{
Vector3f out = new Vector3f();
GeometryUtils.normal(a, b, c, out);
return out;
}
public static float[] buildNormals(int[] indices, float[] vertices)
{
List<List<Vector3f>> rawNormals = new ArrayList<>();
for(int i = 0; i < vertices.length / 3; i++)
rawNormals.add(new ArrayList<>());
for(int i = 0; i < indices.length; i += 3)
{
Vector3f a = new Vector3f(vertices[indices[i] * 3], vertices[indices[i + 1] * 3], vertices[indices[i + 2] * 3]);
Vector3f b = new Vector3f(vertices[indices[i] * 3 + 1], vertices[indices[i + 1] * 3 + 1], vertices[indices[i + 2] * 3 + 1]);
Vector3f c = new Vector3f(vertices[indices[i] * 3 + 2], vertices[indices[i + 1] * 3 + 2], vertices[indices[i + 2] * 3 + 2]);
Vector3f normal = calculateNormal(a, b, c);
rawNormals.get(indices[i]).add(normal);
rawNormals.get(indices[i + 1]).add(normal);
rawNormals.get(indices[i + 2]).add(normal);
}
float[] normals = new float[rawNormals.size() * 3];
int n = 0;
for(int i = 0; i < rawNormals.size(); i++)
{
Vector3f value = new Vector3f();
for(Vector3f v : rawNormals.get(i))
value = addVectors(value, v);
int size = rawNormals.get(i).size();
normals[n] = value.x / size;
normals[n + 1] = value.y / size;
normals[n + 2] = value.z / size;
n += 3;
}
return normals;
}
Is there anything that looks wrong with it? Thanks.