//global scene parameters, they will be automatically set by semantic
float4x4    g_matProj : PROJ;
float4x4	g_matView : VIEW;

float3      g_LightDir : LIGHTDIR;
float4      g_LightColor : LIGHTCOLOR;
float4      g_AmbientColor : AMBIENT;

texture g_texSky;
sampler g_sSky = sampler_state
{
    Texture = <g_texSky>;
    AddressU = Clamp;
    AddressV = Clamp;
	AddressW = Clamp;
    MipFilter = NONE;
    MagFilter = LINEAR;
    MinFilter = LINEAR;
};

struct VS_INPUT
{
    float3 Pos : POSITION;
};

struct VS_OUTPUT
{
    float4 Pos : POSITION;
	float3 Normal : TEXCOORD0;
};

struct VS_OUTPUTDS
{
    float4 Pos : POSITION;
	float3 Normal : TEXCOORD0;
	float2 TexCoord : TEXCOORD1;

	#ifdef DEPTHWORLD
		float DepthWorld : TEXCOORD2;
	#else
		float2 DepthZW : TEXCOORD2;
	#endif

	#ifdef WRITEWORLD
		float3 World : TEXCOORD3;
	#endif
};

VS_OUTPUT VSSky(VS_INPUT i)
{
    VS_OUTPUT o;

	o.Normal = i.Pos;
	float3 v = mul(i.Pos, (float3x3)g_matView);
	o.Pos = mul(float4(v*2, 1), g_matProj);
	o.Pos.z = o.Pos.w;
	
    return o;
}

/*VS_OUTPUTDS VSSkyDS(VS_INPUT i)
{
    VS_OUTPUTDS o;

	float4 wpos = mul(float4(i.Pos, 1), matWorld);
	o.Pos = mul(wpos, matViewProj);
	o.Normal = normalize(mul(i.Normal, matWorld));

	#ifdef WRITEWORLD
		o.World = wpos.xyz;
	#endif
	
	#ifdef DEPTHWORLD
		float4 wview = mul(wpos, matView);
		o.DepthWorld = wview.z;
	#else
		o.DepthZW = o.Pos.zw;
	#endif
	
    return o;
}*/

void PSSky(VS_OUTPUT i, out float oDepth : DEPTH, out float4 oColor : COLOR)
{
	float4 tex = texCUBE(g_sSky, i.Normal) * ((saturate(-g_LightDir.z) * g_LightColor) + g_AmbientColor);

	//oDepth = 1;
	oColor = tex;
}

struct PS_OUT
{
	float4 Depth : COLOR0; //32bit float
	float4 NXY : COLOR1; //2x16bit float
	float4 Color : COLOR2; //32-bit argb
#ifdef WRITEWORLD
	float4 World : COLOR3;
#endif
};

/*PS_OUT PSMaterialDS(VS_OUTPUTDS i, uniform bool tex)
{
	PS_OUT o;

	#ifdef WRITEWORLD
		o.World = float4(i.World, 1);
	#endif

	#ifdef DEPTHWORLD
		o.Depth = i.DepthWorld;
	#else
		o.Depth = i.DepthZW.x / i.DepthZW.y;
	#endif

	o.NXY = float4(normalize(i.Normal).xy, 0, 0);
	o.Color = Diffuse;
	if(tex)
		o.Color *= tex2D(STexture, i.TexCoord);

	o.Color.a = sign(i.Normal.z) * 0.5 + 0.5;

	return o;
}*/

stateblock RSMaterial = stateblock_state
{
	CullMode = CW;
	ZFunc = LESSEQUAL;
    ZEnable = true;
    ZWriteEnable = false;
    AlphaBlendEnable = false;
    AlphaTestEnable = false;
};

technique RenderSky
{
	pass P0
    {      
		StateBlock = (RSMaterial);

        VertexShader = compile vs_2_0 VSSky();
        PixelShader  = compile ps_2_0 PSSky();
    }
}

/*technique RenderDS
{
	pass P0
    {      
		StateBlock = (RSMaterial);

        VertexShader = compile vs_2_0 VSMaterialDS(false);
        PixelShader  = compile ps_2_0 PSMaterialDS(false);
    }
}*/