#version 150

uniform sampler2D t0, ts, tg1;
uniform sampler1D n0;
uniform float z_near, z_far;
uniform mat4 mat_proj;

in vec3 view_dir;

void main(void) {
	ivec2 tc = ivec2(gl_FragCoord.xy);
	vec4 v0 = texelFetch(t0, tc, 0), vs = texelFetch(ts, tc, 0), vg1 = texelFetch(tg1, tc, 0);
	vec3 n = vec3(vg1.xyz);
	vec3 bn = cross(n, vec3(0, 0, 1));
	vec3 bn2 = cross(n, bn);
	vec4 pos;
	pos.w = 1;
	pos.xyz = view_dir * vs.w;
	vec4 spos = pos, tpos, tv0;
	vec2 tsp;
	float sclz = dot(vec3(0,0,1), n);
	/*float l = 20 * 0.5;
	pos.xyz += bn2 * l;
	for (int i = 0; i < 16; ++i) {
		tpos = mat_proj * pos;
		tsp = -(tpos.xy / tpos.w) / 2. + 0.5;
		tv0 = texture(ts, tsp);
		l *= 0.5;
		pos.xyz += bn2 * (step(pos.z, tv0.w) * 2. - 1.) * l;
	}*/
	/*vec3 rn;
	float ss = 0.;
	for (int i = 0; i < 32; ++i) {
		rn = texelFetch(n0, i, 0).rgb * 2 - 1;
		rn *= step(0., dot(n, rn)) * 2 - 1.;
		//rn /= 10;
		rn /= vs.w;
		spos = pos + vec4(rn, 0);
		tpos = mat_proj * spos;
		tsp = -(tpos.xy / tpos.w) / 2. + 0.5;
		tv0 = texture(ts, tsp);
		//spos.z = tv0.w;
		ss += step(-0.1, tv0.w-vs.w);
		//ss += step(vs.w, tv0.w);
	}
	ss /= 32;*/
	float minz = v0.r, maxz = v0.g, blurz = v0.b, curz = v0.w, avgz = (minz+maxz)/2;
	float dz = maxz - minz;
	//qgl_FragData[0].rgb = vec3(max(-(blurz - curz) / maxz,0.)* (curz-minz) / dz * 10);
	qgl_FragData[0].rgb = vec3(blurz/10);
	//qgl_FragData[0].rgb = vec3(length(pos.z - spos.z)/15);
	//qgl_FragData[0].rgb = vec3(abs(v0.w/1));
}
