three_rs/textures/depth_texture.rs
1//! Port of `three.js/src/textures/DepthTexture.js` (rung 1 subset).
2//!
3//! The handle is an `Rc` so that the JS pattern in the example — one
4//! `DepthTexture` referenced both by the render target and by the quad
5//! material's colour node — maps across directly.
6
7use super::TextureId;
8use crate::error::Error;
9use std::cell::RefCell;
10use std::rc::Rc;
11
12/// `three.js/src/constants.js` texture types, as far as the port needs them.
13#[derive(Clone, Copy, Debug, PartialEq, Eq)]
14#[non_exhaustive]
15pub enum TextureType {
16 /// `UnsignedByteType`.
17 UnsignedByte,
18 /// `HalfFloatType`.
19 HalfFloat,
20 /// `UnsignedIntType`.
21 UnsignedInt,
22 /// `FloatType`.
23 Float,
24}
25
26impl TextureType {
27 /// Whether this type can back a render target's colour attachment.
28 pub(crate) fn is_color(self) -> bool {
29 matches!(self, TextureType::UnsignedByte | TextureType::HalfFloat)
30 }
31
32 /// Whether this type can back a depth attachment.
33 pub(crate) fn is_depth(self) -> bool {
34 matches!(self, TextureType::UnsignedInt | TextureType::Float)
35 }
36
37 /// `WebGPUTextureUtils.getFormat()` for a colour texture with
38 /// `RGBAFormat` and `NoColorSpace`.
39 ///
40 /// `pub(crate)`: the type is checked where the caller supplies it
41 /// (`RenderTarget::new_with_options`), which is what turns the mismatch
42 /// into an [`Error`] rather than the panic below.
43 pub(crate) fn color_gpu_format(self) -> wgpu::TextureFormat {
44 match self {
45 TextureType::UnsignedByte => wgpu::TextureFormat::Rgba8Unorm,
46 TextureType::HalfFloat => wgpu::TextureFormat::Rgba16Float,
47 other => panic!(
48 "three-rs: the render target's texture type is a colour type \
49 (RenderTarget::new_with_options checks it), got {other:?}"
50 ),
51 }
52 }
53}
54
55/// `three.js/src/constants.js` texture filters.
56#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
57pub enum TextureFilter {
58 /// `NearestFilter`.
59 Nearest,
60 /// `LinearFilter`.
61 Linear,
62}
63
64/// The state behind a [`DepthTexture`] handle.
65#[derive(Debug)]
66pub struct DepthTextureInner {
67 /// `texture.type` — `UnsignedIntType` or `FloatType`.
68 pub texture_type: TextureType,
69 /// `texture.magFilter`.
70 pub mag_filter: TextureFilter,
71 /// `texture.minFilter`.
72 pub min_filter: TextureFilter,
73 /// `texture.image.width`.
74 pub width: u32,
75 /// `texture.image.height`.
76 pub height: u32,
77 /// The GPU texture, created by the renderer when the owning render target
78 /// is first used.
79 pub(crate) gpu: Option<wgpu::Texture>,
80 /// `texture.isMultisampleRenderTargetTexture` — set when the owning render
81 /// target's `samples` is raised above 1, which is what makes the node
82 /// builder declare the binding `texture_depth_multisampled_2d` and the
83 /// bind-group layout entry `multisampled: true`.
84 pub multisample: bool,
85 /// Whether the GPU texture is also a copy source and destination — see
86 /// `DepthTexture::set_copyable`.
87 pub copyable: bool,
88}
89
90/// three.js' `DepthTexture`.
91#[derive(Clone)]
92pub struct DepthTexture(Rc<RefCell<DepthTextureInner>>, TextureId);
93
94/// The id is identity, not content: leaving it out keeps the `Debug` of a
95/// binding description — what `examples/dump_wgsl.rs` prints beside the WGSL —
96/// a function of the texture itself.
97impl std::fmt::Debug for DepthTexture {
98 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
99 f.debug_tuple("DepthTexture").field(&self.0).finish()
100 }
101}
102
103impl Default for DepthTexture {
104 fn default() -> Self {
105 Self::new()
106 }
107}
108
109impl DepthTexture {
110 /// `depthTexture.dispose()` — drops this handle, and nothing more: a texture
111 /// handle is an `Rc`, so the renderer frees the GPU side once every handle
112 /// is gone, at the top of the next render (`docs/scene-graph.md`,
113 /// "Identity and eviction"). Dropping the handle does the same; this
114 /// exists so three.js code ports line for line.
115 pub fn dispose(self) {}
116
117 /// `new DepthTexture()`: `UnsignedIntType`, `NearestFilter`, no size yet.
118 pub fn new() -> Self {
119 Self(
120 Rc::new(RefCell::new(DepthTextureInner {
121 texture_type: TextureType::UnsignedInt,
122 mag_filter: TextureFilter::Nearest,
123 min_filter: TextureFilter::Nearest,
124 width: 0,
125 height: 0,
126 gpu: None,
127 multisample: false,
128 copyable: false,
129 })),
130 TextureId::next(),
131 )
132 }
133
134 /// `depthTexture.minFilter = depthTexture.magFilter = LinearFilter` —
135 /// what `ShadowNode.setupRenderTarget()` sets for PCF, so that the
136 /// comparison sampler gives four bilinear-weighted comparisons per tap.
137 pub fn set_filters(&self, min_filter: TextureFilter, mag_filter: TextureFilter) {
138 let mut inner = self.0.borrow_mut();
139 inner.min_filter = min_filter;
140 inner.mag_filter = mag_filter;
141 }
142
143 /// `texture.isMultisampleRenderTargetTexture`, which
144 /// `RenderTarget::set_samples` keeps in step with the target's sample
145 /// count. A multisampled depth attachment is never resolved — the fog
146 /// composite reads sample 0 of it directly.
147 pub fn set_multisample(&self, multisample: bool) {
148 let mut inner = self.0.borrow_mut();
149 if inner.multisample != multisample {
150 inner.multisample = multisample;
151 inner.gpu = None;
152 }
153 }
154
155 /// Let this depth texture be copied from and into
156 /// (`COPY_SRC | COPY_DST`): `TRAANode` copies the scene pass's depth into
157 /// its history's every frame. Off by default, so the usage of every other
158 /// depth attachment is what it was. Drops the GPU texture if it was
159 /// created without the flags.
160 pub(crate) fn set_copyable(&self) {
161 let mut inner = self.0.borrow_mut();
162 if !inner.copyable {
163 inner.copyable = true;
164 inner.gpu = None;
165 }
166 }
167
168 /// Whether this depth texture is a multisampled render-target attachment.
169 pub fn is_multisample(&self) -> bool {
170 self.0.borrow().multisample
171 }
172
173 /// `depthTexture.type = type`. Errors rather than deferring the failure to
174 /// the pass that would have used the texture: only `UnsignedIntType` and
175 /// `FloatType` have a depth format.
176 pub fn set_type(&self, texture_type: TextureType) -> Result<(), Error> {
177 if !texture_type.is_depth() {
178 return Err(Error::UnsupportedTextureType {
179 what: "depth",
180 texture_type,
181 });
182 }
183
184 self.0.borrow_mut().texture_type = texture_type;
185
186 Ok(())
187 }
188
189 /// `texture.type`.
190 pub fn texture_type(&self) -> TextureType {
191 self.0.borrow().texture_type
192 }
193
194 /// `WebGPUTextureUtils.getFormat()` for `DepthFormat`.
195 ///
196 /// `pub(crate)`: [`Self::set_type`] is the only way in and it rejects a
197 /// non-depth type, so the panic below is an invariant.
198 pub(crate) fn gpu_format(&self) -> wgpu::TextureFormat {
199 match self.texture_type() {
200 TextureType::UnsignedInt => wgpu::TextureFormat::Depth24Plus,
201 TextureType::Float => wgpu::TextureFormat::Depth32Float,
202 other => panic!(
203 "three-rs: the depth texture's type is a depth type \
204 (DepthTexture::set_type checks it), got {other:?}"
205 ),
206 }
207 }
208
209 /// `texture.id` — unique per texture, stable for its lifetime.
210 pub fn id(&self) -> usize {
211 self.1.get()
212 }
213
214 /// The handle's liveness, without the handle; see [`TextureOwner`].
215 ///
216 /// [`TextureOwner`]: super::TextureOwner
217 pub(crate) fn owner(&self) -> super::TextureOwner {
218 Rc::downgrade(&self.0) as super::TextureOwner
219 }
220
221 pub(crate) fn inner(&self) -> &RefCell<DepthTextureInner> {
222 &self.0
223 }
224}