HLSL raymarcher

glint · Examples · Tutorials · Gallery

A raymarched scene written in HLSL: cbuffer parameters, structs, [loop] attributes and mul() with matrices.

HLSL raymarcher: an HLSL 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 HLSL.

vertex shader

// HLSL vertex shader (translated to GLSL in the browser).
float4x4 mvp;

struct VSOut
{
    float4 pos : SV_Position;
    float2 uv : TEXCOORD0;
    float3 normal : NORMAL;
};

VSOut main(float4 pos : POSITION, float3 normal : NORMAL, float2 uv : TEXCOORD0)
{
    VSOut o;
    o.pos = mul(mvp, pos);
    o.uv = uv;
    o.normal = normal;
    return o;
}

fragment shader

// Raymarching in HLSL. cbuffer members and globals are uniforms; params (glow, hue) have sliders.
cbuffer Frame
{
    float time;
    float2 resolution;
    float2 mouse;
    float3 spectrum;
};
float glow;
float hue;

struct Hit
{
    float dist;
    float steps;
};

float3x3 rotY(float a)
{
    float c = cos(a), s = sin(a);
    return float3x3(c, 0, s,
                    0, 1, 0,
                   -s, 0, c);
}

float sdTorus(float3 p, float2 t)
{
    float2 q = float2(length(p.xz) - t.x, p.y);
    return length(q) - t.y;
}

float map(float3 p)
{
    p = mul(rotY(time * 0.5), p);
    float d = sdTorus(p, float2(1.0, 0.3 + 0.2 * spectrum.x));
    d = min(d, sdTorus(p.yxz, float2(1.6, 0.12)));
    return min(d, p.y + 1.5);
}

Hit march(float3 ro, float3 rd)
{
    Hit h;
    h.dist = 0;
    h.steps = 0;
    [loop]
    for (int i = 0; i < 100; i++)
    {
        float d = map(ro + rd * h.dist);
        if (d < 0.001 || h.dist > 30.0) break;
        h.dist += d;
        h.steps += 1;
    }
    return h;
}

float4 main(float4 pos : SV_Position) : SV_Target
{
    float2 uv = (pos.xy - 0.5 * resolution) / resolution.y;
    float3 ro = float3(0, 0.6, 4.5);
    float3 rd = normalize(float3(uv, -1.6));
    ro = mul(rotY((mouse.x - 0.5) * 3), ro);
    rd = mul(rotY((mouse.x - 0.5) * 3), rd);
    Hit h = march(ro, rd);
    float3 tint = 0.5 + 0.5 * cos(6.28318 * (hue + float3(0, 0.33, 0.67)));
    float3 col = tint * (h.steps / 100.0) * glow;          // cheap glow from step count
    if (h.dist < 30.0)
    {
        float3 p = ro + rd * h.dist;
        float2 e = float2(0.001, 0);
        float3 n = normalize(float3(map(p + e.xyy) - map(p - e.xyy), map(p + e.yxy) - map(p - e.yxy), map(p + e.yyx) - map(p - e.yyx)));
        col += tint * saturate(dot(n, normalize(float3(0.5, 1, 0.3)))) * 0.8;
        col = lerp(col, float3(0.02, 0.02, 0.05), saturate(h.dist / 30.0));
    }
    return float4(pow(col, 0.4545), 1);
}

More HLSL & Bonzomatic examples

Bonzomatic starter · HLSL starter · Fire (HLSL)