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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
//! Image resource types

use {
    super::{
        access_type_from_u8, access_type_into_u8, device::Device, format_aspect_mask, DriverError,
    },
    ash::vk,
    derive_builder::{Builder, UninitializedFieldError},
    gpu_allocator::{
        vulkan::{Allocation, AllocationCreateDesc, AllocationScheme},
        MemoryLocation,
    },
    log::{trace, warn},
    parking_lot::Mutex,
    std::{
        collections::{hash_map::Entry, HashMap},
        fmt::{Debug, Formatter},
        mem::take,
        ops::Deref,
        ptr::null,
        sync::{
            atomic::{AtomicU8, Ordering},
            Arc,
        },
        thread::panicking,
    },
    vk_sync::AccessType,
};

/// Smart pointer handle to an [image] object.
///
/// Also contains information about the object.
///
/// ## `Deref` behavior
///
/// `Image` automatically dereferences to [`vk::Image`] (via the [`Deref`] trait), so you can
/// call `vk::Image`'s methods on a value of type `Image`. To avoid name clashes with `vk::Image`'s
/// methods, the methods of `Image` itself are associated functions, called using
/// [fully qualified syntax]:
///
/// ```no_run
/// # use std::sync::Arc;
/// # use ash::vk;
/// # use screen_13::driver::{AccessType, DriverError};
/// # use screen_13::driver::device::{Device, DeviceInfo};
/// # use screen_13::driver::image::{Image, ImageInfo};
/// # fn main() -> Result<(), DriverError> {
/// # let device = Arc::new(Device::create_headless(DeviceInfo::new())?);
/// # let info = ImageInfo::image_1d(1, vk::Format::R8_UINT, vk::ImageUsageFlags::STORAGE);
/// # let my_image = Image::create(&device, info)?;
/// let prev = Image::access(&my_image, AccessType::AnyShaderWrite);
/// # Ok(()) }
/// ```
///
/// [image]: https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VkImage.html
/// [deref]: core::ops::Deref
/// [fully qualified syntax]: https://doc.rust-lang.org/book/ch19-03-advanced-traits.html#fully-qualified-syntax-for-disambiguation-calling-methods-with-the-same-name
pub struct Image {
    allocation: Option<Allocation>, // None when we don't own the image (Swapchain images)
    device: Arc<Device>,
    image: vk::Image,
    #[allow(clippy::type_complexity)]
    image_view_cache: Mutex<HashMap<ImageViewInfo, ImageView>>,

    /// Information used to create this object.
    pub info: ImageInfo,

    /// A name for debugging purposes.
    pub name: Option<String>,

    prev_access: AtomicU8,
}

impl Image {
    /// Creates a new image on the given device.
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```no_run
    /// # use std::sync::Arc;
    /// # use ash::vk;
    /// # use screen_13::driver::DriverError;
    /// # use screen_13::driver::device::{Device, DeviceInfo};
    /// # use screen_13::driver::image::{Image, ImageInfo};
    /// # fn main() -> Result<(), DriverError> {
    /// # let device = Arc::new(Device::create_headless(DeviceInfo::default())?);
    /// let info = ImageInfo::image_2d(32, 32, vk::Format::R8G8B8A8_UNORM, vk::ImageUsageFlags::SAMPLED);
    /// let image = Image::create(&device, info)?;
    ///
    /// assert_ne!(*image, vk::Image::null());
    /// assert_eq!(image.info.width, 32);
    /// assert_eq!(image.info.height, 32);
    /// # Ok(()) }
    /// ```
    #[profiling::function]
    pub fn create(device: &Arc<Device>, info: impl Into<ImageInfo>) -> Result<Self, DriverError> {
        let info: ImageInfo = info.into();

        //trace!("create: {:?}", &info);
        trace!("create");

        assert!(
            !info.usage.is_empty(),
            "Unspecified image usage {:?}",
            info.usage
        );

        let device = Arc::clone(device);
        let create_info = info
            .image_create_info()
            .queue_family_indices(&device.physical_device.queue_family_indices);
        let image = unsafe {
            device.create_image(&create_info, None).map_err(|err| {
                warn!("{err}");

                DriverError::Unsupported
            })?
        };
        let requirements = unsafe { device.get_image_memory_requirements(image) };
        let allocation = {
            profiling::scope!("allocate");

            device
                .allocator
                .as_ref()
                .unwrap()
                .lock()
                .allocate(&AllocationCreateDesc {
                    name: "image",
                    requirements,
                    location: MemoryLocation::GpuOnly,
                    linear: false,
                    allocation_scheme: AllocationScheme::GpuAllocatorManaged,
                })
                .map_err(|err| {
                    warn!("{err}");

                    DriverError::Unsupported
                })
        }?;

        unsafe {
            device
                .bind_image_memory(image, allocation.memory(), allocation.offset())
                .map_err(|err| {
                    warn!("{err}");

                    DriverError::Unsupported
                })?;
        }

        Ok(Self {
            allocation: Some(allocation),
            device,
            image,
            image_view_cache: Mutex::new(Default::default()),
            info,
            name: None,
            prev_access: AtomicU8::new(access_type_into_u8(AccessType::Nothing)),
        })
    }

