
#include "gamma.sdr"
#include "z-compress.sdr"

in float fragRadius;
in vec4 fragPosition;
in vec4 fragTexCoord;
in vec4 fragColor;

out vec4 fragOut0;

uniform sampler2DArray baseMap;
uniform sampler2D depthMap;

layout (std140) uniform genericData {
	float window_width;
	float window_height;
	float nearZ;
	float farZ;
	int linear_depth;
	int srgb;
	int blend_alpha;
};


void main()
{
	vec4 fragmentColor = texture(baseMap, fragTexCoord.xyz);
	fragmentColor.rgb = mix(fragmentColor.rgb, srgb_to_linear(fragmentColor.rgb), float(srgb));
	fragmentColor *= mix(fragColor, vec4(srgb_to_linear(fragColor.rgb), fragColor.a), float(srgb));
	vec2 offset = vec2(fragRadius * abs(0.5 - fragTexCoord.x) * 2.0, fragRadius * abs(0.5 - fragTexCoord.y) * 2.0);
	float offset_len = length(offset);
	if ( offset_len > fragRadius ) {
		fragOut0 = vec4(0.0, 0.0, 0.0, 0.0);
		return;
	}
	vec2 depthCoord = vec2(gl_FragCoord.x / window_width, gl_FragCoord.y / window_height );
	vec4 sceneDepth = texture(depthMap, depthCoord);
	float sceneDepthLinear;
	float fragDepthLinear;
	if ( linear_depth == 1 ) {
		sceneDepthLinear = -uncompress_depth_value(sceneDepth.z);
		fragDepthLinear = -fragPosition.z;
	} else {
		sceneDepthLinear = ( 2.0 * farZ * nearZ ) / ( farZ + nearZ - sceneDepth.x * (farZ-nearZ) );
		fragDepthLinear = ( 2.0 * farZ * nearZ ) / ( farZ + nearZ - gl_FragCoord.z * (farZ-nearZ) );
	}
	// assume UV of 0.5, 0.5 is the centroid of this sphere volume
	float depthOffset = sqrt((fragRadius*fragRadius) - (offset_len*offset_len));
	float frontDepth = fragDepthLinear - depthOffset;
	float backDepth = fragDepthLinear + depthOffset;
	float intensity = smoothstep(max(nearZ, frontDepth), backDepth, sceneDepthLinear);
	fragmentColor.rgb *= (srgb == 1) ? 1.5 : 1.0;
	fragmentColor = (blend_alpha == 1) ? vec4(fragmentColor.rgb, fragmentColor.a * intensity) : vec4(fragmentColor.rgb * intensity, fragmentColor.a);
	fragOut0 = max(fragmentColor, vec4(0.0));
}
