octahedral.slang

cross platform rendering playground

src/shaders/lib/octahedral.slang

520 B
#pragma once

// octahedral encoding: unit direction <-> [-1, 1]²
// from McGuire's reference, based on Meyer et al.

vec2 OctEncode(vec3 n) {
    n /= abs(n.x) + abs(n.y) + abs(n.z);
    vec2 uv = n.z >= 0.0 ? n.xy : (1.0 - abs(n.yx)) * (vec2(n.x >= 0.0 ? 1.0 : -1.0, n.y >= 0.0 ? 1.0 : -1.0));
    return uv;
}

vec3 OctDecode(vec2 uv) {
    vec3 n = vec3(uv.x, uv.y, 1.0 - abs(uv.x) - abs(uv.y));
    f32 t = max(-n.z, 0.0);
    n.x += n.x >= 0.0 ? -t : t;
    n.y += n.y >= 0.0 ? -t : t;
    return normalize(n);
}