Candle

glint · Examples · Tutorials · Gallery

A candle flame from an ellipse that narrows as it rises, pushed sideways by noise that grows with height: blue at the base, a white core, and a warm glow on the wax.

Candle: 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 noise(vec2 p) {
    vec2 i = floor(p), f = fract(p);
    f = f * f * (3.0 - 2.0 * f);
    return mix(mix(hash(i), hash(i + vec2(1.0, 0.0)), f.x), mix(hash(i + vec2(0.0, 1.0)), hash(i + vec2(1.0, 1.0)), f.x), f.y);
}
float fbm(vec2 p) {
    float v = 0.0, a = 0.5;
    for (int i = 0; i < 5; i++) { v += a * noise(p); p = p * 2.03 + 17.0; a *= 0.5; }
    return v;
}

void main() {
    vec2 uv = (gl_FragCoord.xy - 0.5 * resolution) / resolution.y;
    vec2 q = uv - vec2(0.0, -0.02);
    float flicker = noise(vec2(time * 3.0, 0.0));
    // Sway: more the higher up the flame.
    q.x += (noise(vec2(q.y * 5.0 - time * 5.0, time)) - 0.5) * 0.08 * max(q.y, 0.0) * 3.0;
    vec2 f = q;
    f.x *= 1.0 + max(f.y - 0.04, 0.0) * 10.0;                      // narrow towards a point
    float e = length(vec2(f.x / 0.042, (f.y - 0.06) / (f.y > 0.06 ? 0.15 + 0.02 * flicker : 0.06)));
    vec3 glow = vec3(1.0, 0.5, 0.15) * 0.06 / (length(q - vec2(0.0, 0.08)) + 0.08) * (0.9 + 0.2 * flicker);
    vec3 col = vec3(0.02, 0.01, 0.01) + glow * 0.8;
    // The candle, lit from above.
    if (abs(uv.x) < 0.09 && uv.y < -0.04) {
        float lightOnWax = exp((uv.y + 0.04) * 4.0);
        col = vec3(0.9, 0.8, 0.65) * (0.15 + 0.6 * lightOnWax) * (1.0 - 0.4 * pow(abs(uv.x) / 0.09, 2.0));
    }
    col = mix(col, vec3(0.05), smoothstep(0.004, 0.0, max(abs(q.x) - 0.004, abs(q.y + 0.0) - 0.03)));   // wick
    vec3 flame = mix(vec3(1.0, 0.45, 0.1), vec3(1.0, 0.9, 0.5), smoothstep(1.0, 0.4, e));
    flame = mix(flame, vec3(1.0, 1.0, 0.95), smoothstep(0.45, 0.2, e));
    flame = mix(flame, vec3(0.2, 0.35, 1.0), smoothstep(0.03, -0.02, q.y) * 0.8);               // blue base
    col = mix(col, flame, smoothstep(1.0, 0.8, e));
    fragColor = vec4(col + glow * 0.3, 1.0);
}

More More GLSL examples

Soap bubbles · Sierpinski tetrahedron · CRT television · Lightning · Planet · Isometric city · Gyroscope · Moiré