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
// Copyright (c) 2021 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 crate::{
    descriptor_set::{
        layout::{DescriptorSetLayout, DescriptorSetLayoutCreateFlags, DescriptorType},
        sys::UnsafeDescriptorSet,
    },
    device::{Device, DeviceOwned, DeviceOwnedDebugWrapper},
    instance::InstanceOwnedDebugWrapper,
    macros::{impl_id_counter, vulkan_bitflags},
    Requires, RequiresAllOf, RequiresOneOf, Validated, ValidationError, Version, VulkanError,
    VulkanObject,
};
use ahash::HashMap;
use smallvec::SmallVec;
use std::{cell::Cell, marker::PhantomData, mem::MaybeUninit, num::NonZeroU64, ptr, sync::Arc};

/// Pool that descriptors are allocated from.
///
/// A pool has a maximum number of descriptor sets and a maximum number of descriptors (one value
/// per descriptor type) it can allocate.
#[derive(Debug)]
pub struct DescriptorPool {
    handle: ash::vk::DescriptorPool,
    device: InstanceOwnedDebugWrapper<Arc<Device>>,
    id: NonZeroU64,

    flags: DescriptorPoolCreateFlags,
    max_sets: u32,
    pool_sizes: HashMap<DescriptorType, u32>,
    max_inline_uniform_block_bindings: u32,

    // Unimplement `Sync`, as Vulkan descriptor pools are not thread safe.
    _marker: PhantomData<Cell<ash::vk::DescriptorPool>>,
}

impl DescriptorPool {
    /// Creates a new `DescriptorPool`.
    #[inline]
    pub fn new(
        device: Arc<Device>,
        create_info: DescriptorPoolCreateInfo,
    ) -> Result<DescriptorPool, Validated<VulkanError>> {
        Self::validate_new(&device, &create_info)?;

        unsafe { Ok(Self::new_unchecked(device, create_info)?) }
    }

    fn validate_new(
        device: &Device,
        create_info: &DescriptorPoolCreateInfo,
    ) -> Result<(), Box<ValidationError>> {
        // VUID-vkCreateDescriptorPool-pCreateInfo-parameter
        create_info
            .validate(device)
            .map_err(|err| err.add_context("create_info"))?;

        Ok(())
    }

    #[cfg_attr(not(feature = "document_unchecked"), doc(hidden))]
    pub unsafe fn new_unchecked(
        device: Arc<Device>,
        create_info: DescriptorPoolCreateInfo,
    ) -> Result<DescriptorPool, VulkanError> {
        let &DescriptorPoolCreateInfo {
            flags,
            max_sets,
            ref pool_sizes,
            max_inline_uniform_block_bindings,
            _ne: _,
        } = &create_info;

        let pool_sizes_vk: SmallVec<[_; 8]> = pool_sizes
            .iter()
            .map(|(&ty, &descriptor_count)| ash::vk::DescriptorPoolSize {
                ty: ty.into(),
                descriptor_count,
            })
            .collect();

        let mut create_info_vk = ash::vk::DescriptorPoolCreateInfo {
            flags: flags.into(),
            max_sets,
            pool_size_count: pool_sizes_vk.len() as u32,
            p_pool_sizes: pool_sizes_vk.as_ptr(),
            ..Default::default()
        };

        let mut inline_uniform_block_create_info_vk = None;

        if max_inline_uniform_block_bindings != 0 {
            let next = inline_uniform_block_create_info_vk.insert(
                ash::vk::DescriptorPoolInlineUniformBlockCreateInfo {
                    max_inline_uniform_block_bindings,
                    ..Default::default()
                },
            );

            next.p_next = create_info_vk.p_next;
            create_info_vk.p_next = next as *const _ as *const _;
        }

        let handle = unsafe {
            let fns = device.fns();
            let mut output = MaybeUninit::uninit();
            (fns.v1_0.create_descriptor_pool)(
                device.handle(),
                &create_info_vk,
                ptr::null(),
                output.as_mut_ptr(),
            )
            .result()
            .map_err(VulkanError::from)?;
            output.assume_init()
        };

        unsafe { Ok(Self::from_handle(device, handle, create_info)) }
    }

