1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
use crate::renderer::*;

///
/// A simple anti-aliasing approach which smooths otherwise jagged edges (for example lines) but also
/// smooths the rest of the image.
///
#[derive(Clone, Default, Debug)]
pub struct FxaaEffect {}

impl FxaaEffect {
    ///
    /// Applies the FXAA effect to the given color texture.
    /// Must be called in the callback given as input to a [RenderTarget], [ColorTarget] or [DepthTarget] write method.
    ///
    #[deprecated = "use `apply_screen_effect` instead"]
    pub fn apply(&self, context: &Context, color_texture: ColorTexture) {
        apply_screen_effect(
            context,
            self,
            &Camera::new_2d(Viewport::new_at_origo(
                color_texture.width(),
                color_texture.height(),
            )),
            &[],
            Some(color_texture),
            None,
        );
    }
}

impl Effect for FxaaEffect {
    fn fragment_shader_source(
        &self,
        _lights: &[&dyn Light],
        color_texture: Option<ColorTexture>,
        _depth_texture: Option<DepthTexture>,
    ) -> String {
        let color_texture =
            color_texture.expect("Must supply a color texture to apply a fxaa effect");
        format!(
            "{}\n{}",
            color_texture.fragment_shader_source(),
            include_str!("shaders/fxaa_effect.frag")
        )
    }

    fn id(&self, color_texture: Option<ColorTexture>, _depth_texture: Option<DepthTexture>) -> u16 {
        let color_texture =
            color_texture.expect("Must supply a color texture to apply a fxaa effect");
        0b1u16 << 14 | 0b1u16 << 13 | 0b1u16 << 12 | 0b1u16 << 11 | color_texture.id()
    }

    fn fragment_attributes(&self) -> FragmentAttributes {
        FragmentAttributes {
            uv: true,
            ..FragmentAttributes::NONE
        }
    }

    fn use_uniforms(
        &self,
        program: &Program,
        _camera: &Camera,
        _lights: &[&dyn Light],
        color_texture: Option<ColorTexture>,
        _depth_texture: Option<DepthTexture>,
    ) {
        let color_texture =
            color_texture.expect("Must supply a color texture to apply a fxaa effect");
        let w = color_texture.width();
        let h = color_texture.height();
        color_texture.use_uniforms(program);
        program.use_uniform("resolution", vec2(w as f32, h as f32));
    }

    fn render_states(&self) -> RenderStates {
        RenderStates {
            write_mask: WriteMask::COLOR,
            depth_test: DepthTest::Always,
            cull: Cull::Back,
            ..Default::default()
        }
    }
}