Snowflakes

glint · Examples · Tutorials · Gallery

Falling snowflakes, every one different: fold the angle into one twelfth of the circle (six arms, each mirrored) and draw an arm with side branches whose lengths come from the flake's own random numbers.

Snowflakes: 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 segment(vec2 p, vec2 a, vec2 b) {
    vec2 pa = p - a, ba = b - a;
    return length(pa - ba * clamp(dot(pa, ba) / dot(ba, ba), 0.0, 1.0));
}

float flake(vec2 p, float seed) {
    float a = atan(p.y, p.x), r = length(p);
    float s = 3.14159 / 3.0;
    a = abs(mod(a, s) - s * 0.5);                               // six arms, each mirrored
    p = r * vec2(cos(a), sin(a));
    float d = segment(p, vec2(0.0), vec2(1.0, 0.0));
    for (int i = 1; i <= 3; i++) {
        float x = float(i) * 0.25;
        float len = 0.1 + 0.3 * hash(seed + float(i));
        d = min(d, segment(p, vec2(x, 0.0), vec2(x + len * 0.6, len)));
    }
    return min(d, abs(r - 0.18 * hash(seed + 9.0)));
}

void main() {
    vec2 uv = gl_FragCoord.xy / resolution.y;
    vec3 col = mix(vec3(0.35, 0.5, 0.75), vec3(0.05, 0.1, 0.25), gl_FragCoord.y / resolution.y);
    // Three layers, near ones bigger and faster; one flake per cell.
    for (int layer = 0; layer < 3; layer++) {
        float fl = float(layer);
        float cells = 3.0 + fl * 2.0;
        vec2 q = uv * cells + vec2(sin(time * 0.3 + fl) * 0.3, time * (0.6 - fl * 0.15));
        vec2 id = floor(q), f = fract(q) - 0.5;
        float seed = hash(id + fl * 17.0) * 100.0;
        f += (hash2(seed) - 0.5) * 0.4;
        f = rot(time * (hash(seed) - 0.5)) * f;
        float size = 0.3 - fl * 0.06;
        float d = flake(f / size, seed) * size;
        float w = 0.012 / cells * 3.0;
        col += vec3(0.95, 0.97, 1.0) * (smoothstep(w, 0.0, d) + 0.004 / (d + 0.01)) * (1.0 - fl * 0.25) * step(0.3, hash(id + 3.0 + fl));
    }
    fragColor = vec4(col, 1.0);
}

More More GLSL examples

Hyperbolic tiling · Wave interference · Lorenz attractor · Voxel world · Maurer rose · Spirograph · Field lines · Tesseract