    /// Creates a new `DescriptorPool` from a raw object handle.
    ///
    /// # Safety
    ///
    /// - `handle` must be a valid Vulkan object handle created from `device`.
    /// - `create_info` must match the info used to create the object.
    #[inline]
    pub unsafe fn from_handle(
        device: Arc<Device>,
        handle: ash::vk::DescriptorPool,
        create_info: DescriptorPoolCreateInfo,
    ) -> DescriptorPool {
        let DescriptorPoolCreateInfo {
            flags,
            max_sets,
            pool_sizes,
            max_inline_uniform_block_bindings,
            _ne: _,
        } = create_info;

        DescriptorPool {
            handle,
            device: InstanceOwnedDebugWrapper(device),
            id: Self::next_id(),

            flags,
            max_sets,
            pool_sizes,
            max_inline_uniform_block_bindings,

            _marker: PhantomData,
        }
    }

    /// Returns the flags that the descriptor pool was created with.
    #[inline]
    pub fn flags(&self) -> DescriptorPoolCreateFlags {
        self.flags
    }

    /// Returns the maximum number of sets that can be allocated from the pool.
    #[inline]
    pub fn max_sets(&self) -> u32 {
        self.max_sets
    }

    /// Returns the number of descriptors of each type that the pool was created with.
    #[inline]
    pub fn pool_sizes(&self) -> &HashMap<DescriptorType, u32> {
        &self.pool_sizes
    }

    /// Returns the maximum number of [`DescriptorType::InlineUniformBlock`] bindings that can
    /// be allocated from the descriptor pool.
    #[inline]
    pub fn max_inline_uniform_block_bindings(&self) -> u32 {
        self.max_inline_uniform_block_bindings
    }

    /// Allocates descriptor sets from the pool, one for each element in `allocate_info`.
    /// Returns an iterator to the allocated sets, or an error.
    ///
    /// The `FragmentedPool` errors often can't be prevented. If the function returns this error,
    /// you should just create a new pool.
    ///
    /// # Safety
    ///
    /// - When the pool is dropped, the returned descriptor sets must not be in use by either
    ///   the host or device.
    /// - If the device API version is less than 1.1, and the [`khr_maintenance1`] extension is not
    ///   enabled on the device, then
    ///   the length of `allocate_infos` must not be greater than the number of descriptor sets
    ///   remaining in the pool, and
    ///   the total number of descriptors of each type being allocated must not be greater than the
    ///   number of descriptors of that type remaining in the pool.
    ///
    /// [`khr_maintenance1`]: crate::device::DeviceExtensions::khr_maintenance1
    #[inline]
    pub unsafe fn allocate_descriptor_sets(
        &self,
        allocate_infos: impl IntoIterator<Item = DescriptorSetAllocateInfo>,
    ) -> Result<impl ExactSizeIterator<Item = DescriptorPoolAlloc>, Validated<VulkanError>> {
        let allocate_infos: SmallVec<[_; 1]> = allocate_infos.into_iter().collect();
        self.validate_allocate_descriptor_sets(&allocate_infos)?;

        Ok(self.allocate_descriptor_sets_unchecked(allocate_infos)?)
    }

    fn validate_allocate_descriptor_sets(
        &self,
        allocate_infos: &[DescriptorSetAllocateInfo],
    ) -> Result<(), Box<ValidationError>> {
        for (index, info) in allocate_infos.iter().enumerate() {
            info.validate(self.device())
                .map_err(|err| err.add_context(format!("allocate_infos[{}]", index)))?;

            let &DescriptorSetAllocateInfo {
                ref layout,
                variable_descriptor_count: _,
                _ne: _,
            } = info;

            if layout
                .flags()
                .intersects(DescriptorSetLayoutCreateFlags::UPDATE_AFTER_BIND_POOL)
                && !self
                    .flags
                    .intersects(DescriptorPoolCreateFlags::UPDATE_AFTER_BIND)
            {
                return Err(Box::new(ValidationError {
                    problem: format!(
                        "`allocate_infos[{}].layout.flags()` contains \
                        `DescriptorSetLayoutCreateFlags::UPDATE_AFTER_BIND_POOL`, but \
                        `self.flags` does not contain \
                        `DescriptorPoolCreateFlags::UPDATE_AFTER_BIND`",
                        index
                    )
                    .into(),
                    vuids: &["VUID-VkDescriptorSetAllocateInfo-pSetLayouts-03044"],
                    ..Default::default()
                }));
            }
        }

        Ok(())
    }

    #[cfg_attr(not(feature = "document_unchecked"), doc(hidden))]
    pub unsafe fn allocate_descriptor_sets_unchecked(
        &self,
        allocate_infos: impl IntoIterator<Item = DescriptorSetAllocateInfo>,
    ) -> Result<impl ExactSizeIterator<Item = DescriptorPoolAlloc>, VulkanError> {
        let allocate_infos = allocate_infos.into_iter();

        let (lower_size_bound, _) = allocate_infos.size_hint();
        let mut layouts_vk = Vec::with_capacity(lower_size_bound);
        let mut variable_descriptor_counts = Vec::with_capacity(lower_size_bound);
        let mut layouts = Vec::with_capacity(lower_size_bound);

        for info in allocate_infos {
            let DescriptorSetAllocateInfo {
                layout,
                variable_descriptor_count,
                _ne: _,
            } = info;

            layouts_vk.push(layout.handle());
            variable_descriptor_counts.push(variable_descriptor_count);
            layouts.push(layout);
        }

        let mut output = vec![];

        if !layouts_vk.is_empty() {
            let variable_desc_count_alloc_info = if (self.device.api_version() >= Version::V1_2
                || self.device.enabled_extensions().ext_descriptor_indexing)
                && variable_descriptor_counts.iter().any(|c| *c != 0)
            {
                Some(ash::vk::DescriptorSetVariableDescriptorCountAllocateInfo {
                    descriptor_set_count: layouts_vk.len() as u32,
                    p_descriptor_counts: variable_descriptor_counts.as_ptr(),
                    ..Default::default()
                })
            } else {
                None
            };

            let info_vk = ash::vk::DescriptorSetAllocateInfo {
                descriptor_pool: self.handle,
                descriptor_set_count: layouts_vk.len() as u32,
                p_set_layouts: layouts_vk.as_ptr(),
                p_next: if let Some(next) = variable_desc_count_alloc_info.as_ref() {
                    next as *const _ as *const _
                } else {
                    ptr::null()
                },
                ..Default::default()
            };

            output.reserve(layouts_vk.len());

            let fns = self.device.fns();
            (fns.v1_0.allocate_descriptor_sets)(
                self.device.handle(),
                &info_vk,
                output.as_mut_ptr(),
            )
            .result()
            .map_err(VulkanError::from)
            .map_err(|err| match err {
                VulkanError::OutOfHostMemory
                | VulkanError::OutOfDeviceMemory
                | VulkanError::OutOfPoolMemory => err,
                // According to the specs, because `VK_ERROR_FRAGMENTED_POOL` was added after
                // version 1.0 of Vulkan, any negative return value except out-of-memory errors
                // must be considered as a fragmented pool error.
                _ => VulkanError::FragmentedPool,
            })?;

            output.set_len(layouts_vk.len());
        }

        Ok(output
            .into_iter()
            .zip(layouts)
            .zip(variable_descriptor_counts)
            .map(
                move |((handle, layout), variable_descriptor_count)| DescriptorPoolAlloc {
                    handle,
                    id: DescriptorPoolAlloc::next_id(),
                    layout: DeviceOwnedDebugWrapper(layout),
                    variable_descriptor_count,
                },
            ))
    }

