Skip to main content

wde_renderer/passes/
pipeline_status.rs

1//! Status of the pipelines and their shaders, and the parts of passes skipped each frame (see
2//! [`PipelineStatusView`]).
3use std::sync::Mutex;
4
5use bevy::prelude::*;
6
7use super::{CachedPipelineIndex, PipelineManager, RenderPassId};
8use crate::{
9    core::RenderApp,
10    sync::{ExtractSchedule, MainWorld}
11};
12
13pub(crate) struct PipelineStatusPlugin;
14impl Plugin for PipelineStatusPlugin {
15    fn build(&self, app: &mut App) {
16        app.init_resource::<PipelineStatusView>();
17        app.get_sub_app_mut(RenderApp)
18            .unwrap()
19            .init_resource::<PipelineStatus>()
20            .add_systems(ExtractSchedule, extract);
21    }
22}
23
24// ── MAIN WORLD ──────────────────────────────────────────────────
25
26/// Status of the pipelines and their shaders, and the parts of passes skipped in the last frame. The
27/// `Debug/Pipeline Status` window of the editor shows it.
28#[derive(Resource, Default, Clone)]
29pub struct PipelineStatusView {
30    /// Collects the reports below. Disable it when unused.
31    pub enabled: bool,
32    /// Sorted by status, failed ones first.
33    pub pipelines: Vec<DebugPipelineReport>,
34    /// Parts of passes skipped in the last rendered frame, in their execution order.
35    pub skips: Vec<DebugSkip>
36}
37
38#[derive(Clone, Debug)]
39pub struct DebugPipelineReport {
40    /// `None` while waiting for its bind group layouts.
41    pub id: Option<CachedPipelineIndex>,
42    pub label: &'static str,
43    pub compute: bool,
44    pub status: DebugPipelineStatus,
45    pub shaders: Vec<DebugShaderReport>
46}
47
48#[derive(Clone, Debug, PartialEq, Eq)]
49pub enum DebugPipelineStatus {
50    /// Failed to build, with its error. It is rebuilt when one of its shaders changes.
51    Failed(String),
52    /// Not queued yet, as a bind group layout is missing.
53    WaitingLayouts,
54    /// Waiting for its shaders to load.
55    Pending,
56    Ready
57}
58impl DebugPipelineStatus {
59    pub(crate) fn rank(&self) -> u8 {
60        match self {
61            Self::Failed(_) => 0,
62            Self::WaitingLayouts => 1,
63            Self::Pending => 2,
64            Self::Ready => 3
65        }
66    }
67}
68
69#[derive(Clone, Debug)]
70pub struct DebugShaderReport {
71    pub path: String,
72    pub status: DebugShaderStatus
73}
74
75#[derive(Clone, Debug, PartialEq, Eq)]
76pub enum DebugShaderStatus {
77    Loading,
78    Loaded,
79    /// Failed to load (missing file or include), with its error.
80    Failed(String)
81}
82
83/// A part of a pass skipped in a frame.
84#[derive(Clone, Debug, PartialEq, Eq)]
85pub struct DebugSkip {
86    pub pass: RenderPassId,
87    pub pass_label: &'static str,
88    /// `None` for the whole pass, or a step of a custom pass.
89    pub sub_pass: Option<&'static str>,
90    pub reason: DebugSkipReason,
91    /// Times it was skipped in the frame.
92    pub count: u32
93}
94
95#[derive(Clone, Debug, PartialEq, Eq)]
96pub enum DebugSkipReason {
97    /// A pipeline was requested while pending or failed.
98    Pipeline(CachedPipelineIndex),
99    /// A sub-pass has no pipeline yet, as its pipeline asset is not prepared.
100    NoPipeline,
101    NoBindGroup(u32),
102    NoMesh,
103    /// The render pass could not be created.
104    RenderPass(String),
105    /// The custom render of the pass did not complete.
106    CustomRender
107}
108impl std::fmt::Display for DebugSkipReason {
109    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
110        match self {
111            Self::Pipeline(id) => write!(f, "pipeline {id} not ready"),
112            Self::NoPipeline => f.write_str("no pipeline"),
113            Self::NoBindGroup(index) => write!(f, "no bind group {index}"),
114            Self::NoMesh => f.write_str("mesh not loaded"),
115            Self::RenderPass(error) => write!(f, "render pass: {error}"),
116            Self::CustomRender => f.write_str("custom render incomplete")
117        }
118    }
119}
120
121// ── RENDER WORLD ────────────────────────────────────────────────
122
123/// Records the parts of passes skipped in the frame being rendered (see [`PipelineStatusView`]).
124#[derive(Resource, Default)]
125pub(crate) struct PipelineStatus(Mutex<SkipState>);
126
127#[derive(Default)]
128struct SkipState {
129    enabled: bool,
130    pass: Option<(RenderPassId, &'static str)>,
131    skips: Vec<DebugSkip>,
132    /// Skips of the last rendered frame, sent to the main world.
133    finished: Option<Vec<DebugSkip>>
134}
135impl SkipState {
136    fn add(&mut self, sub_pass: Option<&'static str>, reason: DebugSkipReason) {
137        let Some((pass, pass_label)) = self.pass else {
138            return;
139        };
140        match self
141            .skips
142            .iter_mut()
143            .find(|s| s.pass == pass && s.sub_pass == sub_pass && s.reason == reason)
144        {
145            Some(skip) => skip.count += 1,
146            None => self.skips.push(DebugSkip {
147                pass,
148                pass_label,
149                sub_pass,
150                reason,
151                count: 1
152            })
153        }
154    }
155}
156
157fn extract(
158    mut main_world: ResMut<MainWorld>,
159    status: Res<PipelineStatus>,
160    manager: Res<PipelineManager>,
161    asset_server: Res<AssetServer>
162) {
163    let mut view = main_world.resource_mut::<PipelineStatusView>();
164    let mut state = status.0.lock().unwrap();
165    state.enabled = view.enabled;
166    if !view.enabled {
167        return;
168    }
169    view.pipelines = manager.report(&asset_server);
170    if let Some(skips) = state.finished.take() {
171        view.skips = skips;
172    }
173}
174
175impl PipelineStatus {
176    pub(crate) fn begin_pass(world: &World, id: RenderPassId, label: &'static str) {
177        // Pipelines requested outside of the passes are not reported
178        world.resource::<PipelineManager>().take_misses();
179        world.resource::<PipelineStatus>().0.lock().unwrap().pass = Some((id, label));
180    }
181
182    pub(crate) fn skip(world: &World, sub_pass: Option<&'static str>, reason: DebugSkipReason) {
183        let mut state = world.resource::<PipelineStatus>().0.lock().unwrap();
184        if state.enabled {
185            state.add(sub_pass, reason);
186        }
187    }
188
189    /// Reports the pipelines requested by the pass while not ready, not reported by its sub-passes.
190    pub(crate) fn end_pass(world: &World) {
191        let misses = world.resource::<PipelineManager>().take_misses();
192        let mut state = world.resource::<PipelineStatus>().0.lock().unwrap();
193        if state.enabled {
194            let pass = state.pass.map(|(id, _)| id);
195            for id in misses {
196                let reason = DebugSkipReason::Pipeline(id);
197                if !state
198                    .skips
199                    .iter()
200                    .any(|s| Some(s.pass) == pass && s.reason == reason)
201                {
202                    state.add(None, reason);
203                }
204            }
205        }
206        state.pass = None;
207    }
208
209    pub(crate) fn end_frame(world: &World) {
210        let mut state = world.resource::<PipelineStatus>().0.lock().unwrap();
211        if state.enabled {
212            state.finished = Some(std::mem::take(&mut state.skips));
213        } else {
214            state.skips.clear();
215        }
216    }
217}