Skip to main content

wde_pbr/post_process/
smaa.rs

1use wde_logger::prelude::*;
2
3use bevy::{
4    ecs::system::{
5        SystemParamItem,
6        lifetimeless::{SQuery, SRes, SResMut}
7    },
8    prelude::*
9};
10use wde_renderer::{prelude::*, wgpu_utils::*};
11
12use super::data::{PostProcessBuffers, PostProcessTextures};
13use super::settings::{AntiAliasing, PostProcessUniform};
14
15/// Precomputed lookup textures of the SMAA, from its reference implementation.
16#[derive(Resource)]
17pub(crate) struct SmaaLuts {
18    /// Areas covered on each side of an edge, by distance to its ends and crossing edges.
19    area: Handle<Texture>,
20    /// Length to add at the end of the edge searches.
21    search: Handle<Texture>
22}
23impl SmaaLuts {
24    pub fn load(asset_server: &AssetServer) -> Self {
25        let lut = |path: &'static str, label: &'static str, format| {
26            asset_server
27                .load_builder()
28                .with_settings(move |settings: &mut TextureLoaderSettings| {
29                    settings.label = label.to_string();
30                    settings.format = format;
31                })
32                .load(path)
33        };
34        Self {
35            area: lut(
36                "core/render/post_process/smaa_area_lut.png",
37                "smaa-area-lut",
38                TextureFormat::Rg8Unorm
39            ),
40            search: lut(
41                "core/render/post_process/smaa_search_lut.png",
42                "smaa-search-lut",
43                TextureFormat::R8Unorm
44            )
45        }
46    }
47}
48
49/// Intermediate textures of the SMAA, resized with the window.
50#[derive(Asset, Clone, TypePath, Default)]
51pub struct SmaaTextures;
52impl SmaaTextures {
53    /// Edges with the left (r) and top (g) neighbors.
54    pub const EDGES_IDX: u32 = 0;
55    /// Blending weights with the left/right (rg) and top/bottom (ba) neighbors.
56    pub const WEIGHTS_IDX: u32 = 1;
57
58    pub const EDGES_FORMAT: TextureFormat = TextureFormat::Rg8Unorm;
59    pub const WEIGHTS_FORMAT: TextureFormat = TextureFormat::Rgba8Unorm;
60}
61impl RenderData for SmaaTextures {
62    type Params = (SQuery<&'static Window>, SRes<Messages<SurfaceResized>>);
63
64    fn describe((window, _): &mut SystemParamItem<Self::Params>, builder: &mut RenderDataBuilder) {
65        let size = {
66            let window = window.single().unwrap();
67            (
68                window.resolution.physical_width().max(1),
69                window.resolution.physical_height().max(1)
70            )
71        };
72        for (idx, label, format) in [
73            (Self::EDGES_IDX, "smaa-edges", Self::EDGES_FORMAT),
74            (Self::WEIGHTS_IDX, "smaa-weights", Self::WEIGHTS_FORMAT)
75        ] {
76            builder.add_texture(
77                idx,
78                Texture {
79                    label: label.to_string(),
80                    size,
81                    format,
82                    usages: TextureUsages::RENDER_ATTACHMENT | TextureUsages::TEXTURE_BINDING,
83                    ..Default::default()
84                }
85            );
86        }
87    }
88
89    fn recreate((_, surface_resized): &SystemParamItem<Self::Params>) -> Option<bool> {
90        Some(
91            surface_resized
92                .get_cursor()
93                .read(surface_resized)
94                .next()
95                .is_some()
96        )
97    }
98}
99
100/// Inputs of the edge detection: the tonemapped image and the parameters.
101#[derive(Asset, Clone, TypePath, Default)]
102pub(crate) struct SmaaEdgesBinding;
103impl RenderBinding for SmaaEdgesBinding {
104    type Params = (
105        SRenderData<PostProcessTextures>,
106        SRenderData<PostProcessBuffers>
107    );
108
109    fn describe(
110        &mut self,
111        (textures, buffers): &SystemParamItem<Self::Params>,
112        builder: &mut RenderBindingBuilder
113    ) {
114        builder
115            .add_texture_view(textures, PostProcessTextures::LDR_IDX)
116            .add_texture_sampler(textures, PostProcessTextures::LDR_IDX)
117            .add_buffer(buffers, PostProcessBuffers::PARAMS_IDX);
118    }
119
120    fn has_dependencies(&self) -> bool {
121        true
122    }
123
124    fn label(&self) -> &str {
125        "smaa-edges-binding"
126    }
127}
128
129/// Inputs of the blending weights: the edges, the lookup textures and the parameters.
130#[derive(Asset, Clone, TypePath, Default)]
131pub(crate) struct SmaaWeightsBinding;
132impl RenderBinding for SmaaWeightsBinding {
133    type Params = (
134        SRenderData<SmaaTextures>,
135        SRenderData<PostProcessBuffers>,
136        SRes<SmaaLuts>
137    );
138
139    fn describe(
140        &mut self,
141        (textures, buffers, luts): &SystemParamItem<Self::Params>,
142        builder: &mut RenderBindingBuilder
143    ) {
144        builder
145            .add_texture_view(textures, SmaaTextures::EDGES_IDX)
146            .add_texture_sampler(textures, SmaaTextures::EDGES_IDX)
147            .add_texture_view_from_id(Some(luts.area.id()))
148            .add_texture_view_from_id(Some(luts.search.id()))
149            .add_buffer(buffers, PostProcessBuffers::PARAMS_IDX);
150    }
151
152    fn has_dependencies(&self) -> bool {
153        true
154    }
155
156    fn label(&self) -> &str {
157        "smaa-weights-binding"
158    }
159}
160
161/// Inputs of the neighborhood blending: the tonemapped image, the blending weights and the parameters.
162#[derive(Asset, Clone, TypePath, Default)]
163pub(crate) struct SmaaBlendBinding;
164impl RenderBinding for SmaaBlendBinding {
165    type Params = (
166        SRenderData<PostProcessTextures>,
167        SRenderData<SmaaTextures>,
168        SRenderData<PostProcessBuffers>
169    );
170
171    fn describe(
172        &mut self,
173        (ldr, smaa, buffers): &SystemParamItem<Self::Params>,
174        builder: &mut RenderBindingBuilder
175    ) {
176        builder
177            .add_texture_view(ldr, PostProcessTextures::LDR_IDX)
178            .add_texture_sampler(ldr, PostProcessTextures::LDR_IDX)
179            .add_texture_view(smaa, SmaaTextures::WEIGHTS_IDX)
180            .add_texture_sampler(smaa, SmaaTextures::WEIGHTS_IDX)
181            .add_buffer(buffers, PostProcessBuffers::PARAMS_IDX);
182    }
183
184    fn has_dependencies(&self) -> bool {
185        true
186    }
187
188    fn label(&self) -> &str {
189        "smaa-blend-binding"
190    }
191}
192
193/// First two passes of the SMAA, from the LDR texture of the [`PostProcessTextures`]: the edge detection,
194/// then the blending weights of each pixel. The neighborhood blending is done by [`RenderPassAntiAliasing`](super::RenderPassAntiAliasing).
195///
196/// It has a render index of 96, and does nothing when the [`AntiAliasing`] is not SMAA.
197pub struct RenderPassSmaa;
198impl RenderPass for RenderPassSmaa {
199    type Params = ();
200
201    fn describe(_: &SystemParamItem<Self::Params>) -> RenderPassDesc {
202        RenderPassDesc::default()
203    }
204
205    fn id() -> RenderPassId {
206        96
207    }
208    fn label() -> &'static str {
209        "smaa"
210    }
211
212    fn custom_render(world: &mut World, command_buffer: &mut CommandBuffer) -> Option<bool> {
213        if world.resource::<PostProcessUniform>().anti_aliasing() != AntiAliasing::Smaa {
214            return Some(true);
215        }
216        Some(render_smaa(world, command_buffer))
217    }
218}
219
220fn render_smaa(world: &World, command_buffer: &mut CommandBuffer) -> bool {
221    let pipeline_manager = world.resource::<PipelineManager>();
222    let pipeline =
223        |id: Option<CachedPipelineIndex>| match id.map(|id| pipeline_manager.get_pipeline(id)) {
224            Some(CachedPipelineStatus::OkRender(p)) => Some(p),
225            _ => None
226        };
227    let (Some(edges_pipeline), Some(weights_pipeline)) = (
228        pipeline(
229            world
230                .resource::<RenderAssets<SmaaEdgesPipeline>>()
231                .iter()
232                .next()
233                .map(|(_, p)| p.0)
234        ),
235        pipeline(
236            world
237                .resource::<RenderAssets<SmaaWeightsPipeline>>()
238                .iter()
239                .next()
240                .map(|(_, p)| p.0)
241        )
242    ) else {
243        return false;
244    };
245
246    fn bind_group<B: RenderBinding + Asset + Clone>(world: &World) -> Option<&BindGroup> {
247        world
248            .resource::<RenderAssets<GpuRenderBinding<B>>>()
249            .iter()
250            .next()
251            .map(|(_, b)| &b.bind_group)
252    }
253    let (Some(edges_input), Some(weights_input)) = (
254        bind_group::<SmaaEdgesBinding>(world),
255        bind_group::<SmaaWeightsBinding>(world)
256    ) else {
257        return false;
258    };
259
260    let meshes = world.resource::<RenderAssets<GpuMesh>>();
261    let Some((Some(vertices), Some(indices))) = world
262        .resource::<PostProcessingMesh>()
263        .0
264        .as_ref()
265        .and_then(|m| meshes.get(m.id()))
266        .map(|m| (m.vertex_buffer.as_ref(), m.index_buffer.as_ref()))
267    else {
268        return false;
269    };
270
271    let gpu_textures = world.resource::<RenderAssets<GpuTexture>>();
272    let Some((_, data)) = world
273        .resource::<RenderAssets<GpuRenderData<SmaaTextures>>>()
274        .iter()
275        .next()
276    else {
277        return false;
278    };
279    let texture = |idx| data.get_texture(idx).and_then(|t| gpu_textures.get(t.id()));
280    let (Some(edges), Some(weights)) = (
281        texture(SmaaTextures::EDGES_IDX),
282        texture(SmaaTextures::WEIGHTS_IDX)
283    ) else {
284        return false;
285    };
286
287    // Debug views: the weights step also shows its inputs
288    let id = |idx| data.get_texture(idx).unwrap().id();
289    let (edges_id, weights_id) = (id(SmaaTextures::EDGES_IDX), id(SmaaTextures::WEIGHTS_IDX));
290    let luts = world.resource::<SmaaLuts>();
291    let edges_step = [edges_id];
292    let weights_step = [weights_id, edges_id, luts.area.id(), luts.search.id()];
293
294    // Both targets are cleared, as the edge detection discards the pixels without edges
295    for (target, pipeline, bind_group, step, debug_textures) in [
296        (edges, edges_pipeline, edges_input, "edges", &edges_step[..]),
297        (
298            weights,
299            weights_pipeline,
300            weights_input,
301            "weights",
302            &weights_step[..]
303        )
304    ] {
305        let mut render_pass = match command_buffer.create_render_pass("smaa", |builder| {
306            builder.add_color_attachment(RenderPassColorAttachment {
307                texture: Some(&target.texture.view),
308                load: LoadOp::Clear(WdeColor::TRANSPARENT.into()),
309                store: StoreOp::Store,
310                resolve_target: None
311            });
312            Ok(())
313        }) {
314            Ok(render_pass) => render_pass,
315            Err(e) => {
316                trace!("Failed to create the SMAA render pass: {}.", e);
317                return false;
318            }
319        };
320        if render_pass.set_pipeline(pipeline).is_err() {
321            return false;
322        }
323        render_pass.set_bind_group(0, bind_group);
324        render_pass
325            .set_vertex_buffer(0, vertices)
326            .set_index_buffer(indices);
327        if render_pass.draw_indexed(0..6, 0..1).is_err() {
328            return false;
329        }
330        drop(render_pass);
331        RenderGraphDebug::capture(world, command_buffer, step, debug_textures);
332    }
333    true
334}
335
336fn fullscreen_pipeline(
337    label: &'static str,
338    frag: &'static str,
339    layout: Option<BindGroupLayout>,
340    render_targets: Option<Vec<TextureFormat>>,
341    asset_server: &AssetServer
342) -> RenderPipelineDescriptor {
343    RenderPipelineDescriptor {
344        label,
345        vert: Some(asset_server.load("core/render/post_process/fullscreen.vert.wgsl")),
346        frag: Some(asset_server.load(frag)),
347        bind_group_layouts: vec![layout],
348        depth: DepthDescriptor {
349            enabled: false,
350            ..default()
351        },
352        render_targets,
353        ..default()
354    }
355}
356
357#[derive(TypePath, Default, Clone, Debug)]
358pub(crate) struct SmaaEdgesPipeline(pub CachedPipelineIndex);
359impl RenderAsset for SmaaEdgesPipeline {
360    type SourceAsset = RenderPipelineAsset<SmaaEdgesPipeline>;
361    type Params = (
362        SRes<AssetServer>,
363        SResMut<PipelineManager>,
364        SBinding<SmaaEdgesBinding>
365    );
366
367    fn prepare(
368        _id: AssetId<Self::SourceAsset>,
369        asset: Self::SourceAsset,
370        (asset_server, pipeline_manager, binding): &mut SystemParamItem<Self::Params>
371    ) -> Result<Self, PrepareAssetError<Self::SourceAsset>> {
372        Ok(SmaaEdgesPipeline(pipeline_manager.create_render_pipeline(
373            fullscreen_pipeline(
374                "smaa-edges",
375                "core/render/post_process/smaa_edges.frag.wgsl",
376                binding.iter().next().map(|(_, b)| b.layout.clone()),
377                Some(vec![SmaaTextures::EDGES_FORMAT]),
378                asset_server
379            ),
380            asset
381        )?))
382    }
383}
384
385#[derive(TypePath, Default, Clone, Debug)]
386pub(crate) struct SmaaWeightsPipeline(pub CachedPipelineIndex);
387impl RenderAsset for SmaaWeightsPipeline {
388    type SourceAsset = RenderPipelineAsset<SmaaWeightsPipeline>;
389    type Params = (
390        SRes<AssetServer>,
391        SResMut<PipelineManager>,
392        SBinding<SmaaWeightsBinding>
393    );
394
395    fn prepare(
396        _id: AssetId<Self::SourceAsset>,
397        asset: Self::SourceAsset,
398        (asset_server, pipeline_manager, binding): &mut SystemParamItem<Self::Params>
399    ) -> Result<Self, PrepareAssetError<Self::SourceAsset>> {
400        Ok(SmaaWeightsPipeline(
401            pipeline_manager.create_render_pipeline(
402                fullscreen_pipeline(
403                    "smaa-weights",
404                    "core/render/post_process/smaa_weights.frag.wgsl",
405                    binding.iter().next().map(|(_, b)| b.layout.clone()),
406                    Some(vec![SmaaTextures::WEIGHTS_FORMAT]),
407                    asset_server
408                ),
409                asset
410            )?
411        ))
412    }
413}
414
415/// Neighborhood blending, drawn by the anti-aliasing sub-pass.
416#[derive(TypePath, Default, Clone, Debug)]
417pub(crate) struct SmaaBlendPipeline(pub CachedPipelineIndex);
418impl RenderAsset for SmaaBlendPipeline {
419    type SourceAsset = RenderPipelineAsset<SmaaBlendPipeline>;
420    type Params = (
421        SRes<AssetServer>,
422        SResMut<PipelineManager>,
423        SBinding<SmaaBlendBinding>
424    );
425
426    fn prepare(
427        _id: AssetId<Self::SourceAsset>,
428        asset: Self::SourceAsset,
429        (asset_server, pipeline_manager, binding): &mut SystemParamItem<Self::Params>
430    ) -> Result<Self, PrepareAssetError<Self::SourceAsset>> {
431        Ok(SmaaBlendPipeline(pipeline_manager.create_render_pipeline(
432            fullscreen_pipeline(
433                "smaa-blend",
434                "core/render/post_process/smaa_blend.frag.wgsl",
435                binding.iter().next().map(|(_, b)| b.layout.clone()),
436                Some(vec![PostProcessTextures::LDR_FORMAT]),
437                asset_server
438            ),
439            asset
440        )?))
441    }
442}