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.
vec3 evalDiffuseIrradiance(vec3 normal) {
float x = normal.x;
float y = normal.y;
float z = normal.z;
code
// SH basis functions - same logic as in compute shader, scalar only
float shBasis[9];
shBasis[0] = 0.282095; // 0: Y0^0
shBasis[1] = 0.488603 * y; // 1: Y1^-1
shBasis[2] = 0.488603 * z; // 2: Y1^0
shBasis[3] = 0.488603 * x; // 3: Y1^1
shBasis[4] = 1.092548 * x * y; // 4: Y2^-2
shBasis[5] = 1.092548 * y * z; // 5: Y2^-1
shBasis[6] = 0.315392 * (3.0 * z * z - 1.0); // 6: Y2^0
shBasis[7] = 1.092548 * x * z; // 7: Y2^1
shBasis[8] = 0.546274 * (x * x - y * y); // 8: Y2^2
vec3 irradiance = vec3(0.0);
for (int i = 0; i < 9; ++i) {
irradiance += shBuffer.shCoeffs[i] * shBasis[i];
}
return irradiance;
}
code
Assistant
User
This looks promising and the lighting is directionally consistent. However, the irradiance output is very low I am only seeing values between 0 and 0.04. The environmental cubemap is fairly neutral in terms of it's brightness, so I expect such low values to be an error.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
#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
Your approach to generate SH coefficients for diffuse radiance using cube maps and depth testing is fundamentally sound. However, there are some important aspects to ensure correctness:
Directional consistency: Make sure the SH basis functions in compute and lighting shaders match and are oriented consistently w.r.t the cube map directions.
Depth testing: In the compute shader, test the sample against the depth map to avoid light bleeding. In the lighting shader, additional shadowing can be done using the depth cube map or screen-space techniques.
Negative irradiance: SH can produce negative values, but physically diffuse irradiance should not be negative. Clamp or saturate irradiance in the lighting shader.
Below is a complete and corrected compute shader that:
// - Samples the irradiance (color) from the irradiance cube map.
// - Performs depth testing by comparing the sample depth from the depth cube map with the expected depth for that direction (using the probe position).
// - Accumulates valid samples into SH basis functions, weighted by solid angle.
// - Normalizes the SH coefficients by total weight (solid angle).
// - Uses consistent SH basis functions.
// - Adds comments and clamps negative values in the lighting shader.
Completed Compute Shader for SH coefficient generation
glsl
#version 450
#extension GL_EXT_scalar_block_layout : enable
#define PI 3.1415926535897932384626433832795
#define SH_ORDER 2 // Second order SH: 9 coefficients
#define NUM_COEFFS ((SH_ORDER + 1) * (SH_ORDER + 1))
#define NUM_SAMPLES 64 // We'll uniformly sample directions on the sphere
// Thread group size 1 (single invocation for simplicity)
layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in;
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; // World space position of the probe
};
// Precomputed constants for SH basis functions (real SH)
// Reference: https://www.ppsloan.org/publications/StupidSH36.pdf
float SHBasis(int l, int m, vec3 dir) {
// Here, l ∈ [0..2], m ∈ [-l..l]
float x = dir.x;
float y = dir.y;
float z = dir.z;
if (l == 0 && m == 0) return 0.282095; // Y0^0
else if (l == 1 && m == -1) return 0.488603 * y; // Y1^-1
else if (l == 1 && m == 0) return 0.488603 * z; // Y1^0
else if (l == 1 && m == 1) return 0.488603 * x; // Y1^1
else if (l == 2 && m == -2) return 1.092548 * x * y; // Y2^-2
else if (l == 2 && m == -1) return 1.092548 * y * z; // Y2^-1
else if (l == 2 && m == 0) return 0.315392 * (3.0 * z * z - 1.0); // Y2^0
else if (l == 2 && m == 1) return 1.092548 * x * z; // Y2^1
else if (l == 2 && m == 2) return 0.546274 * (x * x - y * y); // Y2^2
return 0.0;
}
// Uniformly sample the sphere using the Fibonacci sphere or random (here Fibonacci)
// Returns direction on the unit sphere
vec3 fibonacciSphereSample(int i, int n) {
float phi = 2.0 * PI * float(i) / 1.61803398875; // Golden angle approx 2pi / phi, phi~1.618...
float cosTheta = 1.0 - 2.0 * (float(i) + 0.5) / float(n);
float sinTheta = sqrt(1.0 - cosTheta * cosTheta);
return normalize(vec3(cos(phi) * sinTheta, sin(phi) * sinTheta, cosTheta));
}
// Convert direction vector to spherical depth value from probePos
// Returns depth in [0,1] as stored in depth cube map
float getSampleDepth(vec3 dir) {
// We assume depth map stores linear depth with respect to probePos, normalized to [0,1]
// Distance from probePos to first intersection along dir.
// Sample depth map using dir:
float depthFromMap = texture(depthMap, dir).r;
return depthFromMap;
}
// Convert world-space sample direction to expected linear depth from probePos
// This depends on your scene setup, here we assume distance max range = maxDepth
// Adjust maxDepth accordingly! (could be uniform)
float getExpectedDepth(vec3 dir) {
// For depth comparison, we fetch from depth cube map which stores depth in [0,1]
// Here we can estimate expected linear depth = distance to scene geometry along dir.
// But since we don't have the actual scene intersection in compute shader,
// we rely on depth map value sampled above.
// Or if depthMap stores distance, no need to compute here.
// For strict depth test, we just compare sampled depth w.r.t expected max range.
return getSampleDepth(dir);
}
// Solid angle weight for a given sample direction on sphere, integrate using equal area approx
float solidAngleWeight(int i, int n) {
return 4.0 * PI / float(n); // equal weight for uniform samples
}
void main() {
// Reset SH coefficients before accumulation
for (int i = 0; i < NUM_COEFFS; ++i) {
shBuffer.shCoeffs[i] = vec3(0.0);
}
float totalWeight = 0.0;
// For each sample direction on the sphere
for (int i = 0; i < NUM_SAMPLES; ++i) {
vec3 dir = fibonacciSphereSample(i, NUM_SAMPLES);
// Sample irradiance color from irradiance cube map
vec3 radiance = texture(irradianceMap, dir).rgb;
// Depth test to avoid light bleeding / shadowing
// Sample depth from depth cube map for this direction
float depthSampled = getSampleDepth(dir);
// Compute distance from probe to "surface" point along dir from depth
// Here we assume depth map stores normalized linear depth.
// To implement correct depth test:
// - Calculate expected depth of sample based on probePos and scene geometry.
// - If sample depth indicates surface is closer or equal (within epsilon), accept sample
// - Otherwise, discard to avoid light leaking.
// Because we only have depth map and probePos, we do:
// Compute real distance of sample = depthSampled * maxDepthRange
// Here we must know maxDepthRange, assuming 1.0; if not known, need uniform.
// For safer, assume maxDepthRange=probe max distance in depth map = 1.0
float maxDepthRange = 1.0;
float sampleDistance = depthSampled * maxDepthRange;
float expectedDistance = length(dir); // distance along direction is 1 on unit sphere
// Because distances are normalized, and we don't have actual scene geometry in compute,
// We accept sample if sampleDistance >= expectedDistance with a small bias
// Note: The depthCubeMap stores depth along view direction from probe, so expectedDistance is from probe to far plane (1.0)
// We expect sampleDistance to be less or equal to distance on irradianceMap direction
// This is the main point to avoid light bleeding.
// We invert logic: if sampleDistance < expected distance - reject sample (occluded), else accept
// Because depths are normalized, we can compare directly
if (sampleDistance < expectedDistance - 0.05) {
// Occluded, discard sample
continue;
}
// Weight for uniform sphere sampling
float weight = solidAngleWeight(i, NUM_SAMPLES);
// Accumulate SH coefficients per channel for each basis
// idx order for 9 coeffs is standard: l=0,m=0 ... l=2,m=2 (in "nested for" order)
int idx = 0;
for (int l = 0; l <= SH_ORDER; ++l) {
for (int m = -l; m <= l; ++m) {
float basis = SHBasis(l, m, dir);
shBuffer.shCoeffs[idx] += radiance * basis * weight;
idx++;
}
}
totalWeight += weight;
}
// Normalize SH coefficients by total weight
if (totalWeight > 0.0) {
for (int i = 0; i < NUM_COEFFS; ++i) {
shBuffer.shCoeffs[i] /= totalWeight;
}
}
}
Modify your evaluation function to clamp the negative irradiance to zero to avoid unphysical 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 values (SH coefficients can produce negatives)
irradiance = max(irradiance, vec3(0.0));
return irradiance;
}
Further Recommendations
Depth map precision: Ensure your depth cube map encodes linear depth from the probe position properly (not non-linear depth). Otherwise, depth test will be incorrect.
Sampling: Increase NUM_SAMPLES for smoother SH coefficients.
Bias in depth test: Tweak bias (0.05 here) based on scene scale/debug.
Compute shader optimization: For larger scale, dispatch multiple threads and accumulate atomically or reduce later.
Double depth check: You can optionally do shadow testing also in the lighting shader using the depth cube map for each fragment to reduce light bleeding on dynamic objects or screen-space.
This should provide stable SH coefficients with depth occlusion and no light bleeding, producing smooth ambient shadows in your global illumination solution. Let me know if you want help integrating this into your Vulkan pipeline!
If your resulting SH irradiance is very low (0..0.04), while your environment cubemap appears reasonably bright, the most common causes are related to how the SH coefficients are accumulated, weighted, or normalized.
Here are probable reasons and how to fix them:
Key points to verify and fix:
1. Weighting samples by solid angle
In SH projection, you integrate:
[
c_l^m = \int_{\Omega} L(\omega) Y_l^m(\omega) d\omega
]
Your sample weighting currently uses:
glsl
float weight = 4.0 * PI / float(NUM_SAMPLES);
which is nominally correct for uniform sphere samples.
Check: Are your sphere samples indeed uniform over the sphere (solid angle)?
Your Fibonacci sphere does mostly uniform sampling, but note the golden angle phi calculation in your sample code:
glsl
float phi = 2.0 * PI * float(i) / 1.61803398875;
The golden ratio constant 1.618... shouldn't appear as denominator here. The standard Fibonacci sphere sampling uses:
glsl
float phi = 2.0 * PI * float(i) / golden_ratio_conjugate;
But usually, the correct and simple Fibonacci sphere sampling is:
When projecting irradiance on a sphere into SH, the incoming light is weighted by cosine of the angle between the sample direction and the normal because irradiance is an integral of incident radiance weighted by cosine.
But when computing SH coefficients, you need to add the cosine weight as well.
Use:
[
w = \cos \theta \cdot \Delta \omega
]
Where:
(\theta) is angle between sample direction and the hemisphere pole (in your case, projection on a sphere at the probe, it's commonly the normal direction for irradiance)
(\Delta \omega) is the solid angle per sample
Your current integration weights all samples equally; you need to modulate each sample's contribution by (\max(0, \cos\theta)).
Since your probe gets radiance from all directions, but for diffuse irradiance, the hemisphere weighted by cosine is appropriate.
If you're integrating over the full sphere rather than hemisphere, you must include (\max(\cos \theta,0)) to restrict to hemisphere.
Note: The up vector is typically ((0,0,1)) or the probe's "up" direction.
If you want SH coefficients for irradiance for any surface normal (\mathbf{n}), you can use the full-sphere SH or pre-transform. However, irradiance is usually hemisphere weighted.
3. No explicit normalization by (\pi)
Irradiance is often normalized by (\pi) with Lambertian surfaces:
[
E = \pi \int_{\Omega} L(\omega) \cos\theta d\omega
]
Since you integrate (L(\omega) \cos\theta d\omega), final scaling by (\pi) may be needed — either divide or multiply.
In SH lighting, this is nuanced because LIGHTING uses SH irradiance as is.
If lighting is low, try multiplying your SH coefficients by (\pi) after integration.
4. Check your depth-test rejection fraction
If you discard too many samples during depth testing, your SH accumulates from a small fraction of the sphere, which can reduce final values drastically.
Test by temporarily disabling depth test to verify if your SH coefficients increase significantly.
5. Verify the irradiance map values
Ensure the irradiance cube map contains correct radiance values, not HDR compressed or low dynamic range values.
const float golden_angle = 2.39996322972865332; // approx 2*PI*(1 - 1/golden_ratio)
vec3 fibonacciSphereSample(int i, int n) {
float phi = float(i) * golden_angle;
float cosTheta = 1.0 - 2.0 * (float(i) + 0.5) / float(n);
float sinTheta = sqrt(1.0 - cosTheta * cosTheta);
return normalize(vec3(cos(phi) * sinTheta, sin(phi) * sinTheta, cosTheta));
}
void main() {
// Zero out coeffs
for (int i = 0; i < NUM_COEFFS; ++i) {
shBuffer.shCoeffs[i] = vec3(0.0);
}
float totalWeight = 0.0;
vec3 hemisphereUp = vec3(0, 0, 1); // define 'up' direction for cosine
for (int i = 0; i < NUM_SAMPLES; ++i) {
vec3 dir = fibonacciSphereSample(i, NUM_SAMPLES);
// Sample irradiance and depth as before
vec3 radiance = texture(irradianceMap, dir).rgb;
float depthSampled = getSampleDepth(dir);
float sampleDistance = depthSampled; // assuming normalized 0..1 depth (adjust maxDepthRange accordingly)
float expectedDistance = 1.0; // normalized unit sphere distance
if (sampleDistance < expectedDistance - 0.05) {
continue; // occluded / shadowed
}
// Cosine weighting (Lambertian cosine)
float cosTheta = max(dot(dir, hemisphereUp), 0.0);
if (cosTheta <= 0.0) continue; // skip back hemisphere for diffuse
float weight = solidAngleWeight(i, NUM_SAMPLES) * cosTheta;
int idx = 0;
for (int l = 0; l <= SH_ORDER; ++l) {
for (int m = -l; m <= l; ++m) {
float basis = SHBasis(l, m, dir);
shBuffer.shCoeffs[idx] += radiance * basis * weight;
idx++;
}
}
totalWeight += weight;
}
if (totalWeight > 0.0) {
for (int i = 0; i < NUM_COEFFS; ++i) {
// Optional: multiply by PI as diffuse irradiance factor
shBuffer.shCoeffs[i] = (shBuffer.shCoeffs[i] / totalWeight) * PI;
}
}
}
Check your lighting shader: no change needed except clamping negatives.
Extra:
You can also tweak hemisphereUp vector per probe orientation or sample directions if needed.
This fix should raise your irradiance values to expected levels around 0.1 to 1.0 depending on environment brightness, removing unexpectedly low irradiance.
If you want, I can create a fully integrated final version with Vulkan bindings and the entire shader structured, let me know!