-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtexture.rs
More file actions
1207 lines (1082 loc) · 35.4 KB
/
texture.rs
File metadata and controls
1207 lines (1082 loc) · 35.4 KB
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
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Texture and sampler enums and mappings for the platform layer.
//!
//! This module defines stable enums for texture formats, dimensions, view
//! dimensions, filtering, and addressing. It provides explicit mappings to the
//! underlying `wgpu` types and basic helpers such as bytes‑per‑pixel.
use wgpu;
use crate::wgpu::gpu::Gpu;
/// Wrapper for texture usage flags.
///
/// This abstraction hides `wgpu::TextureUsages` from higher layers while
/// preserving bitwise-OR composition for combining flags.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct TextureUsages(wgpu::TextureUsages);
impl TextureUsages {
/// Render attachment usage.
pub const RENDER_ATTACHMENT: TextureUsages =
TextureUsages(wgpu::TextureUsages::RENDER_ATTACHMENT);
/// Texture binding usage.
pub const TEXTURE_BINDING: TextureUsages =
TextureUsages(wgpu::TextureUsages::TEXTURE_BINDING);
/// Copy destination usage.
pub const COPY_DST: TextureUsages =
TextureUsages(wgpu::TextureUsages::COPY_DST);
/// Copy source usage.
pub const COPY_SRC: TextureUsages =
TextureUsages(wgpu::TextureUsages::COPY_SRC);
/// Create an empty flags set.
pub const fn empty() -> Self {
return TextureUsages(wgpu::TextureUsages::empty());
}
pub(crate) fn to_wgpu(self) -> wgpu::TextureUsages {
return self.0;
}
pub(crate) fn from_wgpu(flags: wgpu::TextureUsages) -> Self {
return TextureUsages(flags);
}
/// Check whether this flags set contains another set.
pub fn contains(self, other: TextureUsages) -> bool {
return self.0.contains(other.0);
}
}
impl std::ops::BitOr for TextureUsages {
type Output = TextureUsages;
fn bitor(self, rhs: TextureUsages) -> TextureUsages {
return TextureUsages(self.0 | rhs.0);
}
}
impl std::ops::BitOrAssign for TextureUsages {
fn bitor_assign(&mut self, rhs: TextureUsages) {
self.0 |= rhs.0;
}
}
#[derive(Debug)]
/// Errors returned when building a texture or preparing its initial upload.
pub enum TextureBuildError {
/// Width or height is zero or exceeds device limits.
InvalidDimensions { width: u32, height: u32 },
/// Provided data length does not match expected tightly packed size.
DataLengthMismatch { expected: usize, actual: usize },
/// Internal arithmetic overflow while computing sizes or paddings.
Overflow,
/// The texture format does not support bytes_per_pixel calculation.
UnsupportedFormat,
}
/// Align `value` up to the next multiple of `alignment`.
///
/// `alignment` must be a power of two. This is used to compute
/// `bytes_per_row` for `Queue::write_texture` (256‑byte requirement).
fn align_up(value: u32, alignment: u32) -> u32 {
let mask = alignment - 1;
return (value + mask) & !mask;
}
/// Filter function used for sampling.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum FilterMode {
Nearest,
Linear,
}
impl FilterMode {
pub(crate) fn to_wgpu(self) -> wgpu::FilterMode {
return match self {
FilterMode::Nearest => wgpu::FilterMode::Nearest,
FilterMode::Linear => wgpu::FilterMode::Linear,
};
}
pub(crate) fn to_wgpu_mipmap(self) -> wgpu::MipmapFilterMode {
return match self {
FilterMode::Nearest => wgpu::MipmapFilterMode::Nearest,
FilterMode::Linear => wgpu::MipmapFilterMode::Linear,
};
}
}
/// Texture addressing mode when sampling outside the [0,1] range.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum AddressMode {
ClampToEdge,
Repeat,
MirrorRepeat,
}
impl AddressMode {
pub(crate) fn to_wgpu(self) -> wgpu::AddressMode {
return match self {
AddressMode::ClampToEdge => wgpu::AddressMode::ClampToEdge,
AddressMode::Repeat => wgpu::AddressMode::Repeat,
AddressMode::MirrorRepeat => wgpu::AddressMode::MirrorRepeat,
};
}
}
/// Unified texture format wrapper.
///
/// This abstraction wraps `wgpu::TextureFormat` to hide the underlying graphics
/// API from higher layers. Common formats are exposed as associated constants.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub struct TextureFormat(wgpu::TextureFormat);
impl TextureFormat {
// -------------------------------------------------------------------------
// Common color formats
// -------------------------------------------------------------------------
/// 8-bit RGBA, linear (non-sRGB).
pub const RGBA8_UNORM: TextureFormat =
TextureFormat(wgpu::TextureFormat::Rgba8Unorm);
/// 8-bit RGBA, sRGB encoded.
pub const RGBA8_UNORM_SRGB: TextureFormat =
TextureFormat(wgpu::TextureFormat::Rgba8UnormSrgb);
/// 8-bit BGRA, linear (non-sRGB). Common swapchain format.
pub const BGRA8_UNORM: TextureFormat =
TextureFormat(wgpu::TextureFormat::Bgra8Unorm);
/// 8-bit BGRA, sRGB encoded. Common swapchain format.
pub const BGRA8_UNORM_SRGB: TextureFormat =
TextureFormat(wgpu::TextureFormat::Bgra8UnormSrgb);
// -------------------------------------------------------------------------
// Depth/stencil formats
// -------------------------------------------------------------------------
/// 32-bit floating point depth.
pub const DEPTH32_FLOAT: TextureFormat =
TextureFormat(wgpu::TextureFormat::Depth32Float);
/// 24-bit depth (platform may choose precision).
pub const DEPTH24_PLUS: TextureFormat =
TextureFormat(wgpu::TextureFormat::Depth24Plus);
/// 24-bit depth + 8-bit stencil.
pub const DEPTH24_PLUS_STENCIL8: TextureFormat =
TextureFormat(wgpu::TextureFormat::Depth24PlusStencil8);
// -------------------------------------------------------------------------
// Conversions
// -------------------------------------------------------------------------
pub(crate) fn to_wgpu(self) -> wgpu::TextureFormat {
return self.0;
}
pub(crate) fn from_wgpu(fmt: wgpu::TextureFormat) -> Self {
return TextureFormat(fmt);
}
// -------------------------------------------------------------------------
// Format queries
// -------------------------------------------------------------------------
/// Whether this format is sRGB encoded.
pub fn is_srgb(self) -> bool {
return self.0.is_srgb();
}
/// Return the sRGB variant of the format when applicable.
pub fn add_srgb_suffix(self) -> Self {
return TextureFormat(self.0.add_srgb_suffix());
}
/// Number of bytes per pixel for common formats.
///
/// Returns `None` for compressed or exotic formats where a simple
/// bytes-per-pixel value is not applicable.
pub fn bytes_per_pixel(self) -> Option<u32> {
return match self.0 {
wgpu::TextureFormat::Rgba8Unorm
| wgpu::TextureFormat::Rgba8UnormSrgb
| wgpu::TextureFormat::Bgra8Unorm
| wgpu::TextureFormat::Bgra8UnormSrgb => Some(4),
wgpu::TextureFormat::Depth32Float => Some(4),
wgpu::TextureFormat::Depth24Plus => Some(4),
wgpu::TextureFormat::Depth24PlusStencil8 => Some(4),
_ => None,
};
}
}
/// Depth/stencil texture formats supported for render attachments.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum DepthFormat {
Depth32Float,
Depth24Plus,
Depth24PlusStencil8,
}
impl DepthFormat {
pub(crate) fn to_wgpu(self) -> wgpu::TextureFormat {
return match self {
DepthFormat::Depth32Float => wgpu::TextureFormat::Depth32Float,
DepthFormat::Depth24Plus => wgpu::TextureFormat::Depth24Plus,
DepthFormat::Depth24PlusStencil8 => {
wgpu::TextureFormat::Depth24PlusStencil8
}
};
}
}
#[derive(Debug)]
/// Wrapper for a depth (and optional stencil) texture used as a render attachment.
pub struct DepthTexture {
pub(crate) raw: wgpu::Texture,
pub(crate) view: wgpu::TextureView,
pub(crate) label: Option<String>,
pub(crate) format: DepthFormat,
}
impl DepthTexture {
/// Borrow the underlying `wgpu::Texture`.
pub fn raw(&self) -> &wgpu::Texture {
return &self.raw;
}
/// Borrow the full‑range `wgpu::TextureView` for depth attachment.
pub fn view(&self) -> &wgpu::TextureView {
return &self.view;
}
/// The depth format used by this attachment.
pub fn format(&self) -> DepthFormat {
return self.format;
}
/// Optional debug label used during creation.
pub fn label(&self) -> Option<&str> {
return self.label.as_deref();
}
/// Convenience: return a `TextureViewRef` for use in render pass attachments.
pub fn view_ref(&self) -> crate::wgpu::surface::TextureViewRef<'_> {
return crate::wgpu::surface::TextureViewRef { raw: &self.view };
}
}
#[derive(Debug)]
/// Wrapper for a multi-sampled color render target with an attachment view.
pub struct ColorAttachmentTexture {
pub(crate) raw: wgpu::Texture,
pub(crate) view: wgpu::TextureView,
pub(crate) label: Option<String>,
}
impl ColorAttachmentTexture {
/// Borrow the underlying `wgpu::Texture`.
pub fn raw(&self) -> &wgpu::Texture {
return &self.raw;
}
/// Borrow the full-range `wgpu::TextureView` suitable as a color attachment.
pub fn view(&self) -> &wgpu::TextureView {
return &self.view;
}
/// Optional debug label used during creation.
pub fn label(&self) -> Option<&str> {
return self.label.as_deref();
}
/// Convenience: return a `TextureViewRef` for use in render pass attachments.
pub fn view_ref(&self) -> crate::wgpu::surface::TextureViewRef<'_> {
return crate::wgpu::surface::TextureViewRef { raw: &self.view };
}
}
/// Builder for a color render attachment texture (commonly used for MSAA).
pub struct ColorAttachmentTextureBuilder {
label: Option<String>,
width: u32,
height: u32,
format: TextureFormat,
sample_count: u32,
}
impl ColorAttachmentTextureBuilder {
/// Create a builder with zero size and sample count 1.
pub fn new(format: TextureFormat) -> Self {
return Self {
label: None,
width: 0,
height: 0,
format,
sample_count: 1,
};
}
/// Set the 2D attachment size in pixels.
pub fn with_size(mut self, width: u32, height: u32) -> Self {
self.width = width;
self.height = height;
return self;
}
/// Configure multisampling. Count MUST be >= 1.
pub fn with_sample_count(mut self, count: u32) -> Self {
self.sample_count = count.max(1);
return self;
}
/// Attach a debug label for the created texture.
pub fn with_label(mut self, label: &str) -> Self {
self.label = Some(label.to_string());
return self;
}
/// Create the color attachment texture on the device.
pub fn build(self, gpu: &Gpu) -> ColorAttachmentTexture {
let size = wgpu::Extent3d {
width: self.width.max(1),
height: self.height.max(1),
depth_or_array_layers: 1,
};
let format = self.format.to_wgpu();
let raw = gpu.device().create_texture(&wgpu::TextureDescriptor {
label: self.label.as_deref(),
size,
mip_level_count: 1,
sample_count: self.sample_count,
dimension: wgpu::TextureDimension::D2,
format,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
view_formats: &[],
});
let view = raw.create_view(&wgpu::TextureViewDescriptor {
label: None,
format: Some(format),
dimension: Some(wgpu::TextureViewDimension::D2),
aspect: wgpu::TextureAspect::All,
base_mip_level: 0,
mip_level_count: None,
base_array_layer: 0,
array_layer_count: None,
usage: Some(wgpu::TextureUsages::RENDER_ATTACHMENT),
});
return ColorAttachmentTexture {
raw,
view,
label: self.label,
};
}
}
/// Builder for a depth texture attachment sized to the current framebuffer.
pub struct DepthTextureBuilder {
label: Option<String>,
width: u32,
height: u32,
format: DepthFormat,
sample_count: u32,
}
impl Default for DepthTextureBuilder {
fn default() -> Self {
return Self::new();
}
}
impl DepthTextureBuilder {
/// Create a builder with no size and `Depth32Float` format.
pub fn new() -> Self {
return Self {
label: None,
width: 0,
height: 0,
format: DepthFormat::Depth32Float,
sample_count: 1,
};
}
/// Set the 2D attachment size in pixels.
pub fn with_size(mut self, width: u32, height: u32) -> Self {
self.width = width;
self.height = height;
return self;
}
/// Choose a depth format.
pub fn with_format(mut self, format: DepthFormat) -> Self {
self.format = format;
return self;
}
/// Configure multi‑sampling.
pub fn with_sample_count(mut self, count: u32) -> Self {
self.sample_count = count.max(1);
return self;
}
/// Attach a debug label for the created texture.
pub fn with_label(mut self, label: &str) -> Self {
self.label = Some(label.to_string());
return self;
}
/// Create the depth texture on the device.
pub fn build(self, gpu: &Gpu) -> DepthTexture {
let size = wgpu::Extent3d {
width: self.width.max(1),
height: self.height.max(1),
depth_or_array_layers: 1,
};
let format = self.format.to_wgpu();
let raw = gpu.device().create_texture(&wgpu::TextureDescriptor {
label: self.label.as_deref(),
size,
mip_level_count: 1,
sample_count: self.sample_count,
dimension: wgpu::TextureDimension::D2,
format,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
view_formats: &[],
});
let view = raw.create_view(&wgpu::TextureViewDescriptor {
label: None,
format: Some(format),
dimension: Some(wgpu::TextureViewDimension::D2),
aspect: match self.format {
DepthFormat::Depth24PlusStencil8 => wgpu::TextureAspect::All,
_ => wgpu::TextureAspect::DepthOnly,
},
base_mip_level: 0,
mip_level_count: None,
base_array_layer: 0,
array_layer_count: None,
usage: Some(wgpu::TextureUsages::RENDER_ATTACHMENT),
});
return DepthTexture {
raw,
view,
label: self.label,
format: self.format,
};
}
}
/// Physical storage dimension of a texture.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum TextureDimension {
TwoDimensional,
ThreeDimensional,
}
impl TextureDimension {
pub(crate) fn to_wgpu(self) -> wgpu::TextureDimension {
return match self {
TextureDimension::TwoDimensional => wgpu::TextureDimension::D2,
TextureDimension::ThreeDimensional => wgpu::TextureDimension::D3,
};
}
}
/// View dimensionality exposed to shaders when sampling.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum ViewDimension {
TwoDimensional,
ThreeDimensional,
}
impl ViewDimension {
pub(crate) fn to_wgpu(self) -> wgpu::TextureViewDimension {
return match self {
ViewDimension::TwoDimensional => wgpu::TextureViewDimension::D2,
ViewDimension::ThreeDimensional => wgpu::TextureViewDimension::D3,
};
}
}
#[derive(Debug)]
/// Wrapper around `wgpu::Sampler` that preserves a label.
pub struct Sampler {
pub(crate) raw: wgpu::Sampler,
pub(crate) label: Option<String>,
}
impl Sampler {
/// Borrow the underlying `wgpu::Sampler`.
pub fn raw(&self) -> &wgpu::Sampler {
return &self.raw;
}
/// Optional debug label used during creation.
pub fn label(&self) -> Option<&str> {
return self.label.as_deref();
}
}
/// Builder for creating a sampler.
pub struct SamplerBuilder {
label: Option<String>,
min_filter: FilterMode,
mag_filter: FilterMode,
mipmap_filter: FilterMode,
address_u: AddressMode,
address_v: AddressMode,
address_w: AddressMode,
lod_min: f32,
lod_max: f32,
anisotropy_clamp: u16,
}
impl Default for SamplerBuilder {
fn default() -> Self {
return Self::new();
}
}
impl SamplerBuilder {
/// Create a new builder with nearest filtering and clamp addressing.
pub fn new() -> Self {
return Self {
label: None,
min_filter: FilterMode::Nearest,
mag_filter: FilterMode::Nearest,
mipmap_filter: FilterMode::Nearest,
address_u: AddressMode::ClampToEdge,
address_v: AddressMode::ClampToEdge,
address_w: AddressMode::ClampToEdge,
lod_min: 0.0,
lod_max: 32.0,
anisotropy_clamp: 1,
};
}
/// Set both min and mag filter to nearest.
pub fn nearest(mut self) -> Self {
self.min_filter = FilterMode::Nearest;
self.mag_filter = FilterMode::Nearest;
return self;
}
/// Set both min and mag filter to linear.
pub fn linear(mut self) -> Self {
self.min_filter = FilterMode::Linear;
self.mag_filter = FilterMode::Linear;
return self;
}
/// Convenience: nearest filtering with clamp-to-edge addressing.
pub fn nearest_clamp(mut self) -> Self {
self = self.nearest();
self.address_u = AddressMode::ClampToEdge;
self.address_v = AddressMode::ClampToEdge;
self.address_w = AddressMode::ClampToEdge;
return self;
}
/// Convenience: linear filtering with clamp-to-edge addressing.
pub fn linear_clamp(mut self) -> Self {
self = self.linear();
self.address_u = AddressMode::ClampToEdge;
self.address_v = AddressMode::ClampToEdge;
self.address_w = AddressMode::ClampToEdge;
return self;
}
/// Set address mode for U (x) coordinate.
pub fn with_address_mode_u(mut self, mode: AddressMode) -> Self {
self.address_u = mode;
return self;
}
/// Set address mode for V (y) coordinate.
pub fn with_address_mode_v(mut self, mode: AddressMode) -> Self {
self.address_v = mode;
return self;
}
/// Set address mode for W (z) coordinate.
pub fn with_address_mode_w(mut self, mode: AddressMode) -> Self {
self.address_w = mode;
return self;
}
/// Set mipmap filtering mode.
pub fn with_mip_filter(mut self, mode: FilterMode) -> Self {
self.mipmap_filter = mode;
return self;
}
/// Set minimum and maximum level-of-detail clamps.
pub fn with_lod(mut self, min: f32, max: f32) -> Self {
self.lod_min = min;
self.lod_max = max;
return self;
}
/// Attach a debug label.
pub fn with_label(mut self, label: &str) -> Self {
self.label = Some(label.to_string());
return self;
}
/// Set the maximum anisotropic filtering level.
///
/// Valid values are `1` (disabled) through `16`. Values outside this range
/// are clamped. Higher values improve texture quality at oblique viewing
/// angles but increase GPU cost.
///
/// Common values:
/// - `1`: Disabled (default)
/// - `4`: Good balance of quality and performance
/// - `8`: High quality
/// - `16`: Maximum quality
///
/// Note: Anisotropic filtering is most effective with linear filtering and
/// mipmapped textures. wgpu also requires all filter modes to be linear when
/// anisotropy is enabled; otherwise anisotropy is disabled.
///
/// ```no_run
/// # use lambda_platform::wgpu::texture::{FilterMode, SamplerBuilder};
/// # fn demo(gpu: &lambda_platform::wgpu::gpu::Gpu) {
/// // High-quality sampler for floor/wall textures viewed at angles
/// let aniso_sampler = SamplerBuilder::new()
/// .linear_clamp()
/// .with_mip_filter(FilterMode::Linear)
/// .with_anisotropy_clamp(8)
/// .build(gpu);
///
/// // Default sampler (no anisotropy) for UI textures
/// let ui_sampler = SamplerBuilder::new().linear_clamp().build(gpu);
/// # let _ = (aniso_sampler, ui_sampler);
/// # }
/// ```
pub fn with_anisotropy_clamp(mut self, clamp: u16) -> Self {
self.anisotropy_clamp = clamp.clamp(1, 16);
return self;
}
fn to_descriptor(
&self,
max_supported_anisotropy: u16,
) -> wgpu::SamplerDescriptor<'_> {
let max_supported_anisotropy = max_supported_anisotropy.clamp(1, 16);
let mut anisotropy_clamp =
self.anisotropy_clamp.min(max_supported_anisotropy);
if anisotropy_clamp > 1
&& !matches!(
(self.min_filter, self.mag_filter, self.mipmap_filter),
(FilterMode::Linear, FilterMode::Linear, FilterMode::Linear)
)
{
logging::warn!(
"Sampler anisotropy requested ({}), but all filters must be \
linear; anisotropy disabled.",
anisotropy_clamp
);
anisotropy_clamp = 1;
}
return wgpu::SamplerDescriptor {
label: self.label.as_deref(),
address_mode_u: self.address_u.to_wgpu(),
address_mode_v: self.address_v.to_wgpu(),
address_mode_w: self.address_w.to_wgpu(),
mag_filter: self.mag_filter.to_wgpu(),
min_filter: self.min_filter.to_wgpu(),
mipmap_filter: self.mipmap_filter.to_wgpu_mipmap(),
lod_min_clamp: self.lod_min,
lod_max_clamp: self.lod_max,
anisotropy_clamp,
..Default::default()
};
}
/// Create the sampler on the provided device.
pub fn build(self, gpu: &Gpu) -> Sampler {
let requested_anisotropy = self.anisotropy_clamp.clamp(1, 16);
let downlevel = gpu.adapter().get_downlevel_capabilities();
let supports_anisotropy = downlevel
.flags
.contains(wgpu::DownlevelFlags::ANISOTROPIC_FILTERING);
if requested_anisotropy > 1 && !supports_anisotropy {
logging::warn!(
"Sampler anisotropy requested ({}), but adapter does not report \
anisotropic filtering support; anisotropy disabled.",
requested_anisotropy
);
}
let max_supported_anisotropy = if supports_anisotropy { 16 } else { 1 };
let desc = self.to_descriptor(max_supported_anisotropy);
let raw = gpu.device().create_sampler(&desc);
return Sampler {
raw,
label: self.label,
};
}
}
#[derive(Debug)]
/// Wrapper around `wgpu::Texture` and its default `TextureView`.
///
/// The view covers the full resource with a view dimension that matches the
/// texture (D2/D3). The view usage mirrors the texture usage to satisfy wgpu
/// validation rules.
pub struct Texture {
pub(crate) raw: wgpu::Texture,
pub(crate) view: wgpu::TextureView,
pub(crate) label: Option<String>,
}
impl Texture {
/// Borrow the underlying `wgpu::Texture`.
pub fn raw(&self) -> &wgpu::Texture {
return &self.raw;
}
/// Borrow the default full‑range `wgpu::TextureView`.
pub fn view(&self) -> &wgpu::TextureView {
return &self.view;
}
/// Convenience: return a `TextureViewRef` for use in render pass attachments.
pub fn view_ref(&self) -> crate::wgpu::surface::TextureViewRef<'_> {
return crate::wgpu::surface::TextureViewRef { raw: &self.view };
}
/// Optional debug label used during creation.
pub fn label(&self) -> Option<&str> {
return self.label.as_deref();
}
}
/// Builder for creating a sampled texture with optional initial data upload.
///
/// - 2D path: call `new_2d()` then `with_size(w, h)`.
/// - 3D path: call `new_3d()` then `with_size_3d(w, h, d)`.
///
/// The `with_data` payload is expected to be tightly packed (no row or image
/// padding). Row padding and `rows_per_image` are computed internally.
pub struct TextureBuilder {
/// Optional debug label propagated to the created texture.
label: Option<String>,
/// Color format for the texture (filterable formats only).
format: TextureFormat,
/// Physical storage dimension (D2/D3).
dimension: TextureDimension,
/// Width in texels.
width: u32,
/// Height in texels.
height: u32,
/// Depth in texels (1 for 2D).
depth: u32,
/// Combined usage flags for the texture.
usage: TextureUsages,
/// Optional tightly‑packed pixel payload for level 0 (rows are `width*bpp`).
data: Option<Vec<u8>>,
}
impl TextureBuilder {
/// Construct a new 2D texture builder for a color format.
///
/// Default usage is `TEXTURE_BINDING | COPY_DST` for sampling with initial
/// data upload.
pub fn new_2d(format: TextureFormat) -> Self {
return Self {
label: None,
format,
dimension: TextureDimension::TwoDimensional,
width: 0,
height: 0,
depth: 1,
usage: TextureUsages::TEXTURE_BINDING | TextureUsages::COPY_DST,
data: None,
};
}
/// Construct a new 3D texture builder for a color format.
///
/// Default usage is `TEXTURE_BINDING | COPY_DST` for sampling with initial
/// data upload.
pub fn new_3d(format: TextureFormat) -> Self {
return Self {
label: None,
format,
dimension: TextureDimension::ThreeDimensional,
width: 0,
height: 0,
depth: 0,
usage: TextureUsages::TEXTURE_BINDING | TextureUsages::COPY_DST,
data: None,
};
}
/// Set the 2D texture size in pixels.
pub fn with_size(mut self, width: u32, height: u32) -> Self {
self.width = width;
self.height = height;
self.depth = 1;
return self;
}
/// Set the 3D texture size in voxels.
pub fn with_size_3d(mut self, width: u32, height: u32, depth: u32) -> Self {
self.width = width;
self.height = height;
self.depth = depth;
return self;
}
/// Provide tightly packed pixel data for level 0 upload.
pub fn with_data(mut self, pixels: &[u8]) -> Self {
self.data = Some(pixels.to_vec());
return self;
}
/// Set the texture usage flags.
///
/// Use bitwise-OR to combine flags:
/// ```ignore
/// .with_usage(TextureUsages::TEXTURE_BINDING | TextureUsages::COPY_DST)
/// ```
pub fn with_usage(mut self, usage: TextureUsages) -> Self {
self.usage = usage;
return self;
}
/// Attach a debug label.
pub fn with_label(mut self, label: &str) -> Self {
self.label = Some(label.to_string());
return self;
}
/// Create the GPU texture and upload initial data if provided.
pub fn build(self, gpu: &Gpu) -> Result<Texture, TextureBuildError> {
// Validate dimensions
if self.width == 0 || self.height == 0 {
return Err(TextureBuildError::InvalidDimensions {
width: self.width,
height: self.height,
});
}
if let TextureDimension::ThreeDimensional = self.dimension {
if self.depth == 0 {
return Err(TextureBuildError::InvalidDimensions {
width: self.width,
height: self.height,
});
}
}
let size = wgpu::Extent3d {
width: self.width,
height: self.height,
depth_or_array_layers: match self.dimension {
TextureDimension::TwoDimensional => 1,
TextureDimension::ThreeDimensional => self.depth,
},
};
// Validate data length if provided
if let Some(ref pixels) = self.data {
let bpp = self
.format
.bytes_per_pixel()
.ok_or(TextureBuildError::UnsupportedFormat)? as usize;
let wh = (self.width as usize)
.checked_mul(self.height as usize)
.ok_or(TextureBuildError::Overflow)?;
let expected = match self.dimension {
TextureDimension::TwoDimensional => {
wh.checked_mul(bpp).ok_or(TextureBuildError::Overflow)?
}
TextureDimension::ThreeDimensional => wh
.checked_mul(self.depth as usize)
.and_then(|n| n.checked_mul(bpp))
.ok_or(TextureBuildError::Overflow)?,
};
if pixels.len() != expected {
return Err(TextureBuildError::DataLengthMismatch {
expected,
actual: pixels.len(),
});
}
}
// Resolve usage flags
let usage = self.usage.to_wgpu();
let descriptor = wgpu::TextureDescriptor {
label: self.label.as_deref(),
size,
mip_level_count: 1,
sample_count: 1,
dimension: self.dimension.to_wgpu(),
format: self.format.to_wgpu(),
usage,
view_formats: &[],
};
let texture = gpu.device().create_texture(&descriptor);
let view_dimension = match self.dimension {
TextureDimension::TwoDimensional => wgpu::TextureViewDimension::D2,
TextureDimension::ThreeDimensional => wgpu::TextureViewDimension::D3,
};
let view = texture.create_view(&wgpu::TextureViewDescriptor {
label: None,
format: None,
dimension: Some(view_dimension),
aspect: wgpu::TextureAspect::All,
base_mip_level: 0,
mip_level_count: None,
base_array_layer: 0,
array_layer_count: None,
usage: Some(usage),
});
if let Some(pixels) = self.data.as_ref() {
// Compute 256-byte aligned bytes_per_row and pad rows if necessary.
let bpp = self
.format
.bytes_per_pixel()
.ok_or(TextureBuildError::UnsupportedFormat)?;
let row_bytes = self
.width
.checked_mul(bpp)
.ok_or(TextureBuildError::Overflow)?;
let padded_row_bytes = align_up(row_bytes, 256);
// Prepare a staging buffer with zeroed padding between rows (and images).
let images = match self.dimension {
TextureDimension::TwoDimensional => 1,
TextureDimension::ThreeDimensional => self.depth,
} as u64;
let total_bytes = (padded_row_bytes as u64)
.checked_mul(self.height as u64)
.and_then(|n| n.checked_mul(images))
.ok_or(TextureBuildError::Overflow)? as usize;
let mut staging = vec![0u8; total_bytes];
let src_row_stride = row_bytes as usize;
let dst_row_stride = padded_row_bytes as usize;
match self.dimension {
TextureDimension::TwoDimensional => {
for row in 0..(self.height as usize) {
let src_off = row
.checked_mul(src_row_stride)
.ok_or(TextureBuildError::Overflow)?;
let dst_off = row
.checked_mul(dst_row_stride)
.ok_or(TextureBuildError::Overflow)?;
staging[dst_off..(dst_off + src_row_stride)]
.copy_from_slice(&pixels[src_off..(src_off + src_row_stride)]);
}
}
TextureDimension::ThreeDimensional => {
let slice_stride = (self.height as usize)
.checked_mul(src_row_stride)
.ok_or(TextureBuildError::Overflow)?;
let dst_image_stride = (self.height as usize)
.checked_mul(dst_row_stride)
.ok_or(TextureBuildError::Overflow)?;
for z in 0..(self.depth as usize) {
for y in 0..(self.height as usize) {
let z_base_src = z
.checked_mul(slice_stride)
.ok_or(TextureBuildError::Overflow)?;
let y_off_src = y
.checked_mul(src_row_stride)
.ok_or(TextureBuildError::Overflow)?;
let src_off = z_base_src
.checked_add(y_off_src)
.ok_or(TextureBuildError::Overflow)?;
let z_base_dst = z
.checked_mul(dst_image_stride)
.ok_or(TextureBuildError::Overflow)?;
let y_off_dst = y