    /// Keeps track of some `next_access` which affects this object.
    ///
    /// Returns the previous access for which a pipeline barrier should be used to prevent data
    /// corruption.
    ///
    /// # Note
    ///
    /// Used to maintain object state when passing a _Screen 13_-created `vk::Image` handle to
    /// external code such as [_Ash_] or [_Erupt_] bindings.
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```no_run
    /// # use std::sync::Arc;
    /// # use ash::vk;
    /// # use screen_13::driver::{AccessType, DriverError};
    /// # use screen_13::driver::device::{Device, DeviceInfo};
    /// # use screen_13::driver::image::{Image, ImageInfo};
    /// # fn main() -> Result<(), DriverError> {
    /// # let device = Arc::new(Device::create_headless(DeviceInfo::new())?);
    /// # let info = ImageInfo::image_1d(1, vk::Format::R8_UINT, vk::ImageUsageFlags::STORAGE);
    /// # let my_image = Image::create(&device, info)?;
    /// // Initially we want to "Read Other"
    /// let next = AccessType::AnyShaderReadOther;
    /// let prev = Image::access(&my_image, next);
    /// assert_eq!(prev, AccessType::Nothing);
    ///
    /// // External code may now "Read Other"; no barrier required
    ///
    /// // Subsequently we want to "Write"
    /// let next = AccessType::FragmentShaderWrite;
    /// let prev = Image::access(&my_image, next);
    /// assert_eq!(prev, AccessType::AnyShaderReadOther);
    ///
    /// // A barrier on "Read Other" before "Write" is required!
    /// # Ok(()) }
    /// ```
    ///
    /// [_Ash_]: https://crates.io/crates/ash
    /// [_Erupt_]: https://crates.io/crates/erupt
    #[profiling::function]
    pub fn access(this: &Self, next_access: AccessType) -> AccessType {
        access_type_from_u8(
            this.prev_access
                .swap(access_type_into_u8(next_access), Ordering::Relaxed),
        )
    }

    #[profiling::function]
    pub(super) fn clone_raw(this: &Self) -> Self {
        // Moves the image view cache from the current instance to the clone!
        let mut image_view_cache = this.image_view_cache.lock();
        let image_view_cache = take(&mut *image_view_cache);
        let Self { image, info, .. } = *this;

        Self {
            allocation: None,
            device: Arc::clone(&this.device),
            image,
            image_view_cache: Mutex::new(image_view_cache),
            info,
            name: this.name.clone(),
            prev_access: AtomicU8::new(access_type_into_u8(AccessType::Nothing)),
        }
    }

    #[profiling::function]
    fn drop_allocation(this: &Self, allocation: Allocation) {
        {
            profiling::scope!("views");

            this.image_view_cache.lock().clear();
        }

        unsafe {
            this.device.destroy_image(this.image, None);
        }

        {
            profiling::scope!("deallocate");

            this.device
                .allocator
                .as_ref()
                .unwrap()
                .lock()
                .free(allocation)
                .unwrap_or_else(|_| warn!("Unable to free image allocation"));
        }
    }

    /// Consumes a Vulkan image created by some other library.
    ///
    /// The image is not destroyed automatically on drop, unlike images created through the
    /// [`Image::create`] function.
    #[profiling::function]
    pub fn from_raw(device: &Arc<Device>, image: vk::Image, info: impl Into<ImageInfo>) -> Self {
        let device = Arc::clone(device);
        let info = info.into();

        Self {
            allocation: None,
            device,
            image,
            image_view_cache: Mutex::new(Default::default()),
            info,
            name: None,
            prev_access: AtomicU8::new(access_type_into_u8(AccessType::Nothing)),
        }
    }

    #[profiling::function]
    pub(crate) fn view(this: &Self, info: ImageViewInfo) -> Result<vk::ImageView, DriverError> {
        let mut image_view_cache = this.image_view_cache.lock();

        Ok(match image_view_cache.entry(info) {
            Entry::Occupied(entry) => entry.get().image_view,
            Entry::Vacant(entry) => {
                entry
                    .insert(ImageView::create(&this.device, info, this.image)?)
                    .image_view
            }
        })
    }
}

impl Debug for Image {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        if let Some(name) = &self.name {
            write!(f, "{} ({:?})", name, self.image)
        } else {
            write!(f, "{:?}", self.image)
        }
    }
}

impl Deref for Image {
    type Target = vk::Image;

    fn deref(&self) -> &Self::Target {
        &self.image
    }
}

impl Drop for Image {
    // This function is not profiled because drop_allocation is
    fn drop(&mut self) {
        if panicking() {
            return;
        }

        // When our allocation is some we allocated ourself; otherwise somebody
        // else owns this image and we should not destroy it. Usually it's the swapchain...
        if let Some(allocation) = self.allocation.take() {
            Self::drop_allocation(self, allocation);
        }
    }
}

/// Information used to create an [`Image`] instance.
#[derive(Builder, Clone, Copy, Debug, Hash, PartialEq, Eq)]
#[builder(
    build_fn(private, name = "fallible_build", error = "ImageInfoBuilderError"),
    derive(Copy, Clone, Debug),
    pattern = "owned"
)]
#[non_exhaustive]
pub struct ImageInfo {
    /// The number of layers in the image.
    #[builder(default = "1", setter(strip_option))]
    pub array_elements: u32,

    /// Image extent of the Z axis, when describing a three dimensional image.
    #[builder(setter(strip_option))]
    pub depth: u32,

    /// A bitmask of describing additional parameters of the image.
    #[builder(default, setter(strip_option))]
    pub flags: vk::ImageCreateFlags,

    /// The format and type of the texel blocks that will be contained in the image.
    #[builder(setter(strip_option))]
    pub fmt: vk::Format,

    /// Image extent of the Y axis, when describing a two or three dimensional image.
    #[builder(setter(strip_option))]
    pub height: u32,

    /// The number of levels of detail available for minified sampling of the image.
    #[builder(default = "1", setter(strip_option))]
    pub mip_level_count: u32,

    /// Specifies the number of [samples per texel].
    ///
    /// [samples per texel]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#primsrast-multisampling
    #[builder(default = "SampleCount::Type1", setter(strip_option))]
    pub sample_count: SampleCount,

    /// Specifies the tiling arrangement of the texel blocks in memory.
    ///
    /// The default value is [`vk::ImageTiling::OPTIMAL`].
    #[builder(default = "vk::ImageTiling::OPTIMAL", setter(strip_option))]
    pub tiling: vk::ImageTiling,

    /// The basic dimensionality of the image.
    ///
    /// Layers in array textures do not count as a dimension for the purposes of the image type.
    #[builder(setter(strip_option))]
    pub ty: ImageType,

    /// A bitmask of describing the intended usage of the image.
    #[builder(default, setter(strip_option))]
    pub usage: vk::ImageUsageFlags,

    /// Image extent of the X axis.
    #[builder(setter(strip_option))]
    pub width: u32,
}

impl ImageInfo {
    /// Specifies a cube image.
    #[inline(always)]
    pub const fn cube(size: u32, fmt: vk::Format, usage: vk::ImageUsageFlags) -> ImageInfo {
        Self::new(ImageType::Cube, size, size, 1, 1, fmt, usage)
    }

    /// Specifies a one-dimensional image.
    #[inline(always)]
    pub const fn image_1d(size: u32, fmt: vk::Format, usage: vk::ImageUsageFlags) -> ImageInfo {
        Self::new(ImageType::Texture1D, size, 1, 1, 1, fmt, usage)
    }

    /// Specifies a two-dimensional image.
    #[inline(always)]
    pub const fn image_2d(
        width: u32,
        height: u32,
        fmt: vk::Format,
        usage: vk::ImageUsageFlags,
    ) -> ImageInfo {
        Self::new(ImageType::Texture2D, width, height, 1, 1, fmt, usage)
    }

    /// Specifies a two-dimensional image array.
    #[inline(always)]
    pub const fn image_2d_array(
        width: u32,
        height: u32,
        array_elements: u32,
        fmt: vk::Format,
        usage: vk::ImageUsageFlags,
    ) -> ImageInfo {
        Self::new(
            ImageType::TextureArray2D,
            width,
            height,
            1,
            array_elements,
            fmt,
            usage,
        )
    }

    /// Specifies a three-dimensional image.
    #[inline(always)]
    pub const fn image_3d(
        width: u32,
        height: u32,
        depth: u32,
        fmt: vk::Format,
        usage: vk::ImageUsageFlags,
    ) -> ImageInfo {
        Self::new(ImageType::Texture3D, width, height, depth, 1, fmt, usage)
    }

    #[inline(always)]
    const fn new(
        ty: ImageType,
        width: u32,
        height: u32,
        depth: u32,
        array_elements: u32,
        fmt: vk::Format,
        usage: vk::ImageUsageFlags,
    ) -> Self {
        Self {
            ty,
            width,
            height,
            depth,
            array_elements,
            fmt,
            usage,
            flags: vk::ImageCreateFlags::empty(),
            tiling: vk::ImageTiling::OPTIMAL,
            mip_level_count: 1,
            sample_count: SampleCount::Type1,
        }
    }

