Skip to main content

wde_pbr/deferred/culling/
lod.rs

1use bevy::prelude::*;
2use wde_camera::prelude::*;
3use wde_renderer::prelude::*;
4
5/// Coloring of the meshes, to check their levels of detail.
6#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Reflect)]
7pub enum MeshDebugView {
8    #[default]
9    Off,
10    /// By drawn level: green, yellow, orange then red, and blue for the meshes without levels.
11    Levels,
12    /// By area of their triangles on screen: red under 1 pixel, orange 4, yellow 16, green 64,
13    /// blue over 256.
14    TriangleDensity
15}
16
17/// Selection of the levels of detail of the meshes (see [`Mesh::lods`]).
18#[derive(Resource, Clone, ExtractResource, Reflect)]
19#[extract_app(RenderApp)]
20#[reflect(Resource)]
21pub struct LodSettings {
22    /// Draw far meshes with their simplified levels of detail.
23    pub enabled: bool,
24    /// Largest error of the drawn level, in pixels on screen.
25    pub max_pixel_error: f32,
26    /// Draw every mesh with this level, or its coarsest one.
27    pub force_level: Option<usize>,
28    pub debug_view: MeshDebugView,
29    /// Draw the edges of the triangles over the meshes.
30    pub wireframe: bool
31}
32impl LodSettings {
33    /// Whether a debug view changes the look of the meshes.
34    pub fn debugging(&self) -> bool {
35        self.debug_view != MeshDebugView::Off || self.wireframe
36    }
37
38    /// Debug views of level `lod` of a mesh with `levels` levels, as given to the shaders (see
39    /// `mesh_debug_albedo`): `lod + 1` in the low bits in the levels view, or `MAX_MESH_LODS + 1`
40    /// without levels, then the density and wireframe flags.
41    pub(crate) fn debug_flags(settings: Option<&Self>, lod: usize, levels: usize) -> u32 {
42        let Some(settings) = settings else {
43            return 0;
44        };
45        let view = match settings.debug_view {
46            MeshDebugView::Off => 0,
47            MeshDebugView::Levels if levels <= 1 => MAX_MESH_LODS as u32 + 1,
48            MeshDebugView::Levels => lod as u32 + 1,
49            MeshDebugView::TriangleDensity => DEBUG_DENSITY
50        };
51        view | if settings.wireframe {
52            DEBUG_WIREFRAME
53        } else {
54            0
55        }
56    }
57}
58impl Default for LodSettings {
59    fn default() -> Self {
60        Self {
61            enabled: true,
62            max_pixel_error: 1.0,
63            force_level: None,
64            debug_view: MeshDebugView::Off,
65            wireframe: false
66        }
67    }
68}
69
70/// Same as `MESH_DEBUG_DENSITY` and `MESH_DEBUG_WIREFRAME` in the shaders.
71const DEBUG_DENSITY: u32 = 1 << 4;
72const DEBUG_WIREFRAME: u32 = 1 << 5;
73
74/// Culling camera, as seen by the level of detail selection.
75#[derive(Clone, Copy)]
76pub(crate) struct LodView {
77    position: Vec3,
78    forward: Vec3,
79    /// Size on screen in pixels of one world unit at one unit of distance, on the view axis.
80    pixels_per_unit: f32,
81    /// Cosine of the angle between the view axis and the screen corners.
82    min_cos: f32
83}
84
85#[derive(Resource, Default)]
86pub(crate) struct LodCamera(pub Option<LodView>);
87
88pub(super) fn extract_lod_camera(
89    camera: Extract<Query<(&GlobalTransform, &CameraView), With<CullingCamera>>>,
90    window: Extract<Query<&Window>>,
91    mut lod_camera: ResMut<LodCamera>
92) {
93    lod_camera.0 = match (camera.single(), window.single()) {
94        (Ok((transform, view)), Ok(window)) if window.height() > 0.0 => {
95            let tan_half_fov = (view.fov.to_radians() * 0.5).tan();
96            let aspect = window.width() / window.height();
97            let tan_corner = tan_half_fov * (1.0 + aspect * aspect).sqrt();
98            Some(LodView {
99                position: transform.translation(),
100                forward: transform.forward().as_vec3(),
101                pixels_per_unit: window.resolution.physical_height() as f32 / (2.0 * tan_half_fov),
102                min_cos: 1.0 / (1.0 + tan_corner * tan_corner).sqrt()
103            })
104        }
105        _ => None
106    };
107}
108
109/// Coarsest level of `lods` whose error on screen stays under the limit, for a mesh with
110/// world-space `bounds` and largest `scale`.
111pub(crate) fn select_lod(
112    lods: &[GpuMeshLod],
113    bounds: &Aabb,
114    scale: f32,
115    view: Option<&LodView>,
116    settings: &LodSettings
117) -> usize {
118    let coarsest = lods.len().saturating_sub(1);
119    if !settings.enabled || coarsest == 0 {
120        return 0;
121    }
122    if let Some(level) = settings.force_level {
123        return level.min(coarsest);
124    }
125    let Some(view) = view else {
126        return 0;
127    };
128    // Nearest point of the bounds
129    let to_bounds = view.position.clamp(bounds.min, bounds.max) - view.position;
130    let distance = to_bounds.length();
131    if distance <= 0.0 {
132        return 0;
133    }
134    // The projection stretches the error by 1 / cos² of the angle to the view axis, at most up to
135    // the screen corners (farther points are off screen, only drawn in the shadows)
136    let cos = (to_bounds.dot(view.forward) / distance).clamp(view.min_cos, 1.0);
137    let max_error =
138        settings.max_pixel_error * distance * cos * cos / (view.pixels_per_unit * scale);
139    lods.iter()
140        .rposition(|lod| lod.error <= max_error)
141        .unwrap_or(0)
142}
143
144#[cfg(test)]
145mod tests {
146    use super::*;
147
148    const LODS: [GpuMeshLod; 3] = [
149        GpuMeshLod {
150            first_index: 0,
151            index_count: 300,
152            error: 0.0
153        },
154        GpuMeshLod {
155            first_index: 300,
156            index_count: 150,
157            error: 0.01
158        },
159        GpuMeshLod {
160            first_index: 450,
161            index_count: 75,
162            error: 0.1
163        }
164    ];
165
166    /// Level of a unit box at `distance` in front of the camera, `side` units off its axis.
167    fn select_at(distance: f32, side: f32, scale: f32) -> usize {
168        let view = LodView {
169            position: Vec3::new(side, 0.0, distance + 1.0),
170            forward: Vec3::NEG_Z,
171            pixels_per_unit: 1000.0,
172            min_cos: 0.5
173        };
174        let bounds = Aabb::new(Vec3::new(-1.0, -1.0, -1.0), Vec3::new(1.0, 1.0, 1.0));
175        select_lod(&LODS, &bounds, scale, Some(&view), &LodSettings::default())
176    }
177
178    fn select(distance: f32, scale: f32) -> usize {
179        select_at(distance, 0.0, scale)
180    }
181
182    #[test]
183    fn coarser_with_distance() {
184        assert_eq!(select(0.0, 1.0), 0);
185        assert_eq!(select(5.0, 1.0), 0);
186        assert_eq!(select(10.0, 1.0), 1);
187        assert_eq!(select(99.0, 1.0), 1);
188        assert_eq!(select(100.0, 1.0), 2);
189    }
190
191    #[test]
192    fn finer_when_scaled_up() {
193        assert_eq!(select(100.0, 2.0), 1);
194    }
195
196    #[test]
197    fn debug_flags() {
198        let mut settings = LodSettings::default();
199        assert_eq!(LodSettings::debug_flags(Some(&settings), 2, 4), 0);
200        settings.debug_view = MeshDebugView::Levels;
201        assert_eq!(LodSettings::debug_flags(Some(&settings), 2, 4), 3);
202        assert_eq!(
203            LodSettings::debug_flags(Some(&settings), 0, 1),
204            MAX_MESH_LODS as u32 + 1
205        );
206        settings.wireframe = true;
207        assert_eq!(
208            LodSettings::debug_flags(Some(&settings), 2, 4),
209            3 | DEBUG_WIREFRAME
210        );
211        settings.debug_view = MeshDebugView::TriangleDensity;
212        assert_eq!(
213            LodSettings::debug_flags(Some(&settings), 2, 4),
214            DEBUG_DENSITY | DEBUG_WIREFRAME
215        );
216    }
217
218    #[test]
219    fn finer_off_axis() {
220        // Nearest point 100 units ahead and 100 to the side: 141 units away, at 45°
221        assert_eq!(select_at(99.0, 101.0, 1.0), 1);
222        // Far off screen, clamped to the corners
223        assert_eq!(select_at(0.0, 401.0, 1.0), 2);
224    }
225}