Dithered retro

glint · Examples · Tutorials · Gallery

A raymarched scene drawn like an old handheld: big pixels, four shades of green, and ordered (Bayer) dithering for everything in between.

Dithered retro: a GLSL shader

An example in glint, a free live shader editor in the browser: the GLSL code floats over the running picture and recompiles as you type.

The code

One pass, in GLSL.

fragment shader

#version 300 es
precision highp float;

uniform float time;
uniform vec2 resolution;

in vec2 v_texcoord;
out vec4 fragColor;

float hash(float n) { return fract(sin(n * 127.1) * 43758.5453); }
float hash(vec2 p) { return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); }
vec2 hash2(float n) { return fract(sin(vec2(n * 127.1, n * 269.5)) * 43758.5453); }
mat2 rot(float a) { float c = cos(a), s = sin(a); return mat2(c, s, -s, c); }
vec3 pal(float t) { return 0.5 + 0.5 * cos(6.28318 * (t + vec3(0.0, 0.33, 0.67))); }

float sdTorus(vec3 p, vec2 t) { vec2 q = vec2(length(p.xz) - t.x, p.y); return length(q) - t.y; }
float map(vec3 p) {
    vec3 q = p;
    q.xy = rot(time * 0.7) * q.xy;
    q.yz = rot(time * 0.5) * q.yz;
    return min(sdTorus(q, vec2(0.8, 0.3)), p.y + 1.2);
}
vec3 normal(vec3 p) {
    vec2 e = vec2(0.002, 0.0);
    return normalize(vec3(map(p + e.xyy) - map(p - e.xyy), map(p + e.yxy) - map(p - e.yxy), map(p + e.yyx) - map(p - e.yyx)));
}
// 4x4 Bayer matrix threshold, 0..1.
float bayer(vec2 p) {
    ivec2 i = ivec2(mod(p, 4.0));
    int m[16] = int[16](0, 8, 2, 10, 12, 4, 14, 6, 3, 11, 1, 9, 15, 7, 13, 5);
    return (float(m[i.y * 4 + i.x]) + 0.5) / 16.0;
}

void main() {
    // Big pixels: work on a grid 3 screen pixels wide.
    float px = 3.0;
    vec2 cell = floor(gl_FragCoord.xy / px);
    vec2 uv = (cell * px - 0.5 * resolution) / resolution.y;
    vec3 ro = vec3(0.0, 0.3, -3.0), rd = normalize(vec3(uv, 1.3));
    float t = 0.0;
    for (int i = 0; i < 80; i++) {
        float d = map(ro + rd * t);
        if (d < 0.001 || t > 12.0) break;
        t += d;
    }
    float shade = 0.15;
    if (t < 12.0) {
        vec3 p = ro + rd * t;
        vec3 n = normal(p);
        vec3 l = normalize(vec3(0.5, 0.9, -0.4));
        shade = 0.1 + 0.9 * max(dot(n, l), 0.0);
        // A soft shadow on the floor.
        if (p.y < -1.19) { float s = 1.0, tt = 0.05; for (int i = 0; i < 24; i++) { float h = map(p + l * tt); s = min(s, 8.0 * h / tt); tt += clamp(h, 0.02, 0.3); } shade *= 0.4 + 0.6 * clamp(s, 0.0, 1.0); }
    }
    // Four levels; the dither pattern decides between the two nearest.
    float level = floor(shade * 3.0 + bayer(cell));
    vec3 greens[4] = vec3[4](vec3(0.06, 0.22, 0.06), vec3(0.19, 0.38, 0.19), vec3(0.55, 0.67, 0.06), vec3(0.61, 0.74, 0.06));
    fragColor = vec4(greens[int(clamp(level, 0.0, 3.0))], 1.0);
}

More More GLSL examples

Snowfall · Ink in water · Infinite spheres · Night sky · Chrome balls · Stained glass · DNA helix · Clock