Newton fractal

glint · Examples · Tutorials · Gallery

Newton's method for z³ = 1 from every starting point: coloured by which of the three roots it ends up at, shaded by how long it took. The borders between them are fractal; a relaxation factor keeps it moving.

Newton fractal: 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))); }

vec2 cmul(vec2 a, vec2 b) { return vec2(a.x * b.x - a.y * b.y, a.x * b.y + a.y * b.x); }
vec2 cdiv(vec2 a, vec2 b) { return vec2(a.x * b.x + a.y * b.y, a.y * b.x - a.x * b.y) / dot(b, b); }

void main() {
    vec2 uv = (gl_FragCoord.xy - 0.5 * resolution) / resolution.y;
    vec2 z = rot(time * 0.05) * uv * (1.6 + 0.8 * sin(time * 0.1));
    float relax = 1.0 + 0.35 * sin(time * 0.23);                    // 1 is plain Newton
    float n = 0.0;
    for (int i = 0; i < 40; i++) {
        vec2 z2 = cmul(z, z);
        vec2 f = cmul(z2, z) - vec2(1.0, 0.0), df = 3.0 * z2;
        vec2 dz = relax * cdiv(f, df);
        z -= dz;
        n += 1.0;
        if (dot(dz, dz) < 1e-8) break;
    }
    // Which root: the three cube roots of 1 sit at angles 0, 120 and 240 degrees.
    float a = atan(z.y, z.x);
    float root = floor(mod(a / 2.0944 + 0.5, 3.0));
    vec3 col = root < 0.5 ? vec3(0.95, 0.35, 0.3) : root < 1.5 ? vec3(0.3, 0.8, 0.45) : vec3(0.3, 0.45, 0.95);
    col *= 1.0 - n / 45.0;
    fragColor = vec4(pow(col, vec3(0.8)), 1.0);
}

More More GLSL examples

Phyllotaxis · Pong · Jellyfish · Fireflies · Burning ship · Perfect loop · Piano overlay · Listening piano