    /// Frees some descriptor sets.
    ///
    /// Note that it is not mandatory to free sets. Destroying or resetting the pool destroys all
    /// the descriptor sets.
    ///
    /// # Safety
    ///
    /// - All elements of `descriptor_sets` must have been allocated from `self`,
    ///   and not freed previously.
    /// - All elements of `descriptor_sets` must not be in use by the host or device.
    #[inline]
    pub unsafe fn free_descriptor_sets(
        &self,
        descriptor_sets: impl IntoIterator<Item = UnsafeDescriptorSet>,
    ) -> Result<(), Validated<VulkanError>> {
        self.validate_free_descriptor_sets()?;

        Ok(self.free_descriptor_sets_unchecked(descriptor_sets)?)
    }

    fn validate_free_descriptor_sets(&self) -> Result<(), Box<ValidationError>> {
        if !self
            .flags
            .intersects(DescriptorPoolCreateFlags::FREE_DESCRIPTOR_SET)
        {
            return Err(Box::new(ValidationError {
                context: "self.flags()".into(),
                problem: "does not contain `DescriptorPoolCreateFlags::FREE_DESCRIPTOR_SET`".into(),
                vuids: &["VUID-vkFreeDescriptorSets-descriptorPool-00312"],
                ..Default::default()
            }));
        }

        Ok(())
    }

    #[cfg_attr(not(feature = "document_unchecked"), doc(hidden))]
    pub unsafe fn free_descriptor_sets_unchecked(
        &self,
        descriptor_sets: impl IntoIterator<Item = UnsafeDescriptorSet>,
    ) -> Result<(), VulkanError> {
        let sets: SmallVec<[_; 8]> = descriptor_sets.into_iter().map(|s| s.handle()).collect();
        if !sets.is_empty() {
            let fns = self.device.fns();
            (fns.v1_0.free_descriptor_sets)(
                self.device.handle(),
                self.handle,
                sets.len() as u32,
                sets.as_ptr(),
            )
            .result()
            .map_err(VulkanError::from)?;
        }

        Ok(())
    }

    /// Resets the pool.
    ///
    /// This destroys all descriptor sets and empties the pool.
    ///
    /// # Safety
    ///
    /// - All descriptor sets that were previously allocated from `self` must not be in use by the
    ///   host or device.
    #[inline]
    pub unsafe fn reset(&self) -> Result<(), VulkanError> {
        let fns = self.device.fns();
        (fns.v1_0.reset_descriptor_pool)(
            self.device.handle(),
            self.handle,
            ash::vk::DescriptorPoolResetFlags::empty(),
        )
        .result()
        .map_err(VulkanError::from)?;

        Ok(())
    }
}

impl Drop for DescriptorPool {
    #[inline]
    fn drop(&mut self) {
        unsafe {
            let fns = self.device.fns();
            (fns.v1_0.destroy_descriptor_pool)(self.device.handle(), self.handle, ptr::null());
        }
    }
}

unsafe impl VulkanObject for DescriptorPool {
    type Handle = ash::vk::DescriptorPool;

    #[inline]
    fn handle(&self) -> Self::Handle {
        self.handle
    }
}

unsafe impl DeviceOwned for DescriptorPool {
    #[inline]
    fn device(&self) -> &Arc<Device> {
        &self.device
    }
}

impl_id_counter!(DescriptorPool);

/// Parameters to create a new `UnsafeDescriptorPool`.
#[derive(Clone, Debug)]
pub struct DescriptorPoolCreateInfo {
    /// Additional properties of the descriptor pool.
    ///
    /// The default value is empty.
    pub flags: DescriptorPoolCreateFlags,

    /// The maximum number of descriptor sets that can be allocated from the pool.
    ///
    /// The default value is `0`, which must be overridden.
    pub max_sets: u32,

    /// The number of descriptors of each type to allocate for the pool.
    ///
    /// If the descriptor type is [`DescriptorType::InlineUniformBlock`], then the value is the
    /// number of bytes to allocate for such descriptors. The value must then be a multiple of 4.
    ///
    /// The default value is empty, which must be overridden.
    pub pool_sizes: HashMap<DescriptorType, u32>,

    /// The maximum number of [`DescriptorType::InlineUniformBlock`] bindings that can be allocated
    /// from the descriptor pool.
    ///
    /// If this is not 0, the device API version must be at least 1.3, or the
    /// [`khr_inline_uniform_block`](crate::device::DeviceExtensions::ext_inline_uniform_block)
    /// extension must be enabled on the device.
    ///
    /// The default value is 0.
    pub max_inline_uniform_block_bindings: u32,

