How can use shaders in my project
Posted: Sat Jun 19, 2010 2:52 am
Hello everyone. I don't understand how use shaders.
For example:
This simple shader "water effect":
water.cg:
What will i write in code to use this shader?
For example:
This simple shader "water effect":
water.cg:
Code: Select all
/**Vertex shader**/
struct app2vert
{
float4 Position:POSITION;
};
struct vert2frag
{
float4 HPosition:POSITION;
float4 TexCoord0:TEXCOORD0;
float4 TexCoord1:TEXCOORD1;
float4 Color0:COLOR0;
float4 Color1:COLOR1;
};
void calcWave(out float disp, out float2 normal,
float dampening, float3 viewPosition,
float waveTime, float height,
float frequency, float2 waveDirection)
{
float distance1=dot(viewPosition.xy, waveDirection);
distance1=frequency*distance1+waveTime;
disp=height*sin(distance1)/dampening;
normal=-cos(distance1)*height*frequency*(waveDirection.xy)/(.4*dampening);
}
vert2frag main(
app2vert IN,
uniform float4x4 ModelViewProj,
uniform float4x4 ModelView,
uniform float4x4 ModelViewIT
uniform float4x4 TextureMat,
uniform float Time,
uniform float4 Wave1,
uniform float4 Wave1Origin,
uniform float4 Wave2,
uniform float4 Wave2Origin,
const uniform float4 WaveData[5])
{
vert2frag OUT;
float4 position=float4(IN.Position.x,0,IN.Position.y,1);
float4 normal=float4(0,1,0,0);
float dampening=1+dot(position.xyz,position.xyz)/1000;
float i,disp;
float2 norm;
for(i=0;i<5;i=i+1)
{
float waveTime=Time.x*WaveData[i].z;
float frequency=WaveData[i].z;
float height=WaveData[i].w;
float2 waveDir=WaveData[i].xy;
calcWave(disp,norm,dampening,IN.Position.xyz,waveTime,height,frequency,waveDir);
position.y=position.y+disp;
normal.xz=normal.xz+norm;
}
OUT.HPosition=mul(ModelViewProj,position);
//Transform normal into eye-space
normal=mul(ModelViewIT,normal);
normal.xyz=normalize(normal.xyz);
//get a vector from the vertex to the eye
float3 eyeToVert=mul(ModelView,position).xyz;
eyeToVert=normalize(eyeToVert);
//calculate the reflected vector for cubemap look-up
float4 reflected=mul(TextureMat,reflect(eyeToVert,normal.xyz).xyzz);
//output two reflection vectors for the two environment cubemaps
OUT.TexCoord0=reflected;
OUT.TexCoord1=reflected;
//Calculate a fresnel term(note that f0=0)
float fres=1+dot(eyeToVert,normal.xyz);
fres=pow(fres,5);
//set the two color coefficients (the magic constants are arbitrary), these two color coefficients are used
//to calculate the contribution from each of the two environment cubemaps(one bright,one dark)
OUT.Color0=(fres*1.4+min(reflected.y,0)).xxxx+float4(.2,.3,.3,0);
OUT.Color1=(fres*1.26).xxxx;
return OUT;
}
/**Pixel shader**/
float4 main(in float3 color0:COLOR0,
in float3 color1:COLOR1,
in float3 reflectVec:TEXCOORD0,
in float3 reflectVecDark:TEXCOORD1,
uniform samplerCUBE environmentMaps[2]
):COLOR
{
float3 reflectColor=texCUBE(environmentMaps[0],reflectVec).rgb;
float3 reflectColorDark=texCUBE(environmentMaps[1],reflectVecDark).rgb;
float3 color=(reflectColor*color0)+(reflectColorDark*color1);
return float4 (color,1.0);
}