logo
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
// Copyright (c) 2017 The vulkano developers
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or https://opensource.org/licenses/MIT>,
// at your option. All files in the project carrying such
// notice may not be copied, modified, or distributed except
// according to those terms.

use super::layout::{DescriptorSetLayout, DescriptorSetLayoutBinding, DescriptorType};
use crate::{
    buffer::{view::BufferViewAbstract, BufferAccess, BufferInner},
    device::DeviceOwned,
    image::{view::ImageViewType, ImageType, ImageViewAbstract},
    sampler::{Sampler, SamplerImageViewIncompatibleError},
    DeviceSize, VulkanObject,
};
use smallvec::SmallVec;
use std::{
    error::Error,
    fmt::{Display, Error as FmtError, Formatter},
    ptr,
    sync::Arc,
};

/// Represents a single write operation to the binding of a descriptor set.
///
/// `WriteDescriptorSet` specifies the binding number and target array index, and includes one or
/// more resources of a given type that need to be written to that location. Two constructors are
/// provided for each resource type:
/// - The basic constructor variant writes a single element to array index 0. It is intended for
///   non-arrayed bindings, where `descriptor_count` in the descriptor set layout is 1.
/// - The `_array` variant writes several elements and allows specifying the target array index.
///   At least one element must be provided; a panic results if the provided iterator is empty.
pub struct WriteDescriptorSet {
    binding: u32,
    first_array_element: u32,
    elements: WriteDescriptorSetElements,
}

impl WriteDescriptorSet {
    /// Write an empty element to array element 0.
    ///
    /// See `none_array` for more information.
    #[inline]
    pub fn none(binding: u32) -> Self {
        Self::none_array(binding, 0, 1)
    }

    /// Write a number of consecutive empty elements.
    ///
    /// This is used for push descriptors in combination with `Sampler` descriptors that have
    /// immutable samplers in the layout. The Vulkan spec requires these elements to be explicitly
    /// written, but since there is no data to write, a dummy write is provided instead.
    ///
    /// For regular descriptor sets, the data for such descriptors is automatically valid, and dummy
    /// writes are not allowed.
    #[inline]
    pub fn none_array(binding: u32, first_array_element: u32, num_elements: u32) -> Self {
        assert!(num_elements != 0);
        Self {
            binding,
            first_array_element,
            elements: WriteDescriptorSetElements::None(num_elements),
        }
    }

    /// Write a single buffer to array element 0.
    #[inline]
    pub fn buffer(binding: u32, buffer: Arc<dyn BufferAccess>) -> Self {
        Self::buffer_array(binding, 0, [buffer])
    }

    /// Write a number of consecutive buffer elements.
    #[inline]
    pub fn buffer_array(
        binding: u32,
        first_array_element: u32,
        elements: impl IntoIterator<Item = Arc<dyn BufferAccess>>,
    ) -> Self {
        let elements: SmallVec<_> = elements.into_iter().collect();
        assert!(!elements.is_empty());
        Self {
            binding,
            first_array_element,
            elements: WriteDescriptorSetElements::Buffer(elements),
        }
    }

    /// Write a single buffer view to array element 0.
    #[inline]
    pub fn buffer_view(binding: u32, buffer_view: Arc<dyn BufferViewAbstract>) -> Self {
        Self::buffer_view_array(binding, 0, [buffer_view])
    }

    /// Write a number of consecutive buffer view elements.
    #[inline]
    pub fn buffer_view_array(
        binding: u32,
        first_array_element: u32,
        elements: impl IntoIterator<Item = Arc<dyn BufferViewAbstract>>,
    ) -> Self {
        let elements: SmallVec<_> = elements.into_iter().collect();
        assert!(!elements.is_empty());
        Self {
            binding,
            first_array_element,
            elements: WriteDescriptorSetElements::BufferView(elements),
        }
    }

    /// Write a single image view to array element 0.
    #[inline]
    pub fn image_view(binding: u32, image_view: Arc<dyn ImageViewAbstract>) -> Self {
        Self::image_view_array(binding, 0, [image_view])
    }

    /// Write a number of consecutive image view elements.
    #[inline]
    pub fn image_view_array(
        binding: u32,
        first_array_element: u32,
        elements: impl IntoIterator<Item = Arc<dyn ImageViewAbstract>>,
    ) -> Self {
        let elements: SmallVec<_> = elements.into_iter().collect();
        assert!(!elements.is_empty());
        Self {
            binding,
            first_array_element,
            elements: WriteDescriptorSetElements::ImageView(elements),
        }
    }