    pub _ne: crate::NonExhaustive,
}

impl Default for DescriptorPoolCreateInfo {
    #[inline]
    fn default() -> Self {
        Self {
            flags: DescriptorPoolCreateFlags::empty(),
            max_sets: 0,
            pool_sizes: HashMap::default(),
            max_inline_uniform_block_bindings: 0,
            _ne: crate::NonExhaustive(()),
        }
    }
}

impl DescriptorPoolCreateInfo {
    pub(crate) fn validate(&self, device: &Device) -> Result<(), Box<ValidationError>> {
        let &Self {
            flags,
            max_sets,
            ref pool_sizes,
            max_inline_uniform_block_bindings,
            _ne: _,
        } = self;

        flags.validate_device(device).map_err(|err| {
            err.add_context("flags")
                .set_vuids(&["VUID-VkDescriptorPoolCreateInfo-flags-parameter"])
        })?;

        if max_sets == 0 {
            return Err(Box::new(ValidationError {
                context: "max_sets".into(),
                problem: "is zero".into(),
                vuids: &["VUID-VkDescriptorPoolCreateInfo-maxSets-00301"],
                ..Default::default()
            }));
        }

        if pool_sizes.is_empty() {
            return Err(Box::new(ValidationError {
                context: "pool_sizes".into(),
                problem: "is empty".into(),
                // vuids?
                ..Default::default()
            }));
        }

        // VUID-VkDescriptorPoolCreateInfo-pPoolSizes-parameter
        for (&descriptor_type, &pool_size) in pool_sizes.iter() {
            flags.validate_device(device).map_err(|err| {
                err.add_context("pool_sizes")
                    .set_vuids(&["VUID-VkDescriptorPoolSize-type-parameter"])
            })?;

            if pool_size == 0 {
                return Err(Box::new(ValidationError {
                    context: format!("pool_sizes[DescriptorType::{:?}]", descriptor_type).into(),
                    problem: "is zero".into(),
                    vuids: &["VUID-VkDescriptorPoolSize-descriptorCount-00302"],
                    ..Default::default()
                }));
            }

            if descriptor_type == DescriptorType::InlineUniformBlock {
                return Err(Box::new(ValidationError {
                    context: "pool_sizes[DescriptorType::InlineUniformBlock]".into(),
                    problem: "is not a multiple of 4".into(),
                    vuids: &["VUID-VkDescriptorPoolSize-type-02218"],
                    ..Default::default()
                }));
            }
        }

        if max_inline_uniform_block_bindings != 0
            && !(device.api_version() >= Version::V1_3
                || device.enabled_extensions().ext_inline_uniform_block)
        {
            return Err(Box::new(ValidationError {
                context: "max_inline_uniform_block_bindings".into(),
                problem: "is not zero".into(),
                requires_one_of: RequiresOneOf(&[
                    RequiresAllOf(&[Requires::APIVersion(Version::V1_3)]),
                    RequiresAllOf(&[Requires::DeviceExtension("ext_inline_uniform_block")]),
                ]),
                // vuids?
                ..Default::default()
            }));
        }

        Ok(())
    }
}

vulkan_bitflags! {
    #[non_exhaustive]

    /// Flags specifying additional properties of a descriptor pool.
    DescriptorPoolCreateFlags = DescriptorPoolCreateFlags(u32);

    /// Individual descriptor sets can be freed from the pool. Otherwise you must reset or
    /// destroy the whole pool at once.
    FREE_DESCRIPTOR_SET = FREE_DESCRIPTOR_SET,

    /// The pool can allocate descriptor sets with a layout whose flags include
    /// [`DescriptorSetLayoutCreateFlags::UPDATE_AFTER_BIND_POOL`].
    ///
    /// A pool created with this flag can still allocate descriptor sets without the flag.
    /// However, descriptor copy operations are only allowed between pools of the same type;
    /// it is not possible to copy between a descriptor set whose pool has `UPDATE_AFTER_BIND`,
    /// and a descriptor set whose pool does not have this flag.
    UPDATE_AFTER_BIND = UPDATE_AFTER_BIND
    RequiresOneOf([
        RequiresAllOf([APIVersion(V1_2)]),
        RequiresAllOf([DeviceExtension(ext_descriptor_indexing)]),
    ]),

    /* TODO: enable
    // TODO: document
    HOST_ONLY = HOST_ONLY_EXT
    RequiresOneOf([
        RequiresAllOf([DeviceExtension(ext_mutable_descriptor_type)]),
        RequiresAllOf([DeviceExtension(valve_mutable_descriptor_type)]),
    ]), */
}

