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