I am trying to figure out how to optimize lighting in opengl 2. I am using 4 lights per object, with the lights sorted by distance. It works well with just one light, but with any more than that It starts to slow down. I would like a way to speed up my lighting while getting similar visual results. Here is my lighting code:
#version 120
uniform vec4 ulight1;
uniform vec4 ulight2;
uniform vec4 ulight3;
uniform vec4 ulight4;
varying vec4 v_color;
varying vec3 v_position;
varying vec3 v_normal;
vec3 ambient = vec3(0.2,0.2,0.2);
vec3 lightcolor = vec3(0.6,0.6,0.6);
vec3 phong() {
vec3 nn = normalize(v_normal);
vec3 dtl1 = ulight1.xyz-(v_position);
vec3 dtl2 = ulight2.xyz-(v_position);
vec3 dtl3 = ulight3.xyz-(v_position);
vec3 dtl4 = ulight4.xyz-(v_position);
float dis1 = length(dtl1);
float dis2 = length(dtl2);
float dis3 = length(dtl3);
float dis4 = length(dtl4);
float att1 = (1.0 / (1.0 + (dis1 * dis1)));
float att2 = (1.0 / (1.0 + (dis2 * dis2)));
float att3 = (1.0 / (1.0 + (dis3 * dis3)));
float att4 = (1.0 / (1.0 + (dis4 * dis4)));
float d1 = max(dot(nn,normalize(dtl1)),0.0);
float d2 = max(dot(nn,normalize(dtl2)),0.0);
float d3 = max(dot(nn,normalize(dtl3)),0.0);
float d4 = max(dot(nn,normalize(dtl4)),0.0);
vec3 lw1 = att1*(ambient+lightcolor*d1)*ulight1.w;
vec3 lw2 = att2*(ambient+lightcolor*d2)*ulight2.w;
vec3 lw3 = att3*(ambient+lightcolor*d3)*ulight3.w;
vec3 lw4 = att4*(ambient+lightcolor*d4)*ulight4.w;
return lw1+lw2+lw3+lw4;
}
This function is called once per pixel in the fragment shader. The width of each light tells it whether or not that light is enabled.