// Copyright (C) 2011 by The Alexandra Institute Ltd.
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#version 330

precision mediump float;

// Attributes
// See RSMVS.glsl
in vec3 kWSPos;
in vec3 kWSNormal;
in float fDepth;
in vec4 kCSPos;
in vec2 kTexcoord;

// Packed FBO output
out vec4 FRAGDATA0;	// Position + texcoord.u
out vec4 FRAGDATA1;	// Normal + Depth
out vec4 FRAGDATA2;	// Flux + texcoord.v

// Uniforms
uniform vec3 kLightIntensity;	// Light intensity (W/sr)
uniform float fNearPlane;		// Near-plane placement
uniform vec2 kPixelSize;		// Size of a pixel on the near-plane
uniform float fPixelArea;		// Area of a pixel on the near-plane
uniform vec2 kViewport;			// Size of the viewport

// Shader code
void main()
{
	// Find clip-space position
	vec4 kCSPosW = kCSPos / kCSPos.w;

	// Find position on the near-plane
	vec2 kTexPos = ((kCSPosW + 1.0) * 0.5).xy;
	kTexPos *= kViewport;
	kTexPos = (kTexPos - (kViewport * 0.5) + 0.5) * kPixelSize;

	// Calculate the solid angle of the pixel
	float fSolidAngle = fPixelArea / pow(fNearPlane * fNearPlane + dot(kTexPos, kTexPos), 1.5);

	// Write data to RSM textures
	FRAGDATA0 = vec4(kWSPos, kTexcoord.x);
	FRAGDATA1 = vec4(kWSNormal, fDepth);
	FRAGDATA2 = vec4(kLightIntensity * fSolidAngle, kTexcoord.y);
}
