/*
   Author: Themaister
   License: Public domain
*/

#include "../compat_includes.inc"
uniform COMPAT_Texture2D(decal) : TEXUNIT0;
uniform float4x4 modelViewProj;

float min(float2 x)
{
   if (x.x > x.y)
      return x.y;
   else
      return x.x;
}

struct out_vertex
{
	float4 position : COMPAT_POS;
	float2 texCoord : TEXCOORD0;
#ifndef HLSL_4
	float4 Color    : COLOR;
#endif
};

out_vertex main_vertex(COMPAT_IN_VERTEX)
{
	out_vertex OUT;
#ifdef HLSL_4
	float4 position = VIN.position;
	float2 texCoord = VIN.texCoord;
#else
	OUT.Color = color;
#endif
	OUT.position = mul(modelViewProj, position);
   
	float2 box_scale = floor(COMPAT_output_size / COMPAT_video_size);
	box_scale = float2(min(box_scale), min(box_scale));

	float2 scale = (COMPAT_output_size / COMPAT_video_size) / box_scale;
	float2 middle = 0.5 * COMPAT_video_size / COMPAT_texture_size;
	float2 diff = texCoord.xy - middle;
	OUT.texCoord = middle + diff * scale;
	
	return OUT;
}

float4 main_fragment (COMPAT_IN_FRAGMENT) : COMPAT_Output
{
   return COMPAT_SamplePoint(decal, VOUT.texCoord);
}
COMPAT_END