    /// Write a single image view and sampler to array element 0.
    #[inline]
    pub fn image_view_sampler(
        binding: u32,
        image_view: Arc<dyn ImageViewAbstract>,
        sampler: Arc<Sampler>,
    ) -> Self {
        Self::image_view_sampler_array(binding, 0, [(image_view, sampler)])
    }

    /// Write a number of consecutive image view and sampler elements.
    #[inline]
    pub fn image_view_sampler_array(
        binding: u32,
        first_array_element: u32,
        elements: impl IntoIterator<Item = (Arc<dyn ImageViewAbstract>, Arc<Sampler>)>,
    ) -> Self {
        let elements: SmallVec<_> = elements.into_iter().collect();
        assert!(!elements.is_empty());
        Self {
            binding,
            first_array_element,
            elements: WriteDescriptorSetElements::ImageViewSampler(elements),
        }
    }

    /// Write a single sampler to array element 0.
    #[inline]
    pub fn sampler(binding: u32, sampler: Arc<Sampler>) -> Self {
        Self::sampler_array(binding, 0, [sampler])
    }

    /// Write a number of consecutive sampler elements.
    #[inline]
    pub fn sampler_array(
        binding: u32,
        first_array_element: u32,
        elements: impl IntoIterator<Item = Arc<Sampler>>,
    ) -> Self {
        let elements: SmallVec<_> = elements.into_iter().collect();
        assert!(!elements.is_empty());
        Self {
            binding,
            first_array_element,
            elements: WriteDescriptorSetElements::Sampler(elements),
        }
    }

    /// Returns the binding number that is updated by this descriptor write.
    #[inline]
    pub fn binding(&self) -> u32 {
        self.binding
    }

    /// Returns the first array element in the binding that is updated by this descriptor write.
    #[inline]
    pub fn first_array_element(&self) -> u32 {
        self.first_array_element
    }

    /// Returns a reference to the elements held by this descriptor write.
    #[inline]
    pub fn elements(&self) -> &WriteDescriptorSetElements {
        &self.elements
    }

    pub(crate) fn to_vulkan_info(&self, descriptor_type: DescriptorType) -> DescriptorWriteInfo {
        match &self.elements {
            WriteDescriptorSetElements::None(num_elements) => {
                debug_assert!(matches!(descriptor_type, DescriptorType::Sampler));
                DescriptorWriteInfo::Image(
                    std::iter::repeat_with(|| ash::vk::DescriptorImageInfo {
                        sampler: ash::vk::Sampler::null(),
                        image_view: ash::vk::ImageView::null(),
                        image_layout: ash::vk::ImageLayout::UNDEFINED,
                    })
                    .take(*num_elements as usize)
                    .collect(),
                )
            }
            WriteDescriptorSetElements::Buffer(elements) => {
                debug_assert!(matches!(
                    descriptor_type,
                    DescriptorType::UniformBuffer
                        | DescriptorType::StorageBuffer
                        | DescriptorType::UniformBufferDynamic
                        | DescriptorType::StorageBufferDynamic
                ));
                DescriptorWriteInfo::Buffer(
                    elements
                        .iter()
                        .map(|buffer| {
                            let size = buffer.size();
                            let BufferInner { buffer, offset } = buffer.inner();

                            debug_assert_eq!(
                                offset
                                    % buffer
                                        .device()
                                        .physical_device()
                                        .properties()
                                        .min_storage_buffer_offset_alignment,
                                0
                            );
                            debug_assert!(
                                size <= buffer
                                    .device()
                                    .physical_device()
                                    .properties()
                                    .max_storage_buffer_range
                                    as DeviceSize
                            );
                            ash::vk::DescriptorBufferInfo {
                                buffer: buffer.internal_object(),
                                offset,
                                range: size,
                            }
                        })
                        .collect(),
                )
            }
            WriteDescriptorSetElements::BufferView(elements) => {
                debug_assert!(matches!(
                    descriptor_type,
                    DescriptorType::UniformTexelBuffer | DescriptorType::StorageTexelBuffer
                ));
                DescriptorWriteInfo::BufferView(
                    elements
                        .iter()
                        .map(|buffer_view| buffer_view.internal_object())
                        .collect(),
                )
            }
            WriteDescriptorSetElements::ImageView(elements) => {
                // Note: combined image sampler can occur with immutable samplers
                debug_assert!(matches!(
                    descriptor_type,
                    DescriptorType::CombinedImageSampler
                        | DescriptorType::SampledImage
                        | DescriptorType::StorageImage
                        | DescriptorType::InputAttachment
                ));
                DescriptorWriteInfo::Image(
                    elements
                        .iter()
                        .map(|image_view| {
                            let layouts = image_view.image().descriptor_layouts().expect(
                                "descriptor_layouts must return Some when used in an image view",
                            );
                            ash::vk::DescriptorImageInfo {
                                sampler: ash::vk::Sampler::null(),
                                image_view: image_view.internal_object(),
                                image_layout: layouts.layout_for(descriptor_type).into(),
                            }
                        })
                        .collect(),
                )
            }
            WriteDescriptorSetElements::ImageViewSampler(elements) => {
                debug_assert!(matches!(
                    descriptor_type,
                    DescriptorType::CombinedImageSampler
                ));
                DescriptorWriteInfo::Image(
                    elements
                        .iter()
                        .map(|(image_view, sampler)| {
                            let layouts = image_view.image().descriptor_layouts().expect(
                                "descriptor_layouts must return Some when used in an image view",
                            );
                            ash::vk::DescriptorImageInfo {
                                sampler: sampler.internal_object(),
                                image_view: image_view.internal_object(),
                                image_layout: layouts.layout_for(descriptor_type).into(),
                            }
                        })
                        .collect(),
                )
            }
            WriteDescriptorSetElements::Sampler(elements) => {
                debug_assert!(matches!(descriptor_type, DescriptorType::Sampler));
                DescriptorWriteInfo::Image(
                    elements
                        .iter()
                        .map(|sampler| ash::vk::DescriptorImageInfo {
                            sampler: sampler.internal_object(),
                            image_view: ash::vk::ImageView::null(),
                            image_layout: ash::vk::ImageLayout::UNDEFINED,
                        })
                        .collect(),
                )
            }
        }
    }

    pub(crate) fn to_vulkan(
        &self,
        dst_set: ash::vk::DescriptorSet,
        descriptor_type: DescriptorType,
    ) -> ash::vk::WriteDescriptorSet {
        ash::vk::WriteDescriptorSet {
            dst_set,
            dst_binding: self.binding,
            dst_array_element: self.first_array_element,
            descriptor_count: 0,
            descriptor_type: descriptor_type.into(),
            p_image_info: ptr::null(),
            p_buffer_info: ptr::null(),
            p_texel_buffer_view: ptr::null(),
            ..Default::default()
        }
    }
}

/// The elements held by a `WriteDescriptorSet`.
pub enum WriteDescriptorSetElements {
    None(u32),
    Buffer(SmallVec<[Arc<dyn BufferAccess>; 1]>),
    BufferView(SmallVec<[Arc<dyn BufferViewAbstract>; 1]>),
    ImageView(SmallVec<[Arc<dyn ImageViewAbstract>; 1]>),
    ImageViewSampler(SmallVec<[(Arc<dyn ImageViewAbstract>, Arc<Sampler>); 1]>),
    Sampler(SmallVec<[Arc<Sampler>; 1]>),
}

impl WriteDescriptorSetElements {
    /// Returns the number of elements.
    #[inline]
    pub fn len(&self) -> u32 {
        match self {
            Self::None(num_elements) => *num_elements,
            Self::Buffer(elements) => elements.len() as u32,
            Self::BufferView(elements) => elements.len() as u32,
            Self::ImageView(elements) => elements.len() as u32,
            Self::ImageViewSampler(elements) => elements.len() as u32,
            Self::Sampler(elements) => elements.len() as u32,
        }
    }
}

#[derive(Clone, Debug)]
pub(crate) enum DescriptorWriteInfo {
    Image(SmallVec<[ash::vk::DescriptorImageInfo; 1]>),
    Buffer(SmallVec<[ash::vk::DescriptorBufferInfo; 1]>),
    BufferView(SmallVec<[ash::vk::BufferView; 1]>),
}

pub(crate) fn check_descriptor_write<'a>(
    write: &WriteDescriptorSet,
    layout: &'a DescriptorSetLayout,
    variable_descriptor_count: u32,
) -> Result<&'a DescriptorSetLayoutBinding, DescriptorSetUpdateError> {
    let layout_binding = match layout.bindings().get(&write.binding()) {
        Some(binding) => binding,
        None => {
            return Err(DescriptorSetUpdateError::InvalidBinding {
                binding: write.binding(),
            })
        }
    };

    let max_descriptor_count = if layout_binding.variable_descriptor_count {
        variable_descriptor_count
    } else {
        layout_binding.descriptor_count
    };

    let elements = write.elements();
    let num_elements = elements.len();
    debug_assert!(num_elements != 0);

    let descriptor_range_start = write.first_array_element();
    let descriptor_range_end = descriptor_range_start + num_elements;

    if descriptor_range_end > max_descriptor_count {
        return Err(DescriptorSetUpdateError::ArrayIndexOutOfBounds {
            binding: write.binding(),
            available_count: max_descriptor_count,
            written_count: descriptor_range_end,
        });
    }

    match elements {
        WriteDescriptorSetElements::None(_num_elements) => match layout_binding.descriptor_type {
            DescriptorType::Sampler
                if layout.push_descriptor() && !layout_binding.immutable_samplers.is_empty() => {}
            _ => {
                return Err(DescriptorSetUpdateError::IncompatibleDescriptorType {
                    binding: write.binding(),
                })
            }
        },
        WriteDescriptorSetElements::Buffer(elements) => {
            match layout_binding.descriptor_type {
                DescriptorType::StorageBuffer | DescriptorType::StorageBufferDynamic => {
                    for (index, buffer) in elements.iter().enumerate() {
                        assert_eq!(
                            buffer.device().internal_object(),
                            layout.device().internal_object(),
                        );

                        if !buffer.inner().buffer.usage().storage_buffer {
                            return Err(DescriptorSetUpdateError::MissingUsage {
                                binding: write.binding(),
                                index: descriptor_range_start + index as u32,
                                usage: "storage_buffer",
                            });
                        }
                    }
                }
                DescriptorType::UniformBuffer | DescriptorType::UniformBufferDynamic => {
                    for (index, buffer) in elements.iter().enumerate() {
                        assert_eq!(
                            buffer.device().internal_object(),
                            layout.device().internal_object(),
                        );

                        if !buffer.inner().buffer.usage().uniform_buffer {
                            return Err(DescriptorSetUpdateError::MissingUsage {
                                binding: write.binding(),
                                index: descriptor_range_start + index as u32,
                                usage: "uniform_buffer",
                            });
                        }
                    }
                }
                _ => {
                    return Err(DescriptorSetUpdateError::IncompatibleDescriptorType {
                        binding: write.binding(),
                    })
                }
            }

            // Note that the buffer content is not checked. This is technically not unsafe as
            // long as the data in the buffer has no invalid memory representation (ie. no
            // bool, no enum, no pointer, no str) and as long as the robust buffer access
            // feature is enabled.
            // TODO: this is not checked ^

            // TODO: eventually shouldn't be an assert ; for now robust_buffer_access is always
            //       enabled so this assert should never fail in practice, but we put it anyway
            //       in case we forget to adjust this code
            assert!(layout.device().enabled_features().robust_buffer_access);
        }
        WriteDescriptorSetElements::BufferView(elements) => {
            match layout_binding.descriptor_type {
                DescriptorType::StorageTexelBuffer => {
                    for (index, buffer_view) in elements.iter().enumerate() {
                        assert_eq!(
                            buffer_view.device().internal_object(),
                            layout.device().internal_object(),
                        );

                        // TODO: storage_texel_buffer_atomic
                        if !buffer_view
                            .buffer()
                            .inner()
                            .buffer
                            .usage()
                            .storage_texel_buffer
                        {
                            return Err(DescriptorSetUpdateError::MissingUsage {
                                binding: write.binding(),
                                index: descriptor_range_start + index as u32,
                                usage: "storage_texel_buffer",
                            });
                        }
                    }
                }
                DescriptorType::UniformTexelBuffer => {
                    for (index, buffer_view) in elements.iter().enumerate() {
                        assert_eq!(
                            buffer_view.device().internal_object(),
                            layout.device().internal_object(),
                        );

                        if !buffer_view
                            .buffer()
                            .inner()
                            .buffer
                            .usage()
                            .uniform_texel_buffer
                        {
                            return Err(DescriptorSetUpdateError::MissingUsage {
                                binding: write.binding(),
                                index: descriptor_range_start + index as u32,
                                usage: "uniform_texel_buffer",
                            });
                        }
                    }
                }
                _ => {
                    return Err(DescriptorSetUpdateError::IncompatibleDescriptorType {
                        binding: write.binding(),
                    })
                }
            }
        }
        WriteDescriptorSetElements::ImageView(elements) => match layout_binding.descriptor_type {
            DescriptorType::CombinedImageSampler
                if !layout_binding.immutable_samplers.is_empty() =>
            {
                let immutable_samplers = &layout_binding.immutable_samplers
                    [descriptor_range_start as usize..descriptor_range_end as usize];

                for (index, (image_view, sampler)) in
                    elements.iter().zip(immutable_samplers).enumerate()
                {
                    assert_eq!(
                        image_view.device().internal_object(),
                        layout.device().internal_object(),
                    );

                    // VUID-VkWriteDescriptorSet-descriptorType-00337
                    if !image_view.usage().sampled {
                        return Err(DescriptorSetUpdateError::MissingUsage {
                            binding: write.binding(),
                            index: descriptor_range_start + index as u32,
                            usage: "sampled",
                        });
                    }

                    // VUID-VkDescriptorImageInfo-imageView-00343
                    if matches!(
                        image_view.view_type(),
                        ImageViewType::Dim2d | ImageViewType::Dim2dArray
                    ) && image_view.image().inner().image.dimensions().image_type()
                        == ImageType::Dim3d
                    {
                        return Err(DescriptorSetUpdateError::ImageView2dFrom3d {
                            binding: write.binding(),
                            index: descriptor_range_start + index as u32,
                        });
                    }

                    // VUID-VkDescriptorImageInfo-imageView-01976
                    if image_view.subresource_range().aspects.depth
                        && image_view.subresource_range().aspects.stencil
                    {
                        return Err(DescriptorSetUpdateError::ImageViewDepthAndStencil {
                            binding: write.binding(),
                            index: descriptor_range_start + index as u32,
                        });
                    }

                    if let Err(error) = sampler.check_can_sample(image_view.as_ref()) {
                        return Err(DescriptorSetUpdateError::ImageViewIncompatibleSampler {
                            binding: write.binding(),
                            index: descriptor_range_start + index as u32,
                            error,
                        });
                    }
                }
            }
            DescriptorType::SampledImage => {
                for (index, image_view) in elements.iter().enumerate() {
                    assert_eq!(
                        image_view.device().internal_object(),
                        layout.device().internal_object(),
                    );

                    // VUID-VkWriteDescriptorSet-descriptorType-00337
                    if !image_view.usage().sampled {
                        return Err(DescriptorSetUpdateError::MissingUsage {
                            binding: write.binding(),
                            index: descriptor_range_start + index as u32,
                            usage: "sampled",
                        });
                    }

                    // VUID-VkDescriptorImageInfo-imageView-00343
                    if matches!(
                        image_view.view_type(),
                        ImageViewType::Dim2d | ImageViewType::Dim2dArray
                    ) && image_view.image().inner().image.dimensions().image_type()
                        == ImageType::Dim3d
                    {
                        return Err(DescriptorSetUpdateError::ImageView2dFrom3d {
                            binding: write.binding(),
                            index: descriptor_range_start + index as u32,
                        });
                    }

                    // VUID-VkDescriptorImageInfo-imageView-01976
                    if image_view.subresource_range().aspects.depth
                        && image_view.subresource_range().aspects.stencil
                    {
                        return Err(DescriptorSetUpdateError::ImageViewDepthAndStencil {
                            binding: write.binding(),
                            index: descriptor_range_start + index as u32,
                        });
                    }

                    // VUID-VkWriteDescriptorSet-descriptorType-01946
                    if image_view.sampler_ycbcr_conversion().is_some() {
                        return Err(
                            DescriptorSetUpdateError::ImageViewHasSamplerYcbcrConversion {
                                binding: write.binding(),
                                index: descriptor_range_start + index as u32,
                            },
                        );
                    }
                }
            }
            DescriptorType::StorageImage => {
                for (index, image_view) in elements.iter().enumerate() {
                    assert_eq!(
                        image_view.device().internal_object(),
                        layout.device().internal_object(),
                    );

                    // VUID-VkWriteDescriptorSet-descriptorType-00339
                    if !image_view.usage().storage {
                        return Err(DescriptorSetUpdateError::MissingUsage {
                            binding: write.binding(),
                            index: descriptor_range_start + index as u32,
                            usage: "storage",
                        });
                    }

                    // VUID-VkDescriptorImageInfo-imageView-00343
                    if matches!(
                        image_view.view_type(),
                        ImageViewType::Dim2d | ImageViewType::Dim2dArray
                    ) && image_view.image().inner().image.dimensions().image_type()
                        == ImageType::Dim3d
                    {
                        return Err(DescriptorSetUpdateError::ImageView2dFrom3d {
                            binding: write.binding(),
                            index: descriptor_range_start + index as u32,
                        });
                    }

                    // VUID-VkDescriptorImageInfo-imageView-01976
                    if image_view.subresource_range().aspects.depth
                        && image_view.subresource_range().aspects.stencil
                    {
                        return Err(DescriptorSetUpdateError::ImageViewDepthAndStencil {
                            binding: write.binding(),
                            index: descriptor_range_start + index as u32,
                        });
                    }

                    // VUID-VkWriteDescriptorSet-descriptorType-00336
                    if !image_view.component_mapping().is_identity() {
                        return Err(DescriptorSetUpdateError::ImageViewNotIdentitySwizzled {
                            binding: write.binding(),
                            index: descriptor_range_start + index as u32,
                        });
                    }

                    // VUID??
                    if image_view.sampler_ycbcr_conversion().is_some() {
                        return Err(
                            DescriptorSetUpdateError::ImageViewHasSamplerYcbcrConversion {
                                binding: write.binding(),
                                index: descriptor_range_start + index as u32,
                            },
                        );
                    }
                }
            }
            DescriptorType::InputAttachment => {
                for (index, image_view) in elements.iter().enumerate() {
                    assert_eq!(
                        image_view.device().internal_object(),
                        layout.device().internal_object(),
                    );

                    // VUID-VkWriteDescriptorSet-descriptorType-00338
                    if !image_view.usage().input_attachment {
                        return Err(DescriptorSetUpdateError::MissingUsage {
                            binding: write.binding(),
                            index: descriptor_range_start + index as u32,
                            usage: "input_attachment",
                        });
                    }

                    // VUID-VkDescriptorImageInfo-imageView-00343
                    if matches!(
                        image_view.view_type(),
                        ImageViewType::Dim2d | ImageViewType::Dim2dArray
                    ) && image_view.image().inner().image.dimensions().image_type()
                        == ImageType::Dim3d
                    {
                        return Err(DescriptorSetUpdateError::ImageView2dFrom3d {
                            binding: write.binding(),
                            index: descriptor_range_start + index as u32,
                        });
                    }

                    // VUID-VkDescriptorImageInfo-imageView-01976
                    if image_view.subresource_range().aspects.depth
                        && image_view.subresource_range().aspects.stencil
                    {
                        return Err(DescriptorSetUpdateError::ImageViewDepthAndStencil {
                            binding: write.binding(),
                            index: descriptor_range_start + index as u32,
                        });
                    }

                    // VUID-VkWriteDescriptorSet-descriptorType-00336
                    if !image_view.component_mapping().is_identity() {
                        return Err(DescriptorSetUpdateError::ImageViewNotIdentitySwizzled {
                            binding: write.binding(),
                            index: descriptor_range_start + index as u32,
                        });
                    }

                    // VUID??
                    if image_view.sampler_ycbcr_conversion().is_some() {
                        return Err(
                            DescriptorSetUpdateError::ImageViewHasSamplerYcbcrConversion {
                                binding: write.binding(),
                                index: descriptor_range_start + index as u32,
                            },
                        );
                    }

                    // VUID??
                    if image_view.view_type().is_arrayed() {
                        return Err(DescriptorSetUpdateError::ImageViewIsArrayed {
                            binding: write.binding(),
                            index: descriptor_range_start + index as u32,
                        });
                    }
                }
            }
            _ => {
                return Err(DescriptorSetUpdateError::IncompatibleDescriptorType {
                    binding: write.binding(),
                })
            }
        },
        WriteDescriptorSetElements::ImageViewSampler(elements) => match layout_binding
            .descriptor_type
        {
            DescriptorType::CombinedImageSampler => {
                if !layout_binding.immutable_samplers.is_empty() {
                    return Err(DescriptorSetUpdateError::SamplerIsImmutable {
                        binding: write.binding(),
                    });
                }

                for (index, (image_view, sampler)) in elements.iter().enumerate() {
                    assert_eq!(
                        image_view.device().internal_object(),
                        layout.device().internal_object(),
                    );
                    assert_eq!(
                        sampler.device().internal_object(),
                        layout.device().internal_object(),
                    );

                    // VUID-VkWriteDescriptorSet-descriptorType-00337
                    if !image_view.usage().sampled {
                        return Err(DescriptorSetUpdateError::MissingUsage {
                            binding: write.binding(),
                            index: descriptor_range_start + index as u32,
                            usage: "sampled",
                        });
                    }

                    // VUID-VkDescriptorImageInfo-imageView-00343
                    if matches!(
                        image_view.view_type(),
                        ImageViewType::Dim2d | ImageViewType::Dim2dArray
                    ) && image_view.image().inner().image.dimensions().image_type()
                        == ImageType::Dim3d
                    {
                        return Err(DescriptorSetUpdateError::ImageView2dFrom3d {
                            binding: write.binding(),
                            index: descriptor_range_start + index as u32,
                        });
                    }

                    // VUID-VkDescriptorImageInfo-imageView-01976
                    if image_view.subresource_range().aspects.depth
                        && image_view.subresource_range().aspects.stencil
                    {
                        return Err(DescriptorSetUpdateError::ImageViewDepthAndStencil {
                            binding: write.binding(),
                            index: descriptor_range_start + index as u32,
                        });
                    }

                    if image_view.sampler_ycbcr_conversion().is_some() {
                        return Err(
                            DescriptorSetUpdateError::ImageViewHasSamplerYcbcrConversion {
                                binding: write.binding(),
                                index: descriptor_range_start + index as u32,
                            },
                        );
                    }

                    if sampler.sampler_ycbcr_conversion().is_some() {
                        return Err(DescriptorSetUpdateError::SamplerHasSamplerYcbcrConversion {
                            binding: write.binding(),
                            index: descriptor_range_start + index as u32,
                        });
                    }

                    if let Err(error) = sampler.check_can_sample(image_view.as_ref()) {
                        return Err(DescriptorSetUpdateError::ImageViewIncompatibleSampler {
                            binding: write.binding(),
                            index: descriptor_range_start + index as u32,
                            error,
                        });
                    }
                }
            }
            _ => {
                return Err(DescriptorSetUpdateError::IncompatibleDescriptorType {
                    binding: write.binding(),
                })
            }
        },
        WriteDescriptorSetElements::Sampler(elements) => match layout_binding.descriptor_type {
            DescriptorType::Sampler => {
                if !layout_binding.immutable_samplers.is_empty() {
                    return Err(DescriptorSetUpdateError::SamplerIsImmutable {
                        binding: write.binding(),
                    });
                }

                for (index, sampler) in elements.iter().enumerate() {
                    assert_eq!(
                        sampler.device().internal_object(),
                        layout.device().internal_object(),
                    );

                    if sampler.sampler_ycbcr_conversion().is_some() {
                        return Err(DescriptorSetUpdateError::SamplerHasSamplerYcbcrConversion {
                            binding: write.binding(),
                            index: descriptor_range_start + index as u32,
                        });
                    }
                }
            }
            _ => {
                return Err(DescriptorSetUpdateError::IncompatibleDescriptorType {
                    binding: write.binding(),
                })
            }
        },
    }

    Ok(layout_binding)
}

#[derive(Clone, Copy, Debug)]
pub enum DescriptorSetUpdateError {
    /// Tried to write more elements than were available in a binding.
    ArrayIndexOutOfBounds {
        /// Binding that is affected.
        binding: u32,
        /// Number of available descriptors in the binding.
        available_count: u32,
        /// The number of descriptors that were in the update.
        written_count: u32,
    },

    /// Tried to write an image view with a 2D type and a 3D underlying image.
    ImageView2dFrom3d { binding: u32, index: u32 },

    /// Tried to write an image view that has both the `depth` and `stencil` aspects.
    ImageViewDepthAndStencil { binding: u32, index: u32 },

    /// Tried to write an image view with an attached sampler YCbCr conversion to a binding that
    /// does not support it.
    ImageViewHasSamplerYcbcrConversion { binding: u32, index: u32 },

    /// Tried to write an image view of an arrayed type to a descriptor type that does not support
    /// it.
    ImageViewIsArrayed { binding: u32, index: u32 },

    /// Tried to write an image view that was not compatible with the sampler that was provided as
    /// part of the update or immutably in the layout.
    ImageViewIncompatibleSampler {
        binding: u32,
        index: u32,
        error: SamplerImageViewIncompatibleError,
    },

    /// Tried to write an image view to a descriptor type that requires it to be identity swizzled,
    /// but it was not.
    ImageViewNotIdentitySwizzled { binding: u32, index: u32 },