    /// Specifies a one-dimensional image.
    #[deprecated = "Use ImageInfo::image_1d()"]
    #[doc(hidden)]
    pub fn new_1d(fmt: vk::Format, size: u32, usage: vk::ImageUsageFlags) -> ImageInfoBuilder {
        Self::image_1d(size, fmt, usage).to_builder()
    }

    /// Specifies a two-dimensional image.
    #[deprecated = "Use ImageInfo::image_2d()"]
    #[doc(hidden)]
    pub fn new_2d(
        fmt: vk::Format,
        width: u32,
        height: u32,
        usage: vk::ImageUsageFlags,
    ) -> ImageInfoBuilder {
        Self::image_2d(width, height, fmt, usage).to_builder()
    }

    /// Specifies a two-dimensional image array.
    #[deprecated = "Use ImageInfo::image_2d_array()"]
    #[doc(hidden)]
    pub fn new_2d_array(
        fmt: vk::Format,
        width: u32,
        height: u32,
        array_elements: u32,
        usage: vk::ImageUsageFlags,
    ) -> ImageInfoBuilder {
        Self::image_2d_array(width, height, array_elements, fmt, usage).to_builder()
    }

    /// Specifies a three-dimensional image.
    #[deprecated = "Use ImageInfo::image_3d()"]
    #[doc(hidden)]
    pub fn new_3d(
        fmt: vk::Format,
        width: u32,
        height: u32,
        depth: u32,
        usage: vk::ImageUsageFlags,
    ) -> ImageInfoBuilder {
        Self::image_3d(width, height, depth, fmt, usage).to_builder()
    }

    /// Specifies a cube image.
    #[deprecated = "Use ImageInfo::cube()"]
    #[doc(hidden)]
    pub fn new_cube(fmt: vk::Format, size: u32, usage: vk::ImageUsageFlags) -> ImageInfoBuilder {
        Self::cube(size, fmt, usage).to_builder()
    }

    /// Provides an `ImageViewInfo` for this format, type, aspect, array elements, and mip levels.
    pub fn default_view_info(self) -> ImageViewInfo {
        self.into()
    }

    fn image_create_info<'a>(self) -> vk::ImageCreateInfoBuilder<'a> {
        let (ty, extent, array_layers) = match self.ty {
            ImageType::Texture1D => (
                vk::ImageType::TYPE_1D,
                vk::Extent3D {
                    width: self.width,
                    height: 1,
                    depth: 1,
                },
                1,
            ),
            ImageType::TextureArray1D => (
                vk::ImageType::TYPE_1D,
                vk::Extent3D {
                    width: self.width,
                    height: 1,
                    depth: 1,
                },
                self.array_elements,
            ),
            ImageType::Texture2D => (
                vk::ImageType::TYPE_2D,
                vk::Extent3D {
                    width: self.width,
                    height: self.height,
                    depth: 1,
                },
                if self.flags.contains(vk::ImageCreateFlags::CUBE_COMPATIBLE) {
                    self.array_elements
                } else {
                    1
                },
            ),
            ImageType::TextureArray2D => (
                vk::ImageType::TYPE_2D,
                vk::Extent3D {
                    width: self.width,
                    height: self.height,
                    depth: 1,
                },
                self.array_elements,
            ),
            ImageType::Texture3D => (
                vk::ImageType::TYPE_3D,
                vk::Extent3D {
                    width: self.width,
                    height: self.height,
                    depth: self.depth,
                },
                1,
            ),
            ImageType::Cube => (
                vk::ImageType::TYPE_2D,
                vk::Extent3D {
                    width: self.width,
                    height: self.height,
                    depth: 1,
                },
                6,
            ),
            ImageType::CubeArray => (
                vk::ImageType::TYPE_2D,
                vk::Extent3D {
                    width: self.width,
                    height: self.height,
                    depth: 1,
                },
                6 * self.array_elements,
            ),
        };

        vk::ImageCreateInfo::builder()
            .flags(self.flags)
            .image_type(ty)
            .format(self.fmt)
            .extent(extent)
            .mip_levels(self.mip_level_count)
            .array_layers(array_layers)
            .samples(self.sample_count.into_vk())
            .tiling(self.tiling)
            .usage(self.usage)
            .sharing_mode(vk::SharingMode::CONCURRENT)
            .initial_layout(vk::ImageLayout::UNDEFINED)
    }

    /// Converts an `ImageInfo` into an `ImageInfoBuilder`.
    #[inline(always)]
    pub fn to_builder(self) -> ImageInfoBuilder {
        ImageInfoBuilder {
            array_elements: Some(self.array_elements),
            depth: Some(self.depth),
            flags: Some(self.flags),
            fmt: Some(self.fmt),
            height: Some(self.height),
            mip_level_count: Some(self.mip_level_count),
            sample_count: Some(self.sample_count),
            tiling: Some(self.tiling),
            ty: Some(self.ty),
            usage: Some(self.usage),
            width: Some(self.width),
        }
    }
}

impl From<ImageInfoBuilder> for ImageInfo {
    fn from(info: ImageInfoBuilder) -> Self {
        info.build()
    }
}

impl ImageInfoBuilder {
    /// Builds a new `ImageInfo`.
    ///
    /// # Panics
    ///
    /// If any of the following functions have not been called this function will panic:
    ///
    /// * `ty`
    /// * `fmt`
    /// * `width`
    /// * `height`
    /// * `depth`
    #[inline(always)]
    pub fn build(self) -> ImageInfo {
        match self.fallible_build() {
            Err(ImageInfoBuilderError(err)) => panic!("{err}"),
            Ok(info) => info,
        }
    }
}

#[derive(Debug)]
struct ImageInfoBuilderError(UninitializedFieldError);

impl From<UninitializedFieldError> for ImageInfoBuilderError {
    fn from(err: UninitializedFieldError) -> Self {
        Self(err)
    }
}

/// Describes a subset of an image.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ImageSubresource {
    /// The number of layers for which this subset applies.
    ///
    /// The default value of `None` equates to `vk::REMAINING_ARRAY_LAYERS`.
    pub array_layer_count: Option<u32>,

    /// The portion of the image for which this subset applies.
    pub aspect_mask: vk::ImageAspectFlags,

    /// The first array layer for which this subset applies.
    pub base_array_layer: u32,

    /// The first mip level for which this subset applies.
    pub base_mip_level: u32,

    /// The number of mip levels for which this subset applies.
    ///
    /// The default value of `None` equates to `vk::REMAINING_MIP_LEVELS`.
    pub mip_level_count: Option<u32>,
}

impl ImageSubresource {
    pub(crate) fn into_vk(self) -> vk::ImageSubresourceRange {
        vk::ImageSubresourceRange {
            aspect_mask: self.aspect_mask,
            base_mip_level: self.base_mip_level,
            base_array_layer: self.base_array_layer,
            layer_count: self.array_layer_count.unwrap_or(vk::REMAINING_ARRAY_LAYERS),
            level_count: self.mip_level_count.unwrap_or(vk::REMAINING_MIP_LEVELS),
        }
    }
}

impl From<ImageViewInfo> for ImageSubresource {
    fn from(info: ImageViewInfo) -> Self {
        Self {
            aspect_mask: info.aspect_mask,
            base_mip_level: info.base_mip_level,
            base_array_layer: info.base_array_layer,
            array_layer_count: Some(info.array_layer_count.unwrap_or(vk::REMAINING_ARRAY_LAYERS)),
            mip_level_count: Some(info.mip_level_count.unwrap_or(vk::REMAINING_MIP_LEVELS)),
        }
    }
}

// TODO: Remove this and use vk::ImageType instead
/// Describes the number of dimensions and array elements of an image.
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
pub enum ImageType {
    /// One dimensional (linear) image.
    Texture1D = 0,
    /// One dimensional (linear) image with multiple array elements.
    TextureArray1D = 1,
    /// Two dimensional (planar) image.
    Texture2D = 2,
    /// Two dimensional (planar) image with multiple array elements.
    TextureArray2D = 3,
    /// Three dimensional (volume) image.
    Texture3D = 4,
    /// Six two-dimensional images.
    Cube = 5,
    /// Six two-dimensional images with multiple array elements.
    CubeArray = 6,
}

impl ImageType {
    pub(crate) fn into_vk(self) -> vk::ImageViewType {
        match self {
            Self::Cube => vk::ImageViewType::CUBE,
            Self::CubeArray => vk::ImageViewType::CUBE_ARRAY,
            Self::Texture1D => vk::ImageViewType::TYPE_1D,
            Self::Texture2D => vk::ImageViewType::TYPE_2D,
            Self::Texture3D => vk::ImageViewType::TYPE_3D,
            Self::TextureArray1D => vk::ImageViewType::TYPE_1D_ARRAY,
            Self::TextureArray2D => vk::ImageViewType::TYPE_2D_ARRAY,
        }
    }
}

impl From<ImageType> for vk::ImageType {
    fn from(value: ImageType) -> Self {
        match value {
            ImageType::Texture1D | ImageType::TextureArray1D => vk::ImageType::TYPE_1D,
            ImageType::Texture2D
            | ImageType::TextureArray2D
            | ImageType::Cube
            | ImageType::CubeArray => vk::ImageType::TYPE_2D,
            ImageType::Texture3D => vk::ImageType::TYPE_3D,
        }
    }
}

