
#ifndef NUM_LIGHTS
	#define NUM_LIGHTS 1
#endif

#ifndef ADAPTIVE_STEPS
	#define ADAPTIVE_STEPS
#endif

varying vec3 normal;
varying vec3 lightDir[NUM_LIGHTS];
varying vec3 eye;
varying float camdot;

uniform sampler2D t_color;
uniform sampler2D t_disp;
uniform sampler2D t_normal;
/*uniform sampler2D t_occlusion;
uniform sampler2D t_specular;*/
uniform float parallaxHeight;

void main(void) {
	vec3 e = normalize(eye);

	#ifdef ADAPTIVE_STEPS
		float lod = 3.0+30.0*camdot;
	#else
		float lod = 5.0;
	#endif

	vec2 texcoord = gl_TexCoord[0].xy;
	float height = texture2D(t_disp, texcoord).r;

	// steep
	//float numSteps = 5.0;
	float numSteps = lod;
	numSteps = mix(numSteps*2.0, numSteps, float(e));
	float step = 1.0/numSteps;
	vec2 delta = vec2(-e.x,e.y)*parallaxHeight/(e.z*numSteps);
	float bheight = 1.0;
	int counter = 0;
	while (height < bheight && counter < 100) {
		bheight -= step;
		texcoord += delta;
		height = texture2D(t_disp, texcoord).r;
		counter++;
	}

	vec3 n = normalize(-1.0+2.0*texture2D(t_normal, texcoord).xyz);

	vec4 col = texture2D(t_color, texcoord);
	vec4 final = vec4(0.0);
	vec4 fambient = vec4(0.0);
	vec4 fdiff = vec4(0.0);
	vec4 fspec = vec4(0.0);

	for (int i = 0; i < NUM_LIGHTS; i++) {
		vec3 l = normalize(lightDir[i]);
		float diff = dot(n, l);

		fambient += gl_LightSource[i].ambient;

		if (diff > 0.0) {
			fdiff += gl_LightSource[i].diffuse*diff;

			vec3 r = reflect(-l, n);
			fspec += vec4(gl_LightSource[i].specular.xyz, 1.0)*pow(max(dot(r, e), 0.0), gl_LightSource[i].specular.w);
		}
	}

	gl_FragColor = fambient*col + fdiff*col + fspec;
}
