Skip to content

Instantly share code, notes, and snippets.

@thatcosmonaut
Created September 8, 2020 04:05
Show Gist options
  • Save thatcosmonaut/4ff5736f4fc341cfa2ea832db0903a44 to your computer and use it in GitHub Desktop.
Save thatcosmonaut/4ff5736f4fc341cfa2ea832db0903a44 to your computer and use it in GitHub Desktop.
sampling from a cube map as though it were a 3d texture
float ComputeShadow(float4 positionLightSpace, int directionalLightIndex)
{
float bias = 0.005;
// maps to [-1, 1]
float3 projectionCoords = positionLightSpace.xyz / positionLightSpace.w;
// map our UV sample coordinates to a cube map sample vector
float3 cubeMapSampleVector;
if (directionalLightIndex == 0)
{
cubeMapSampleVector = float3(1.0f, projectionCoords.y, -projectionCoords.x);
}
else if (directionalLightIndex == 1)
{
cubeMapSampleVector = float3(-1.0f, projectionCoords.y, projectionCoords.x);
}
else if (directionalLightIndex == 2)
{
cubeMapSampleVector = float3(projectionCoords.x, 1.0f, projectionCoords.y);
}
else if (directionalLightIndex == 3)
{
cubeMapSampleVector = float3(projectionCoords.x, -1.0f, -projectionCoords.y);
}
else if (directionalLightIndex == 4)
{
cubeMapSampleVector = float3(projectionCoords.x, projectionCoords.y, 1.0);
}
else
{
cubeMapSampleVector = float3(-projectionCoords.x, projectionCoords.y, -1.0);
}
float closestDepth = SAMPLE_CUBEMAP(shadowMap, cubeMapSampleVector).r;
float currentDepth = projectionCoords.z;
if (projectionCoords.z > 1.0) { return 0.0; }
float shadow = currentDepth - bias > closestDepth ? 1.0 : 0.0;
return shadow;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment