Field lines

glint · Examples · Tutorials · Gallery

Four moving electric charges. In 2D, adding up each charge's angle to the point gives a function whose contours are exactly the field lines; adding up 1 / distance gives the equipotentials.

Field lines: 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))); }

void main() {
    vec2 uv = (gl_FragCoord.xy - 0.5 * resolution) / resolution.y;
    float psi = 0.0, v = 0.0;
    vec3 dots = vec3(0.0);
    for (int i = 0; i < 4; i++) {
        float fi = float(i);
        float q = mod(fi, 2.0) < 1.0 ? 1.0 : -1.0;
        vec2 c = vec2(sin(time * 0.3 + fi * 1.7) * 0.5, cos(time * 0.4 + fi * 2.3) * 0.3);
        vec2 d = uv - c;
        psi += q * atan(d.y, d.x);                                // stream function
        v += q / length(d);                                       // potential
        dots += (q > 0.0 ? vec3(1.0, 0.3, 0.2) : vec3(0.2, 0.5, 1.0)) * smoothstep(0.025, 0.02, length(d));
    }
    float lines = abs(fract(psi * 16.0 / 6.28318) - 0.5) * 2.0;
    float equi = abs(fract(v * 0.4) - 0.5) * 2.0;
    vec3 col = mix(vec3(0.05, 0.04, 0.08), v > 0.0 ? vec3(0.35, 0.08, 0.06) : vec3(0.05, 0.12, 0.35), min(abs(v) * 0.15, 1.0));
    col += vec3(0.8) * smoothstep(0.12, 0.0, lines) * 0.6;
    col += vec3(0.9, 0.8, 0.3) * smoothstep(0.08, 0.0, 1.0 - equi) * 0.25;
    fragColor = vec4(col + dots, 1.0);
}

More More GLSL examples

Voxel world · Snowflakes · Maurer rose · Spirograph · Tesseract · Black hole · Low poly · 10 PRINT