Skip to content

Instantly share code, notes, and snippets.

@orlp
Created April 19, 2019 08:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save orlp/7c07706a6611730b22cafebf742193be to your computer and use it in GitHub Desktop.
Save orlp/7c07706a6611730b22cafebf742193be to your computer and use it in GitHub Desktop.
// Original idea by Mikkel Gjoel (https://computergraphics.stackexchange.com/a/5952/10515),
// simplified to one readable function.
// Demo at https://www.shadertoy.com/view/Wts3zH.
// Dithers and quantizes color value c in [0, 1] to the given color depth.
// It's expected that rng contains a uniform random variable on [0, 1].
uint dither_quantize(float c, uint depth, float rng) {
float cmax = float(depth) - 1.0;
float ci = c * cmax;
float d;
if (ci < 0.5 || ci >= cmax - 0.5) {
// Uniform distribution on [-0.5, 0.5] for edges.
d = rng - 0.5;
} else {
// Symmetric triangular distribution on [-1, 1].
d = (rng < 0.5) ? sqrt(2.0 * rng) - 1.0 : 1.0 - sqrt(2.0 - 2.0*rng);
}
return uint(clamp(ci + d + 0.5, 0.0, cmax));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment