-
-
Notifications
You must be signed in to change notification settings - Fork 4.5k
Expand file tree
/
Copy pathimage.rs
More file actions
2590 lines (2429 loc) · 101 KB
/
image.rs
File metadata and controls
2590 lines (2429 loc) · 101 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
use crate::ImageLoader;
#[cfg(feature = "basis-universal")]
use super::basis::*;
#[cfg(feature = "dds")]
use super::dds::*;
#[cfg(feature = "ktx2")]
use super::ktx2::*;
use bevy_app::{App, Plugin};
#[cfg(not(feature = "bevy_reflect"))]
use bevy_reflect::TypePath;
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::{std_traits::ReflectDefault, Reflect};
use bevy_asset::{uuid_handle, Asset, AssetApp, Assets, Handle, RenderAssetUsages};
use bevy_color::{Color, ColorToComponents, Gray, LinearRgba, Srgba, Xyza};
use bevy_ecs::resource::Resource;
use bevy_math::{AspectRatio, UVec2, UVec3, Vec2};
use core::hash::Hash;
use serde::{Deserialize, Serialize};
use thiserror::Error;
use wgpu_types::{
AddressMode, CompareFunction, Extent3d, Features, FilterMode, MipmapFilterMode,
SamplerBorderColor, SamplerDescriptor, TextureDataOrder, TextureDescriptor, TextureDimension,
TextureFormat, TextureUsages, TextureViewDescriptor,
};
/// Trait used to provide default values for Bevy-external types that
/// do not implement [`Default`].
#[deprecated(
note = "Use ExtractedView::texture_format where possible. Bevy does not encourage a default TextureFormat anymore. If you really need this, use TextureFormat::Rgba8UnormSrgb"
)]
pub trait BevyDefault {
/// Returns the default value for a type.
fn bevy_default() -> Self;
}
#[expect(deprecated, reason = "deprecated")]
impl BevyDefault for TextureFormat {
fn bevy_default() -> Self {
TextureFormat::Rgba8UnormSrgb
}
}
/// Trait used to provide texture's srgb formats with static lifetime for `TextureDescriptor.view_formats`.
pub trait TextureSrgbViewFormats {
/// Returns the srgb view formats for a type.
fn srgb_view_formats(&self) -> &'static [TextureFormat];
}
impl TextureSrgbViewFormats for TextureFormat {
/// Returns the srgb formats if the format has an srgb variant, otherwise returns an empty slice.
///
/// Covers all the possible results of [`TextureFormat::add_srgb_suffix`](wgpu_types::TextureFormat::add_srgb_suffix).
fn srgb_view_formats(&self) -> &'static [TextureFormat] {
match self {
TextureFormat::Rgba8Unorm => &[TextureFormat::Rgba8UnormSrgb],
TextureFormat::Bgra8Unorm => &[TextureFormat::Bgra8UnormSrgb],
TextureFormat::Bc1RgbaUnorm => &[TextureFormat::Bc1RgbaUnormSrgb],
TextureFormat::Bc2RgbaUnorm => &[TextureFormat::Bc2RgbaUnormSrgb],
TextureFormat::Bc3RgbaUnorm => &[TextureFormat::Bc3RgbaUnormSrgb],
TextureFormat::Bc7RgbaUnorm => &[TextureFormat::Bc7RgbaUnormSrgb],
TextureFormat::Etc2Rgb8Unorm => &[TextureFormat::Etc2Rgb8UnormSrgb],
TextureFormat::Etc2Rgb8A1Unorm => &[TextureFormat::Etc2Rgb8A1UnormSrgb],
TextureFormat::Etc2Rgba8Unorm => &[TextureFormat::Etc2Rgba8UnormSrgb],
TextureFormat::Astc {
block: wgpu_types::AstcBlock::B4x4,
channel: wgpu_types::AstcChannel::Unorm,
} => &[TextureFormat::Astc {
block: wgpu_types::AstcBlock::B4x4,
channel: wgpu_types::AstcChannel::UnormSrgb,
}],
TextureFormat::Astc {
block: wgpu_types::AstcBlock::B5x4,
channel: wgpu_types::AstcChannel::Unorm,
} => &[TextureFormat::Astc {
block: wgpu_types::AstcBlock::B5x4,
channel: wgpu_types::AstcChannel::UnormSrgb,
}],
TextureFormat::Astc {
block: wgpu_types::AstcBlock::B5x5,
channel: wgpu_types::AstcChannel::Unorm,
} => &[TextureFormat::Astc {
block: wgpu_types::AstcBlock::B5x5,
channel: wgpu_types::AstcChannel::UnormSrgb,
}],
TextureFormat::Astc {
block: wgpu_types::AstcBlock::B6x5,
channel: wgpu_types::AstcChannel::Unorm,
} => &[TextureFormat::Astc {
block: wgpu_types::AstcBlock::B6x5,
channel: wgpu_types::AstcChannel::UnormSrgb,
}],
TextureFormat::Astc {
block: wgpu_types::AstcBlock::B6x6,
channel: wgpu_types::AstcChannel::Unorm,
} => &[TextureFormat::Astc {
block: wgpu_types::AstcBlock::B6x6,
channel: wgpu_types::AstcChannel::UnormSrgb,
}],
TextureFormat::Astc {
block: wgpu_types::AstcBlock::B8x5,
channel: wgpu_types::AstcChannel::Unorm,
} => &[TextureFormat::Astc {
block: wgpu_types::AstcBlock::B8x5,
channel: wgpu_types::AstcChannel::UnormSrgb,
}],
TextureFormat::Astc {
block: wgpu_types::AstcBlock::B8x6,
channel: wgpu_types::AstcChannel::Unorm,
} => &[TextureFormat::Astc {
block: wgpu_types::AstcBlock::B8x6,
channel: wgpu_types::AstcChannel::UnormSrgb,
}],
TextureFormat::Astc {
block: wgpu_types::AstcBlock::B8x8,
channel: wgpu_types::AstcChannel::Unorm,
} => &[TextureFormat::Astc {
block: wgpu_types::AstcBlock::B8x8,
channel: wgpu_types::AstcChannel::UnormSrgb,
}],
TextureFormat::Astc {
block: wgpu_types::AstcBlock::B10x5,
channel: wgpu_types::AstcChannel::Unorm,
} => &[TextureFormat::Astc {
block: wgpu_types::AstcBlock::B10x5,
channel: wgpu_types::AstcChannel::UnormSrgb,
}],
TextureFormat::Astc {
block: wgpu_types::AstcBlock::B10x6,
channel: wgpu_types::AstcChannel::Unorm,
} => &[TextureFormat::Astc {
block: wgpu_types::AstcBlock::B10x6,
channel: wgpu_types::AstcChannel::UnormSrgb,
}],
TextureFormat::Astc {
block: wgpu_types::AstcBlock::B10x8,
channel: wgpu_types::AstcChannel::Unorm,
} => &[TextureFormat::Astc {
block: wgpu_types::AstcBlock::B10x8,
channel: wgpu_types::AstcChannel::UnormSrgb,
}],
TextureFormat::Astc {
block: wgpu_types::AstcBlock::B10x10,
channel: wgpu_types::AstcChannel::Unorm,
} => &[TextureFormat::Astc {
block: wgpu_types::AstcBlock::B10x10,
channel: wgpu_types::AstcChannel::UnormSrgb,
}],
TextureFormat::Astc {
block: wgpu_types::AstcBlock::B12x10,
channel: wgpu_types::AstcChannel::Unorm,
} => &[TextureFormat::Astc {
block: wgpu_types::AstcBlock::B12x10,
channel: wgpu_types::AstcChannel::UnormSrgb,
}],
TextureFormat::Astc {
block: wgpu_types::AstcBlock::B12x12,
channel: wgpu_types::AstcChannel::Unorm,
} => &[TextureFormat::Astc {
block: wgpu_types::AstcBlock::B12x12,
channel: wgpu_types::AstcChannel::UnormSrgb,
}],
_ => &[],
}
}
}
/// A handle to a 1 x 1 transparent white image.
///
/// Like [`Handle<Image>::default`], this is a handle to a fallback image asset.
/// While that handle points to an opaque white 1 x 1 image, this handle points to a transparent 1 x 1 white image.
// Number randomly selected by fair WolframAlpha query. Totally arbitrary.
pub const TRANSPARENT_IMAGE_HANDLE: Handle<Image> =
uuid_handle!("d18ad97e-a322-4981-9505-44c59a4b5e46");
/// Adds the [`Image`] as an asset and makes sure that they are extracted and prepared for the GPU.
pub struct ImagePlugin {
/// The default image sampler to use when [`ImageSampler`] is set to `Default`.
pub default_sampler: ImageSamplerDescriptor,
}
impl Default for ImagePlugin {
fn default() -> Self {
ImagePlugin::default_linear()
}
}
impl ImagePlugin {
/// Creates image settings with linear sampling by default.
pub fn default_linear() -> ImagePlugin {
ImagePlugin {
default_sampler: ImageSamplerDescriptor::linear(),
}
}
/// Creates image settings with nearest sampling by default.
pub fn default_nearest() -> ImagePlugin {
ImagePlugin {
default_sampler: ImageSamplerDescriptor::nearest(),
}
}
}
impl Plugin for ImagePlugin {
fn build(&self, app: &mut App) {
#[cfg(feature = "exr")]
app.init_asset_loader::<crate::ExrTextureLoader>();
#[cfg(feature = "hdr")]
app.init_asset_loader::<crate::HdrTextureLoader>();
app.init_asset::<Image>();
#[cfg(feature = "bevy_reflect")]
app.register_asset_reflect::<Image>();
let mut image_assets = app.world_mut().resource_mut::<Assets<Image>>();
image_assets
.insert(&Handle::default(), Image::default())
.unwrap();
image_assets
.insert(&TRANSPARENT_IMAGE_HANDLE, Image::transparent())
.unwrap();
#[cfg(feature = "compressed_image_saver")]
if let Some(processor) = app
.world()
.get_resource::<bevy_asset::processor::AssetProcessor>()
{
processor.register_processor::<bevy_asset::processor::LoadTransformAndSave<
ImageLoader,
bevy_asset::transformer::IdentityAssetTransformer<Image>,
crate::CompressedImageSaver,
>>(crate::CompressedImageSaver.into());
processor.set_default_processor::<bevy_asset::processor::LoadTransformAndSave<
ImageLoader,
bevy_asset::transformer::IdentityAssetTransformer<Image>,
crate::CompressedImageSaver,
>>("png");
}
app.preregister_asset_loader::<ImageLoader>(ImageLoader::SUPPORTED_FILE_EXTENSIONS);
}
}
/// The format of an on-disk image asset.
#[derive(Debug, Serialize, Deserialize, Copy, Clone)]
pub enum ImageFormat {
/// An image in basis universal format.
#[cfg(feature = "basis-universal")]
Basis,
/// An image in BMP format.
#[cfg(feature = "bmp")]
Bmp,
/// An image in DDS format.
#[cfg(feature = "dds")]
Dds,
/// An image in Farbfeld format.
#[cfg(feature = "ff")]
Farbfeld,
/// An image in GIF format.
#[cfg(feature = "gif")]
Gif,
/// An image in Open EXR format.
#[cfg(feature = "exr")]
OpenExr,
/// An image in Radiance HDR format.
#[cfg(feature = "hdr")]
Hdr,
/// An image in ICO format.
#[cfg(feature = "ico")]
Ico,
/// An image in JPEG format.
#[cfg(feature = "jpeg")]
Jpeg,
/// An image in Khronos KTX2 format.
#[cfg(feature = "ktx2")]
Ktx2,
/// An image in PNG format.
#[cfg(feature = "png")]
Png,
/// An image in general PNM format
#[cfg(feature = "pnm")]
Pnm,
/// An image in QOI format.
#[cfg(feature = "qoi")]
Qoi,
/// An image in TGA format.
#[cfg(feature = "tga")]
Tga,
/// An image in TIFF format.
#[cfg(feature = "tiff")]
Tiff,
/// An image in WEBP format.
#[cfg(feature = "webp")]
WebP,
}
macro_rules! feature_gate {
($feature: tt, $value: ident) => {{
#[cfg(not(feature = $feature))]
{
tracing::warn!("feature \"{}\" is not enabled", $feature);
return None;
}
#[cfg(feature = $feature)]
ImageFormat::$value
}};
}
impl ImageFormat {
/// Gets the file extensions for a given format.
pub const fn to_file_extensions(&self) -> &'static [&'static str] {
match self {
#[cfg(feature = "basis-universal")]
ImageFormat::Basis => &["basis"],
#[cfg(feature = "bmp")]
ImageFormat::Bmp => &["bmp"],
#[cfg(feature = "dds")]
ImageFormat::Dds => &["dds"],
#[cfg(feature = "ff")]
ImageFormat::Farbfeld => &["ff", "farbfeld"],
#[cfg(feature = "gif")]
ImageFormat::Gif => &["gif"],
#[cfg(feature = "exr")]
ImageFormat::OpenExr => &["exr"],
#[cfg(feature = "hdr")]
ImageFormat::Hdr => &["hdr"],
#[cfg(feature = "ico")]
ImageFormat::Ico => &["ico"],
#[cfg(feature = "jpeg")]
ImageFormat::Jpeg => &["jpg", "jpeg"],
#[cfg(feature = "ktx2")]
ImageFormat::Ktx2 => &["ktx2"],
#[cfg(feature = "pnm")]
ImageFormat::Pnm => &["pam", "pbm", "pgm", "ppm"],
#[cfg(feature = "png")]
ImageFormat::Png => &["png"],
#[cfg(feature = "qoi")]
ImageFormat::Qoi => &["qoi"],
#[cfg(feature = "tga")]
ImageFormat::Tga => &["tga"],
#[cfg(feature = "tiff")]
ImageFormat::Tiff => &["tif", "tiff"],
#[cfg(feature = "webp")]
ImageFormat::WebP => &["webp"],
// FIXME: https://github.com/rust-lang/rust/issues/129031
#[expect(
clippy::allow_attributes,
reason = "`unreachable_patterns` may not always lint"
)]
#[allow(
unreachable_patterns,
reason = "The wildcard pattern will be unreachable if all formats are enabled; otherwise, it will be reachable"
)]
_ => &[],
}
}
/// Gets the MIME types for a given format.
///
/// If a format doesn't have any dedicated MIME types, this list will be empty.
pub const fn to_mime_types(&self) -> &'static [&'static str] {
match self {
#[cfg(feature = "basis-universal")]
ImageFormat::Basis => &["image/basis", "image/x-basis"],
#[cfg(feature = "bmp")]
ImageFormat::Bmp => &["image/bmp", "image/x-bmp"],
#[cfg(feature = "dds")]
ImageFormat::Dds => &["image/vnd-ms.dds"],
#[cfg(feature = "hdr")]
ImageFormat::Hdr => &["image/vnd.radiance"],
#[cfg(feature = "gif")]
ImageFormat::Gif => &["image/gif"],
#[cfg(feature = "ff")]
ImageFormat::Farbfeld => &[],
#[cfg(feature = "ico")]
ImageFormat::Ico => &["image/x-icon"],
#[cfg(feature = "jpeg")]
ImageFormat::Jpeg => &["image/jpeg"],
#[cfg(feature = "ktx2")]
ImageFormat::Ktx2 => &["image/ktx2"],
#[cfg(feature = "png")]
ImageFormat::Png => &["image/png"],
#[cfg(feature = "qoi")]
ImageFormat::Qoi => &["image/qoi", "image/x-qoi"],
#[cfg(feature = "exr")]
ImageFormat::OpenExr => &["image/x-exr"],
#[cfg(feature = "pnm")]
ImageFormat::Pnm => &[
"image/x-portable-bitmap",
"image/x-portable-graymap",
"image/x-portable-pixmap",
"image/x-portable-anymap",
],
#[cfg(feature = "tga")]
ImageFormat::Tga => &["image/x-targa", "image/x-tga"],
#[cfg(feature = "tiff")]
ImageFormat::Tiff => &["image/tiff"],
#[cfg(feature = "webp")]
ImageFormat::WebP => &["image/webp"],
// FIXME: https://github.com/rust-lang/rust/issues/129031
#[expect(
clippy::allow_attributes,
reason = "`unreachable_patterns` may not always lint"
)]
#[allow(
unreachable_patterns,
reason = "The wildcard pattern will be unreachable if all formats are enabled; otherwise, it will be reachable"
)]
_ => &[],
}
}
/// Returns the image format associated with the given MIME type.
///
/// `None` is returned if the MIME type is unknown, or its format's feature is not enabled.
pub fn from_mime_type(mime_type: &str) -> Option<Self> {
#[expect(
clippy::allow_attributes,
reason = "`unreachable_code` may not always lint"
)]
#[allow(
unreachable_code,
reason = "If all features listed below are disabled, then all arms will have a `return None`, keeping the surrounding `Some()` from being constructed."
)]
Some(match mime_type.to_ascii_lowercase().as_str() {
// note: farbfeld does not have a MIME type
"image/basis" | "image/x-basis" => feature_gate!("basis-universal", Basis),
"image/bmp" | "image/x-bmp" => feature_gate!("bmp", Bmp),
"image/vnd-ms.dds" => feature_gate!("dds", Dds),
"image/vnd.radiance" => feature_gate!("hdr", Hdr),
"image/gif" => feature_gate!("gif", Gif),
"image/x-icon" => feature_gate!("ico", Ico),
"image/jpeg" => feature_gate!("jpeg", Jpeg),
"image/ktx2" => feature_gate!("ktx2", Ktx2),
"image/png" => feature_gate!("png", Png),
"image/qoi" | "image/x-qoi" => feature_gate!("qoi", Qoi),
"image/x-exr" => feature_gate!("exr", OpenExr),
"image/x-portable-bitmap"
| "image/x-portable-graymap"
| "image/x-portable-pixmap"
| "image/x-portable-anymap" => feature_gate!("pnm", Pnm),
"image/x-targa" | "image/x-tga" => feature_gate!("tga", Tga),
"image/tiff" => feature_gate!("tiff", Tiff),
"image/webp" => feature_gate!("webp", WebP),
_ => return None,
})
}
/// Returns the image format associated with the given file extension.
///
/// `None` is returned if the extension is unknown, or its format's feature is not enabled.
pub fn from_extension(extension: &str) -> Option<Self> {
#[expect(
clippy::allow_attributes,
reason = "`unreachable_code` may not always lint"
)]
#[allow(
unreachable_code,
reason = "If all features listed below are disabled, then all arms will have a `return None`, keeping the surrounding `Some()` from being constructed."
)]
Some(match extension.to_ascii_lowercase().as_str() {
"basis" => feature_gate!("basis-universal", Basis),
"bmp" => feature_gate!("bmp", Bmp),
"dds" => feature_gate!("dds", Dds),
"ff" | "farbfeld" => feature_gate!("ff", Farbfeld),
"gif" => feature_gate!("gif", Gif),
"exr" => feature_gate!("exr", OpenExr),
"hdr" => feature_gate!("hdr", Hdr),
"ico" => feature_gate!("ico", Ico),
"jpg" | "jpeg" => feature_gate!("jpeg", Jpeg),
"ktx2" => feature_gate!("ktx2", Ktx2),
"pam" | "pbm" | "pgm" | "ppm" => feature_gate!("pnm", Pnm),
"png" => feature_gate!("png", Png),
"qoi" => feature_gate!("qoi", Qoi),
"tga" => feature_gate!("tga", Tga),
"tif" | "tiff" => feature_gate!("tiff", Tiff),
"webp" => feature_gate!("webp", WebP),
_ => return None,
})
}
/// Returns the equivalent [`image::ImageFormat`] if available.
pub fn as_image_crate_format(&self) -> Option<image::ImageFormat> {
#[expect(
clippy::allow_attributes,
reason = "`unreachable_code` may not always lint"
)]
#[allow(
unreachable_code,
reason = "If all features listed below are disabled, then all arms will have a `return None`, keeping the surrounding `Some()` from being constructed."
)]
Some(match self {
#[cfg(feature = "bmp")]
ImageFormat::Bmp => image::ImageFormat::Bmp,
#[cfg(feature = "dds")]
ImageFormat::Dds => image::ImageFormat::Dds,
#[cfg(feature = "ff")]
ImageFormat::Farbfeld => image::ImageFormat::Farbfeld,
#[cfg(feature = "gif")]
ImageFormat::Gif => image::ImageFormat::Gif,
#[cfg(feature = "exr")]
ImageFormat::OpenExr => image::ImageFormat::OpenExr,
#[cfg(feature = "hdr")]
ImageFormat::Hdr => image::ImageFormat::Hdr,
#[cfg(feature = "ico")]
ImageFormat::Ico => image::ImageFormat::Ico,
#[cfg(feature = "jpeg")]
ImageFormat::Jpeg => image::ImageFormat::Jpeg,
#[cfg(feature = "png")]
ImageFormat::Png => image::ImageFormat::Png,
#[cfg(feature = "pnm")]
ImageFormat::Pnm => image::ImageFormat::Pnm,
#[cfg(feature = "qoi")]
ImageFormat::Qoi => image::ImageFormat::Qoi,
#[cfg(feature = "tga")]
ImageFormat::Tga => image::ImageFormat::Tga,
#[cfg(feature = "tiff")]
ImageFormat::Tiff => image::ImageFormat::Tiff,
#[cfg(feature = "webp")]
ImageFormat::WebP => image::ImageFormat::WebP,
#[cfg(feature = "basis-universal")]
ImageFormat::Basis => return None,
#[cfg(feature = "ktx2")]
ImageFormat::Ktx2 => return None,
// FIXME: https://github.com/rust-lang/rust/issues/129031
#[expect(
clippy::allow_attributes,
reason = "`unreachable_patterns` may not always lint"
)]
#[allow(
unreachable_patterns,
reason = "The wildcard pattern will be unreachable if all formats are enabled; otherwise, it will be reachable"
)]
_ => return None,
})
}
/// Returns the equivalent bevy [`ImageFormat`] of an [`image::ImageFormat`].
///
/// Returns `None` if the format is unsupported, or its feature is disabled.
pub fn from_image_crate_format(format: image::ImageFormat) -> Option<ImageFormat> {
#[expect(
clippy::allow_attributes,
reason = "`unreachable_code` may not always lint"
)]
#[allow(
unreachable_code,
reason = "If all features listed below are disabled, then all arms will have a `return None`, keeping the surrounding `Some()` from being constructed."
)]
Some(match format {
image::ImageFormat::Bmp => feature_gate!("bmp", Bmp),
image::ImageFormat::Dds => feature_gate!("dds", Dds),
image::ImageFormat::Farbfeld => feature_gate!("ff", Farbfeld),
image::ImageFormat::Gif => feature_gate!("gif", Gif),
image::ImageFormat::OpenExr => feature_gate!("exr", OpenExr),
image::ImageFormat::Hdr => feature_gate!("hdr", Hdr),
image::ImageFormat::Ico => feature_gate!("ico", Ico),
image::ImageFormat::Jpeg => feature_gate!("jpeg", Jpeg),
image::ImageFormat::Png => feature_gate!("png", Png),
image::ImageFormat::Pnm => feature_gate!("pnm", Pnm),
image::ImageFormat::Qoi => feature_gate!("qoi", Qoi),
image::ImageFormat::Tga => feature_gate!("tga", Tga),
image::ImageFormat::Tiff => feature_gate!("tiff", Tiff),
image::ImageFormat::WebP => feature_gate!("webp", WebP),
_ => return None,
})
}
}
/// A trait for creating [`Extent3d`] values.
pub trait ToExtents {
/// Converts this type to an [`Extent3d`].
fn to_extents(self) -> Extent3d;
}
impl ToExtents for UVec2 {
fn to_extents(self) -> Extent3d {
Extent3d {
width: self.x,
height: self.y,
depth_or_array_layers: 1,
}
}
}
impl ToExtents for UVec3 {
fn to_extents(self) -> Extent3d {
Extent3d {
width: self.x,
height: self.y,
depth_or_array_layers: self.z,
}
}
}
/// An image, optimized for usage in rendering.
///
/// ## Remote Inspection
///
/// To transmit an [`Image`] between two running Bevy apps, e.g. through BRP, use [`SerializedImage`](crate::SerializedImage).
/// This type is only meant for short-term transmission between same versions and should not be stored anywhere.
#[derive(Asset, Debug, Clone, PartialEq)]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(opaque, Default, Debug, Clone)
)]
#[cfg_attr(not(feature = "bevy_reflect"), derive(TypePath))]
pub struct Image {
/// Raw pixel data.
/// If the image is being used as a storage texture which doesn't need to be initialized by the
/// CPU, then this should be `None`.
/// Otherwise, it should always be `Some`.
pub data: Option<Vec<u8>>,
/// For texture data with layers and mips, this field controls how wgpu interprets the buffer layout.
///
/// Use [`TextureDataOrder::default()`] for all other cases.
pub data_order: TextureDataOrder,
// TODO: this nesting makes accessing Image metadata verbose. Either flatten out descriptor or add accessors.
/// Describes the data layout of the GPU texture.\
/// For example, whether a texture contains 1D/2D/3D data, and what the format of the texture data is.
///
/// ## Field Usage Notes
/// - [`TextureDescriptor::label`] is used for caching purposes when not using `Asset<Image>`.\
/// If you use assets, the label is purely a debugging aid.
/// - [`TextureDescriptor::view_formats`] is currently unused by Bevy.
pub texture_descriptor: TextureDescriptor<Option<&'static str>, &'static [TextureFormat]>,
/// The [`ImageSampler`] to use during rendering.
pub sampler: ImageSampler,
/// Describes how the GPU texture should be interpreted.\
/// For example, 2D image data could be read as plain 2D, an array texture of layers of 2D with the same dimensions (and the number of layers in that case),
/// a cube map, an array of cube maps, etc.
///
/// ## Field Usage Notes
/// - [`TextureViewDescriptor::label`] is used for caching purposes when not using `Asset<Image>`.\
/// If you use assets, the label is purely a debugging aid.
pub texture_view_descriptor: Option<TextureViewDescriptor<Option<&'static str>>>,
/// Where this image asset will be used. See [`RenderAssetUsages`] for more.
pub asset_usage: RenderAssetUsages,
/// Whether this image should be copied on the GPU when resized.
pub copy_on_resize: bool,
}
/// Used in [`Image`], this determines what image sampler to use when rendering. The default setting,
/// [`ImageSampler::Default`], will read the sampler from the `ImagePlugin` at setup.
/// Setting this to [`ImageSampler::Descriptor`] will override the global default descriptor for this [`Image`].
#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Default, Debug, Clone)
)]
pub enum ImageSampler {
/// Default image sampler, derived from the `ImagePlugin` setup.
#[default]
Default,
/// Custom sampler for this image which will override global default.
Descriptor(ImageSamplerDescriptor),
}
impl ImageSampler {
/// Returns an image sampler with [`ImageFilterMode::Linear`] min and mag filters
#[inline]
pub fn linear() -> ImageSampler {
ImageSampler::Descriptor(ImageSamplerDescriptor::linear())
}
/// Returns an image sampler with [`ImageFilterMode::Nearest`] min and mag filters
#[inline]
pub fn nearest() -> ImageSampler {
ImageSampler::Descriptor(ImageSamplerDescriptor::nearest())
}
/// Initialize the descriptor if it is not already initialized.
///
/// Descriptor is typically initialized by Bevy when the image is loaded,
/// so this is convenient shortcut for updating the descriptor.
pub fn get_or_init_descriptor(&mut self) -> &mut ImageSamplerDescriptor {
match self {
ImageSampler::Default => {
*self = ImageSampler::Descriptor(ImageSamplerDescriptor::default());
match self {
ImageSampler::Descriptor(descriptor) => descriptor,
_ => unreachable!(),
}
}
ImageSampler::Descriptor(descriptor) => descriptor,
}
}
}
/// How edges should be handled in texture addressing.
///
/// See [`ImageSamplerDescriptor`] for information how to configure this.
///
/// This type mirrors [`AddressMode`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Default, Debug, Clone)
)]
pub enum ImageAddressMode {
/// Clamp the value to the edge of the texture.
///
/// -0.25 -> 0.0
/// 1.25 -> 1.0
#[default]
ClampToEdge,
/// Repeat the texture in a tiling fashion.
///
/// -0.25 -> 0.75
/// 1.25 -> 0.25
Repeat,
/// Repeat the texture, mirroring it every repeat.
///
/// -0.25 -> 0.25
/// 1.25 -> 0.75
MirrorRepeat,
/// Clamp the value to the border of the texture
/// Requires the wgpu feature [`Features::ADDRESS_MODE_CLAMP_TO_BORDER`].
///
/// -0.25 -> border
/// 1.25 -> border
ClampToBorder,
}
/// Texel mixing mode when sampling between texels.
///
/// This type mirrors [`FilterMode`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Default, Debug, Clone)
)]
pub enum ImageFilterMode {
/// Nearest neighbor sampling.
///
/// This creates a pixelated effect when used as a mag filter.
#[default]
Nearest,
/// Linear Interpolation.
///
/// This makes textures smooth but blurry when used as a mag filter.
Linear,
}
/// Comparison function used for depth and stencil operations.
///
/// This type mirrors [`CompareFunction`].
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect), reflect(Debug, Clone))]
pub enum ImageCompareFunction {
/// Function never passes
Never,
/// Function passes if new value less than existing value
Less,
/// Function passes if new value is equal to existing value. When using
/// this compare function, make sure to mark your Vertex Shader's `@builtin(position)`
/// output as `@invariant` to prevent artifacting.
Equal,
/// Function passes if new value is less than or equal to existing value
LessEqual,
/// Function passes if new value is greater than existing value
Greater,
/// Function passes if new value is not equal to existing value. When using
/// this compare function, make sure to mark your Vertex Shader's `@builtin(position)`
/// output as `@invariant` to prevent artifacting.
NotEqual,
/// Function passes if new value is greater than or equal to existing value
GreaterEqual,
/// Function always passes
Always,
}
/// Color variation to use when the sampler addressing mode is [`ImageAddressMode::ClampToBorder`].
///
/// This type mirrors [`SamplerBorderColor`].
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect), reflect(Debug, Clone))]
pub enum ImageSamplerBorderColor {
/// RGBA color `[0, 0, 0, 0]`.
TransparentBlack,
/// RGBA color `[0, 0, 0, 1]`.
OpaqueBlack,
/// RGBA color `[1, 1, 1, 1]`.
OpaqueWhite,
/// On the Metal wgpu backend, this is equivalent to [`Self::TransparentBlack`] for
/// textures that have an alpha component, and equivalent to [`Self::OpaqueBlack`]
/// for textures that do not have an alpha component. On other backends,
/// this is equivalent to [`Self::TransparentBlack`]. Requires
/// [`Features::ADDRESS_MODE_CLAMP_TO_ZERO`]. Not supported on the web.
Zero,
}
/// Indicates to an `ImageLoader` how an [`Image`] should be sampled.
///
/// As this type is part of the `ImageLoaderSettings`,
/// it will be serialized to an image asset `.meta` file which might require a migration in case of
/// a breaking change.
///
/// This types mirrors [`SamplerDescriptor`], but that might change in future versions.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Default, Debug, Clone)
)]
pub struct ImageSamplerDescriptor {
/// An optional label used to identify this sampler in logs.
pub label: Option<String>,
/// How to deal with out of bounds accesses in the u (i.e. x) direction.
pub address_mode_u: ImageAddressMode,
/// How to deal with out of bounds accesses in the v (i.e. y) direction.
pub address_mode_v: ImageAddressMode,
/// How to deal with out of bounds accesses in the w (i.e. z) direction.
pub address_mode_w: ImageAddressMode,
/// How to filter the texture when it needs to be magnified (made larger).
pub mag_filter: ImageFilterMode,
/// How to filter the texture when it needs to be minified (made smaller).
pub min_filter: ImageFilterMode,
/// How to filter between mip map levels
pub mipmap_filter: ImageFilterMode,
/// Minimum level of detail (i.e. mip level) to use.
pub lod_min_clamp: f32,
/// Maximum level of detail (i.e. mip level) to use.
pub lod_max_clamp: f32,
/// If this is enabled, this is a comparison sampler using the given comparison function.
pub compare: Option<ImageCompareFunction>,
/// Must be at least 1. If this is not 1, all filter modes must be linear.
pub anisotropy_clamp: u16,
/// Border color to use when `address_mode` is [`ImageAddressMode::ClampToBorder`].
pub border_color: Option<ImageSamplerBorderColor>,
}
impl Default for ImageSamplerDescriptor {
fn default() -> Self {
Self {
address_mode_u: Default::default(),
address_mode_v: Default::default(),
address_mode_w: Default::default(),
mag_filter: Default::default(),
min_filter: Default::default(),
mipmap_filter: Default::default(),
lod_min_clamp: 0.0,
lod_max_clamp: 32.0,
compare: None,
anisotropy_clamp: 1,
border_color: None,
label: None,
}
}
}
impl ImageSamplerDescriptor {
/// Returns a sampler descriptor with [`Linear`](ImageFilterMode::Linear) min and mag filters
#[inline]
pub fn linear() -> ImageSamplerDescriptor {
ImageSamplerDescriptor {
mag_filter: ImageFilterMode::Linear,
min_filter: ImageFilterMode::Linear,
mipmap_filter: ImageFilterMode::Linear,
..Default::default()
}
}
/// Returns a sampler descriptor with [`Nearest`](ImageFilterMode::Nearest) min and mag filters
#[inline]
pub fn nearest() -> ImageSamplerDescriptor {
ImageSamplerDescriptor {
mag_filter: ImageFilterMode::Nearest,
min_filter: ImageFilterMode::Nearest,
mipmap_filter: ImageFilterMode::Nearest,
..Default::default()
}
}
/// Returns this sampler descriptor with a new `ImageFilterMode` min, mag, and mipmap filters
#[inline]
pub fn set_filter(&mut self, filter: ImageFilterMode) -> &mut Self {
self.mag_filter = filter;
self.min_filter = filter;
self.mipmap_filter = filter;
self
}
/// Returns this sampler descriptor with a new `ImageAddressMode` for u, v, and w
#[inline]
pub fn set_address_mode(&mut self, address_mode: ImageAddressMode) -> &mut Self {
self.address_mode_u = address_mode;
self.address_mode_v = address_mode;
self.address_mode_w = address_mode;
self
}
/// Returns this sampler descriptor with an `anisotropy_clamp` value and also
/// set filters to `ImageFilterMode::Linear`, which is required to
/// use anisotropy.
#[inline]
pub fn set_anisotropic_filter(&mut self, anisotropy_clamp: u16) -> &mut Self {
self.mag_filter = ImageFilterMode::Linear;
self.min_filter = ImageFilterMode::Linear;
self.mipmap_filter = ImageFilterMode::Linear;
self.anisotropy_clamp = anisotropy_clamp;
self
}
/// Converts this sampler to its `wgpu` equivalent.
pub fn as_wgpu(&self) -> SamplerDescriptor<Option<&str>> {
SamplerDescriptor {
label: self.label.as_deref(),
address_mode_u: self.address_mode_u.into(),
address_mode_v: self.address_mode_v.into(),
address_mode_w: self.address_mode_w.into(),
mag_filter: self.mag_filter.into(),
min_filter: self.min_filter.into(),
mipmap_filter: self.mipmap_filter.into(),
lod_min_clamp: self.lod_min_clamp,
lod_max_clamp: self.lod_max_clamp,
compare: self.compare.map(Into::into),
anisotropy_clamp: self.anisotropy_clamp,
border_color: self.border_color.map(Into::into),
}
}
}
impl From<ImageAddressMode> for AddressMode {
fn from(value: ImageAddressMode) -> Self {
match value {
ImageAddressMode::ClampToEdge => AddressMode::ClampToEdge,
ImageAddressMode::Repeat => AddressMode::Repeat,
ImageAddressMode::MirrorRepeat => AddressMode::MirrorRepeat,
ImageAddressMode::ClampToBorder => AddressMode::ClampToBorder,
}
}
}
impl From<ImageFilterMode> for FilterMode {
fn from(value: ImageFilterMode) -> Self {
match value {
ImageFilterMode::Nearest => FilterMode::Nearest,
ImageFilterMode::Linear => FilterMode::Linear,
}
}
}
impl From<ImageFilterMode> for MipmapFilterMode {
fn from(value: ImageFilterMode) -> Self {
match value {
ImageFilterMode::Nearest => MipmapFilterMode::Nearest,
ImageFilterMode::Linear => MipmapFilterMode::Linear,
}
}
}
impl From<ImageCompareFunction> for CompareFunction {
fn from(value: ImageCompareFunction) -> Self {
match value {
ImageCompareFunction::Never => CompareFunction::Never,
ImageCompareFunction::Less => CompareFunction::Less,
ImageCompareFunction::Equal => CompareFunction::Equal,
ImageCompareFunction::LessEqual => CompareFunction::LessEqual,
ImageCompareFunction::Greater => CompareFunction::Greater,
ImageCompareFunction::NotEqual => CompareFunction::NotEqual,
ImageCompareFunction::GreaterEqual => CompareFunction::GreaterEqual,
ImageCompareFunction::Always => CompareFunction::Always,
}
}
}
impl From<ImageSamplerBorderColor> for SamplerBorderColor {
fn from(value: ImageSamplerBorderColor) -> Self {
match value {
ImageSamplerBorderColor::TransparentBlack => SamplerBorderColor::TransparentBlack,
ImageSamplerBorderColor::OpaqueBlack => SamplerBorderColor::OpaqueBlack,
ImageSamplerBorderColor::OpaqueWhite => SamplerBorderColor::OpaqueWhite,
ImageSamplerBorderColor::Zero => SamplerBorderColor::Zero,
}
}
}
impl From<AddressMode> for ImageAddressMode {
fn from(value: AddressMode) -> Self {
match value {
AddressMode::ClampToEdge => ImageAddressMode::ClampToEdge,
AddressMode::Repeat => ImageAddressMode::Repeat,
AddressMode::MirrorRepeat => ImageAddressMode::MirrorRepeat,
AddressMode::ClampToBorder => ImageAddressMode::ClampToBorder,
}
}
}
impl From<MipmapFilterMode> for ImageFilterMode {
fn from(value: MipmapFilterMode) -> Self {
match value {
MipmapFilterMode::Nearest => ImageFilterMode::Nearest,
MipmapFilterMode::Linear => ImageFilterMode::Linear,
}