struct ImageView {
    device: Arc<Device>,
    image_view: vk::ImageView,
}

impl ImageView {
    #[profiling::function]
    fn create(
        device: &Arc<Device>,
        info: impl Into<ImageViewInfo>,
        image: vk::Image,
    ) -> Result<Self, DriverError> {
        let info = info.into();
        let device = Arc::clone(device);
        let create_info = vk::ImageViewCreateInfo {
            s_type: vk::StructureType::IMAGE_VIEW_CREATE_INFO,
            p_next: null(),
            flags: vk::ImageViewCreateFlags::empty(),
            view_type: info.ty.into_vk(),
            format: info.fmt,
            components: vk::ComponentMapping {
                r: vk::ComponentSwizzle::R,
                g: vk::ComponentSwizzle::G,
                b: vk::ComponentSwizzle::B,
                a: vk::ComponentSwizzle::A,
            },
            image,
            subresource_range: vk::ImageSubresourceRange {
                aspect_mask: info.aspect_mask,
                base_array_layer: info.base_array_layer,
                base_mip_level: info.base_mip_level,
                level_count: info.mip_level_count.unwrap_or(vk::REMAINING_MIP_LEVELS),
                layer_count: info.array_layer_count.unwrap_or(vk::REMAINING_ARRAY_LAYERS),
            },
        };

        let image_view =
            unsafe { device.create_image_view(&create_info, None) }.map_err(|err| {
                warn!("{err}");

                DriverError::Unsupported
            })?;

        Ok(Self { device, image_view })
    }
}

impl Drop for ImageView {
    #[profiling::function]
    fn drop(&mut self) {
        if panicking() {
            return;
        }

        unsafe {
            self.device.destroy_image_view(self.image_view, None);
        }
    }
}

/// Information used to reinterpret an existing [`Image`] instance.
#[derive(Builder, Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[builder(
    build_fn(private, name = "fallible_build", error = "ImageViewInfoBuilderError"),
    derive(Clone, Copy, Debug),
    pattern = "owned"
)]
#[non_exhaustive]
pub struct ImageViewInfo {
    /// The number of layers that will be contained in the view.
    ///
    /// The default value of `None` equates to `vk::REMAINING_ARRAY_LAYERS`.
    #[builder(default)]
    pub array_layer_count: Option<u32>,

    /// The portion of the image that will be contained in the view.
    pub aspect_mask: vk::ImageAspectFlags,

    /// The first array layer that will be contained in the view.
    #[builder(default)]
    pub base_array_layer: u32,

    /// The first mip level that will be contained in the view.
    #[builder(default)]
    pub base_mip_level: u32,

    /// The format and type of the texel blocks that will be contained in the view.
    pub fmt: vk::Format,

    /// The number of mip levels that will be contained in the view.
    ///
    /// The default value of `None` equates to `vk::REMAINING_MIP_LEVELS`.
    #[builder(default)]
    pub mip_level_count: Option<u32>,

    /// The basic dimensionality of the view.
    pub ty: ImageType,
}

impl ImageViewInfo {
    /// Specifies a default view with the given `fmt` and `ty` values.
    ///
    /// # Note
    ///
    /// Automatically sets [`aspect_mask`](Self::aspect_mask) to a suggested value.
    #[inline(always)]
    pub const fn new(fmt: vk::Format, ty: ImageType) -> ImageViewInfo {
        Self {
            array_layer_count: None,
            aspect_mask: format_aspect_mask(fmt),
            base_array_layer: 0,
            base_mip_level: 0,
            fmt,
            mip_level_count: None,
            ty,
        }
    }

    /// Converts a `ImageViewInfo` into a `ImageViewInfoBuilder`.
    #[inline(always)]
    pub fn to_builder(self) -> ImageViewInfoBuilder {
        ImageViewInfoBuilder {
            array_layer_count: Some(self.array_layer_count),
            aspect_mask: Some(self.aspect_mask),
            base_array_layer: Some(self.base_array_layer),
            base_mip_level: Some(self.base_mip_level),
            fmt: Some(self.fmt),
            mip_level_count: Some(self.mip_level_count),
            ty: Some(self.ty),
        }
    }

    /// Takes this instance and returns it with a newly specified `ImageType`.
    pub fn with_ty(mut self, ty: ImageType) -> Self {
        self.ty = ty;
        self
    }
}

impl From<ImageInfo> for ImageViewInfo {
    fn from(info: ImageInfo) -> Self {
        Self {
            array_layer_count: Some(info.array_elements),
            aspect_mask: format_aspect_mask(info.fmt),
            base_array_layer: 0,
            base_mip_level: 0,
            fmt: info.fmt,
            mip_level_count: Some(info.mip_level_count),
            ty: info.ty,
        }
    }
}

impl From<ImageViewInfoBuilder> for ImageViewInfo {
    fn from(info: ImageViewInfoBuilder) -> Self {
        info.build()
    }
}

impl ImageViewInfoBuilder {
    /// Specifies a default view with the given `fmt` and `ty` values.
    #[deprecated = "Use ImageViewInfo::new()"]
    #[doc(hidden)]
    pub fn new(fmt: vk::Format, ty: ImageType) -> Self {
        Self::default().fmt(fmt).ty(ty)
    }

    /// Builds a new 'ImageViewInfo'.
    ///
    /// # Panics
    ///
    /// If any of the following values have not been set this function will panic:
    ///
    /// * `ty`
    /// * `fmt`
    /// * `aspect_mask`
    #[inline(always)]
    pub fn build(self) -> ImageViewInfo {
        match self.fallible_build() {
            Err(ImageViewInfoBuilderError(err)) => panic!("{err}"),
            Ok(info) => info,
        }
    }
}

#[derive(Debug)]
struct ImageViewInfoBuilderError(UninitializedFieldError);

impl From<UninitializedFieldError> for ImageViewInfoBuilderError {
    fn from(err: UninitializedFieldError) -> Self {
        Self(err)
    }
}

/// Specifies sample counts supported for an image used for storage operation.
///
/// Values must not exceed the device limits specified by [Device.physical_device.props.limits].
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum SampleCount {
    /// Single image sample. This is the usual mode.
    Type1,

    /// Multiple image samples.
    Type2,

    /// Multiple image samples.
    Type4,

    /// Multiple image samples.
    Type8,

    /// Multiple image samples.
    Type16,

    /// Multiple image samples.
    Type32,

    /// Multiple image samples.
    Type64,

    /// Single image sample. This is the usual mode.
    #[deprecated = "Use Type1"]
    X1,

    /// Multiple image samples.
    #[deprecated = "Use Type2"]
    X2,

    /// Multiple image samples.
    #[deprecated = "Use Type4"]
    X4,

    /// Multiple image samples.
    #[deprecated = "Use Type8"]
    X8,

    /// Multiple image samples.
    #[deprecated = "Use Type16"]
    X16,

    /// Multiple image samples.
    #[deprecated = "Use Type32"]
    X32,

    /// Multiple image samples.
    #[deprecated = "Use Type64"]
    X64,
}

impl SampleCount {
    pub(super) fn into_vk(self) -> vk::SampleCountFlags {
        #[allow(deprecated)]
        match self {
            Self::Type1 | Self::X1 => vk::SampleCountFlags::TYPE_1,
            Self::Type2 | Self::X2 => vk::SampleCountFlags::TYPE_2,
            Self::Type4 | Self::X4 => vk::SampleCountFlags::TYPE_4,
            Self::Type8 | Self::X8 => vk::SampleCountFlags::TYPE_8,
            Self::Type16 | Self::X16 => vk::SampleCountFlags::TYPE_16,
            Self::Type32 | Self::X32 => vk::SampleCountFlags::TYPE_32,
            Self::Type64 | Self::X64 => vk::SampleCountFlags::TYPE_64,
        }
    }
}

