Skip to main content

wde_renderer/passes/
render_graph_debug.rs

1//! Debug views of the render graph (see [`RenderGraphDebugView`]).
2use std::{sync::Mutex, time::Duration};
3
4use bevy::{
5    ecs::system::{
6        SystemParamItem,
7        lifetimeless::{SRes, SResMut}
8    },
9    prelude::*
10};
11use bytemuck::{Pod, Zeroable};
12use wde_logger::trace;
13use wde_wgpu::{
14    bind_group::{BindGroupBuilder, BindGroupLayout},
15    command_buffer::{CommandBuffer, RenderPassColorAttachment},
16    render_pass::RenderPassInstance
17};
18
19use crate::{
20    assets::{GpuTexture, PrepareAssetError, RenderAsset, RenderAssets, Shader, Texture},
21    core::{Render, RenderApp, RenderInstance, RenderSet, SwapchainFrame},
22    prelude::{TextureFormat, TextureSampleType, TextureUsages, WdeColor},
23    sync::{ExtractSchedule, MainWorld}
24};
25
26use super::{
27    CachedPipelineIndex, CachedPipelineStatus, DebugFrameTimings, DebugTiming, DepthDescriptor,
28    LoadOp, PipelineManager, PushConstantDescriptor, RenderPassDesc, RenderPassId,
29    RenderPipelineAsset, RenderPipelineDescriptor, RenderPipelineRegisterPlugin, ShaderStages,
30    StoreOp, render_graph_timings::Timings
31};
32
33pub(crate) struct RenderGraphDebugPlugin;
34impl Plugin for RenderGraphDebugPlugin {
35    fn build(&self, app: &mut App) {
36        app.init_resource::<RenderGraphDebugView>().add_plugins((
37            RenderPipelineRegisterPlugin::<DebugViewFloatPipeline>::default(),
38            RenderPipelineRegisterPlugin::<DebugViewDepthPipeline>::default(),
39            RenderPipelineRegisterPlugin::<DebugViewUintPipeline>::default()
40        ));
41        app.get_sub_app_mut(RenderApp)
42            .unwrap()
43            .init_resource::<RenderGraphDebug>()
44            .add_systems(ExtractSchedule, extract)
45            .add_systems(
46                Render,
47                (
48                    begin_frame.before(RenderSet::ExtractAuto),
49                    end_frame.after(RenderSet::Submit)
50                )
51            );
52    }
53}
54
55// ── MAIN WORLD ──────────────────────────────────────────────────
56
57/// Debug view of the render graph, in the main world: records the passes of each frame with the textures they
58/// write, and draws the selected texture, as it is at the selected point of the frame, into the `target` texture.
59/// The `Debug/Pipeline` window of the editor drives it.
60///
61/// Passes rendered by the render graph are recorded automatically, with one point after each of their sub-passes
62/// showing their attachments. A pass with a [`RenderPass::custom_render`](super::RenderPass::custom_render)
63/// reports its own steps with [`RenderGraphDebug::capture`].
64///
65/// Each pass is also timed, on the CPU while recording its commands and on the GPU with timestamps when the device
66/// supports them, along with the whole frame.
67#[derive(Resource, Clone)]
68pub struct RenderGraphDebugView {
69    /// Records the passes of each frame into the `report`, and draws the selected texture. Disable it when unused.
70    pub enabled: bool,
71    pub selection: Option<DebugSelection>,
72    pub settings: DebugViewSettings,
73    /// Texture the selected texture is drawn into, in the [`RenderGraphDebugView::TARGET_FORMAT`], with the
74    /// `RENDER_ATTACHMENT` usage. It keeps its content while the selected point is not reached.
75    pub target: Option<AssetId<Texture>>,
76    /// Passes of the last rendered frame, in their execution order.
77    pub report: Vec<DebugPassReport>,
78    /// Number of frames the timings are computed over.
79    pub timing_window: usize,
80    pub timings: DebugFrameTimings
81}
82impl Default for RenderGraphDebugView {
83    fn default() -> Self {
84        Self {
85            enabled: false,
86            selection: None,
87            settings: DebugViewSettings::default(),
88            target: None,
89            report: vec![],
90            timing_window: 120,
91            timings: DebugFrameTimings::default()
92        }
93    }
94}
95impl RenderGraphDebugView {
96    pub const TARGET_FORMAT: TextureFormat = TextureFormat::Rgba8UnormSrgb;
97    /// Id of the last reported pass, holding the frame presented on screen after every pass.
98    pub const FINAL_PASS: RenderPassId = RenderPassId::MAX;
99
100    /// Report of the selected texture in the last frame.
101    pub fn selected_texture(&self) -> Option<&DebugTextureReport> {
102        let selection = self.selection?;
103        self.report
104            .iter()
105            .find(|p| p.id == selection.pass)?
106            .points
107            .get(selection.point)?
108            .textures
109            .get(selection.texture)
110    }
111}
112
113/// A texture at a point of a pass.
114#[derive(Clone, Copy, Debug, PartialEq, Eq)]
115pub struct DebugSelection {
116    pub pass: RenderPassId,
117    /// Index of the point in [`DebugPassReport::points`].
118    pub point: usize,
119    /// Index of the texture in [`DebugPointReport::textures`].
120    pub texture: usize
121}
122
123/// How the selected texture is displayed.
124#[derive(Clone, Copy, Debug, PartialEq)]
125pub struct DebugViewSettings {
126    pub mode: DebugViewMode,
127    pub channels: DebugChannels,
128    /// Values mapped to black and white.
129    pub range: [f32; 2],
130    /// Exposure in EV stops of the [`DebugViewMode::Color`].
131    pub exposure: f32,
132    /// Reinhard tonemapping of the [`DebugViewMode::Color`], for HDR colors.
133    pub tonemap: bool,
134    /// Views the stencil aspect of depth-stencil textures instead of their depth.
135    pub stencil: bool,
136    pub layer: u32,
137    pub mip: u32
138}
139impl Default for DebugViewSettings {
140    fn default() -> Self {
141        Self {
142            mode: DebugViewMode::Color,
143            channels: DebugChannels::Rgb,
144            range: [0.0, 1.0],
145            exposure: 0.0,
146            tonemap: false,
147            stencil: false,
148            layer: 0,
149            mip: 0
150        }
151    }
152}
153impl DebugViewSettings {
154    /// Sensible settings to view a texture of this format.
155    pub fn for_format(format: TextureFormat) -> Self {
156        let data = |channels, range| Self {
157            mode: DebugViewMode::Data,
158            channels,
159            range,
160            ..Default::default()
161        };
162        match format {
163            // Perspective depth: the scene is close to the far plane
164            TextureFormat::Depth24Plus | TextureFormat::Depth24PlusStencil8 => {
165                data(DebugChannels::R, [0.99, 1.0])
166            }
167            f if f.has_depth_aspect() => data(DebugChannels::R, [0.0, 1.0]),
168            TextureFormat::Stencil8 => Self::for_stencil(),
169            TextureFormat::R32Float => data(DebugChannels::R, [0.0, 100.0]),
170            f if f.sample_type(None, None) == Some(TextureSampleType::Uint) => {
171                data(DebugChannels::Rgb, [0.0, 255.0])
172            }
173            f if f.is_srgb() => Self::default(),
174            f if f.components() <= 2 => data(DebugChannels::Rgb, [0.0, 1.0]),
175            TextureFormat::Rgba16Float
176            | TextureFormat::Rgba32Float
177            | TextureFormat::Rg11b10Ufloat => Self {
178                tonemap: true,
179                ..Default::default()
180            },
181            _ => data(DebugChannels::Rgb, [0.0, 1.0])
182        }
183    }
184
185    /// Settings to view the stencil aspect of a texture.
186    pub fn for_stencil() -> Self {
187        Self {
188            mode: DebugViewMode::Integer,
189            channels: DebugChannels::R,
190            range: [0.0, 255.0],
191            stencil: true,
192            ..Default::default()
193        }
194    }
195}
196
197/// Linear color of an integer value in the [`DebugViewMode::Integer`]: black for 0, and hues spread by the golden
198/// ratio for the others.
199pub fn debug_integer_color(value: u32) -> [f32; 3] {
200    if value == 0 {
201        return [0.0; 3];
202    }
203    let hue = ((value - 1) as f32 * 0.618_034).fract();
204    [0.0, 2.0 / 3.0, 1.0 / 3.0].map(|offset| {
205        let ramp = (((hue + offset).fract() * 6.0 - 3.0).abs() - 1.0).clamp(0.0, 1.0);
206        1.0 + (ramp - 1.0) * DEBUG_INTEGER_SATURATION
207    })
208}
209const DEBUG_INTEGER_SATURATION: f32 = 0.8;
210
211#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
212pub enum DebugViewMode {
213    /// Values shown as they are, from black to white.
214    Data,
215    /// Linear colors, with an exposure and an optional tonemapping.
216    #[default]
217    Color,
218    /// Rounded values, each with its own color (see [`debug_integer_color`]), such as stencil values. The `Rgb`
219    /// channels show the red one.
220    Integer
221}
222
223#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
224pub enum DebugChannels {
225    #[default]
226    Rgb,
227    R,
228    G,
229    B,
230    A
231}
232
233/// A pass of the last frame.
234#[derive(Clone, Debug)]
235pub struct DebugPassReport {
236    pub id: RenderPassId,
237    pub label: &'static str,
238    /// Rendered by [`RenderPass::custom_render`](super::RenderPass::custom_render), its points being the steps it reported.
239    pub custom: bool,
240    /// Points of the pass where its textures can be viewed: after each sub-pass, or each step of a custom pass.
241    pub points: Vec<DebugPointReport>,
242    /// Time to record the commands of the pass, its sub-passes described.
243    pub cpu_time: Option<DebugTiming>,
244    /// Time of the pass on the GPU, including the debug view drawn in it.
245    pub gpu_time: Option<DebugTiming>
246}
247
248#[derive(Clone, Debug)]
249pub struct DebugPointReport {
250    pub label: String,
251    pub textures: Vec<DebugTextureReport>
252}
253
254#[derive(Clone, Debug)]
255pub struct DebugTextureReport {
256    pub label: String,
257    /// `None` for the swapchain, which is copied to be viewed.
258    pub id: Option<AssetId<Texture>>,
259    pub format: Option<TextureFormat>,
260    pub size: (u32, u32),
261    pub layers: u32,
262    pub mips: u32,
263    /// Whether the texture can be drawn: the signed integer formats can't, nor the swapchain without the
264    /// `COPY_SRC` usage (only set in debug builds).
265    pub viewable: bool
266}
267impl DebugTextureReport {
268    fn new(world: &World, id: Option<AssetId<Texture>>) -> Self {
269        let Some(id) = id else {
270            let texture = world
271                .resource::<SwapchainFrame>()
272                .data
273                .as_ref()
274                .map(|f| &f.texture.texture);
275            return Self {
276                label: "swapchain".to_string(),
277                id: None,
278                format: texture.map(|t| t.format()),
279                size: texture.map_or((0, 0), |t| (t.width(), t.height())),
280                layers: 1,
281                mips: 1,
282                viewable: texture.is_some_and(|t| t.usage().contains(TextureUsages::COPY_SRC))
283            };
284        };
285        let Some(texture) = world.resource::<RenderAssets<GpuTexture>>().get(id) else {
286            return Self {
287                label: "(not ready)".to_string(),
288                id: Some(id),
289                format: None,
290                size: (0, 0),
291                layers: 0,
292                mips: 0,
293                viewable: false
294            };
295        };
296        let texture = &texture.texture;
297        Self {
298            label: texture.label.clone(),
299            id: Some(id),
300            format: Some(texture.format),
301            size: texture.size,
302            layers: texture.layer_count,
303            mips: texture.mip_level_count,
304            viewable: texture.sample_count == 1
305                && view_pipeline_kind(texture.sample_type(false)).is_some()
306        }
307    }
308}
309
310// ── RENDER WORLD ────────────────────────────────────────────────
311
312/// Debug view of the render graph, in the render world (see [`RenderGraphDebugView`]).
313#[derive(Resource, Default)]
314pub struct RenderGraphDebug(Mutex<DebugState>);
315
316#[derive(Default)]
317struct DebugState {
318    enabled: bool,
319    selection: Option<DebugSelection>,
320    settings: DebugViewSettings,
321    target: Option<AssetId<Texture>>,
322    /// Passes of the frame being rendered.
323    report: Vec<DebugPassReport>,
324    /// Passes of the last rendered frame, sent to the main world.
325    finished: Vec<DebugPassReport>,
326    /// Copy of the swapchain texture, which can't be read by a shader.
327    swapchain_copy: Option<wde_wgpu::texture::Texture>,
328    timings: Timings,
329    /// Timings of the last rendered frame, sent to the main world.
330    finished_timings: Option<DebugFrameTimings>
331}
332
333fn extract(mut main_world: ResMut<MainWorld>, debug: Res<RenderGraphDebug>) {
334    let mut view = main_world.resource_mut::<RenderGraphDebugView>();
335    let mut state = debug.0.lock().unwrap();
336    state.enabled = view.enabled;
337    state.selection = view.selection;
338    state.settings = view.settings;
339    state.target = view.target;
340    if !state.enabled {
341        state.timings = Timings::default();
342    }
343    state.timings.window = view.timing_window;
344    if !state.finished.is_empty() {
345        view.report = std::mem::take(&mut state.finished);
346    }
347    if let Some(timings) = state.finished_timings.take() {
348        view.timings = timings;
349    }
350}
351
352fn begin_frame(debug: Res<RenderGraphDebug>, instance: Res<RenderInstance>) {
353    let mut state = debug.0.lock().unwrap();
354    if state.enabled {
355        state.timings.begin_frame(&instance.0.read().unwrap());
356    }
357}
358
359fn end_frame(debug: Res<RenderGraphDebug>, instance: Res<RenderInstance>) {
360    let mut state = debug.0.lock().unwrap();
361    if !state.enabled {
362        return;
363    }
364    state.timings.end_frame();
365    let present_mode = instance
366        .0
367        .read()
368        .unwrap()
369        .surface_config
370        .as_ref()
371        .map(|c| c.present_mode);
372    state.finished_timings = Some(state.timings.summary(present_mode));
373}
374
375impl RenderGraphDebug {
376    /// Reports a step of a custom pass, that wrote the `textures`, and draws the selected one if this step is
377    /// selected. Call it from [`RenderPass::custom_render`](super::RenderPass::custom_render) after each step,
378    /// once its render or compute pass is ended.
379    pub fn capture(
380        world: &World,
381        command_buffer: &mut CommandBuffer,
382        label: &str,
383        textures: &[AssetId<Texture>]
384    ) {
385        let Some(debug) = world.get_resource::<RenderGraphDebug>() else {
386            return;
387        };
388        let mut state = debug.0.lock().unwrap();
389        if !state.enabled {
390            return;
391        }
392        let reports = textures
393            .iter()
394            .map(|id| DebugTextureReport::new(world, Some(*id)))
395            .collect();
396        let Some(pass) = state.report.last_mut() else {
397            return;
398        };
399        pass.points.push(DebugPointReport {
400            label: label.to_string(),
401            textures: reports
402        });
403        let point = (pass.id, pass.points.len() - 1);
404        if let Some(selection) = state.selection
405            && (selection.pass, selection.point) == point
406            && let Some(id) = textures.get(selection.texture)
407        {
408            draw_source(world, command_buffer, &mut state, DebugSource::Texture(*id));
409        }
410    }
411
412    pub(crate) fn begin_pass(world: &World, id: RenderPassId, label: &'static str) {
413        let mut state = world.resource::<RenderGraphDebug>().0.lock().unwrap();
414        if state.enabled {
415            state.report.push(DebugPassReport {
416                id,
417                label,
418                custom: false,
419                points: vec![],
420                cpu_time: None,
421                gpu_time: None
422            });
423        }
424    }
425
426    pub(crate) fn begin_graph(world: &World) {
427        let mut state = world.resource::<RenderGraphDebug>().0.lock().unwrap();
428        if state.enabled {
429            state.timings.begin_graph();
430        }
431    }
432
433    pub(crate) fn begin_pass_timing(
434        world: &World,
435        command_buffer: &mut CommandBuffer,
436        id: RenderPassId
437    ) {
438        let mut state = world.resource::<RenderGraphDebug>().0.lock().unwrap();
439        if state.enabled {
440            state.timings.begin_pass(command_buffer, id);
441        }
442    }
443
444    pub(crate) fn end_pass_timing(world: &World, command_buffer: &mut CommandBuffer) {
445        let mut state = world.resource::<RenderGraphDebug>().0.lock().unwrap();
446        if state.enabled {
447            state.timings.end_pass(command_buffer);
448        }
449    }
450
451    pub(crate) fn end_graph(world: &World, command_buffer: &mut CommandBuffer) {
452        let mut state = world.resource::<RenderGraphDebug>().0.lock().unwrap();
453        if state.enabled {
454            let instance = world.resource::<RenderInstance>().0.read().unwrap();
455            state.timings.end_graph(&instance, command_buffer);
456        }
457    }
458
459    /// Reads back the GPU timings, once the render graph commands are submitted.
460    pub(crate) fn submitted(world: &World) {
461        let mut state = world.resource::<RenderGraphDebug>().0.lock().unwrap();
462        if state.enabled {
463            state.timings.submitted();
464        }
465    }
466
467    /// Time blocked acquiring the swapchain texture.
468    pub(crate) fn add_swapchain_wait(&self, wait: Duration) {
469        let mut state = self.0.lock().unwrap();
470        if state.enabled {
471            state.timings.add_swapchain_wait(wait);
472        }
473    }
474
475    /// A frame was presented, after blocking for `wait`.
476    pub(crate) fn presented(&self, wait: Duration) {
477        let mut state = self.0.lock().unwrap();
478        if state.enabled {
479            state.timings.presented(wait);
480        }
481    }
482
483    pub(crate) fn end_custom_pass(world: &World) {
484        let mut state = world.resource::<RenderGraphDebug>().0.lock().unwrap();
485        if let Some(pass) = state.report.last_mut() {
486            pass.custom = true;
487        }
488    }
489
490    /// Reports the points of a pass rendered by the render graph: after each of its sub-passes, showing its
491    /// attachments. Returns the selected point and its texture, if any.
492    pub(crate) fn graph_pass(
493        world: &World,
494        desc: &RenderPassDesc,
495        sub_passes: &[&str]
496    ) -> Option<(usize, Option<DebugSource>)> {
497        let mut state = world.resource::<RenderGraphDebug>().0.lock().unwrap();
498        if !state.enabled {
499            return None;
500        }
501        let attachments: Vec<Option<AssetId<Texture>>> = match &desc.attachments_colors {
502            Some(colors) => colors.iter().map(|c| c.texture).collect(),
503            None => vec![None]
504        }
505        .into_iter()
506        .chain(desc.attachments_depth.as_ref().map(|d| d.texture))
507        .collect();
508        let textures: Vec<_> = attachments
509            .iter()
510            .map(|id| DebugTextureReport::new(world, *id))
511            .collect();
512        let labels = if sub_passes.is_empty() {
513            &["(clear)"][..]
514        } else {
515            sub_passes
516        };
517
518        let selection = state.selection;
519        let pass = state.report.last_mut()?;
520        pass.points = labels
521            .iter()
522            .map(|label| DebugPointReport {
523                label: label.to_string(),
524                textures: textures.clone()
525            })
526            .collect();
527        let selection = selection.filter(|s| s.pass == pass.id && s.point < pass.points.len())?;
528        Some((
529            selection.point,
530            attachments
531                .get(selection.texture)
532                .map(|id| id.map_or(DebugSource::Swapchain, DebugSource::Texture))
533        ))
534    }
535
536    /// Draws the selected texture of a pass rendered by the render graph.
537    pub(crate) fn draw_selected(
538        world: &World,
539        command_buffer: &mut CommandBuffer,
540        source: DebugSource
541    ) {
542        let mut state = world.resource::<RenderGraphDebug>().0.lock().unwrap();
543        draw_source(world, command_buffer, &mut state, source);
544    }
545
546    /// Reports the [`RenderGraphDebugView::FINAL_PASS`], after every pass, and draws the presented frame if it is
547    /// selected.
548    pub(crate) fn final_pass(world: &World, command_buffer: &mut CommandBuffer) {
549        let mut state = world.resource::<RenderGraphDebug>().0.lock().unwrap();
550        if !state.enabled {
551            return;
552        }
553        state.report.push(DebugPassReport {
554            id: RenderGraphDebugView::FINAL_PASS,
555            label: "final",
556            custom: false,
557            points: vec![DebugPointReport {
558                label: "presented frame".to_string(),
559                textures: vec![DebugTextureReport::new(world, None)]
560            }],
561            cpu_time: None,
562            gpu_time: None
563        });
564        if state
565            .selection
566            .is_some_and(|s| s.pass == RenderGraphDebugView::FINAL_PASS)
567        {
568            draw_source(world, command_buffer, &mut state, DebugSource::Swapchain);
569        }
570    }
571
572    pub(crate) fn end_frame(world: &World) {
573        let mut state = world.resource::<RenderGraphDebug>().0.lock().unwrap();
574        if state.enabled {
575            let DebugState {
576                report, timings, ..
577            } = &mut *state;
578            timings.fill_reports(report);
579            state.finished = std::mem::take(&mut state.report);
580        } else {
581            state.report.clear();
582        }
583    }
584}
585
586// ── DRAW ────────────────────────────────────────────────────────
587
588/// A texture drawn by the debug view.
589#[derive(Clone, Copy)]
590pub(crate) enum DebugSource {
591    Texture(AssetId<Texture>),
592    Swapchain
593}
594
595fn draw_source(
596    world: &World,
597    command_buffer: &mut CommandBuffer,
598    state: &mut DebugState,
599    source: DebugSource
600) -> bool {
601    match source {
602        DebugSource::Texture(id) => {
603            let Some(texture) = world.resource::<RenderAssets<GpuTexture>>().get(id) else {
604                return false;
605            };
606            draw(world, command_buffer, state, &texture.texture)
607        }
608        DebugSource::Swapchain => {
609            copy_swapchain(world, command_buffer, state)
610                && draw(
611                    world,
612                    command_buffer,
613                    state,
614                    state.swapchain_copy.as_ref().unwrap()
615                )
616        }
617    }
618}
619
620/// Copies the swapchain texture as it is at this point of the frame.
621fn copy_swapchain(
622    world: &World,
623    command_buffer: &mut CommandBuffer,
624    state: &mut DebugState
625) -> bool {
626    let Some(frame) = world.resource::<SwapchainFrame>().data.as_ref() else {
627        return false;
628    };
629    let source = &frame.texture.texture;
630    if !source.usage().contains(TextureUsages::COPY_SRC) {
631        return false;
632    }
633    let size = (source.width(), source.height());
634    if state
635        .swapchain_copy
636        .as_ref()
637        .is_none_or(|t| t.size != size || t.format != source.format())
638    {
639        let instance = world.resource::<RenderInstance>().0.read().unwrap();
640        state.swapchain_copy = Some(wde_wgpu::texture::Texture::new(
641            &instance,
642            "debug-view-swapchain",
643            size,
644            source.format(),
645            TextureUsages::TEXTURE_BINDING,
646            1,
647            1,
648            1,
649            true,
650            false,
651            false,
652            None
653        ));
654    }
655    command_buffer.copy_texture_to_texture(source, &state.swapchain_copy.as_ref().unwrap().texture);
656    true
657}
658
659#[repr(C)]
660#[derive(Clone, Copy, Pod, Zeroable)]
661struct DebugViewParams {
662    range: [f32; 2],
663    exposure: f32,
664    channels: u32,
665    mode: u32,
666    tonemap: u32,
667    _pad: [u32; 2]
668}
669impl DebugViewParams {
670    fn new(settings: &DebugViewSettings) -> Self {
671        Self {
672            range: settings.range,
673            exposure: settings.exposure.exp2(),
674            channels: settings.channels as u32,
675            mode: settings.mode as u32,
676            tonemap: settings.tonemap as u32,
677            _pad: [0; 2]
678        }
679    }
680}
681
682#[derive(Clone, Copy)]
683enum ViewKind {
684    Float,
685    Depth,
686    Uint
687}
688fn view_pipeline_kind(sample_type: Option<TextureSampleType>) -> Option<ViewKind> {
689    match sample_type? {
690        TextureSampleType::Float { .. } => Some(ViewKind::Float),
691        TextureSampleType::Depth => Some(ViewKind::Depth),
692        TextureSampleType::Uint => Some(ViewKind::Uint),
693        TextureSampleType::Sint => None
694    }
695}
696
697fn view_layout(kind: ViewKind) -> BindGroupLayout {
698    let sample_type = match kind {
699        ViewKind::Float => TextureSampleType::Float { filterable: false },
700        ViewKind::Depth => TextureSampleType::Depth,
701        ViewKind::Uint => TextureSampleType::Uint
702    };
703    BindGroupLayout::new("debug-view", |builder| {
704        builder.add_texture_view_sample_type(0, ShaderStages::FRAGMENT, sample_type);
705    })
706}
707
708fn draw(
709    world: &World,
710    command_buffer: &mut CommandBuffer,
711    state: &DebugState,
712    source: &wde_wgpu::texture::Texture
713) -> bool {
714    let Some(target) = state
715        .target
716        .and_then(|t| world.resource::<RenderAssets<GpuTexture>>().get(t))
717    else {
718        return false;
719    };
720    let settings = &state.settings;
721    let Some(kind) = view_pipeline_kind(source.sample_type(settings.stencil)) else {
722        return false;
723    };
724    let pipeline_id = match kind {
725        ViewKind::Float => pipeline_index::<DebugViewFloatPipeline>(world),
726        ViewKind::Depth => pipeline_index::<DebugViewDepthPipeline>(world),
727        ViewKind::Uint => pipeline_index::<DebugViewUintPipeline>(world)
728    };
729    let pipeline_manager = world.resource::<PipelineManager>();
730    let Some(CachedPipelineStatus::OkRender(pipeline)) =
731        pipeline_id.map(|id| pipeline_manager.get_pipeline(id))
732    else {
733        return false;
734    };
735
736    let view = source.single_view(
737        settings.layer.min(source.layer_count.saturating_sub(1)),
738        settings.mip.min(source.mip_level_count.saturating_sub(1)),
739        settings.stencil
740    );
741    let bind_group = {
742        let instance = world.resource::<RenderInstance>().0.read().unwrap();
743        let Ok(layout) = view_layout(kind).build(&instance) else {
744            return false;
745        };
746        let Ok(bind_group) = BindGroupBuilder::build(
747            "debug-view",
748            &instance,
749            &layout,
750            &vec![BindGroupBuilder::view(0, &view)]
751        ) else {
752            return false;
753        };
754        bind_group
755    };
756
757    let render_pass = command_buffer.create_render_pass("debug-view", |builder| {
758        builder.add_color_attachment(RenderPassColorAttachment {
759            texture: Some(&target.texture.view),
760            load: LoadOp::Clear(WdeColor::BLACK.into()),
761            store: StoreOp::Store,
762            resolve_target: None
763        });
764        Ok(())
765    });
766    let mut render_pass: RenderPassInstance = match render_pass {
767        Ok(render_pass) => render_pass,
768        Err(e) => {
769            trace!("Failed to create the debug view render pass: {}.", e);
770            return false;
771        }
772    };
773    if render_pass.set_pipeline(pipeline).is_err() {
774        return false;
775    }
776    render_pass
777        .set_bind_group(0, &bind_group)
778        .set_push_constants(bytemuck::bytes_of(&DebugViewParams::new(settings)));
779    render_pass.draw(0..3, 0..1).is_ok()
780}
781
782fn pipeline_index<P: RenderAsset + DebugViewPipeline>(
783    world: &World
784) -> Option<CachedPipelineIndex> {
785    world
786        .resource::<RenderAssets<P>>()
787        .iter()
788        .next()
789        .map(|(_, p)| p.index())
790}
791
792trait DebugViewPipeline {
793    fn index(&self) -> CachedPipelineIndex;
794}
795
796macro_rules! debug_view_pipeline {
797    ($name:ident, $kind:expr, $label:literal, $shader:literal) => {
798        #[derive(TypePath, Default, Clone, Debug)]
799        pub(crate) struct $name(CachedPipelineIndex);
800        impl DebugViewPipeline for $name {
801            fn index(&self) -> CachedPipelineIndex {
802                self.0
803            }
804        }
805        impl RenderAsset for $name {
806            type SourceAsset = RenderPipelineAsset<$name>;
807            type Params = (SRes<AssetServer>, SResMut<PipelineManager>);
808
809            fn prepare(
810                _id: AssetId<Self::SourceAsset>,
811                asset: Self::SourceAsset,
812                (asset_server, pipeline_manager): &mut SystemParamItem<Self::Params>
813            ) -> Result<Self, PrepareAssetError<Self::SourceAsset>> {
814                Ok($name(pipeline_manager.create_render_pipeline(
815                    RenderPipelineDescriptor {
816                        label: $label,
817                        vert: Some(asset_server.load::<Shader>("core/render/debug/view.vert.wgsl")),
818                        frag: Some(asset_server.load::<Shader>($shader)),
819                        bind_group_layouts: vec![Some(view_layout($kind))],
820                        push_constants: vec![PushConstantDescriptor {
821                            offset: 0,
822                            size: std::mem::size_of::<DebugViewParams>() as u32
823                        }],
824                        depth: DepthDescriptor {
825                            enabled: false,
826                            ..default()
827                        },
828                        render_targets: Some(vec![RenderGraphDebugView::TARGET_FORMAT]),
829                        cull_mode: None,
830                        vertex_buffer: false,
831                        ..default()
832                    },
833                    asset
834                )?))
835            }
836        }
837    };
838}
839debug_view_pipeline!(
840    DebugViewFloatPipeline,
841    ViewKind::Float,
842    "debug-view-float",
843    "core/render/debug/view_float.frag.wgsl"
844);
845debug_view_pipeline!(
846    DebugViewDepthPipeline,
847    ViewKind::Depth,
848    "debug-view-depth",
849    "core/render/debug/view_depth.frag.wgsl"
850);
851debug_view_pipeline!(
852    DebugViewUintPipeline,
853    ViewKind::Uint,
854    "debug-view-uint",
855    "core/render/debug/view_uint.frag.wgsl"
856);