#version 330 core

uniform sampler2D normal_depth;
uniform sampler2D particle;
uniform sampler2D noise;
uniform vec2 viewport;

in vec3 wpos;
in vec3 color;
in vec2 uv;

layout (location = 0) out vec4 frag_color;

#include <gbuffer_include.frag>
/*
vec3 calc_position(in vec2 uv_pos, in float d)
{
	vec4 wpos = vec4( (uv_pos.x - 0.5)*2.0, (uv_pos.y - 0.5)*2.0, d, 1.0);
	wpos = ProjectionMatrixInverse * wpos;
	return wpos.xyz / wpos.w;
}
*/

float pnoise(in vec3 pos)
{
	float n = texture(noise, pos.xy*20.0).x;//*2.0 - 1.0;
	return max(0.0, n); //0.75 + n*n*n*0.25;
}

void main()
{
	vec4 pcolor = texture(particle, uv) * vec4(color, 1.0);
	if ( pcolor.a < 0.0001 ) discard;

	vec2 uv_pos = gl_FragCoord.xy * viewport;
	float d = texture(normal_depth, uv_pos).w;
	vec3 pos = calc_position(uv_pos, d);

	if ( pos.z > wpos.z ) discard;

	float alpha = clamp(wpos.z - pos.z, 0.0, 1.0);
	frag_color = pcolor*alpha;
	//frag_color = vec4(1.0);
}
