History: Fading Object Shader
Source of version: 4 (current)
Copy to clipboard
!!Description
This shader applies to an object a color that fade to dark when getting away from the camera. I use it for large object, to emphase the feeling of largeness. The object is not textured, but just colorized.
{img src="img/wiki_up/Gradient_shader.jpg" alt="Gradient_shader.jpg"}
!!Usage
To use the shader, you will need to give 2 custom parameters:
* the color of the object.
* the radius of the object.
And then apply the __shader/gradient__ material to your object.
Example :
{CODE(wrap="1", colors="c++")} Vector4 vColour = Vector4(circlecolour.r, circlecolour.g, circlecolour.b, circlecolour.a);
Vector4 vRadius = Vector4(mRadius,0,0,0);
mObject->setCustomParameter(0,vColour);
mObject->setCustomParameter(1,vRadius);
mObject->setMaterial("shader/gradient");
{CODE}
!!Gradientshader.cg
{CODE(wrap="1", colors="c++")} // --------------------------------------------------------------------
// Gradient shader : vertex program
// Author : David de Lorenzo
// -----------------------------------------------------------------
void gradient_vp( in float4 position : POSITION,
uniform float4x4 worldViewProj,
uniform float3 camera_position_object_space,
uniform float4 customParamColour,
uniform float4 customParamRadius,
out float4 oPosition : POSITION,
out float4 oColor : COLOR
)
{
// Get the custom parameters
float objectradius = customParamRadius.x;
// calculate output position
oPosition = mul(worldViewProj, position);
// Calculate the color value, depending on the position
float3 vect_center_to_cam = camera_position_object_space;
float3 position_closest = normalize(vect_center_to_cam) * objectradius;
float Rc = (position_closest.z * position.z ) + (position_closest.x * position.x); // Ratio on Center-to-Cam axis
Rc = Rc / (objectradius * objectradius); // recalibrate (-1..1)
float ratio = (1+Rc); // recalibrate ( 0..2) - (x2 to emphasis the color)
oColor= ratio * customParamColour;
}
// -----------------------------------------------------------------
// Gradient shader : fragment program
// Author : David de Lorenzo
// -----------------------------------------------------------------
float4 main_fp(in float4 color : COLOR) : COLOR0
{
return (color);
}
{CODE}
!!Gradientshader.material
{CODE(wrap="1", colors="c++")} vertex_program shader/gradientVP cg
{
source gradientshader.cg
entry_point gradient_vp
profiles vs_1_1
default_params
{
param_named_auto worldViewProj worldviewproj_matrix
param_named_auto camera_position_object_space camera_position_object_space
}
}
fragment_program shader/gradientFP cg
{
source gradientshader.cg
entry_point main_fp
profiles ps_1_1
}
material shader/gradient
{
technique
{
pass
{
vertex_program_ref shader/gradientVP
{
param_named_auto customParamColour custom 0
param_named_auto customParamRadius custom 1
}
fragment_program_ref shader/gradientFP
{
}
}
}
}
{CODE}
---
Alias: (alias(Fading_Object_Shader))