/// Parameters to allocate a new `UnsafeDescriptorSet` from an `UnsafeDescriptorPool`.
#[derive(Clone, Debug)]
pub struct DescriptorSetAllocateInfo {
    /// The descriptor set layout to create the set for.
    ///
    /// There is no default value.
    pub layout: Arc<DescriptorSetLayout>,

    /// For layouts with a variable-count binding, the number of descriptors to allocate for that
    /// binding. This should be 0 for layouts that don't have a variable-count binding.
    ///
    /// The default value is 0.
    pub variable_descriptor_count: u32,

    pub _ne: crate::NonExhaustive,
}

impl DescriptorSetAllocateInfo {
    /// Returns a `DescriptorSetAllocateInfo` with the specified `layout`.
    #[inline]
    pub fn new(layout: Arc<DescriptorSetLayout>) -> Self {
        Self {
            layout,
            variable_descriptor_count: 0,
            _ne: crate::NonExhaustive(()),
        }
    }

    pub(crate) fn validate(&self, device: &Device) -> Result<(), Box<ValidationError>> {
        let &Self {
            ref layout,
            variable_descriptor_count,
            _ne,
        } = self;

        // VUID-VkDescriptorSetAllocateInfo-commonparent
        assert_eq!(device, layout.device().as_ref());

        if layout
            .flags()
            .intersects(DescriptorSetLayoutCreateFlags::PUSH_DESCRIPTOR)
        {
            return Err(Box::new(ValidationError {
                context: "layout.flags()".into(),
                problem: "contains `DescriptorSetLayoutCreateFlags::PUSH_DESCRIPTOR`".into(),
                vuids: &["VUID-VkDescriptorSetAllocateInfo-pSetLayouts-00308"],
                ..Default::default()
            }));
        }

        if variable_descriptor_count > layout.variable_descriptor_count() {
            return Err(Box::new(ValidationError {
                problem: "`variable_descriptor_count` is greater than
                    `layout.variable_descriptor_count()`"
                    .into(),
                // vuids: https://github.com/KhronosGroup/Vulkan-Docs/issues/2244
                ..Default::default()
            }));
        }

        Ok(())
    }
}

/// Opaque type that represents a descriptor set allocated from a pool.
#[derive(Debug)]
pub struct DescriptorPoolAlloc {
    handle: ash::vk::DescriptorSet,
    id: NonZeroU64,
    layout: DeviceOwnedDebugWrapper<Arc<DescriptorSetLayout>>,
    variable_descriptor_count: u32,
}

impl DescriptorPoolAlloc {
    /// Returns the descriptor set layout of the descriptor set.
    #[inline]
    pub fn layout(&self) -> &Arc<DescriptorSetLayout> {
        &self.layout
    }

    /// Returns the variable descriptor count that this descriptor set was allocated with.
    #[inline]
    pub fn variable_descriptor_count(&self) -> u32 {
        self.variable_descriptor_count
    }
}

unsafe impl VulkanObject for DescriptorPoolAlloc {
    type Handle = ash::vk::DescriptorSet;

    #[inline]
    fn handle(&self) -> Self::Handle {
        self.handle
    }
}

unsafe impl DeviceOwned for DescriptorPoolAlloc {
    #[inline]
    fn device(&self) -> &Arc<Device> {
        self.layout.device()
    }
}

impl_id_counter!(DescriptorPoolAlloc);

