#include "RendererVolumeBooster.glsl"

uniform sampler3D samDataVolume;
uniform sampler3D samSelectionVolume;
uniform sampler2D samBackgroundSelectionColorTransferFunction;
uniform sampler2D samGhostSelectionColorTransferFunction;
uniform sampler2D samBackgroundLightingTransferFunction;
uniform sampler2D samGhostLightingTransferFunction;
uniform sampler2D samSelectionLightingTransferFunction;
uniform samplerRectShadow samGeometryDepth;
uniform samplerRectShadow samGhostCutoutDepth;
uniform samplerRectShadow samSelectionCutoutDepth;
uniform float fCutoutGhost;
uniform vec3 vecDirection;
uniform vec3 vecScale;

void main()
{
	vec3 vecFragment = gl_FragCoord.xyz * vecScale;

	discard(shadowRect(samGeometryDepth,vecFragment).z);
	discard(shadowRect(samSelectionCutoutDepth,vecFragment).z);
	
	vec3 vecOffset = GetOffset(vecFragment)*vecDirection;
	vec3 vecPositionBackground = gl_TexCoord[0].xyz - vecOffset;

	vec4 vecSampleDataVolume = GetDataVolumeSample(samDataVolume,vecPositionBackground);
	vec4 vecColorBackground = GetColor(samBackgroundSelectionColorTransferFunction,vec2(vecSampleDataVolume.a,0.0));
	vec4 vecColorGhost = GetColor(samGhostSelectionColorTransferFunction,half2(vecSampleDataVolume.a,0.0));
		
	float fSampleGhostActive = GetSelectionVolumeSample(samSelectionVolume,vecPositionBackground);
	float fSampleBackgroundActive = 1.0 - fSampleGhostActive;

	vec3 vecProducts = GetProducts(gl_TexCoord[2].xyz,gl_TexCoord[3].xyz,vecSampleDataVolume.xyz);
	vec4 vecLightingBackground = GetLighting(samBackgroundLightingTransferFunction,vecProducts);
	vec4 vecLightingGhost = GetLighting(samGhostLightingTransferFunction,vecProducts);

	float fGhosting = fCutoutGhost*shadowRect(samGhostCutoutDepth,vecFragment).z;
	vecColorBackground = GetShaded(vecColorBackground,vecLightingBackground,fGhosting);
	vecColorGhost = GetShaded(vecColorGhost,vecLightingGhost);

	float fBackgroundActive = min(fSampleBackgroundActive,vecColorBackground.a);
	float fGhostActive = min(fSampleGhostActive,vecColorGhost.a);
	
	vec4 vecColorVolume;
	vecColorVolume = (vecColorBackground*fBackgroundActive + vecColorGhost*fGhostActive) / (fBackgroundActive+fGhostActive);
	vecColorVolume.a = max(fBackgroundActive,fGhostActive);

	gl_FragColor = vecColorVolume;
	gl_FragColor.rgb *= gl_FragColor.a;
}