uniform sampler2D 	posTex,	
					normalmap;
uniform sampler3D 	voxelTex;

varying vec2 		texcoord;
varying vec2		VPOS;

uniform mat4		eyeToWorld;
uniform mat4		eyeToLight;
uniform vec3 		voxelOrg;
uniform vec3		voxelInvDim;
uniform vec2		voxelBias;
uniform vec3 		voxelRes;

uniform vec3 		voxelBrightness; // 0=brightness, 1=contrast, 2=alpha

uniform vec3		sunDir;


vec4 decode(vec2 enc)
{
    vec2 fenc = enc.xy*4.0-2.0;
    float f = dot(fenc,fenc);
    float g = sqrt(1.0-f/4.0);
    vec4 n;
    n.xy = fenc.xy*g;
    n.z = 1.0-f/2.0;
    return n;
}

void main()
{
	vec4 finalcolor;
	vec4 pos;
	pos.z = texture2D(posTex,texcoord.st).r;
	vec4 normal = decode(texture2D(normalmap,texcoord.st).xy);
	
	// convert normal to voxel volume space
	normal.w=0.0;
	vec4 WSnormal=eyeToLight*normal;
	
	// get pos int eye space
	pos.xy=VPOS.xy*-pos.z;
	pos.w=1.0;
	
	// convert to voxel volume space
	pos=eyeToLight*pos;
	
	// displace following the normal
	vec3 ofs=(vec3(1.0)/voxelInvDim)/voxelRes;
	pos.xyz=pos.xyz+WSnormal.xyz*(ofs*vec3(0.5)+voxelBias.x);
	
	// convert to voxel space
	vec3 voxelCoords=(((pos.xyz/*-voxelOrg*/)*voxelInvDim)+vec3(0.5));	
	
	/*float range=1.0/voxelBias.x;
	float end=1.0-voxelBias.x;
	vec3 att1=vec3(1.0)-clamp((voxelCoords-vec3(end))*vec3(range),vec3(0.0),vec3(1.0));
	vec3 att2=clamp(voxelCoords*vec3(range),vec3(0.0),vec3(1.0));
	float att=att1.x*att1.y*att1.z*att2.x*att2.y*att2.z*voxelBrightness.z;
	*/
	// fetch voxelmap
	float occ=texture3D(voxelTex,voxelCoords).r;//*voxelBias.y;		// voxelBias.y => num total samples
	
	occ = 1.0 - occ;
	occ = (occ - voxelBrightness.x) / (1.0 - voxelBrightness.x);
	occ = clamp(occ, 0.0,1.0);
	occ = 1.0 - occ;
	
	occ = (occ+voxelBrightness.y) / (1.0 - voxelBrightness.y);
	occ = clamp(occ, 0.0,1.0);
	
	// get bent normal
//	vec4 bent=decode(occ.yz);
	
	// compute directional occlusion
//	float dOcc=dot(bent,sunDir);
//	float d=dot(WSnormal,sunDir);
//	float dd=clamp(d-dOcc,0.0,1.0);
	
	// compute occlusion
	//occ=(min(occ+voxelBrightness.x,1.0)*voxelBrightness.y);
	
	// store final result
	gl_FragColor.r=occ;//*att;					// num visible samples
	gl_FragColor.a=1.0;//att;//voxelBias.y*att;			// num total samples
}