impl Default for SampleCount {
    fn default() -> Self {
        Self::Type1
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    pub fn image_info_cube() {
        let info = ImageInfo::cube(42, vk::Format::R32_SFLOAT, vk::ImageUsageFlags::empty());
        let builder = info.to_builder().build();

        assert_eq!(info, builder);
    }

    #[test]
    pub fn image_info_cube_builder() {
        let info = ImageInfo::cube(42, vk::Format::R32_SFLOAT, vk::ImageUsageFlags::empty());
        let builder = ImageInfoBuilder::default()
            .ty(ImageType::Cube)
            .fmt(vk::Format::R32_SFLOAT)
            .width(42)
            .height(42)
            .depth(1)
            .build();

        assert_eq!(info, builder);
    }

    #[test]
    pub fn image_info_image_1d() {
        let info = ImageInfo::image_1d(42, vk::Format::R32_SFLOAT, vk::ImageUsageFlags::empty());
        let builder = info.to_builder().build();

        assert_eq!(info, builder);
    }

    #[test]
    pub fn image_info_image_1d_builder() {
        let info = ImageInfo::image_1d(42, vk::Format::R32_SFLOAT, vk::ImageUsageFlags::empty());
        let builder = ImageInfoBuilder::default()
            .ty(ImageType::Texture1D)
            .fmt(vk::Format::R32_SFLOAT)
            .width(42)
            .height(1)
            .depth(1)
            .build();

        assert_eq!(info, builder);
    }

    #[test]
    pub fn image_info_image_2d() {
        let info =
            ImageInfo::image_2d(42, 84, vk::Format::R32_SFLOAT, vk::ImageUsageFlags::empty());
        let builder = info.to_builder().build();

        assert_eq!(info, builder);
    }

    #[test]
    pub fn image_info_image_2d_builder() {
        let info =
            ImageInfo::image_2d(42, 84, vk::Format::R32_SFLOAT, vk::ImageUsageFlags::empty());
        let builder = ImageInfoBuilder::default()
            .ty(ImageType::Texture2D)
            .fmt(vk::Format::R32_SFLOAT)
            .width(42)
            .height(84)
            .depth(1)
            .build();

        assert_eq!(info, builder);
    }

    #[test]
    pub fn image_info_image_2d_array() {
        let info = ImageInfo::image_2d_array(
            42,
            84,
            100,
            vk::Format::default(),
            vk::ImageUsageFlags::empty(),
        );
        let builder = info.to_builder().build();

        assert_eq!(info, builder);
    }

    #[test]
    pub fn image_info_image_2d_array_builder() {
        let info = ImageInfo::image_2d_array(
            42,
            84,
            100,
            vk::Format::R32_SFLOAT,
            vk::ImageUsageFlags::empty(),
        );
        let builder = ImageInfoBuilder::default()
            .ty(ImageType::TextureArray2D)
            .fmt(vk::Format::R32_SFLOAT)
            .width(42)
            .height(84)
            .depth(1)
            .array_elements(100)
            .build();

        assert_eq!(info, builder);
    }

    #[test]
    pub fn image_info_image_3d() {
        let info = ImageInfo::image_3d(
            42,
            84,
            100,
            vk::Format::R32_SFLOAT,
            vk::ImageUsageFlags::empty(),
        );
        let builder = info.to_builder().build();

        assert_eq!(info, builder);
    }

    #[test]
    pub fn image_info_image_3d_builder() {
        let info = ImageInfo::image_3d(
            42,
            84,
            100,
            vk::Format::R32_SFLOAT,
            vk::ImageUsageFlags::empty(),
        );
        let builder = ImageInfoBuilder::default()
            .ty(ImageType::Texture3D)
            .fmt(vk::Format::R32_SFLOAT)
            .width(42)
            .height(84)
            .depth(100)
            .build();

        assert_eq!(info, builder);
    }

    #[test]
    #[should_panic(expected = "Field not initialized: depth")]
    pub fn image_info_builder_uninit_depth() {
        ImageInfoBuilder::default().build();
    }

    #[test]
    #[should_panic(expected = "Field not initialized: fmt")]
    pub fn image_info_builder_uninit_fmt() {
        ImageInfoBuilder::default().depth(1).build();
    }

    #[test]
    #[should_panic(expected = "Field not initialized: height")]
    pub fn image_info_builder_uninit_height() {
        ImageInfoBuilder::default()
            .depth(1)
            .fmt(vk::Format::default())
            .build();
    }

    #[test]
    #[should_panic(expected = "Field not initialized: ty")]
    pub fn image_info_builder_uninit_ty() {
        ImageInfoBuilder::default()
            .depth(1)
            .fmt(vk::Format::default())
            .height(2)
            .build();
    }

    #[test]
    #[should_panic(expected = "Field not initialized: width")]
    pub fn image_info_builder_uninit_width() {
        ImageInfoBuilder::default()
            .depth(1)
            .fmt(vk::Format::default())
            .height(2)
            .ty(ImageType::Texture2D)
            .build();
    }

    #[test]
    pub fn image_view_info() {
        let info = ImageViewInfo::new(vk::Format::default(), ImageType::Texture1D);
        let builder = info.to_builder().build();

        assert_eq!(info, builder);
    }

    #[test]
    pub fn image_view_info_builder() {
        let info = ImageViewInfo::new(vk::Format::default(), ImageType::Texture1D);
        let builder = ImageViewInfoBuilder::default()
            .fmt(vk::Format::default())
            .ty(ImageType::Texture1D)
            .aspect_mask(vk::ImageAspectFlags::COLOR)
            .build();

        assert_eq!(info, builder);
    }

    #[test]
    #[should_panic(expected = "Field not initialized: aspect_mask")]
    pub fn image_view_info_builder_uninit_aspect_mask() {
        ImageViewInfoBuilder::default().build();
    }

    #[test]
    #[should_panic(expected = "Field not initialized: fmt")]
    pub fn image_view_info_builder_unint_fmt() {
        ImageViewInfoBuilder::default()
            .aspect_mask(vk::ImageAspectFlags::empty())
            .build();
    }

    #[test]
    #[should_panic(expected = "Field not initialized: ty")]
    pub fn image_view_info_builder_unint_ty() {
        ImageViewInfoBuilder::default()
            .aspect_mask(vk::ImageAspectFlags::empty())
            .fmt(vk::Format::default())
            .build();
    }
}