
#include "macros.hlsl"
COMMON {
	struct PS_INPUT
	{
		float4 m_vPosition: SV_POSITION;
		float2 m_vUV: TEXCOORD0;
		uint m_uFont: SV_InstanceID;
	}
	struct TextDrawData_t
	{
		float2 m_vTexcoordOffset;
		float2 m_vTexcoordSize;
		float2 m_vPos;
		float2 m_vSize;
		float4 m_vFGColor;
		float4 m_vBGColor;
	}

	StructuredBuffer<TextDrawData_t> g_textData: register( t0 );
	cbuffer ScreenData_t: register( b1 )
	{
		float2 g_vScreenSize;
	}
	Texture2D<float4> g_atlas: register( t2 );
	SamplerState g_atlasSampler: register(s3);
}
VS
{
	struct VS_INPUT
	{
		float2 m_vPosition: POSITION;
	}


	PS_INPUT vsMain( VS_INPUT input, uint uInstance: SV_InstanceID, uint uBaseInstance: SV_StartInstanceLocation )
	{
		uint uInstance = uBaseInstance + uInstance;
		float2 position = input.m_vPosition;
		position*=g_textData[uInstance].m_vSize;
		position+=g_textData[uInstance].m_vPos;
		position/=g_vScreenSize;
		position.y = 1-position.y;
		position*=2;
		position-=1;
		float2 uv = input.m_vPosition;
		uv.y = 1-uv.y;
		uv*=g_textData[uInstance].m_vTexcoordSize;
		uv+=g_textData[uInstance].m_vTexcoordOffset;
		PS_INPUT output = {};
		output.m_vPosition = float4(position, 0, 1);
		output.m_vUV = uv;
		output.m_uFont = uInstance;
		return output;
	}


}
PS
{
	struct PS_OUTPUT
	{
		float4 m_vAlbedo: SV_Target0;
	}
	
	float ScreenPixelRange( float2 uv )
	{
		uint uWidth, uHeight;
		g_atlas.GetDimensions(uWidth, uHeight);
		float2 vUnitRange = 2.0/float2(uWidth, uHeight);
		float2 vScreenTexSize = 1.0/fwidth(uv);
		return max(0.5*dot(vUnitRange, vScreenTexSize), 1);
	}

	PS_OUTPUT psMain( PS_INPUT input )
	{
		PS_OUTPUT output = {};
		float4 vMsd = g_atlas.Sample(g_atlasSampler, input.m_vUV.xy);
		float fSd = median3(vMsd.x, vMsd.y, vMsd.z);
		float fScreenPixelDistance = ScreenPixelRange(input.m_vUV)*(fSd-0.5);
		float fOpacity = clamp(fScreenPixelDistance+0.5, 0.0, 1.0);
		float4 vColor1 = g_textData[input.m_uFont].m_vFGColor;
		float4 vColor2 = g_textData[input.m_uFont].m_vBGColor;
		vColor1.xyz*=vColor1.w;
		vColor2.xyz*=vColor2.w;
		output.m_vAlbedo = lerp(vColor2, vColor1, fOpacity);
		return output;
	}
}
