#version 430

layout(local_size_x = 16, local_size_y = 16) in;
layout(r32ui, binding = 0) coherent uniform uimage2D depthTex;

uniform sampler2D tex;
uniform sampler2D texPrev;
uniform sampler2D tex3D;
uniform sampler2D prevND;
uniform vec2 res;

uniform vec3 originPrev;
uniform mat4 MVPprev;

uniform vec3 origin;
uniform mat4 MVP;

ivec2 offset[] = ivec2[](ivec2(-1, -1), ivec2(0, -1), ivec2(1, -1),
	ivec2(-1, 0), ivec2(0, 0), ivec2(1, 0),
	ivec2(-1, 1), ivec2(0, 1), ivec2(1, 1));

void main() {
	ivec2 storePos = ivec2(gl_GlobalInvocationID.xy);
	vec2 UV = (1.0f * storePos + vec2(0.5)) / res;
	vec3 pos = texture(tex3D, UV).rgb;

	if (isnan(pos.x))
		return;

	//get UV2 offset
	vec4 pos4 = MVP * vec4(pos, 1);
	pos4 /= pos4.w;
	vec2 UV2 = (pos4.xy + 1) / 2;

	//get new pixel pos
	vec2 diff = res*(UV2 - UV) /*/ 2*/;
	ivec2 off = ivec2(trunc(diff));
	ivec2 storePos2 = storePos + off;

	//get new depth as uint
	vec3 dist = pos - origin;
	float depth = sqrt(dot(dist, dist));
	uint udepth = uint(depth * 100);

	//prefer smaller depth (closer to camera)
	//for (int i = 0; i < 9; i++) {
		imageAtomicMin(depthTex, storePos2 + offset[4], udepth);
	//}

	//imageStore(depthTex, storePos2, uvec4(udepth));
}