Topics for v2.x
Topics for v1.x
Shader snippets
Here is a few snippets of shader code that can be useful from time to time.
Patterns
Creates a grid pattern
float cellcount = 15;
//float2 cell = floor(pi.tex * cellcount);
//float2 oddeven = fmod(cell, 2.0);
float2 cellUV = frac((pi.tex+float2(0.5,0.5)) * cellcount) - float2(0.5,0.5);
Math
Smooth bump
Creates a smooth bump that is flat from 0.5 to 1.5. Good for creating rings in a shader
float v = smoothstep(0,0.5,x)*(1-smoothstep(1.5,2,x));
Lightning
Half lambert
Nice but simple lightning as seen in Valve Half lambert
light = dot(vec1, vec2)*0.5+0.5;
Rotate normal
When rotating a normal vector care must be taken not to also accidentally translate it with the objects position. The WorldInverseTransponse matrix handles this for us
float3 normalInWorldSpace = mul(gWIT, normal)
Direction vector from camera to a world position
float3 eyeDir = normalize(float3(gVI[0].w, gVI[1].w, gVI[2].w) - worldSpacePos)
Rotation
Rotate vector around X axis
float3 rotateX(float3 v, float angle)
{
float s, c;
sincos(angle, out s, out c);
return float3(v.x, c*v.y + s*v.z, -s*v.y + c*v.z);
}
Rotate vector around Y axis
float3 rotateY(float3 v, float angle)
{
float s, c;
sincos(angle, out s, out c);
return float3(c*v.x + s*v.z, v.y, -s*v.x + c*v.z);
}
Rotate vector around Z axis
float3 rotateZ(float3 v, float angle)
{
float s, c;
sincos(angle, out s, out c);
return float3(c*v.x + s*v.y, -s*v.x + c*v.y, v.z);
}
Post processing
Color correction
float inBlack=20, inGamma=1.7, inWhite=170;
float outBlack = 0, outWhite = 255;
float3 newColor =
(pow(((originalColor*255.0)-inBlack)/ (inWhite-inBlack), inGamma)*(outWhite-outBlack)+outBlack)/255.0;
Brightness
float3 newColor = brightness * originalColor;
Contrast
float3 newColor = (originalColor-float3(0.5)) * contrast + float3(0.5);
Grayscale
float3 newColor = dot(float3(0.222, 0.707, 0.071), originalColor);
Emboss
float3 embos = tex2D( tex1, pi.tex-0.001)*2.0f- tex2D( tex1, pi.tex+0.001)*2.0f;
float3 newColor = (embos.r+embos.g+embos.b)/3.0f;
Posterization
float gamma = 0.6;
float numColors = 8.0;
float3 c = pow(originalColor, float3(gamma));
c = floor(c * numColors) / numColors;
float3 newColor = pow(c, float3(1.0/gamma));
Black and white
float3 newColor = float3(1.0);
float t = (originalColor.r+originalColor.g+originalColor.b)/3.0f;
if (t<0.1 || t>0.9) newColor = float(0.0);
Invert
float3 newColor = 1-originalColor;