Okay,
So I have been all over the net trying to find ways to correctly render using normals, and directional light (origonally found in one of learningwebgl.com tutorials). In the learningwebgl tutorials the normals are all setup in an array. In my program, I need to be able to load in wavefont OBJ files and then generate normals. I am wondering if it likely to be my normal generation code, or possibly a problem with my shaders. The code is a little confusing (as all the vertex/normal/indices data are in a single array each) but here is my normal generation code:
for(var i=0;i<d["vertices"].length;i++)d["normals"][i] = 0;
for(var i=0;i<d["indices"].length/3;i++){
var a = [d["vertices"][d["indices"][(i*3)]], d["vertices"][d["indices"][(i*3)]+1], d["vertices"][d["indices"][(i*3)]+2]];
var b = [d["vertices"][d["indices"][(i*3)+1]], d["vertices"][d["indices"][(i*3)+1]+1], d["vertices"][d["indices"][(i*3)+1]+2]];
var c = [d["vertices"][d["indices"][(i*3)+2]], d["vertices"][d["indices"][(i*3)+2]+1], d["vertices"][d["indices"][(i*3)+2]+2]];
var e = vec3.cross(vec3.subtract(b, a), vec3.subtract(c, a));
d["normals"][d["indices"][(i*3)]] += -e[0];
d["normals"][d["indices"][(i*3)]+1] += -e[1];
d["normals"][d["indices"][(i*3)]+2] += -e[2];
d["normals"][d["indices"][(i*3)+1]] += -e[0];
d["normals"][d["indices"][(i*3)+1]+1] += -e[1];
d["normals"][d["indices"][(i*3)+1]+2] += -e[2];
d["normals"][d["indices"][(i*3)+2]] += -e[0];
d["normals"][d["indices"][(i*3)+2]+1] += -e[1];
d["normals"][d["indices"][(i*3)+2]+2] += -e[2];
}
for(var i=0;i<d["normals"].length/3;i++){
var old = vec3.normalize([d["normals"][(i*3)],d["normals"][(i*3)+1],d["normals"][(i*3)+2]]);
d["normals"][(i*3)] = old[0];
d["normals"][(i*3)+1] = old[1];
d["normals"][(i*3)+2] = old[2];
}
Important part of the (vertex)shader:
// where uNMatrix = inverse of model view matrix
vec3 transformedNormal = uNMatrix * aVertexNormal;
// vec3 - light pos
float directionalLightWeighting = max(dot(transformedNormal, uLightingDirection), 1.0);
// vec3 = light color
vLightWeighting = uAmbientColor + uDirectionalColor * directionalLightWeighting;
I have tried many normal algorithm's to no avail. I have also found if I don't normalize the normals at the very end, the color/shades do in fact change, it is just obviously incorrect shading.
For an example of what it is currently looking like (with the bottom loop commented) follow this link, select teddy from the dropdown, then click load, then click "(re)generate normals", you can then rotate around the teddy by dragging the mouse:
http://webdesignscript.net/assignment/graphics_a3/
For a look at the shaders they are here:
http://webdesignscript.net/assignment/graphics_a3/scripts/shaders.js
I have been stuck on this for many hours, and am starting to wonder if it might be something shader related, however I am still new to graphicaly programming and would greatly appreciate any help :)
*the matrix library used is glMatrix
Cheers, Josh