75 lines
2.4 KiB
HLSL
75 lines
2.4 KiB
HLSL
// XC_BUILTIN_FORWARD_LIT_D3D12_PS
|
|
Texture2D gBaseColorTexture : register(t0);
|
|
SamplerState gLinearSampler : register(s0);
|
|
Texture2D gShadowMapTexture : register(t1);
|
|
SamplerState gShadowMapSampler : register(s1);
|
|
|
|
cbuffer PerObjectConstants : register(b0) {
|
|
float4x4 gProjectionMatrix;
|
|
float4x4 gViewMatrix;
|
|
float4x4 gModelMatrix;
|
|
float4x4 gNormalMatrix;
|
|
float4 gMainLightDirectionAndIntensity;
|
|
float4 gMainLightColorAndFlags;
|
|
};
|
|
|
|
cbuffer MaterialConstants : register(b1) {
|
|
float4 gBaseColorFactor;
|
|
};
|
|
|
|
cbuffer ShadowReceiverConstants : register(b2) {
|
|
float4x4 gWorldToShadowMatrix;
|
|
float4 gShadowBiasAndTexelSize;
|
|
float4 gShadowOptions;
|
|
};
|
|
|
|
struct PSInput {
|
|
float4 position : SV_POSITION;
|
|
float3 normalWS : TEXCOORD0;
|
|
float2 texcoord : TEXCOORD1;
|
|
float3 positionWS : TEXCOORD2;
|
|
};
|
|
|
|
float ComputeShadowAttenuation(float3 positionWS) {
|
|
if (gShadowOptions.x < 0.5f) {
|
|
return 1.0f;
|
|
}
|
|
|
|
float4 shadowClip = mul(gWorldToShadowMatrix, float4(positionWS, 1.0f));
|
|
if (shadowClip.w <= 0.0f) {
|
|
return 1.0f;
|
|
}
|
|
|
|
float3 shadowNdc = shadowClip.xyz / shadowClip.w;
|
|
float2 shadowUv = float2(
|
|
shadowNdc.x * 0.5f + 0.5f,
|
|
shadowNdc.y * -0.5f + 0.5f);
|
|
if (shadowUv.x < 0.0f || shadowUv.x > 1.0f ||
|
|
shadowUv.y < 0.0f || shadowUv.y > 1.0f ||
|
|
shadowNdc.z < 0.0f || shadowNdc.z > 1.0f) {
|
|
return 1.0f;
|
|
}
|
|
|
|
const float shadowDepth = gShadowMapTexture.Sample(gShadowMapSampler, shadowUv).r;
|
|
const float receiverDepth = shadowNdc.z - gShadowBiasAndTexelSize.x;
|
|
const float shadowStrength = saturate(gShadowBiasAndTexelSize.w);
|
|
return receiverDepth <= shadowDepth ? 1.0f : (1.0f - shadowStrength);
|
|
}
|
|
|
|
float4 MainPS(PSInput input) : SV_TARGET {
|
|
float4 baseColor = gBaseColorTexture.Sample(gLinearSampler, input.texcoord) * gBaseColorFactor;
|
|
if (gMainLightColorAndFlags.a < 0.5f) {
|
|
return baseColor;
|
|
}
|
|
|
|
float3 normalWS = normalize(input.normalWS);
|
|
float3 directionToLightWS = normalize(gMainLightDirectionAndIntensity.xyz);
|
|
float diffuse = saturate(dot(normalWS, directionToLightWS));
|
|
float shadowAttenuation = diffuse > 0.0f
|
|
? ComputeShadowAttenuation(input.positionWS)
|
|
: 1.0f;
|
|
float3 lighting = float3(0.28f, 0.28f, 0.28f) +
|
|
gMainLightColorAndFlags.rgb * (diffuse * gMainLightDirectionAndIntensity.w * shadowAttenuation);
|
|
return float4(baseColor.rgb * lighting, baseColor.a);
|
|
}
|