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
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
//!
//! Functionality for rendering to the screen or into textures.
//!
//!
mod screen;
#[doc(inline)]
pub use screen::*;

mod render_target2d;
#[doc(inline)]
pub use render_target2d::*;

mod render_target2d_array;
#[doc(inline)]
pub use render_target2d_array::*;

mod render_target_cube_map;
#[doc(inline)]
pub use render_target_cube_map::*;

use crate::context::consts;
use crate::core::*;

///
/// Defines which channels (red, green, blue, alpha and depth) to clear when starting to write to a
/// [RenderTarget] or the [Screen].
/// If `None` then the channel is not cleared and if `Some(value)` the channel is cleared to that value (the value must be between 0 and 1).
///
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct ClearState {
    /// Defines the clear value for the red channel.
    pub red: Option<f32>,
    /// Defines the clear value for the green channel.
    pub green: Option<f32>,
    /// Defines the clear value for the blue channel.
    pub blue: Option<f32>,
    /// Defines the clear value for the alpha channel.
    pub alpha: Option<f32>,
    /// Defines the clear value for the depth channel. A value of 1 means a depth value equal to the far plane and 0 means a depth value equal to the near plane.
    pub depth: Option<f32>,
}

impl ClearState {
    ///
    /// Nothing will be cleared.
    ///
    pub const fn none() -> Self {
        Self {
            red: None,
            green: None,
            blue: None,
            alpha: None,
            depth: None,
        }
    }

    ///
    /// The depth will be cleared to the given value.
    ///
    pub const fn depth(depth: f32) -> Self {
        Self {
            red: None,
            green: None,
            blue: None,
            alpha: None,
            depth: Some(depth),
        }
    }

    ///
    /// The color channels (red, green, blue and alpha) will be cleared to the given values.
    ///
    pub const fn color(red: f32, green: f32, blue: f32, alpha: f32) -> Self {
        Self {
            red: Some(red),
            green: Some(green),
            blue: Some(blue),
            alpha: Some(alpha),
            depth: None,
        }
    }

    ///
    /// Both the color channels (red, green, blue and alpha) and depth will be cleared to the given values.
    ///
    pub const fn color_and_depth(red: f32, green: f32, blue: f32, alpha: f32, depth: f32) -> Self {
        Self {
            red: Some(red),
            green: Some(green),
            blue: Some(blue),
            alpha: Some(alpha),
            depth: Some(depth),
        }
    }
}

impl Default for ClearState {
    fn default() -> Self {
        Self::color_and_depth(0.0, 0.0, 0.0, 1.0, 1.0)
    }
}

