xxxxxxxxxx
41
precision mediump float;
// Coordinates of the pixel we are computing
varying vec2 vTexCoord;
// Variables we set with "setUniform" from our sketch
uniform sampler2D image; // image we are applying grain to
uniform float grainVary; // how much variance in the grain texture
uniform float seed; // Seed for rand() function
uniform float pixD;
// The GPU has no random() function, so instead
// do some maths on the position of the pixel to approximate a
// random number. This will be the same each time though
// so you could add another uniform variable that is set
// randomly from JavaScript to change it each time.
float rand(vec2 co, float salt){
return fract(sin(dot(co, vec2(12.9898, 78.233) + salt + seed)) * 43758.5453);
}
void main() {
// Retreive the colour from the image at
// the pixel we are computing
vec2 uv = vTexCoord;
uv = uv;//pixD;
uv.y = 1.0 - uv.y;
vec4 col = texture2D(image, uv);
// Use the rand function to create a random number
// with a different "salt" value for each colour channel
// pass that into sin() to get something between -1, 1
// multiply by the grain variance
col.r += sin(rand(uv, 0.0)) * grainVary;
col.g += sin(rand(uv, 1.0)) * grainVary;
col.b += sin(rand(uv, 2.0)) * grainVary;
// Modified colour is our output
gl_FragColor = col;
}