It is straightforward to use the GLSL discard
keyword in combination with noise to simulate erosion or decay. We can simply discard fragments that correspond to a noise value that is above or below a certain threshold. The following image shows a teapot with this effect. Fragments are discarded when the noise value corresponding to the texture coordinate is outside a certain threshold range.
Set up your OpenGL program to provide position, normal, and texture coordinates to the shader. Be sure to pass the texture coordinate along to the fragment shader. Set up any uniforms needed to implement the shading model of your choice.
Create a seamless noise texture (see Creating a seamless noise texture), and place it in the appropriate texture channel.
The following uniforms are defined in the fragment shader, and should be set via the OpenGL program:
NoiseTex
: The noise texture.LowThreshold
: Fragments are discarded if the noise value is below this value.HighThreshold
: Fragments are discarded if the noise value is above this value.To create a shader program that provides a disintegration effect, use the following steps:
TexCoord
. It should also pass the position and normal to the fragment shader through the variables Position
and Normal
.// Insert uniforms needed for the Phong shading model layout(binding=0) uniform sampler2D NoiseTex; in vec4 Position; in vec3 Normal; in vec2 TexCoord; uniform float LowThreshold; uniform float HighThreshold; layout ( location = 0 ) out vec4 FragColor; vec3 phongModel() { // Compute Phong shading model… } void main() { // Get the noise value at TexCoord vec4 noise = texture( NoiseTex, TexCoord ); // If the value is outside the threshold, discard if( noise.a < LowThreshold || noise.a > HighThreshold) discard; // Color the fragment using the shading model vec3 color = phongModel(); FragColor = vec4( color , 1.0 ); }
The fragment shader starts by retrieving a noise value from the noise texture (NoiseTex
), and storing the result in the variable noise
. We want noise that has a large amount of high-frequency fluctuation, so we choose four-octave noise, which is stored in the alpha channel (noise.a
).
We then discard the fragment if the noise value is below LowThreshold
or above HighThreshold
. As the discard
keyword causes the execution of the shader to stop, the following statements will not execute if the fragment is discarded.
Finally, we compute the shading model and apply the result to the fragment.
3.143.9.115