Skip to main content

three_rs/textures/
texture.rs

1//! Port of `three.js/src/textures/Texture.js` (the 2D path, rung-4 subset).
2//!
3//! One handle covers both roles the ladder needs: an image loaded from disk and
4//! the colour attachment of a `RenderTarget` (`RenderTarget.texture`). Three
5//! makes no distinction either — `renderTarget.texture` is a plain `Texture`
6//! whose image is filled in by the backend.
7
8use std::cell::{Ref, RefCell};
9use std::rc::Rc;
10
11use super::TextureId;
12use super::{Image, TextureFilter};
13use crate::math::ColorSpace;
14use crate::math::{Matrix3, Vector2};
15
16/// `three.js/src/constants.js` wrapping modes.
17#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
18pub enum Wrapping {
19    /// `ClampToEdgeWrapping` — the `Texture` default.
20    ClampToEdge,
21    /// `RepeatWrapping`.
22    Repeat,
23    /// `MirroredRepeatWrapping` — what `rtt()`'s options reach the sampler
24    /// with in `webgpu_postprocessing_anamorphic`, and the reason its
25    /// horizontal streak folds back instead of clamping at the screen edge.
26    MirroredRepeat,
27}
28
29/// `Texture.minFilter` — the mip-aware half of the filter pair.
30#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
31pub enum MinFilter {
32    /// `NearestFilter`.
33    Nearest,
34    /// `NearestMipmapNearestFilter`.
35    NearestMipmapNearest,
36    /// `NearestMipmapLinearFilter`.
37    NearestMipmapLinear,
38    /// `LinearFilter`.
39    Linear,
40    /// `LinearMipmapNearestFilter`.
41    LinearMipmapNearest,
42    /// `LinearMipmapLinearFilter`, the `Texture` default.
43    LinearMipmapLinear,
44}
45
46impl MinFilter {
47    /// `WebGPUTextureUtils._convertFilterMode()`: every `Nearest*` constant
48    /// is `'nearest'`, every `Linear*` one `'linear'`.
49    pub fn min(self) -> TextureFilter {
50        match self {
51            MinFilter::Nearest
52            | MinFilter::NearestMipmapNearest
53            | MinFilter::NearestMipmapLinear => TextureFilter::Nearest,
54            MinFilter::Linear | MinFilter::LinearMipmapNearest | MinFilter::LinearMipmapLinear => {
55                TextureFilter::Linear
56            }
57        }
58    }
59
60    /// `WebGPUTextureUtils` maps `*MipmapLinear` to `mipmapFilter: 'linear'`
61    /// and everything else to `'nearest'`.
62    pub fn mipmap(self) -> TextureFilter {
63        match self {
64            MinFilter::NearestMipmapLinear | MinFilter::LinearMipmapLinear => TextureFilter::Linear,
65            _ => TextureFilter::Nearest,
66        }
67    }
68}
69
70/// One entry of `Texture.mipmaps`: a level the file (or the page) supplies
71/// rather than one the renderer generates. The same shape as a cube face,
72/// and the same type: `data` is the level's bytes in the texture's GPU
73/// format, every array layer of the level one after the other
74/// (`KTX2Loader`'s `concat( layerMips )`); for a block-compressed format
75/// these are whole blocks, rows of blocks top-down.
76pub type Mipmap = Image;
77
78/// The state behind a [`Texture`] handle.
79pub struct TextureInner {
80    /// `texture.image.width`.
81    pub width: u32,
82    /// `texture.image.height`.
83    pub height: u32,
84    /// RGBA8 rows, top-down as decoded. `None` for a render-target texture.
85    pub data: Option<Vec<u8>>,
86    /// `texture.colorSpace`.
87    pub color_space: ColorSpace,
88    /// `texture.flipY`.
89    pub flip_y: bool,
90    /// `texture.generateMipmaps`.
91    pub generate_mipmaps: bool,
92    /// `Texture.mipmaps` — levels supplied by the page or the file, level 0
93    /// first. When there are any they are the whole mip chain:
94    /// `Textures.getMipLevels()` takes its count from them and nothing is
95    /// generated on top (`webgpu_materials_texture_manualmipmap` paints each
96    /// level a different colour; a `CompressedTexture` or a KTX2 `DataTexture`
97    /// brings its own, and a block-compressed format could not be rendered
98    /// into anyway). Each level is in the texture's format, top row first.
99    pub mipmaps: Vec<Image>,
100    /// `texture.wrapS`.
101    pub wrap_s: Wrapping,
102    /// `texture.wrapT`.
103    pub wrap_t: Wrapping,
104    /// `texture.magFilter`.
105    pub mag_filter: TextureFilter,
106    /// `texture.minFilter`.
107    pub min_filter: MinFilter,
108    /// `texture.anisotropy`.
109    pub anisotropy: u16,
110    /// `Texture.offset` / `.repeat` / `.center` / `.rotation` —
111    /// `updateMatrix()`'s inputs.
112    pub offset: Vector2,
113    /// `texture.repeat`.
114    pub repeat: Vector2,
115    /// `texture.center`.
116    pub center: Vector2,
117    /// `texture.rotation`.
118    pub rotation: f64,
119    /// `Texture.matrix`, kept in step with the four above — unless
120    /// [`Texture::set_matrix`] has overridden it.
121    pub matrix: Matrix3,
122    /// `Texture.channel` — which `uv` attribute `TextureNode.getDefaultUV()`
123    /// samples along: 0 is `uv`, 1 is `uv1`. `GLTFLoader` sets it from a
124    /// texture reference's `texCoord`.
125    pub channel: usize,
126    /// `false` for `renderTarget.texture` — the renderer owns the GPU texture.
127    pub(crate) own_gpu: bool,
128    pub(crate) gpu: Option<wgpu::Texture>,
129    /// The format to use if the renderer has to create it (render targets).
130    pub format: wgpu::TextureFormat,
131    /// `Texture.version` — "starts at 0 and counts how many times
132    /// `needsUpdate` is set to true". Part of the renderer's texture cache
133    /// key, exactly as `Material.version` is part of the program cache key.
134    pub version: u32,
135    /// `image.depth` of a `CompressedArrayTexture` — the layer count. Zero
136    /// for every 2-D texture, which is what marks this one as an array: it
137    /// is bound as `texture_2d_array<f32>` and sampled with a layer index.
138    pub depth: u32,
139    /// `Texture.premultiplyAlpha`. Only `KTX2Loader` sets it, from the DFD's
140    /// `KHR_DF_FLAG_ALPHA_PREMULTIPLIED`; it is recorded, not acted on — three's
141    /// WebGPU backend ignores it for compressed uploads as well.
142    pub premultiply_alpha: bool,
143    /// `texture.isStorageTexture` — a [`Texture::storage`]: created with
144    /// `STORAGE_BINDING`, never uploaded to, written by a compute kernel's
145    /// `textureStore()`.
146    pub is_storage: bool,
147}
148
149/// Cloning is a handle copy, as in JS.
150#[derive(Clone)]
151pub struct Texture(Rc<RefCell<TextureInner>>, TextureId);
152
153/// The id is identity, not content: leaving it out keeps the `Debug` of a
154/// binding description — what `examples/dump_wgsl.rs` prints beside the WGSL —
155/// a function of the texture itself.
156impl std::fmt::Debug for Texture {
157    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
158        f.debug_tuple("Texture").field(&self.0).finish()
159    }
160}
161
162impl Texture {
163    /// `texture.dispose()` — drops this handle, and nothing more: a texture
164    /// handle is an `Rc`, so the renderer frees the GPU side once every handle
165    /// is gone, at the top of the next render (`docs/scene-graph.md`,
166    /// "Identity and eviction"). Dropping the handle does the same; this
167    /// exists so three.js code ports line for line.
168    pub fn dispose(self) {}
169
170    /// `new Texture()` defaults: `ClampToEdgeWrapping`, `LinearFilter`,
171    /// `LinearMipmapLinearFilter`, `RGBAFormat`, `UnsignedByteType`,
172    /// `NoColorSpace`, `flipY = true`, `generateMipmaps = true`, anisotropy 1.
173    pub fn new(width: u32, height: u32, data: Option<Vec<u8>>) -> Self {
174        Self(
175            Rc::new(RefCell::new(TextureInner {
176                width,
177                height,
178                data,
179                color_space: ColorSpace::NoColorSpace,
180                flip_y: true,
181                generate_mipmaps: true,
182                mipmaps: Vec::new(),
183                wrap_s: Wrapping::ClampToEdge,
184                wrap_t: Wrapping::ClampToEdge,
185                mag_filter: TextureFilter::Linear,
186                min_filter: MinFilter::LinearMipmapLinear,
187                anisotropy: 1,
188                offset: Vector2::new(0.0, 0.0),
189                repeat: Vector2::new(1.0, 1.0),
190                center: Vector2::new(0.0, 0.0),
191                rotation: 0.0,
192                matrix: Matrix3::identity(),
193                channel: 0,
194                own_gpu: true,
195                gpu: None,
196                format: wgpu::TextureFormat::Rgba8Unorm,
197                version: 0,
198                depth: 0,
199                premultiply_alpha: false,
200                is_storage: false,
201            })),
202            TextureId::next(),
203        )
204    }
205
206    /// The texture behind a render target's colour attachment: no image data,
207    /// no mipmaps, `flipY` irrelevant, and `minFilter = LinearFilter` (which is
208    /// what `RenderTarget`'s options set).
209    pub fn render_target(width: u32, height: u32, format: wgpu::TextureFormat) -> Self {
210        let texture = Self::new(width, height, None);
211        {
212            let mut inner = texture.0.borrow_mut();
213            inner.generate_mipmaps = false;
214            inner.min_filter = MinFilter::Linear;
215            inner.own_gpu = false;
216            inner.format = format;
217        }
218        texture
219    }
220
221    /// `new StorageTexture( width, height )` (`renderers/common/StorageTexture.js`):
222    /// a `Texture` with no image, `LinearFilter` on both filters and
223    /// `isStorageTexture = true`. `generateMipmaps` keeps `Texture`'s `true`,
224    /// so the GPU texture has the full chain; three regenerates it after a
225    /// kernel has stored into level 0, before the next draw that samples it
226    /// (`Bindings._update()`'s `needsMipmap`), and so does the renderer here.
227    ///
228    /// `rgba8unorm` by default; `set_texture_type( TextureType::HalfFloat )`
229    /// makes it `rgba16float`, as `texture.type = HalfFloatType` does. Either
230    /// is a format WebGPU allows as a write-only storage texture on every
231    /// backend, which is what `webgpu_compute_texture*` bind it as.
232    pub fn storage(width: u32, height: u32) -> Self {
233        let texture = Self::new(width, height, None);
234        {
235            let mut inner = texture.0.borrow_mut();
236            inner.min_filter = MinFilter::Linear;
237            inner.is_storage = true;
238        }
239        texture
240    }
241
242    /// `texture.isStorageTexture`.
243    pub fn is_storage(&self) -> bool {
244        self.0.borrow().is_storage
245    }
246
247    /// `new ExternalTexture( sourceTexture )` — a `wgpu::Texture` the caller
248    /// created and goes on owning, wrapped so a material can sample it.
249    ///
250    /// This is how a host that already has GPU textures hands them to the
251    /// scene: a Wayland compositor imports a client's dmabuf as a
252    /// `wgpu::Texture` and wraps it here, and the renderer samples the client's
253    /// pixels with no copy and no upload. Pair it with
254    /// [`Renderer::with_device`](crate::renderer::Renderer::with_device), since
255    /// the texture only works on the device it was created on.
256    ///
257    /// Size and format are taken from the wgpu texture, so they cannot drift
258    /// from it. `own_gpu = false`: the renderer never re-creates, re-uploads or
259    /// destroys it, and never generates mipmaps into it — the handle is a
260    /// refcount, so the underlying texture lives as long as either side holds
261    /// one. Filters are `LinearFilter` on both, wrapping `ClampToEdge`, and
262    /// there is no mip chain to filter between.
263    ///
264    /// `color_space` must agree with the wgpu format's transfer function —
265    /// an `*Srgb` format is [`ColorSpace::Srgb`] and everything else is
266    /// [`ColorSpace::LinearSrgb`] or [`ColorSpace::NoColorSpace`] — because the GPU applies the transfer on
267    /// sample and a mismatch is a silently wrong-looking frame rather than an
268    /// error. It is asserted here.
269    pub fn external(gpu: wgpu::Texture, color_space: ColorSpace) -> Self {
270        assert_eq!(
271            gpu.dimension(),
272            wgpu::TextureDimension::D2,
273            "three-rs: an external Texture is a 2D texture"
274        );
275        assert_eq!(
276            gpu.depth_or_array_layers(),
277            1,
278            "three-rs: an external Texture is a single layer"
279        );
280        assert_eq!(
281            gpu.sample_count(),
282            1,
283            "three-rs: an external Texture is not multisampled"
284        );
285        assert!(
286            gpu.usage().contains(wgpu::TextureUsages::TEXTURE_BINDING),
287            "three-rs: an external Texture must be created with TEXTURE_BINDING"
288        );
289        let format = gpu.format();
290        assert_eq!(
291            format.is_srgb(),
292            color_space == ColorSpace::Srgb,
293            "three-rs: {format:?} and {color_space:?} disagree about the transfer function"
294        );
295
296        let texture = Self::new(gpu.width(), gpu.height(), None);
297        {
298            let mut inner = texture.0.borrow_mut();
299            inner.color_space = color_space;
300            inner.flip_y = false;
301            inner.generate_mipmaps = false;
302            inner.mag_filter = TextureFilter::Linear;
303            inner.min_filter = MinFilter::Linear;
304            inner.own_gpu = false;
305            inner.format = format;
306            inner.gpu = Some(gpu);
307        }
308        texture
309    }
310
311    /// `new DataTexture( new Float32Array( data ), width, height, RedFormat,
312    /// FloatType )` — the SDF atlas texture lib3's `VectorFontAtlas` hands to
313    /// `texture()`.
314    ///
315    /// `DataTexture`'s constructor differs from `Texture`'s in three places
316    /// (`DataTexture.js`): `flipY = false`, `generateMipmaps = false` and
317    /// `minFilter = magFilter = NearestFilter`; lib3 then sets both filters back
318    /// to `LinearFilter`, which is what this builds. The colour space stays
319    /// `NoColorSpace` — the field is distance, not colour, and tagging it sRGB
320    /// would put a transfer function on the SDF (plan §5.3).
321    pub fn data_r32float(width: u32, height: u32, data: &[f32]) -> Self {
322        assert_eq!(
323            data.len() as u32,
324            width * height,
325            "three-rs: a RedFormat DataTexture holds one float per texel"
326        );
327        let texture = Self::new(width, height, Some(bytemuck::cast_slice(data).to_vec()));
328        {
329            let mut inner = texture.0.borrow_mut();
330            inner.flip_y = false;
331            inner.generate_mipmaps = false;
332            inner.mag_filter = TextureFilter::Linear;
333            inner.min_filter = MinFilter::Linear;
334            inner.format = wgpu::TextureFormat::R32Float;
335        }
336        texture
337    }
338
339    /// `new DataTexture( new Uint16Array( data ), width, height, RedFormat,
340    /// HalfFloatType )` — one binary16 bit pattern per texel (`r16float`),
341    /// the format of `ImportanceSampledEnvironment`'s CDF tables.
342    ///
343    /// Keeps all of `DataTexture`'s defaults, as [`data_r8`](Self::data_r8)
344    /// does: `flipY = false`, `generateMipmaps = false` and `NearestFilter`
345    /// on both sides; set the filters afterwards for a filtered lookup.
346    pub fn data_r16float(width: u32, height: u32, data: &[u16]) -> Self {
347        assert_eq!(
348            data.len() as u32,
349            width * height,
350            "three-rs: a RedFormat HalfFloatType DataTexture holds one half per texel"
351        );
352        let texture = Self::new(width, height, Some(bytemuck::cast_slice(data).to_vec()));
353        {
354            let mut inner = texture.0.borrow_mut();
355            inner.flip_y = false;
356            inner.generate_mipmaps = false;
357            inner.mag_filter = TextureFilter::Nearest;
358            inner.min_filter = MinFilter::Nearest;
359            inner.format = wgpu::TextureFormat::R16Float;
360        }
361        texture
362    }
363
364    /// `new DataTexture( new Uint8Array( data ), width, height, RedFormat )` —
365    /// `webgpu_materials_toon`'s gradient maps, one byte per texel
366    /// (`r8unorm`).
367    ///
368    /// Unlike [`data_r32float`](Self::data_r32float) this keeps all of
369    /// `DataTexture`'s own defaults: `NearestFilter` on both sides, which makes
370    /// the map unfilterable (`is_unfilterable`), so
371    /// three binds it with no sampler and reads it with `textureLoad`. That is
372    /// what gives a toon ramp its hard steps.
373    pub fn data_r8(width: u32, height: u32, data: &[u8]) -> Self {
374        assert_eq!(
375            data.len() as u32,
376            width * height,
377            "three-rs: a RedFormat UnsignedByteType DataTexture holds one byte per texel"
378        );
379        let texture = Self::new(width, height, Some(data.to_vec()));
380        {
381            let mut inner = texture.0.borrow_mut();
382            inner.flip_y = false;
383            inner.generate_mipmaps = false;
384            inner.mag_filter = TextureFilter::Nearest;
385            inner.min_filter = MinFilter::Nearest;
386            inner.format = wgpu::TextureFormat::R8Unorm;
387        }
388        texture
389    }
390
391    /// `new DataTexture( new Uint8Array( data ), width, height )` — the
392    /// defaults, `RGBAFormat` + `UnsignedByteType` (`rgba8unorm`, or
393    /// `rgba8unorm-srgb` once the colour space is set to sRGB), with
394    /// `DataTexture`'s own `flipY = false`, `generateMipmaps = false` and
395    /// `NearestFilter` on both sides. `webgpu_textures_partialupdate`'s
396    /// source for `copyTextureToTexture`.
397    pub fn data_rgba8(width: u32, height: u32, data: Vec<u8>) -> Self {
398        assert_eq!(
399            data.len() as u32,
400            width * height * 4,
401            "three-rs: an RGBA UnsignedByteType DataTexture holds four bytes per texel"
402        );
403        let texture = Self::new(width, height, Some(data));
404        {
405            let mut inner = texture.0.borrow_mut();
406            inner.flip_y = false;
407            inner.generate_mipmaps = false;
408            inner.mag_filter = TextureFilter::Nearest;
409            inner.min_filter = MinFilter::Nearest;
410        }
411        texture
412    }
413
414    /// `new DataTexture( new Uint16Array( data ), width, height, RGBAFormat,
415    /// HalfFloatType )` — what `DataTextureLoader` builds from
416    /// [`HdrLoader::parse`](crate::loaders::HdrLoader::parse)'s half-float
417    /// result.
418    ///
419    /// `DataTexture`'s constructor differs from `Texture`'s in three places
420    /// (`DataTexture.js`): `flipY = false`, `generateMipmaps = false` and
421    /// `minFilter = magFilter = NearestFilter`. `HDRLoader`'s `texData` then
422    /// sets both filters back to `LinearFilter` and `flipY` to true, which
423    /// [`HdrLoader::load`](crate::loaders::HdrLoader::load) does; the cube
424    /// loader leaves `flipY` at the `DataTexture` default. The colour space
425    /// is `NoColorSpace` here, and the loaders then set
426    /// `LinearSRGBColorSpace`. Neither carries a transfer function, so
427    /// `rgba16float` is the right format and nothing is applied on sample.
428    ///
429    /// `data` is one binary16 bit pattern per channel, four per texel, which is
430    /// the `Uint16Array` upstream hands `write_texture` unchanged.
431    pub fn data_rgba16float(width: u32, height: u32, data: &[u16]) -> Self {
432        assert_eq!(
433            data.len() as u32,
434            width * height * 4,
435            "three-rs: an RGBA HalfFloatType DataTexture holds four halves per texel"
436        );
437        Self::data_float(
438            width,
439            height,
440            wgpu::TextureFormat::Rgba16Float,
441            bytemuck::cast_slice(data),
442        )
443    }
444
445    /// `new DataTexture( new Float32Array( data ), width, height, RGBAFormat,
446    /// FloatType )` — the `FloatType` half of the same loader.
447    pub fn data_rgba32float(width: u32, height: u32, data: &[f32]) -> Self {
448        assert_eq!(
449            data.len() as u32,
450            width * height * 4,
451            "three-rs: an RGBA FloatType DataTexture holds four floats per texel"
452        );
453        Self::data_float(
454            width,
455            height,
456            wgpu::TextureFormat::Rgba32Float,
457            bytemuck::cast_slice(data),
458        )
459    }
460
461    /// The `DataTexture` defaults both float constructors share.
462    fn data_float(width: u32, height: u32, format: wgpu::TextureFormat, bytes: &[u8]) -> Self {
463        let texture = Self::new(width, height, Some(bytes.to_vec()));
464        {
465            let mut inner = texture.0.borrow_mut();
466            inner.flip_y = false;
467            inner.generate_mipmaps = false;
468            inner.mag_filter = TextureFilter::Linear;
469            inner.min_filter = MinFilter::Linear;
470            inner.format = format;
471        }
472        texture
473    }
474
475    /// `texture.id` — unique per texture, stable for its lifetime.
476    pub fn id(&self) -> usize {
477        self.1.get()
478    }
479
480    /// How many handles share this texture — how the reflector registry
481    /// tells a reflector some graph still samples from one nothing does.
482    pub(crate) fn handle_count(&self) -> usize {
483        Rc::strong_count(&self.0)
484    }
485
486    /// The handle's liveness, without the handle; see [`TextureOwner`].
487    ///
488    /// [`TextureOwner`]: super::TextureOwner
489    pub(crate) fn owner(&self) -> super::TextureOwner {
490        Rc::downgrade(&self.0) as super::TextureOwner
491    }
492
493    /// `Texture.clone()` — `new Texture().copy( this )`: a second texture over
494    /// the same image, with its own id, its own uv transform and its own
495    /// `channel`. `Texture`'s `Clone` impl is JS' assignment (a handle copy);
496    /// this is JS' `.clone()`, and the two are deliberately different names.
497    ///
498    /// Three shares the `Source` between the original and the clone, so the
499    /// WebGPU backend uploads the image once. This port keys its GPU textures
500    /// on the `Texture` id, so a clone is uploaded again — same texels, one
501    /// more upload. Nothing on this ladder clones more than a handful.
502    pub fn clone_texture(&self) -> Self {
503        let inner = self.0.borrow();
504        Self(
505            Rc::new(RefCell::new(TextureInner {
506                width: inner.width,
507                height: inner.height,
508                data: inner.data.clone(),
509                color_space: inner.color_space,
510                flip_y: inner.flip_y,
511                generate_mipmaps: inner.generate_mipmaps,
512                // `Texture.copy()`: `this.mipmaps = source.mipmaps.slice( 0 )`.
513                mipmaps: inner.mipmaps.clone(),
514                wrap_s: inner.wrap_s,
515                wrap_t: inner.wrap_t,
516                mag_filter: inner.mag_filter,
517                min_filter: inner.min_filter,
518                anisotropy: inner.anisotropy,
519                offset: inner.offset,
520                repeat: inner.repeat,
521                center: inner.center,
522                rotation: inner.rotation,
523                matrix: inner.matrix,
524                channel: inner.channel,
525                own_gpu: inner.own_gpu,
526                gpu: None,
527                format: inner.format,
528                version: inner.version,
529                depth: inner.depth,
530                premultiply_alpha: inner.premultiply_alpha,
531                is_storage: inner.is_storage,
532            })),
533            TextureId::next(),
534        )
535    }
536
537    /// `Texture.channel`.
538    pub fn channel(&self) -> usize {
539        self.0.borrow().channel
540    }
541
542    /// `texture.channel = n`. Only 0 and 1 have an accessor
543    /// ([`uv`](crate::nodes::tsl::uv) and [`uv1`](crate::nodes::tsl::uv1)), so
544    /// anything else is refused here rather than silently sampled along `uv`.
545    pub fn set_channel(&self, channel: usize) {
546        assert!(
547            channel <= 1,
548            "three-rs: Texture.channel {channel} has no uv accessor (only uv and uv1 are ported)"
549        );
550        self.0.borrow_mut().channel = channel;
551    }
552
553    /// `texture.colorSpace = SRGBColorSpace`. As with `CubeTexture`, the
554    /// transfer function is applied by the GPU on sample — the format becomes
555    /// `rgba8unorm-srgb` and `WGSLNodeBuilder.needsToWorkingColorSpace()` stays
556    /// false, so no colour-space node appears in the generated WGSL.
557    ///
558    /// `WebGPUTextureUtils.getFormat()` picks the `-srgb` twin of whatever
559    /// the format is — `rgba8unorm-srgb`, `bc7-rgba-unorm-srgb`,
560    /// `astc-4x4-unorm-srgb` — and leaves a format that has none (the float
561    /// formats, BC4/BC5/BC6H) alone, which is what wgpu's
562    /// `add_srgb_suffix` / `remove_srgb_suffix` do.
563    pub fn set_color_space(&self, color_space: ColorSpace) {
564        let mut inner = self.0.borrow_mut();
565        inner.color_space = color_space;
566        inner.format = match color_space {
567            ColorSpace::Srgb => inner.format.add_srgb_suffix(),
568            ColorSpace::NoColorSpace | ColorSpace::LinearSrgb => inner.format.remove_srgb_suffix(),
569        };
570    }
571
572    /// `texture.colorSpace`.
573    pub fn color_space(&self) -> ColorSpace {
574        self.0.borrow().color_space
575    }
576
577    /// `texture.flipY` — an upload-time concern only. `Texture.updateMatrix()`
578    /// goes through `Matrix3.setUvTransform( offset, repeat, rotation, center )`,
579    /// which has no `flipY` term, so the texture matrix is unaffected.
580    pub fn set_flip_y(&self, flip_y: bool) {
581        self.0.borrow_mut().flip_y = flip_y;
582    }
583
584    /// `texture.generateMipmaps = value`.
585    pub fn set_generate_mipmaps(&self, generate_mipmaps: bool) {
586        self.0.borrow_mut().generate_mipmaps = generate_mipmaps;
587    }
588
589    /// `texture.mipmaps[ i ] = image` for every level at once. The levels
590    /// must halve from the texture's own size down, as WebGPU's mip chain
591    /// does; the upload writes each into its level and generates none.
592    pub fn set_mipmaps(&self, mipmaps: Vec<Image>) {
593        let mut inner = self.0.borrow_mut();
594        for (level, image) in mipmaps.iter().enumerate() {
595            let expected = (
596                (inner.width >> level).max(1),
597                (inner.height >> level).max(1),
598            );
599            assert_eq!(
600                (image.width, image.height),
601                expected,
602                "three-rs: mipmap level {level} has the wrong size"
603            );
604        }
605        inner.mipmaps = mipmaps;
606    }
607
608    /// Whether the page supplied its own mip levels ([`Self::set_mipmaps`]).
609    pub(crate) fn has_mipmaps(&self) -> bool {
610        !self.0.borrow().mipmaps.is_empty()
611    }
612
613    /// `texture.minFilter = value`.
614    pub fn set_min_filter(&self, min_filter: MinFilter) {
615        self.0.borrow_mut().min_filter = min_filter;
616    }
617
618    /// `texture.magFilter = value`.
619    pub fn set_mag_filter(&self, mag_filter: TextureFilter) {
620        self.0.borrow_mut().mag_filter = mag_filter;
621    }
622
623    /// `WGSLNodeBuilder.isUnfilterable( texture )`'s `minFilter ===
624    /// NearestFilter && magFilter === NearestFilter` clause — the one a plain
625    /// colour texture can hit.
626    ///
627    /// A texture that is read with no interpolation at all is bound with a
628    /// `non-filtering` sample type and no sampler beside it, and every tap on
629    /// it is a `textureLoad` against `textureDimensions` rather than a
630    /// `textureSample`. That is not an optimisation: it is what
631    /// `webgpu_mrt`'s `pass( scene, camera, { minFilter: NearestFilter,
632    /// magFilter: NearestFilter } )` buys, and the generated composite shader
633    /// looks different because of it.
634    ///
635    /// Three compares against `NearestFilter` exactly, so
636    /// `NearestMipmapNearest` and the rest stay filterable; `MinFilter::min()`
637    /// would collapse them, which is why this reads the variant.
638    pub(crate) fn is_unfilterable(&self) -> bool {
639        let inner = self.0.borrow();
640        inner.min_filter == MinFilter::Nearest && inner.mag_filter == TextureFilter::Nearest
641    }
642
643    /// Borrows the texture's full state.
644    pub fn borrow(&self) -> Ref<'_, TextureInner> {
645        self.0.borrow()
646    }
647
648    pub(crate) fn borrow_mut_inner(&self) -> std::cell::RefMut<'_, TextureInner> {
649        self.0.borrow_mut()
650    }
651
652    /// `( texture.wrapS, texture.wrapT )`.
653    pub fn wrapping(&self) -> (Wrapping, Wrapping) {
654        let inner = self.0.borrow();
655        (inner.wrap_s, inner.wrap_t)
656    }
657
658    /// `texture.wrapS = texture.wrapT = wrapping`.
659    pub fn set_wrapping(&self, wrap_s: Wrapping, wrap_t: Wrapping) {
660        let mut inner = self.0.borrow_mut();
661        inner.wrap_s = wrap_s;
662        inner.wrap_t = wrap_t;
663    }
664
665    /// `texture.anisotropy = n`.
666    pub fn set_anisotropy(&self, anisotropy: u16) {
667        self.0.borrow_mut().anisotropy = anisotropy;
668    }
669
670    /// `texture.repeat.set( x, y )` — and `updateMatrix()`, which three.js runs
671    /// for us every frame because `matrixAutoUpdate` is on by default.
672    pub fn set_repeat(&self, x: f64, y: f64) {
673        self.0.borrow_mut().repeat = Vector2::new(x, y);
674        self.update_matrix();
675    }
676
677    /// `texture.offset.set( x, y )`.
678    pub fn set_offset(&self, x: f64, y: f64) {
679        self.0.borrow_mut().offset = Vector2::new(x, y);
680        self.update_matrix();
681    }
682
683    /// `texture.center.set( x, y )`.
684    pub fn set_center(&self, x: f64, y: f64) {
685        self.0.borrow_mut().center = Vector2::new(x, y);
686        self.update_matrix();
687    }
688
689    /// `texture.rotation = theta`.
690    pub fn set_rotation(&self, rotation: f64) {
691        self.0.borrow_mut().rotation = rotation;
692        self.update_matrix();
693    }
694
695    /// `Texture.updateMatrix()`.
696    pub fn update_matrix(&self) {
697        let mut inner = self.0.borrow_mut();
698        let (offset, repeat, center, rotation) =
699            (inner.offset, inner.repeat, inner.center, inner.rotation);
700        inner.matrix.set_uv_transform(
701            offset.x, offset.y, repeat.x, repeat.y, rotation, center.x, center.y,
702        );
703    }
704
705    /// `texture.matrix.set( … )` with `texture.matrixAutoUpdate = false` — the
706    /// escape hatch `GLTFTextureTransformExtension` uses, because glTF composes
707    /// its uv transform as `T * R * S` and three.js as `T * S * R`. There is no
708    /// `matrixAutoUpdate` field here: the matrix is read once, when the texture
709    /// node is built, so an override simply has to be the last write.
710    pub fn set_matrix(&self, matrix: Matrix3) {
711        self.0.borrow_mut().matrix = matrix;
712    }
713
714    /// `Texture.matrix` — what `TextureNode.setupUV()` multiplies the UV by.
715    pub fn matrix(&self) -> Matrix3 {
716        self.0.borrow().matrix
717    }
718
719    /// `( texture.image.width, texture.image.height )`.
720    pub fn size(&self) -> (u32, u32) {
721        let inner = self.0.borrow();
722        (inner.width, inner.height)
723    }
724
725    /// `texture.image.width = width; texture.image.height = height`.
726    pub fn set_size(&self, width: u32, height: u32) {
727        let mut inner = self.0.borrow_mut();
728        inner.width = width;
729        inner.height = height;
730    }
731
732    /// The byte length one full mip-0 image of this texture takes: `width *
733    /// height * the format's texel size`, which is what [`set_data`] asserts
734    /// and what the renderer uploads.
735    ///
736    /// [`set_data`]: Self::set_data
737    pub fn data_len(&self) -> usize {
738        let inner = self.0.borrow();
739        let bytes_per_texel = inner
740            .format
741            .block_copy_size(None)
742            .expect("three-rs: the texture format has no single block size")
743            as usize;
744        inner.width as usize * inner.height as usize * bytes_per_texel
745    }
746
747    /// `texture.image.data.set( data ); texture.needsUpdate = true` — new
748    /// pixels for a texture that has already been uploaded, at the same size
749    /// and format.
750    ///
751    /// This is the per-frame path for a texture whose contents change but whose
752    /// allocation should not: a screencast frame, an shm client buffer, a video
753    /// texture. The renderer writes the bytes into the GPU texture it already
754    /// has (and regenerates the mip chain if `generate_mipmaps`) instead of
755    /// destroying and re-creating it, so the texture, its view and the bind
756    /// groups built from it survive.
757    ///
758    /// Unlike `Material::set_needs_update`, no separate call is needed: setting
759    /// the data *is* the change, so this bumps the version itself. Panics if
760    /// `data` is not exactly [`data_len`](Self::data_len) bytes — a short
761    /// buffer would otherwise shear or tear the image rather than fail.
762    ///
763    /// Calling it on a [`Texture::external`] or a render target's texture is a
764    /// mistake: the renderer does not own those and will not upload into them.
765    pub fn set_data(&self, data: Vec<u8>) {
766        let expected = self.data_len();
767        assert_eq!(
768            data.len(),
769            expected,
770            "three-rs: set_data got {} bytes for a {:?} texture that holds {expected}",
771            data.len(),
772            self.size(),
773        );
774        assert!(
775            self.0.borrow().own_gpu,
776            "three-rs: set_data on a texture the renderer does not own \
777             (an external texture, or a render target's) — write to the \
778             wgpu::Texture directly"
779        );
780        let mut inner = self.0.borrow_mut();
781        inner.data = Some(data);
782        inner.version += 1;
783    }
784
785    /// `texture.needsUpdate = true`: bump the version so the next frame
786    /// re-uploads the image into the GPU texture the renderer already has.
787    ///
788    /// [`set_data`](Self::set_data) does this for you; this is for forcing a
789    /// re-upload of bytes that were not replaced through it.
790    pub fn set_needs_update(&self) {
791        self.0.borrow_mut().version += 1;
792    }
793
794    /// `Texture.version` — how many times the image has been marked changed.
795    /// The renderer's texture cache is keyed on `( id, version )`.
796    pub fn version(&self) -> u32 {
797        self.0.borrow().version
798    }
799
800    pub(crate) fn set_gpu(&self, gpu: wgpu::Texture) {
801        self.0.borrow_mut().gpu = Some(gpu);
802    }
803
804    pub(crate) fn clear_gpu(&self) {
805        self.0.borrow_mut().gpu = None;
806    }
807
808    pub(crate) fn has_gpu(&self) -> bool {
809        self.0.borrow().gpu.is_some()
810    }
811
812    /// Exchange the GPU textures behind two handles, leaving both identities —
813    /// and everything keyed on them — where they are. This is the port's half
814    /// of `PassNode.toggleTexture()`; see
815    /// [`RenderTarget::toggle_texture`](crate::renderer::RenderTarget::toggle_texture)
816    /// for why the swap is on this end and not on the node's.
817    pub(crate) fn swap_gpu(&self, other: &Texture) {
818        if Rc::ptr_eq(&self.0, &other.0) {
819            return;
820        }
821        std::mem::swap(&mut self.0.borrow_mut().gpu, &mut other.0.borrow_mut().gpu);
822    }
823
824    /// Runs `f` with the uploaded GPU texture. Panics if the texture has not
825    /// been uploaded yet.
826    pub fn with_gpu<R>(&self, f: impl FnOnce(&wgpu::Texture) -> R) -> R {
827        let inner = self.0.borrow();
828        f(inner.gpu.as_ref().expect("three-rs: texture not uploaded"))
829    }
830
831    /// The GPU format this texture uploads as, or renders into.
832    pub fn format(&self) -> wgpu::TextureFormat {
833        self.0.borrow().format
834    }
835
836    /// Sets the GPU format to use if the renderer has to create the texture —
837    /// a render target's attachment.
838    pub fn set_format(&self, format: wgpu::TextureFormat) {
839        self.0.borrow_mut().format = format;
840    }
841
842    /// `texture.type = UnsignedByteType` — three.js names a render target
843    /// attachment's storage by its data type, and
844    /// `WebGPUTextureUtils.getFormat()` turns that into the GPU format. Set it
845    /// on an attachment of a `PassNode`'s target before the first frame, the
846    /// way `webgpu_postprocessing_bloom_emissive` sets it on the `emissive`
847    /// output so the bloom chain reads an LDR texture.
848    ///
849    /// Panics for a depth type, as `color_gpu_format()` does.
850    pub fn set_texture_type(&self, texture_type: crate::textures::TextureType) {
851        self.set_format(texture_type.color_gpu_format());
852    }
853
854    /// `Texture.mipmapCount` — `floor( log2( max( w, h ) ) ) + 1`, or the
855    /// length of `mipmaps` when the texture brings its own.
856    pub fn mip_level_count(&self) -> u32 {
857        let inner = self.0.borrow();
858        // `Textures.getMipLevels()`: `texture.mipmaps.length` when the page
859        // supplied levels, whatever `generateMipmaps` says.
860        if !inner.mipmaps.is_empty() {
861            return inner.mipmaps.len() as u32;
862        }
863        if !inner.generate_mipmaps {
864            return 1;
865        }
866        let max = inner.width.max(inner.height) as f64;
867        (max.log2().floor() as u32) + 1
868    }
869}
870
871/// The derived `Debug` printed every byte of `data` — megabytes for an SDF
872/// atlas, and the program cache key used to be a `format!( "{:?}" )` of a
873/// binding description that reaches here. The length stands in for the pixels.
874impl std::fmt::Debug for TextureInner {
875    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
876        f.debug_struct("TextureInner")
877            .field("width", &self.width)
878            .field("height", &self.height)
879            .field("data", &self.data.as_ref().map(|data| DataLen(data.len())))
880            .field("color_space", &self.color_space)
881            .field("flip_y", &self.flip_y)
882            .field("generate_mipmaps", &self.generate_mipmaps)
883            .field("mipmaps", &self.mipmaps.len())
884            .field("wrap_s", &self.wrap_s)
885            .field("wrap_t", &self.wrap_t)
886            .field("mag_filter", &self.mag_filter)
887            .field("min_filter", &self.min_filter)
888            .field("anisotropy", &self.anisotropy)
889            .field("offset", &self.offset)
890            .field("repeat", &self.repeat)
891            .field("center", &self.center)
892            .field("rotation", &self.rotation)
893            .field("matrix", &self.matrix)
894            .field("own_gpu", &self.own_gpu)
895            .field("gpu", &self.gpu)
896            .field("format", &self.format)
897            .field("depth", &self.depth)
898            .field("premultiply_alpha", &self.premultiply_alpha)
899            .field("is_storage", &self.is_storage)
900            .finish()
901    }
902}
903
904/// `data: 1048576 bytes` in place of a million numbers.
905pub(crate) struct DataLen(pub usize);
906
907impl std::fmt::Debug for DataLen {
908    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
909        write!(f, "{} bytes", self.0)
910    }
911}
912
913#[cfg(test)]
914mod tests {
915    use super::*;
916
917    fn rgba(width: u32, height: u32) -> Texture {
918        Texture::new(
919            width,
920            height,
921            Some(vec![0u8; (width * height * 4) as usize]),
922        )
923    }
924
925    /// `StorageTexture`'s constructor: no image, `LinearFilter` on both, and
926    /// `Texture`'s `generateMipmaps = true` kept — a 512² one has ten levels.
927    #[test]
928    fn a_storage_texture_keeps_its_mip_chain() {
929        let texture = Texture::storage(512, 512);
930        assert!(texture.is_storage());
931        assert!(texture.borrow().data.is_none());
932        assert_eq!(texture.borrow().min_filter, MinFilter::Linear);
933        assert_eq!(texture.borrow().mag_filter, TextureFilter::Linear);
934        assert_eq!(texture.mip_level_count(), 10);
935        assert!(!texture.is_unfilterable());
936    }
937
938    #[test]
939    fn a_new_texture_is_at_version_zero() {
940        assert_eq!(rgba(2, 2).version(), 0);
941    }
942
943    #[test]
944    fn set_data_replaces_the_image_and_bumps_the_version() {
945        let texture = rgba(2, 2);
946        texture.set_data(vec![7u8; 16]);
947
948        assert_eq!(texture.version(), 1);
949        assert_eq!(texture.borrow().data.as_deref(), Some(&[7u8; 16][..]));
950
951        texture.set_data(vec![9u8; 16]);
952        assert_eq!(texture.version(), 2);
953    }
954
955    #[test]
956    fn needs_update_bumps_the_version_on_its_own() {
957        let texture = rgba(2, 2);
958        texture.set_needs_update();
959        texture.set_needs_update();
960        assert_eq!(texture.version(), 2);
961    }
962
963    /// The byte length follows the format, not a hardcoded RGBA8: the SDF
964    /// atlas is `r32float`, one float per texel.
965    #[test]
966    fn data_len_follows_the_format() {
967        assert_eq!(rgba(3, 5).data_len(), 3 * 5 * 4);
968
969        let atlas = Texture::data_r32float(3, 5, &[0.0; 15]);
970        assert_eq!(atlas.data_len(), 3 * 5 * 4);
971    }
972
973    #[test]
974    #[should_panic(expected = "set_data got")]
975    fn set_data_rejects_the_wrong_byte_count() {
976        rgba(2, 2).set_data(vec![0u8; 15]);
977    }
978
979    /// An external texture's GPU handle is the caller's; the renderer must not
980    /// be able to overwrite it through the CPU path.
981    #[test]
982    #[should_panic(expected = "does not own")]
983    fn set_data_refuses_a_texture_the_renderer_does_not_own() {
984        let target = Texture::render_target(2, 2, wgpu::TextureFormat::Rgba8Unorm);
985        target.set_data(vec![0u8; 16]);
986    }
987}