I am building a 3d renderer in C++ using Vulkan.hpp. I am trying to implement Spherical Harmonics (SH) coefficients for diffuse radiance as part of global illumination. To do this I am generating two cube maps: an image cube map and a depth cube map at the probe location. These cube maps are generated by directly rendering the scene 6 times at the probe location and copying the output image to the faces of the cube map. The depth cube map is rendered to a range of 0 to 1. I want to set up a compute shader to calculate the SH coefficients. I also want to do depth testing to ensure the radiance calculated from the SH coefficients doesn't cause and light bleeding and correctly produces ambient shadows. I have the start of the compute shader I want to generate and I have a starting function to incorporate the SH coefficients into the PBR lighting shader. I'm not sure if what I have started with is the right approach though. I have depth testing occurring in the compute shader where I may also need to do testing in the lighting fragment shader. Can you complete the below compute shader or modify it accordingly? Please make any adjustments required to ensure directional consistency and to address negative irradiance values. I have also included the extract from the lighting shader that can also be modified if needed.
#define PI 3.1415926535897932384626433832795
#define SH_ORDER 2 // For second-order SH (9 coefficients)
#define NUM_COEFFS ((SH_ORDER + 1) * (SH_ORDER + 1))
#define NUM_SAMPLES 64 // Number of samples per direction
Thank you for the detailed background! Your setup of rendering cubemaps and computing SH coefficients in a compute shader, then using them in your PBR shader for diffuse irradiance, is the right approach.
I'll complete and adjust your SH compute shader with:
Proper sampling over the sphere (using the cubemap directions),
Projection of radiance (sampled with depth test),
Mercer’s filter or similar to reduce ringing/artifacts,
Directional consistency and normalized SH basis functions,
Clamping or removing negative irradiance contributions for physical correctness,
Depth testing to avoid light bleeding by comparing sample depth with your depth cubemap,
Accumulating SH coefficients in an atomic/threadsafe way (or a single invocation compute shader with loops),
Normalizing final coefficients by total weight.
I will also suggest a small fix to your lighting shader for negative irradiance clamping (irradiance should never be negative).
Finished Compute Shader:
glsl
#version 450
#extension GL_EXT_scalar_block_layout : enable
#define PI 3.1415926535897932384626433832795
#define SH_ORDER 2 // 2nd order SH (9 coeffs)
#define NUM_COEFFS ((SH_ORDER+1)*(SH_ORDER+1))
#define NUM_SAMPLES 64 // Sample count
layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in;
// Coefficients buffer - will accumulate here
layout(scalar, set = 0, binding = 0) buffer SHBuffer {
vec3 shCoeffs[NUM_COEFFS];
} shBuffer;
layout(set = 0, binding = 1) uniform samplerCube irradianceMap;
layout(set = 0, binding = 2) uniform samplerCube depthMap;
layout(set = 0, binding = 3) uniform ProbePosition {
vec3 probePos;
};
/////////////////////////
// SH Basis Functions - normalized and consistent with rendering
float SHBasis(int l, int m, vec3 dir)
{
// Following real SH functions, consistent with your lighting shader
// Index mapping: l=0,m=0 -> 0; l=1,m=-1..1 -> 1..3; l=2,m=-2..2 -> 4..8
// Using the same coefficients as lighting shader
float x = dir.x;
float y = dir.y;
float z = dir.z;
if (l == 0 && m == 0)
return 0.282095; // Y00
else if (l == 1) {
if (m == -1) return 0.488603 * y;
else if (m == 0) return 0.488603 * z;
else if (m == 1) return 0.488603 * x;
} else if (l == 2) {
if (m == -2) return 1.092548 * x * y;
else if (m == -1) return 1.092548 * y * z;
else if (m == 0) return 0.315392 * (3.0*z*z - 1.0);
else if (m == 1) return 1.092548 * x * z;
else if (m == 2) return 0.546274 * (x*x - y*y);
}
return 0.0;
}
/////////////////////////
// Helper to get the flat index of SH coeff: l*(l+1)+m for l=0..2, m=-l..l
int SHIndex(int l, int m) {
return l*l + l + m;
}
/////////////////////////
// Helper for depth testing - using depth cubemap and comparing sampled depth:
// samplePosWorld: probePos + sampleDir * maxDistance
// Returns true if surface depth stored in depth cubemap is closer than sampled depth
bool IsOccluded(vec3 sampleDir, float sampleDepth)
{
// Sample from depth cubemap (depth range assumed 0-1)
float storedDepth = texture(depthMap, sampleDir).r;
// Note: depth stored in depth cubemap range 0..1 (linearized? Assuming linear here)
// If storedDepth < sampleDepth means occluded (something closer)
return storedDepth < sampleDepth;
}
void main() {
// Clear output buffer (assuming single invocation for simplicity)
// If multiple invocations, atomic add needed
// Reset coefficients
for (int i = 0; i < NUM_COEFFS; ++i) {
shBuffer.shCoeffs[i] = vec3(0.0);
}
// Accumulate total weight (for normalization)
float weightSum = 0.0;
// Integration over unit sphere by sampling the irradiance cubemap
// Using stratified cube map sampling - sample NUM_SAMPLES directions uniformly on the sphere by sampling cubemap texels
// Here we approximate integration by uniformly sampling directions:
// For simplicity, choose fixed sampling pattern:
// We'll sample directions by generating sample vectors on the unit sphere
// Use a deterministic sampling for this example (Hammersley, Fibonacci or uniform hemisphere)
// Here we'll use Fibonacci sphere sampling for even distribution over the sphere
// For NUM_SAMPLES samples:
for (int i = 0; i < NUM_SAMPLES; ++i) {
// Fibonacci sphere sampling
float phi = 2.0 * PI * float(i) / 1.61803398875; // golden ratio conjugate
float cosTheta = 1.0 - (2.0 * float(i) + 1.0) / float(NUM_SAMPLES);
float sinTheta = sqrt(1.0 - cosTheta * cosTheta);
vec3 sampleDir = normalize(vec3(cos(phi) * sinTheta, sin(phi) * sinTheta, cosTheta));
// Sample irradiance cubemap for radiance at direction
vec3 radiance = texture(irradianceMap, sampleDir).rgb;
// Depth: assume depth is linear and in 0..1 range, convert to world space distance
float depthVal = texture(depthMap, sampleDir).r;
float maxDistance = 100.0; // your max view depth for probe cubemap
float sampleDistance = depthVal * maxDistance;
// Depth test: check if sampled radiance is occluded
if (IsOccluded(sampleDir, sampleDistance)) {
radiance = vec3(0.0); // zero out occluded samples, avoid light bleeding
}
// Project radiance onto SH basis functions
// weight term for numerical integration over sphere: sinTheta * dTheta * dPhi approx
// We use uniform area weighting approximated by 4*PI / NUM_SAMPLES
float weight = 4.0 * PI / float(NUM_SAMPLES);
// Remove negative radiance values (non-physical, clamping)
radiance = max(radiance, vec3(0.0));
// Evaluate all SH basis functions at sampleDir
for (int l = 0; l <= SH_ORDER; ++l) {
for (int m = -l; m <= l; ++m) {
int idx = SHIndex(l, m);
float basis = SHBasis(l, m, sampleDir);
shBuffer.shCoeffs[idx] += radiance * basis * weight;
}
}
weightSum += weight;
}
// Normalize coefficients by weight sum (should be close to 1)
for (int i = 0; i < NUM_COEFFS; ++i) {
shBuffer.shCoeffs[i] /= weightSum;
}
}
Notes on the Updated Compute Shader
The Fibonacci sphere sampling distributes directions evenly on the sphere for better integral approximation instead of sampling directly from the cubemap texels.
The depth test compares sampled depth with your depth cubemap to zero out occluded (hidden) lighting, avoiding light bleeding.
Negative radiance is clamped for physical correctness.
The SH basis functions mirror those in the lighting shader to avoid directional inconsistency.
Proper normalization by the total integration weight.
You need to dispatch this compute shader with only 1 workgroup (or accumulate partial results with atomics if you want parallelization).
Suggested Adjustment to Lighting Shader
Clamp irradiance to positive values to avoid negative lighting:
glsl
vec3 evalDiffuseIrradiance(vec3 normal) {
float x = normal.x;
float y = normal.y;
float z = normal.z;
float shBasis[9];
shBasis[0] = 0.282095;
shBasis[1] = 0.488603 * y;
shBasis[2] = 0.488603 * z;
shBasis[3] = 0.488603 * x;
shBasis[4] = 1.092548 * x * y;
shBasis[5] = 1.092548 * y * z;
shBasis[6] = 0.315392 * (3.0 * z * z - 1.0);
shBasis[7] = 1.092548 * x * z;
shBasis[8] = 0.546274 * (x * x - y * y);
vec3 irradiance = vec3(0.0);
for (int i = 0; i < 9; ++i) {
irradiance += shBuffer.shCoeffs[i] * shBasis[i];
}
// Clamp negative irradiance components to zero
irradiance = max(irradiance, vec3(0.0));
return irradiance;
}
Further Notes:
If you want better ambient shadows, you can combine this SH coefficient ambient term with a shadow or visibility term in the lighting shader, derived from screen-space or voxel visibility.
You can also apply ambient occlusion or subsurface scattering wraps as you started.
Ensure your depth cubemap encodes/decodes linear depth consistently, otherwise occlusion checks won't work correctly.
Your cube map rendering pass should produce HDR radiance values for accurate SH projection.
If you want me to help you include more physically accurate terms or optimize the shader for parallel execution, just ask!