DNA helix

glint · Examples · Tutorials · Gallery

Instancing: one sphere mesh drawn 120 times. The vertex shader makes every third instance a rung (the sphere squashed into a rod) and twists them all into a double helix.

DNA helix: 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.

vertex shader

#version 300 es
in vec4 a_position;
in vec3 a_normal;

uniform mat4 mvp;
uniform mat3 normalMatrix;
uniform float time;
uniform int instanceCount;

out vec3 v_normal;
out vec3 v_color;

vec3 base(float n) {
    // Four bases, four colours.
    int b = int(mod(floor(fract(sin(n * 91.7) * 4375.5) * 4.0), 4.0));
    return b == 0 ? vec3(1.0, 0.35, 0.3) : b == 1 ? vec3(0.3, 0.8, 1.0) : b == 2 ? vec3(1.0, 0.85, 0.3) : vec3(0.5, 1.0, 0.45);
}

void main() {
    int kind = gl_InstanceID % 3;          // 0, 1: the two strands; 2: the rung between them
    float k = float(gl_InstanceID / 3);    // which step up the helix
    float steps = float(instanceCount / 3);
    float R = 0.45;
    vec3 p = a_position.xyz, n = a_normal;
    if (kind == 2) {
        // The unit sphere (radius 0.5) squashed into a rod as long as the gap between the strands.
        vec3 s = vec3(2.0 * R, 0.07, 0.07);
        p *= s;
        n = normalize(n / s);
        v_color = a_position.x > 0.0 ? base(k) : base(k + 0.5);
    } else {
        p *= 0.2;
        p.x += kind == 0 ? R : -R;
        v_color = vec3(0.85, 0.9, 1.0);
    }
    // Twist round the axis, then lay the helix on its side.
    float a = k * 0.4 + time * 0.8;
    mat2 r = mat2(cos(a), sin(a), -sin(a), cos(a));
    p.xz = r * p.xz;
    n.xz = r * n.xz;
    p.y += (k / steps - 0.5) * 4.0;
    p = vec3(p.y, -p.x, p.z);
    n = vec3(n.y, -n.x, n.z);
    v_normal = normalMatrix * n;
    gl_Position = mvp * vec4(p, 1.0);
}

fragment shader

#version 300 es
precision highp float;

in vec3 v_normal;
in vec3 v_color;
out vec4 fragColor;

void main() {
    vec3 n = normalize(v_normal);
    vec3 l = normalize(vec3(0.4, 0.8, 0.6));
    float diff = max(dot(n, l), 0.0);
    float spec = pow(max(dot(reflect(-l, n), vec3(0.0, 0.0, 1.0)), 0.0), 30.0);
    fragColor = vec4(v_color * (0.2 + 0.8 * diff) + spec * 0.5, 1.0);
}

More More GLSL examples

Night sky · Dithered retro · Chrome balls · Stained glass · Clock · Desert dunes · Apollonian · Digital rain