three_d/core/texture/
depth_texture2d.rs

1use crate::core::texture::*;
2
3///
4/// A 2D depth texture that can be rendered into and read from. See also [RenderTarget] and [DepthTarget].
5///
6pub struct DepthTexture2D {
7    context: Context,
8    id: crate::context::Texture,
9    width: u32,
10    height: u32,
11}
12
13impl DepthTexture2D {
14    ///
15    /// Constructs a new 2D depth texture.
16    ///
17    pub fn new<T: DepthTextureDataType>(
18        context: &Context,
19        width: u32,
20        height: u32,
21        wrap_s: Wrapping,
22        wrap_t: Wrapping,
23    ) -> Self {
24        let id = generate(context);
25        let texture = Self {
26            context: context.clone(),
27            id,
28            width,
29            height,
30        };
31        texture.bind();
32        set_parameters(
33            context,
34            crate::context::TEXTURE_2D,
35            Interpolation::Nearest,
36            Interpolation::Nearest,
37            None,
38            wrap_s,
39            wrap_t,
40            None,
41        );
42        unsafe {
43            context.tex_storage_2d(
44                crate::context::TEXTURE_2D,
45                1,
46                T::internal_format(),
47                width as i32,
48                height as i32,
49            );
50        }
51        texture
52    }
53
54    ///
55    /// Returns a [DepthTarget] which can be used to clear, write to and read from this texture.
56    /// Combine this together with a [ColorTarget] with [RenderTarget::new] to be able to write to both a depth and color target at the same time.
57    ///
58    pub fn as_depth_target(&mut self) -> DepthTarget<'_> {
59        DepthTarget::new_texture2d(&self.context, self)
60    }
61
62    /// The width of this texture.
63    pub fn width(&self) -> u32 {
64        self.width
65    }
66
67    /// The height of this texture.
68    pub fn height(&self) -> u32 {
69        self.height
70    }
71
72    pub(in crate::core) fn bind_as_depth_target(&self) {
73        unsafe {
74            self.context.framebuffer_texture_2d(
75                crate::context::FRAMEBUFFER,
76                crate::context::DEPTH_ATTACHMENT,
77                crate::context::TEXTURE_2D,
78                Some(self.id),
79                0,
80            );
81        }
82    }
83
84    pub(in crate::core) fn bind(&self) {
85        unsafe {
86            self.context
87                .bind_texture(crate::context::TEXTURE_2D, Some(self.id));
88        }
89    }
90}
91
92impl Drop for DepthTexture2D {
93    fn drop(&mut self) {
94        unsafe {
95            self.context.delete_texture(self.id);
96        }
97    }
98}