depth_testing.hlsl

src/4.advanced_d3d11/1.1.depth_testing/depth_testing.hlsl · 64 lines

// Read matrices row by row, as rin stores them; mul(M, v) is then M * v.
#pragma pack_matrix(row_major)

cbuffer transforms : register(b0)
{
    float4x4 model;
    float4x4 normal_matrix;
    float4x4 view;
    float4x4 projection;
    float3 view_position;
};

struct vs_in
{
    float3 position : POSITION;
    float3 normal : NORMAL;
    float2 uv : TEXCOORD;
};

// Position and normal in world space, where the lighting is done.
struct vs_out
{
    float4 position : SV_Position;
    float3 world : WORLD;
    float3 normal : NORMAL;
    float2 uv : TEXCOORD;
};

vs_out vs_main(vs_in v)
{
    vs_out o;
    float4 world = mul(model, float4(v.position, 1.0));
    o.world = world.xyz;
    o.position = mul(projection, mul(view, world));
    o.normal = mul((float3x3)normal_matrix, v.normal);
    o.uv = v.uv;
    return o;
}

cbuffer view_mode : register(b1)
{
    int mode;
    float near_plane;
    float far_plane;
};

Texture2D albedo : register(t0);
SamplerState linear_wrap : register(s0);

// The eye-space distance a 0..1 depth came from: the projection, undone.
float linear_depth(float depth)
{
    return near_plane * far_plane / (far_plane - depth * (far_plane - near_plane));
}

float4 ps_main(vs_out p) : SV_Target
{
    // In a pixel shader SV_Position is the pixel: x and y in pixels, z the
    // depth about to be tested. GL calls it gl_FragCoord.
    float depth = p.position.z;
    if (mode == 1) return float4(depth.xxx, 1.0);
    if (mode == 2) return float4((linear_depth(depth) / 10.0).xxx, 1.0);
    return albedo.Sample(linear_wrap, p.uv);
}
Part of masm64-dx11, LearnOpenGL's lessons rewritten for Direct3D 11 in x64 assembly. Licensed CC BY-NC 4.0, after LearnOpenGL by Joey de Vries.