// Meltdown Shader
//
// Copyright Outerspace Software, all rights reserved

string description = "Meltdown Effect."; 

float4x4	WorldViewProjection;	
float4		DiffuseCol;
float4 		MyTextureResolution0;

float4 Prop0
<
string UIName="Meltdown Stage";
float UIMin=0;
float UIMax=1;
float3 UIDefault=float3(0,0,0);
int UISliders=1;
float UIScale=1;
bool UIInteger=false;
int UIWidget=0;
> = float4(0,0,0,0);

float4 Prop1
<
string UIName="Meltdown Pattern";
float UIMin=0;
float UIMax=100;
float3 UIDefault=float3(40,30,20);
int UISliders=3;
float UIScale=1;
bool UIInteger=false;
int UIWidget=0;
> = float4(40,30,20,1);

float4 Prop2
<
string UIName="Meltdown Bending";
float UIMin=0;
float UIMax=1;
float3 UIDefault=float3(1,0,0);
int UISliders=2;
float UIScale=1;
bool UIInteger=false;
int UIWidget=0;
> = float4(1,0,0,0);

float4 Prop3
<
string UIName="Meltdown Lighting";
float UIMin=0;
float UIMax=2;
float3 UIDefault=float3(1.3,0,0);
int UISliders=1;
float UIScale=1;
bool UIInteger=false;
int UIWidget=0;
> = float4(1.3,0,0,0);

texture MyTexture0;
sampler MyTextureSampler0 = sampler_state
{
   Texture = <MyTexture0>;
   MinFilter = Linear;
   MagFilter = Linear;
   MipFilter = Linear;   
   AddressU  = Wrap;
   AddressV  = Wrap;
};

struct VS_INPUT{
	float4 position:	POSITION;
	float3 normal:		NORMAL;
	float3 diffuse:		COLOR;
	float2 tex:		TEXCOORD0;
};

struct VS_OUTPUT{
	float4 position:	POSITION;
	float4 diffuse:		COLOR;
	float2 tex:		TEXCOORD0;
};

struct PS_OUTPUT{
    float4 color:		COLOR;
};


VS_OUTPUT VS(VS_INPUT input){
	VS_OUTPUT output;      

	float4 p=input.position;

	p.y = 125 - (125-p.y)*3;

	output.position = mul(p, WorldViewProjection);
	output.diffuse  = DiffuseCol;

	float2 uv= input.tex;

	uv.y=uv.y*3;

	output.tex	= uv;
	return output;
}

PS_OUTPUT PS(VS_OUTPUT input){
	PS_OUTPUT output;

	float2 uv=input.tex;

	//Bending	
	float d=(uv.x-Prop2.x)*Prop2.y*2;
	d=d*d;
	uv.y -= d;

	//Melting
	d = sin(uv.x*Prop1.x) + sin(uv.x*Prop1.y + Prop1.z);
	
	d=(d+2)*0.25;	//[0,1]

	//lighting
	float b=(1-d)*Prop0.x*uv.y*4;
	if(b>2) b-=2;
	if(b>1) b=2-b;
	b*=Prop3.x;


	b=b*b*b;

	d=0.5 + d*0.5;	//[0.5,1]

	d=1 + Prop0.x*(d-1);

	uv.y *= d;

   	float4 c = tex2D(MyTextureSampler0, uv);
	c.xyz = c.xyz + b*(float3(1,1,1)-c.xyz);

	const float smooth=0.02;

	if(uv.y<0 || uv.y>1) 
		c.w=0;
	else if(uv.y<smooth)
		c.w=uv.y/smooth;
	else if(uv.y>(1-smooth))
		c.w=(1-uv.y)/smooth;

	output.color = c*DiffuseCol;

	return output;
}


technique Shader
{
    pass P0
    {
	Alphablendenable= TRUE;
	SRCBLEND	= SRCALPHA;
	DESTBLEND	= INVSRCALPHA;
	ALPHAARG1[0]	= DIFFUSE;
	ALPHAOP[0]	= SELECTARG1;
	ALPHATESTENABLE	= TRUE;
	ALPHAREF	= 1;
	ALPHAFUNC	= GREATEREQUAL;

        VertexShader = compile vs_1_1 VS();
        PixelShader  = compile ps_2_0 PS();
    }
}