    /// Tried to write an element type that was not compatible with the descriptor type in the
    /// layout.
    IncompatibleDescriptorType { binding: u32 },

    /// Tried to write to a nonexistent binding.
    InvalidBinding { binding: u32 },

    /// A resource was missing a usage flag that was required.
    MissingUsage {
        binding: u32,
        index: u32,
        usage: &'static str,
    },

    /// Tried to write a sampler that has an attached sampler YCbCr conversion.
    SamplerHasSamplerYcbcrConversion { binding: u32, index: u32 },

    /// Tried to write a sampler to a binding with immutable samplers.
    SamplerIsImmutable { binding: u32 },
}

impl Error for DescriptorSetUpdateError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::ImageViewIncompatibleSampler { error, .. } => Some(error),
            _ => None,
        }
    }
}

impl Display for DescriptorSetUpdateError {
    #[inline]
    fn fmt(&self, f: &mut Formatter) -> Result<(), FmtError> {
        match self {
            Self::ArrayIndexOutOfBounds {
                binding,
                available_count,
                written_count,
            } => write!(
                f,
                "tried to write up to element {} to binding {}, but only {} descriptors are available",
                written_count, binding, available_count,
            ),
            Self::ImageView2dFrom3d { binding, index } => write!(
                f,
                "tried to write an image view to binding {} index {} with a 2D type and a 3D underlying image",
                binding, index,
            ),
            Self::ImageViewDepthAndStencil { binding, index } => write!(
                f,
                "tried to write an image view to binding {} index {} that has both the `depth` and `stencil` aspects",
                binding, index,
            ),
            Self::ImageViewHasSamplerYcbcrConversion { binding, index } => write!(
                f,
                "tried to write an image view to binding {} index {} with an attached sampler YCbCr conversion to binding that does not support it",
                binding, index,
            ),
            Self::ImageViewIsArrayed { binding, index } => write!(
                f,
                "tried to write an image view of an arrayed type to binding {} index {}, but this binding has a descriptor type that does not support arrayed image views",
                binding, index,
            ),
            Self::ImageViewIncompatibleSampler { binding, index, .. } => write!(
                f,
                "tried to write an image view to binding {} index {}, that was not compatible with the sampler that was provided as part of the update or immutably in the layout",
                binding, index,
            ),
            Self::ImageViewNotIdentitySwizzled { binding, index } => write!(
                f,
                "tried to write an image view with non-identity swizzling to binding {} index {}, but this binding has a descriptor type that requires it to be identity swizzled",
                binding, index,
            ),
            Self::IncompatibleDescriptorType { binding } => write!(
                f,
                "tried to write a resource to binding {} whose type was not compatible with the descriptor type",
                binding,
            ),
            Self::InvalidBinding { binding } => write!(
                f,
                "tried to write to a nonexistent binding {}",
                binding,
            ),
            Self::MissingUsage {
                binding,
                index,
                usage,
            } => write!(
                f,
                "tried to write a resource to binding {} index {} that did not have the required usage {} enabled",
                binding, index, usage,
            ),
            Self::SamplerHasSamplerYcbcrConversion { binding, index } => write!(
                f,
                "tried to write a sampler to binding {} index {} that has an attached sampler YCbCr conversion",
                binding, index,
            ),
            Self::SamplerIsImmutable { binding } => write!(
                f,
                "tried to write a sampler to binding {}, which already contains immutable samplers in the descriptor set layout",
                binding,
            ),
        }
    }
}