#[cfg(test)]
mod tests {
    use super::{DescriptorPool, DescriptorPoolCreateInfo};
    use crate::{
        descriptor_set::{
            layout::{
                DescriptorSetLayout, DescriptorSetLayoutBinding, DescriptorSetLayoutCreateInfo,
                DescriptorType,
            },
            pool::DescriptorSetAllocateInfo,
        },
        shader::ShaderStages,
    };

    #[test]
    fn pool_create() {
        let (device, _) = gfx_dev_and_queue!();

        let _ = DescriptorPool::new(
            device,
            DescriptorPoolCreateInfo {
                max_sets: 10,
                pool_sizes: [(DescriptorType::UniformBuffer, 1)].into_iter().collect(),
                ..Default::default()
            },
        )
        .unwrap();
    }

    #[test]
    fn zero_max_set() {
        let (device, _) = gfx_dev_and_queue!();

        DescriptorPool::new(
            device,
            DescriptorPoolCreateInfo {
                max_sets: 0,
                pool_sizes: [(DescriptorType::UniformBuffer, 1)].into_iter().collect(),
                ..Default::default()
            },
        )
        .unwrap_err();
    }

    #[test]
    fn zero_descriptors() {
        let (device, _) = gfx_dev_and_queue!();

        DescriptorPool::new(
            device,
            DescriptorPoolCreateInfo {
                max_sets: 10,
                ..Default::default()
            },
        )
        .unwrap_err();
    }

    #[test]
    fn basic_alloc() {
        let (device, _) = gfx_dev_and_queue!();

        let set_layout = DescriptorSetLayout::new(
            device.clone(),
            DescriptorSetLayoutCreateInfo {
                bindings: [(
                    0,
                    DescriptorSetLayoutBinding {
                        stages: ShaderStages::all_graphics(),
                        ..DescriptorSetLayoutBinding::descriptor_type(DescriptorType::UniformBuffer)
                    },
                )]
                .into(),
                ..Default::default()
            },
        )
        .unwrap();

        let pool = DescriptorPool::new(
            device,
            DescriptorPoolCreateInfo {
                max_sets: 10,
                pool_sizes: [(DescriptorType::UniformBuffer, 10)].into_iter().collect(),
                ..Default::default()
            },
        )
        .unwrap();
        unsafe {
            let sets = pool
                .allocate_descriptor_sets([DescriptorSetAllocateInfo::new(set_layout)])
                .unwrap();
            assert_eq!(sets.count(), 1);
        }
    }

    #[test]
    fn alloc_diff_device() {
        let (device1, _) = gfx_dev_and_queue!();
        let (device2, _) = gfx_dev_and_queue!();

        let set_layout = DescriptorSetLayout::new(
            device1,
            DescriptorSetLayoutCreateInfo {
                bindings: [(
                    0,
                    DescriptorSetLayoutBinding {
                        stages: ShaderStages::all_graphics(),
                        ..DescriptorSetLayoutBinding::descriptor_type(DescriptorType::UniformBuffer)
                    },
                )]
                .into(),
                ..Default::default()
            },
        )
        .unwrap();

        assert_should_panic!({
            let pool = DescriptorPool::new(
                device2,
                DescriptorPoolCreateInfo {
                    max_sets: 10,
                    pool_sizes: [(DescriptorType::UniformBuffer, 10)].into_iter().collect(),
                    ..Default::default()
                },
            )
            .unwrap();

            unsafe {
                let _ = pool.allocate_descriptor_sets([DescriptorSetAllocateInfo::new(set_layout)]);
            }
        });
    }

    #[test]
    fn alloc_zero() {
        let (device, _) = gfx_dev_and_queue!();

        let pool = DescriptorPool::new(
            device,
            DescriptorPoolCreateInfo {
                max_sets: 1,
                pool_sizes: [(DescriptorType::UniformBuffer, 1)].into_iter().collect(),
                ..Default::default()
            },
        )
        .unwrap();
        unsafe {
            let sets = pool.allocate_descriptor_sets([]).unwrap();
            assert_eq!(sets.count(), 0);
        }
    }
}