wde_pbr/deferred/culling/mod.rs
1//! Frustum culling of the PBR batches, on the CPU.
2//!
3//! Each frame, the instances of every batch are tested against the
4//! [`CullingCamera`](wde_camera::prelude::CullingCamera) and each shadow
5//! cascade. Their visible instances are written to their own region of the
6//! [`PbrSsboInstanceToTransform`](crate::prelude::PbrSsboInstanceToTransform) buffer, and the
7//! passes draw that range only.
8//!
9//! # Levels
10//! 1. **Groups**: a [`CullGroup`] gives world-space bounds to a set of meshes, e.g. a village or a
11//! character. A group outside of a view hides all its meshes from it, and a group fully inside
12//! shows them all, both without testing them one by one.
13//! 2. **Meshes**: the remaining meshes (in a group crossing the view edge, or in no group) are
14//! tested with the bounds of their mesh, moved by their transform.
15//!
16//! # Levels of detail
17//! Each visible instance is drawn with the coarsest of the [`Mesh::lods`] whose error, projected
18//! on the screen of the culling camera from the nearest point of its bounds, stays under
19//! [`LodSettings::max_pixel_error`]. The shadow cascades use the level of the camera.
20//!
21//! # Usage
22//! ```rust
23//! // Spawn the group, and keep its bounds up to date
24//! let group = commands.spawn(CullGroup(Aabb::new(Vec3::splat(-20.0), Vec3::splat(20.0)))).id();
25//! // Every mesh of the village is in the group
26//! commands.spawn((Transform::default(), CullGroupMember(group)));
27//! ```
28//! Levels can be toggled with the [`CullingSettings`] and [`LodSettings`] resources, editable in
29//! the `PBR/Culling` editor window along with the [`CullingStats`]. The [`MeshDebugView`]s and the
30//! wireframe of [`LodSettings`] show the drawn levels and the size of their triangles on screen.
31use std::sync::{Arc, Mutex};
32
33use bevy::prelude::*;
34use wde_renderer::prelude::*;
35
36use crate::deferred::build_batches;
37
38mod cull;
39#[cfg(debug_assertions)]
40mod editor;
41mod groups;
42mod lod;
43
44pub use groups::{CullGroup, CullGroupMember, InCullGroup};
45pub use lod::{LodSettings, MeshDebugView};
46
47/// Culling views: the camera, then each shadow cascade.
48pub const CULL_VIEW_COUNT: usize = 4;
49pub(crate) const CAMERA_VIEW: usize = 0;
50pub(crate) const fn shadow_view(cascade: u32) -> usize {
51 1 + cascade as usize
52}
53
54#[derive(Resource, Clone, ExtractResource, Reflect)]
55#[extract_app(RenderApp)]
56#[reflect(Resource)]
57pub struct CullingSettings {
58 /// Draw in each view only what lies in it.
59 pub enabled: bool,
60 /// Test the cull groups before their meshes.
61 pub groups: bool,
62 /// Test each mesh that its group does not decide on.
63 pub meshes: bool,
64 /// Cull the shadow casters of each cascade, not only the camera view.
65 pub shadows: bool,
66 /// Draw the bounds of the cull groups (with the `wde` debug gizmos).
67 pub show_groups: bool
68}
69impl Default for CullingSettings {
70 fn default() -> Self {
71 Self {
72 enabled: true,
73 groups: true,
74 meshes: true,
75 shadows: true,
76 show_groups: false
77 }
78 }
79}
80
81#[derive(Clone, Copy, Default, Debug)]
82pub struct CullingStats {
83 /// Batched instances.
84 pub instances: usize,
85 /// Instances drawn in each view.
86 pub drawn: [usize; CULL_VIEW_COUNT],
87 /// Triangles drawn in each view.
88 pub triangles: [usize; CULL_VIEW_COUNT],
89 /// Instances drawn with each level of detail in the camera view, among the meshes with levels.
90 pub lods: [usize; MAX_MESH_LODS],
91 /// Instances of meshes without levels of detail drawn in the camera view.
92 pub without_lods: usize,
93 pub groups: usize,
94 /// Groups outside of each view.
95 pub groups_culled: [usize; CULL_VIEW_COUNT],
96 /// Mesh bounds tested, over every view.
97 pub mesh_tests: usize,
98 /// CPU time of the culling, in microseconds, smoothed over frames.
99 pub micros: f32
100}
101
102/// [`CullingStats`] of the last rendered frame, shared between the main and render worlds.
103#[derive(Resource, Clone, Default)]
104pub struct CullingStatsShared(pub Arc<Mutex<CullingStats>>);
105
106pub(crate) struct CullingPlugin;
107impl Plugin for CullingPlugin {
108 fn build(&self, app: &mut App) {
109 let stats = CullingStatsShared::default();
110 app.init_resource::<CullingSettings>()
111 .init_resource::<LodSettings>()
112 .insert_resource(stats.clone())
113 .register_type::<CullingSettings>()
114 .register_type::<LodSettings>()
115 .register_type::<CullGroup>()
116 .register_type::<CullGroupMember>()
117 .register_type::<InCullGroup>()
118 .add_plugins((
119 ExtractResourcePlugin::<CullingSettings>::default(),
120 ExtractResourcePlugin::<LodSettings>::default(),
121 ExtractComponentPlugin::<InCullGroup>::default()
122 ))
123 .add_systems(PostUpdate, groups::resolve_cull_groups);
124
125 app.get_sub_app_mut(RenderApp)
126 .unwrap()
127 .insert_resource(stats)
128 .init_resource::<CullingSettings>()
129 .init_resource::<LodSettings>()
130 .init_resource::<lod::LodCamera>()
131 .init_resource::<cull::CameraFrustum>()
132 .init_resource::<cull::ExtractedCullGroups>()
133 .add_systems(
134 ExtractSchedule,
135 (
136 cull::extract_camera_frustum,
137 cull::extract_cull_groups,
138 lod::extract_lod_camera
139 )
140 )
141 .add_systems(
142 Render,
143 (cull::update_world_bounds, cull::cull_instances)
144 .chain()
145 .after(build_batches)
146 .in_set(RenderSet::Prepare)
147 );
148
149 #[cfg(debug_assertions)]
150 app.add_plugins(editor::CullingEditorPlugin);
151 }
152}