///
/// The destination of applying a copy.
///
pub enum CopyDestination<'a, 'b, 'c, 'd, T: TextureDataType> {
    /// Copies to the [Screen].
    Screen,
    /// Copies to a [Texture2D].
    ColorTexture(&'d mut Texture2D<T>),
    /// Copies to a [DepthTargetTexture2D].
    DepthTexture(&'d mut DepthTargetTexture2D),
    /// Copies to a [RenderTarget].
    RenderTarget(&'c RenderTarget<'a, 'b, T>),
}

pub(in crate::core) fn new_framebuffer(
    context: &Context,
) -> ThreeDResult<crate::context::Framebuffer> {
    Ok(context
        .create_framebuffer()
        .ok_or(CoreError::RenderTargetCreation)?)
}

#[cfg(feature = "debug")]
fn check(context: &Context) -> ThreeDResult<()> {
    context
        .check_framebuffer_status()
        .or_else(|status| Err(CoreError::RenderTargetCreation))
}

fn clear(context: &Context, clear_state: &ClearState) {
    Program::set_write_mask(
        context,
        WriteMask {
            red: clear_state.red.is_some(),
            green: clear_state.green.is_some(),
            blue: clear_state.blue.is_some(),
            alpha: clear_state.alpha.is_some(),
            depth: clear_state.depth.is_some(),
        },
    );
    let clear_color = clear_state.red.is_some()
        || clear_state.green.is_some()
        || clear_state.blue.is_some()
        || clear_state.alpha.is_some();
    if clear_color {
        context.clear_color(
            clear_state.red.unwrap_or(0.0),
            clear_state.green.unwrap_or(0.0),
            clear_state.blue.unwrap_or(0.0),
            clear_state.alpha.unwrap_or(1.0),
        );
    }
    if let Some(depth) = clear_state.depth {
        context.clear_depth(depth);
    }
    context.clear(if clear_color && clear_state.depth.is_some() {
        consts::COLOR_BUFFER_BIT | consts::DEPTH_BUFFER_BIT
    } else {
        if clear_color {
            consts::COLOR_BUFFER_BIT
        } else {
            consts::DEPTH_BUFFER_BIT
        }
    });
}

fn copy_from(
    context: &Context,
    color_texture: Option<&impl Texture>,
    depth_texture: Option<&impl Texture>,
    viewport: Viewport,
    write_mask: WriteMask,
) -> ThreeDResult<()> {
    if color_texture.is_some() || depth_texture.is_some() {
        let fragment_shader_source = if color_texture.is_some() && depth_texture.is_some() {
            "
            uniform sampler2D colorMap;
            uniform sampler2D depthMap;
            in vec2 uv;
            layout (location = 0) out vec4 color;
            void main()
            {
                color = texture(colorMap, uv);
                gl_FragDepth = texture(depthMap, uv).r;
            }"
        } else if color_texture.is_some() {
            "
            uniform sampler2D colorMap;
            in vec2 uv;
            layout (location = 0) out vec4 color;
            void main()
            {
                color = texture(colorMap, uv);
            }"
        } else {
            "
            uniform sampler2D depthMap;
            in vec2 uv;
            layout (location = 0) out vec4 color;
            void main()
            {
                gl_FragDepth = texture(depthMap, uv).r;
            }"
        };
        context.effect(fragment_shader_source, |effect| {
            if let Some(tex) = color_texture {
                effect.use_texture("colorMap", tex)?;
            }
            if let Some(tex) = depth_texture {
                effect.use_texture("depthMap", tex)?;
            }
            effect.apply(
                RenderStates {
                    depth_test: DepthTest::Always,
                    write_mask: WriteMask {
                        red: color_texture.is_some() && write_mask.red,
                        green: color_texture.is_some() && write_mask.green,
                        blue: color_texture.is_some() && write_mask.blue,
                        alpha: color_texture.is_some() && write_mask.alpha,
                        depth: depth_texture.is_some() && write_mask.depth,
                    },
                    ..Default::default()
                },
                viewport,
            )
        })
    } else {
        Ok(())
    }
}

fn copy_from_array(
    context: &Context,
    color_texture: Option<(&impl TextureArray, u32)>,
    depth_texture: Option<(&impl TextureArray, u32)>,
    viewport: Viewport,
    write_mask: WriteMask,
) -> ThreeDResult<()> {
    if color_texture.is_some() || depth_texture.is_some() {
        let fragment_shader_source = if color_texture.is_some() && depth_texture.is_some() {
            "
            uniform sampler2DArray colorMap;
            uniform sampler2DArray depthMap;
            uniform int colorLayer;
            uniform int depthLayer;
            in vec2 uv;
            layout (location = 0) out vec4 color;
            void main()
            {
                color = texture(colorMap, vec3(uv, colorLayer));
                gl_FragDepth = texture(depthMap, vec3(uv, depthLayer)).r;
            }"
        } else if color_texture.is_some() {
            "
            uniform sampler2DArray colorMap;
            uniform int colorLayer;
            in vec2 uv;
            layout (location = 0) out vec4 color;
            void main()
            {
                color = texture(colorMap, vec3(uv, colorLayer));
            }"
        } else {
            "
            uniform sampler2DArray depthMap;
            uniform int depthLayer;
            in vec2 uv;
            layout (location = 0) out vec4 color;
            void main()
            {
                gl_FragDepth = texture(depthMap, vec3(uv, depthLayer)).r;
            }"
        };
        context.effect(fragment_shader_source, |effect| {
            if let Some((tex, layer)) = color_texture {
                effect.use_texture_array("colorMap", tex)?;
                effect.use_uniform_int("colorLayer", &(layer as i32))?;
            }
            if let Some((tex, layer)) = depth_texture {
                effect.use_texture_array("depthMap", tex)?;
                effect.use_uniform_int("depthLayer", &(layer as i32))?;
            }
            effect.apply(
                RenderStates {
                    depth_test: DepthTest::Always,
                    write_mask: WriteMask {
                        red: color_texture.is_some() && write_mask.red,
                        green: color_texture.is_some() && write_mask.green,
                        blue: color_texture.is_some() && write_mask.blue,
                        alpha: color_texture.is_some() && write_mask.alpha,
                        depth: depth_texture.is_some() && write_mask.depth,
                    },
                    ..Default::default()
                },
                viewport,
            )
        })
    } else {
        Ok(())
    }
}