Skip to main content

wde_pbr/deferred/lights/
environment.rs

1use bevy::{ecs::system::SystemParamItem, math::Vec3, prelude::*};
2use wde_renderer::prelude::*;
3
4/// Size in pixels of the faces of the environment map.
5pub const ENVIRONMENT_MAP_SIZE: u32 = 128;
6/// Number of mips of the environment map. Mip `i` is prefiltered for the roughness `i / (ENVIRONMENT_MAP_MIPS - 1)`.
7pub const ENVIRONMENT_MAP_MIPS: u32 = 7;
8pub const ENVIRONMENT_MAP_FORMAT: TextureFormat = TextureFormat::Rgba16Float;
9
10const BRDF_LUT_SIZE: u32 = 64;
11const BRDF_LUT_SAMPLES: u32 = 128;
12
13/// Ambient lighting of the scene by its environment (the sky), sampled by the lighting shaders:
14/// - The diffuse irradiance, as 9 RGB spherical harmonics coefficients (`vec4`s) already convolved with the cosine lobe
15///   and divided by π, so that they evaluate to the diffuse light of a white surface.
16/// - The specular radiance, as a cube map whose mips are prefiltered for increasing roughnesses (GGX).
17/// - The scale and bias of the specular reflectance in the split-sum approximation, as a 2D lookup table of
18///   (n·v, roughness).
19///
20/// It is black until it is baked, by the atmosphere when the feature `atmosphere` is enabled.
21#[derive(Asset, Clone, TypePath, Default)]
22pub struct EnvironmentData;
23impl EnvironmentData {
24    pub const SH_BUFFER_IDX: u32 = 0;
25    pub const MAP_IDX: u32 = 1;
26    pub const BRDF_LUT_IDX: u32 = 2;
27
28    pub const SH_COEFFICIENTS: usize = 9;
29
30    /// Adds the environment to a lighting binding: the spherical harmonics, the environment map and its sampler, then the
31    /// BRDF lookup table (sampled with the same sampler).
32    pub fn add_bindings(
33        builder: &mut RenderBindingBuilder,
34        environment: &RenderAssets<GpuRenderData<EnvironmentData>>
35    ) {
36        builder
37            .add_buffer(environment, Self::SH_BUFFER_IDX)
38            .add_texture_cube_view(environment, Self::MAP_IDX)
39            .add_texture_sampler(environment, Self::MAP_IDX)
40            .add_texture_view(environment, Self::BRDF_LUT_IDX);
41    }
42}
43impl RenderData for EnvironmentData {
44    type Params = ();
45
46    fn describe(_: &mut SystemParamItem<Self::Params>, builder: &mut RenderDataBuilder) {
47        let sh_size = Self::SH_COEFFICIENTS * std::mem::size_of::<[f32; 4]>();
48        builder
49            .add_buffer(
50                Self::SH_BUFFER_IDX,
51                Buffer {
52                    label: "environment-sh".to_string(),
53                    size: sh_size,
54                    usage: BufferUsage::UNIFORM | BufferUsage::STORAGE | BufferUsage::COPY_DST,
55                    content: Some(vec![0; sh_size])
56                }
57            )
58            .add_texture(
59                Self::MAP_IDX,
60                Texture {
61                    label: "environment-map".to_string(),
62                    size: (ENVIRONMENT_MAP_SIZE, ENVIRONMENT_MAP_SIZE),
63                    format: ENVIRONMENT_MAP_FORMAT,
64                    usages: TextureUsages::TEXTURE_BINDING | TextureUsages::STORAGE_BINDING,
65                    layer_count: 6,
66                    mip_level_count: ENVIRONMENT_MAP_MIPS,
67                    cube: true,
68                    ..Default::default()
69                }
70            )
71            .add_texture(
72                Self::BRDF_LUT_IDX,
73                Texture {
74                    label: "environment-brdf-lut".to_string(),
75                    size: (BRDF_LUT_SIZE, BRDF_LUT_SIZE),
76                    format: TextureFormat::Rg16Float,
77                    usages: TextureUsages::TEXTURE_BINDING,
78                    data: brdf_lut(),
79                    ..Default::default()
80                }
81            );
82    }
83}
84
85/// Scale and bias of F0 in the split-sum specular reflectance, for (n·v, roughness) at the texel centers.
86fn brdf_lut() -> Vec<u8> {
87    let mut data = Vec::with_capacity((BRDF_LUT_SIZE * BRDF_LUT_SIZE * 4) as usize);
88    for y in 0..BRDF_LUT_SIZE {
89        let roughness = (y as f32 + 0.5) / BRDF_LUT_SIZE as f32;
90        for x in 0..BRDF_LUT_SIZE {
91            let n_dot_v = (x as f32 + 0.5) / BRDF_LUT_SIZE as f32;
92            let (scale, bias) = integrate_brdf(n_dot_v, roughness);
93            data.extend_from_slice(&half::f16::from_f32(scale).to_bits().to_le_bytes());
94            data.extend_from_slice(&half::f16::from_f32(bias).to_bits().to_le_bytes());
95        }
96    }
97    data
98}
99
100/// Integrates the GGX specular BRDF over the hemisphere (normal +Z), with importance sampling.
101fn integrate_brdf(n_dot_v: f32, roughness: f32) -> (f32, f32) {
102    let v = Vec3::new((1.0 - n_dot_v * n_dot_v).sqrt(), 0.0, n_dot_v);
103    let alpha = roughness * roughness;
104    // Schlick-GGX remapping for image based lighting
105    let k = alpha / 2.0;
106    let g1 = |n_dot_x: f32| n_dot_x / (n_dot_x * (1.0 - k) + k);
107
108    let (mut scale, mut bias) = (0.0, 0.0);
109    for i in 0..BRDF_LUT_SAMPLES {
110        let xi = (
111            i as f32 / BRDF_LUT_SAMPLES as f32,
112            i.reverse_bits() as f32 / 4_294_967_296.0
113        );
114        let phi = std::f32::consts::TAU * xi.0;
115        let cos_theta = ((1.0 - xi.1) / (1.0 + (alpha * alpha - 1.0) * xi.1)).sqrt();
116        let sin_theta = (1.0 - cos_theta * cos_theta).sqrt();
117        let h = Vec3::new(phi.cos() * sin_theta, phi.sin() * sin_theta, cos_theta);
118        let l = 2.0 * v.dot(h) * h - v;
119
120        let n_dot_l = l.z;
121        if n_dot_l > 0.0 {
122            let v_dot_h = v.dot(h).max(0.0);
123            let visibility = g1(n_dot_v) * g1(n_dot_l) * v_dot_h / (h.z * n_dot_v);
124            let fresnel = (1.0 - v_dot_h).powi(5);
125            scale += (1.0 - fresnel) * visibility;
126            bias += fresnel * visibility;
127        }
128    }
129    (
130        scale / BRDF_LUT_SAMPLES as f32,
131        bias / BRDF_LUT_SAMPLES as f32
132    )
133}
134
135#[cfg(test)]
136mod tests {
137    use super::*;
138
139    #[test]
140    fn brdf_lut_matches_known_values() {
141        // Smooth surfaces seen from the front reflect F0, rough ones lose energy to the masking
142        let (scale, bias) = integrate_brdf(1.0, 0.05);
143        assert!((scale - 1.0).abs() < 0.02 && bias < 0.01, "{scale} {bias}");
144        let (scale, bias) = integrate_brdf(0.5, 1.0);
145        assert!(scale + bias < 0.8, "{scale} {bias}");
146        // Grazing angles reflect more, through the bias
147        assert!(integrate_brdf(0.05, 0.3).1 > integrate_brdf(0.9, 0.3).1);
148    }
149}