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
// Copyright (c) 2017 The vulkano developers
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://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 std::error;
use std::fmt;
use std::sync::Arc;

use OomError;
use VulkanObject;
use buffer::BufferAccess;
use buffer::BufferViewRef;
use descriptor::descriptor::DescriptorDesc;
use descriptor::descriptor::DescriptorDescTy;
use descriptor::descriptor::DescriptorImageDesc;
use descriptor::descriptor::DescriptorImageDescArray;
use descriptor::descriptor::DescriptorImageDescDimensions;
use descriptor::descriptor::DescriptorType;
use descriptor::descriptor_set::DescriptorPool;
use descriptor::descriptor_set::DescriptorPoolAlloc;
use descriptor::descriptor_set::DescriptorSet;
use descriptor::descriptor_set::DescriptorSetDesc;
use descriptor::descriptor_set::DescriptorWrite;
use descriptor::descriptor_set::StdDescriptorPoolAlloc;
use descriptor::descriptor_set::UnsafeDescriptorSet;
use descriptor::descriptor_set::UnsafeDescriptorSetLayout;
use descriptor::pipeline_layout::PipelineLayoutAbstract;
use device::Device;
use device::DeviceOwned;
use format::Format;
use image::ImageViewAccess;
use sampler::Sampler;

/// An immutable descriptor set that is expected to be long-lived.
///
/// Creating a persistent descriptor set allocates from a pool, and can't be modified once created.
/// You are therefore encouraged to create them at initialization and not the during
/// performance-critical paths.
///
/// > **Note**: You can control of the pool that is used to create the descriptor set, if you wish
/// > so. By creating a implementation of the `DescriptorPool` trait that doesn't perform any
/// > actual allocation, you can skip this allocation and make it acceptable to use a persistent
/// > descriptor set in performance-critical paths..
///
/// The template parameter of the `PersistentDescriptorSet` is complex, and you shouldn't try to
/// express it explicitly. If you want to store your descriptor set in a struct or in a `Vec` for
/// example, you are encouraged to turn the `PersistentDescriptorSet` into a `Box<DescriptorSet>`
/// or a `Arc<DescriptorSet>`.
///
/// # Example
// TODO:
pub struct PersistentDescriptorSet<L, R, P = StdDescriptorPoolAlloc> {
    inner: P,
    resources: R,
    pipeline_layout: L,
    set_id: usize,
    layout: Arc<UnsafeDescriptorSetLayout>,
}

impl<L> PersistentDescriptorSet<L, ()> {
    /// Starts the process of building a `PersistentDescriptorSet`. Returns a builder.
    ///
    /// # Panic
    ///
    /// - Panics if the set id is out of range.
    ///
    pub fn start(layout: L, set_id: usize) -> PersistentDescriptorSetBuilder<L, ()>
        where L: PipelineLayoutAbstract
    {
        assert!(layout.num_sets() > set_id);

        let cap = layout.num_bindings_in_set(set_id).unwrap_or(0);

        PersistentDescriptorSetBuilder {
            layout: layout,
            set_id: set_id,
            binding_id: 0,
            writes: Vec::with_capacity(cap),
            resources: (),
        }
    }
}

unsafe impl<L, R, P> DescriptorSet for PersistentDescriptorSet<L, R, P>
    where L: PipelineLayoutAbstract,
          P: DescriptorPoolAlloc,
          R: PersistentDescriptorSetResources
{
    #[inline]
    fn inner(&self) -> &UnsafeDescriptorSet {
        self.inner.inner()
    }

    #[inline]
    fn num_buffers(&self) -> usize {
        self.resources.num_buffers()
    }

    #[inline]
    fn buffer(&self, index: usize) -> Option<(&BufferAccess, u32)> {
        self.resources.buffer(index)
    }

    #[inline]
    fn num_images(&self) -> usize {
        self.resources.num_images()
    }

    #[inline]
    fn image(&self, index: usize) -> Option<(&ImageViewAccess, u32)> {
        self.resources.image(index)
    }
}

unsafe impl<L, R, P> DescriptorSetDesc for PersistentDescriptorSet<L, R, P>
    where L: PipelineLayoutAbstract
{
    #[inline]
    fn num_bindings(&self) -> usize {
        self.pipeline_layout
            .num_bindings_in_set(self.set_id)
            .unwrap()
    }

    #[inline]
    fn descriptor(&self, binding: usize) -> Option<DescriptorDesc> {
        self.pipeline_layout.descriptor(self.set_id, binding)
    }
}

unsafe impl<L, R, P> DeviceOwned for PersistentDescriptorSet<L, R, P>
    where L: DeviceOwned
{
    #[inline]
    fn device(&self) -> &Arc<Device> {
        self.layout.device()
    }
}

/// Prototype of a `PersistentDescriptorSet`.
///
/// The template parameter `L` is the pipeline layout to use, and the template parameter `R` is
/// an unspecified type that represents the list of resources.
///
/// See the docs of `PersistentDescriptorSet` for an example.
pub struct PersistentDescriptorSetBuilder<L, R> {
    // The pipeline layout.
    layout: L,
    // Id of the set within the pipeline layout.
    set_id: usize,
    // Binding currently being filled.
    binding_id: usize,
    // The writes to perform on a descriptor set in order to put the resources in it.
    writes: Vec<DescriptorWrite>,
    // Holds the resources alive.
    resources: R,
}

// TODO: lots of checks are still missing, see the docs of
//       VkDescriptorImageInfo and VkWriteDescriptorSet

impl<L, R> PersistentDescriptorSetBuilder<L, R>
    where L: PipelineLayoutAbstract
{
    /// Builds a `PersistentDescriptorSet` from the builder.
    #[inline]
    pub fn build(self)
                 -> Result<PersistentDescriptorSet<L, R, StdDescriptorPoolAlloc>,
                           PersistentDescriptorSetBuildError> {
        let mut pool = Device::standard_descriptor_pool(self.layout.device());
        self.build_with_pool(&mut pool)
    }

    /// Builds a `PersistentDescriptorSet` from the builder.
    ///
    /// # Panic
    ///
    /// Panics if the pool doesn't have the same device as the pipeline layout.
    ///
    pub fn build_with_pool<P>(
        self, pool: &mut P)
        -> Result<PersistentDescriptorSet<L, R, P::Alloc>, PersistentDescriptorSetBuildError>
        where P: ?Sized + DescriptorPool
    {
        assert_eq!(self.layout.device().internal_object(),
                   pool.device().internal_object());

        let expected_desc = self.layout.num_bindings_in_set(self.set_id).unwrap();

        if expected_desc > self.binding_id {
            return Err(PersistentDescriptorSetBuildError::MissingDescriptors {
                           expected: expected_desc as u32,
                           obtained: self.binding_id as u32,
                       });
        }

        debug_assert_eq!(expected_desc, self.binding_id);

        let set_layout = self.layout
            .descriptor_set_layout(self.set_id)
            .expect("Unable to get the descriptor set layout")
            .clone();

        let set = unsafe {
            let mut set = pool.alloc(&set_layout)?;
            set.inner_mut()
                .write(pool.device(), self.writes.into_iter());
            set
        };

        Ok(PersistentDescriptorSet {
               inner: set,
               resources: self.resources,
               pipeline_layout: self.layout,
               set_id: self.set_id,
               layout: set_layout,
           })
    }

    /// Call this function if the next element of the set is an array in order to set the value of
    /// each element.
    ///
    /// Returns an error if the descriptor is empty.
    ///
    /// This function can be called even if the descriptor isn't an array, and it is valid to enter
    /// the "array", add one element, then leave.
    #[inline]
    pub fn enter_array(
        self)
        -> Result<PersistentDescriptorSetBuilderArray<L, R>, PersistentDescriptorSetError> {
        let desc = match self.layout.descriptor(self.set_id, self.binding_id) {
            Some(d) => d,
            None => return Err(PersistentDescriptorSetError::EmptyExpected),
        };

        Ok(PersistentDescriptorSetBuilderArray {
               builder: self,
               desc,
               array_element: 0,
           })
    }

    /// Skips the current descriptor if it is empty.
    #[inline]
    pub fn add_empty(
        mut self)
        -> Result<PersistentDescriptorSetBuilder<L, R>, PersistentDescriptorSetError> {
        match self.layout.descriptor(self.set_id, self.binding_id) {
            None => (),
            Some(desc) => return Err(PersistentDescriptorSetError::WrongDescriptorTy {
                                         expected: desc.ty.ty().unwrap(),
                                     }),
        }

        self.binding_id += 1;
        Ok(self)
    }

    /// Binds a buffer as the next descriptor.
    ///
    /// An error is returned if the buffer isn't compatible with the descriptor.
    ///
    /// # Panic
    ///
    /// Panics if the buffer doesn't have the same device as the pipeline layout.
    ///
    #[inline]
    pub fn add_buffer<T>(self, buffer: T)
                         -> Result<PersistentDescriptorSetBuilder<L,
                                                                  (R,
                                                                   PersistentDescriptorSetBuf<T>)>,
                                   PersistentDescriptorSetError>
        where T: BufferAccess
    {
        self.enter_array()?.add_buffer(buffer)?.leave_array()
    }

    /// Binds a buffer view as the next descriptor.
    ///
    /// An error is returned if the buffer isn't compatible with the descriptor.
    ///
    /// # Panic
    ///
    /// Panics if the buffer view doesn't have the same device as the pipeline layout.
    ///
    pub fn add_buffer_view<T>(self, view: T)
        -> Result<PersistentDescriptorSetBuilder<L, (R, PersistentDescriptorSetBufView<T>)>, PersistentDescriptorSetError>
        where T: BufferViewRef
    {
        self.enter_array()?.add_buffer_view(view)?.leave_array()
    }

    /// Binds an image view as the next descriptor.
    ///
    /// An error is returned if the image view isn't compatible with the descriptor.
    ///
    /// # Panic
    ///
    /// Panics if the image view doesn't have the same device as the pipeline layout.
    ///
    #[inline]
    pub fn add_image<T>(self, image_view: T)
                        -> Result<PersistentDescriptorSetBuilder<L,
                                                                 (R,
                                                                  PersistentDescriptorSetImg<T>)>,
                                  PersistentDescriptorSetError>
        where T: ImageViewAccess
    {
        self.enter_array()?.add_image(image_view)?.leave_array()
    }

    /// Binds an image view with a sampler as the next descriptor.
    ///
    /// An error is returned if the image view isn't compatible with the descriptor.
    ///
    /// # Panic
    ///
    /// Panics if the image view or the sampler doesn't have the same device as the pipeline layout.
    ///
    #[inline]
    pub fn add_sampled_image<T>(self, image_view: T, sampler: Arc<Sampler>)
        -> Result<PersistentDescriptorSetBuilder<L, ((R, PersistentDescriptorSetImg<T>), PersistentDescriptorSetSampler)>, PersistentDescriptorSetError>
        where T: ImageViewAccess
    {
        self.enter_array()?
            .add_sampled_image(image_view, sampler)?
            .leave_array()
    }

    /// Binds a sampler as the next descriptor.
    ///
    /// An error is returned if the sampler isn't compatible with the descriptor.
    ///
    /// # Panic
    ///
    /// Panics if the sampler doesn't have the same device as the pipeline layout.
    ///
    #[inline]
    pub fn add_sampler(self, sampler: Arc<Sampler>)
                       -> Result<PersistentDescriptorSetBuilder<L,
                                                                (R,
                                                                 PersistentDescriptorSetSampler)>,
                                 PersistentDescriptorSetError> {
        self.enter_array()?.add_sampler(sampler)?.leave_array()
    }
}

/// Same as `PersistentDescriptorSetBuilder`, but we're in an array.
pub struct PersistentDescriptorSetBuilderArray<L, R> {
    // The original builder.
    builder: PersistentDescriptorSetBuilder<L, R>,
    // Current array elements.
    array_element: usize,
    // Description of the descriptor.
    desc: DescriptorDesc,
}

impl<L, R> PersistentDescriptorSetBuilderArray<L, R>
    where L: PipelineLayoutAbstract
{
    /// Leaves the array. Call this once you added all the elements of the array.
    pub fn leave_array(
        mut self)
        -> Result<PersistentDescriptorSetBuilder<L, R>, PersistentDescriptorSetError> {
        if self.desc.array_count > self.array_element as u32 {
            return Err(PersistentDescriptorSetError::MissingArrayElements {
                           expected: self.desc.array_count,
                           obtained: self.array_element as u32,
                       });
        }

        debug_assert_eq!(self.desc.array_count, self.array_element as u32);

        self.builder.binding_id += 1;
        Ok(self.builder)
    }

    /// Binds a buffer as the next element in the array.
    ///
    /// An error is returned if the buffer isn't compatible with the descriptor.
    ///
    /// # Panic
    ///
    /// Panics if the buffer doesn't have the same device as the pipeline layout.
    ///
    pub fn add_buffer<T>(mut self, buffer: T)
        -> Result<PersistentDescriptorSetBuilderArray<L, (R, PersistentDescriptorSetBuf<T>)>, PersistentDescriptorSetError>
        where T: BufferAccess
    {
        assert_eq!(self.builder.layout.device().internal_object(),
                   buffer.inner().buffer.device().internal_object());

        if self.array_element as u32 >= self.desc.array_count {
            return Err(PersistentDescriptorSetError::ArrayOutOfBounds);
        }

        self.builder.writes.push(match self.desc.ty {
            DescriptorDescTy::Buffer(ref buffer_desc) => {
                // 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!(self.builder
                            .layout
                            .device()
                            .enabled_features()
                            .robust_buffer_access);

                if buffer_desc.storage {
                    if !buffer.inner().buffer.usage_storage_buffer() {
                        return Err(PersistentDescriptorSetError::MissingBufferUsage(
                                   MissingBufferUsage::StorageBuffer));
                    }

                    unsafe {
                        DescriptorWrite::storage_buffer(self.builder.binding_id as u32,
                                                        self.array_element as u32,
                                                        &buffer)
                    }
                } else {
                    if !buffer.inner().buffer.usage_uniform_buffer() {
                        return Err(PersistentDescriptorSetError::MissingBufferUsage(
                                   MissingBufferUsage::UniformBuffer));
                    }

                    unsafe {
                        DescriptorWrite::uniform_buffer(self.builder.binding_id as u32,
                                                        self.array_element as u32,
                                                        &buffer)
                    }
                }
            },
            ref d => {
                return Err(PersistentDescriptorSetError::WrongDescriptorTy {
                               expected: d.ty().unwrap(),
                           });
            },
        });

        Ok(PersistentDescriptorSetBuilderArray {
               builder: PersistentDescriptorSetBuilder {
                   layout: self.builder.layout,
                   set_id: self.builder.set_id,
                   binding_id: self.builder.binding_id,
                   writes: self.builder.writes,
                   resources: (self.builder.resources,
                               PersistentDescriptorSetBuf {
                                   buffer: buffer,
                                   descriptor_num: self.builder.binding_id as u32,
                               }),
               },
               desc: self.desc,
               array_element: self.array_element + 1,
           })
    }

    /// Binds a buffer view as the next element in the array.
    ///
    /// An error is returned if the buffer isn't compatible with the descriptor.
    ///
    /// # Panic
    ///
    /// Panics if the buffer view doesn't have the same device as the pipeline layout.
    ///
    pub fn add_buffer_view<T>(mut self, view: T)
        -> Result<PersistentDescriptorSetBuilderArray<L, (R, PersistentDescriptorSetBufView<T>)>, PersistentDescriptorSetError>
        where T: BufferViewRef
    {
        assert_eq!(self.builder.layout.device().internal_object(),
                   view.view().device().internal_object());

        if self.array_element as u32 >= self.desc.array_count {
            return Err(PersistentDescriptorSetError::ArrayOutOfBounds);
        }

        self.builder.writes.push(match self.desc.ty {
            DescriptorDescTy::TexelBuffer { storage, .. } => {
                if storage {
                    // TODO: storage_texel_buffer_atomic

                    if !view.view().storage_texel_buffer() {
                        return Err(PersistentDescriptorSetError::MissingBufferUsage(
                                   MissingBufferUsage::StorageTexelBuffer));
                    }

                    DescriptorWrite::storage_texel_buffer(self.builder.binding_id as u32,
                                                          self.array_element as u32,
                                                          view.view())
                } else {
                    if !view.view().uniform_texel_buffer() {
                        return Err(PersistentDescriptorSetError::MissingBufferUsage(
                                   MissingBufferUsage::UniformTexelBuffer));
                    }

                    DescriptorWrite::uniform_texel_buffer(self.builder.binding_id as u32,
                                                          self.array_element as u32,
                                                          view.view())
                }
            },
            ref d => {
                return Err(PersistentDescriptorSetError::WrongDescriptorTy {
                               expected: d.ty().unwrap(),
                           });
            },
        });

        Ok(PersistentDescriptorSetBuilderArray {
               builder: PersistentDescriptorSetBuilder {
                   layout: self.builder.layout,
                   set_id: self.builder.set_id,
                   binding_id: self.builder.binding_id,
                   writes: self.builder.writes,
                   resources: (self.builder.resources,
                               PersistentDescriptorSetBufView {
                                   view: view,
                                   descriptor_num: self.builder.binding_id as u32,
                               }),
               },
               desc: self.desc,
               array_element: self.array_element + 1,
           })
    }

    /// Binds an image view as the next element in the array.
    ///
    /// An error is returned if the image view isn't compatible with the descriptor.
    ///
    /// # Panic
    ///
    /// Panics if the image view doesn't have the same device as the pipeline layout.
    ///
    pub fn add_image<T>(mut self, image_view: T)
        -> Result<PersistentDescriptorSetBuilderArray<L, (R, PersistentDescriptorSetImg<T>)>, PersistentDescriptorSetError>
        where T: ImageViewAccess
    {
        assert_eq!(self.builder.layout.device().internal_object(),
                   image_view.parent().inner().image.device().internal_object());

        if self.array_element as u32 >= self.desc.array_count {
            return Err(PersistentDescriptorSetError::ArrayOutOfBounds);
        }

        let desc = match self.builder
            .layout
            .descriptor(self.builder.set_id, self.builder.binding_id) {
            Some(d) => d,
            None => return Err(PersistentDescriptorSetError::EmptyExpected),
        };

        self.builder.writes.push(match desc.ty {
            DescriptorDescTy::Image(ref desc) => {
                image_match_desc(&image_view, &desc)?;

                if desc.sampled {
                    DescriptorWrite::sampled_image(self.builder.binding_id as u32,
                                                   self.array_element as u32,
                                                   &image_view)
                } else {
                    DescriptorWrite::storage_image(self.builder.binding_id as u32,
                                                   self.array_element as u32,
                                                   &image_view)
                }
            },
            DescriptorDescTy::InputAttachment {
                multisampled,
                array_layers,
            } => {
                if !image_view.parent().inner().image.usage_input_attachment() {
                    return Err(PersistentDescriptorSetError::MissingImageUsage(
                                   MissingImageUsage::InputAttachment));
                }

                if multisampled && image_view.samples() == 1 {
                    return Err(PersistentDescriptorSetError::ExpectedMultisampled);
                } else if !multisampled && image_view.samples() != 1 {
                    return Err(PersistentDescriptorSetError::UnexpectedMultisampled);
                }

                let image_layers = image_view.dimensions().array_layers();

                match array_layers {
                    DescriptorImageDescArray::NonArrayed => {
                        if image_layers != 1 {
                            return Err(PersistentDescriptorSetError::ArrayLayersMismatch {
                                           expected: 1,
                                           obtained: image_layers,
                                       });
                        }
                    },
                    DescriptorImageDescArray::Arrayed { max_layers: Some(max_layers) } => {
                        if image_layers > max_layers {
                            // TODO: is this correct? "max" layers? or is it in fact min layers?
                            return Err(PersistentDescriptorSetError::ArrayLayersMismatch {
                                           expected: max_layers,
                                           obtained: image_layers,
                                       });
                        }
                    },
                    DescriptorImageDescArray::Arrayed { max_layers: None } => {},
                };

                DescriptorWrite::input_attachment(self.builder.binding_id as u32,
                                                  self.array_element as u32,
                                                  &image_view)
            },
            ty => {
                return Err(PersistentDescriptorSetError::WrongDescriptorTy {
                               expected: ty.ty().unwrap(),
                           });
            },
        });

        Ok(PersistentDescriptorSetBuilderArray {
               builder: PersistentDescriptorSetBuilder {
                   layout: self.builder.layout,
                   set_id: self.builder.set_id,
                   binding_id: self.builder.binding_id,
                   writes: self.builder.writes,
                   resources: (self.builder.resources,
                               PersistentDescriptorSetImg {
                                   image: image_view,
                                   descriptor_num: self.builder.binding_id as u32,
                               }),
               },
               desc: self.desc,
               array_element: self.array_element + 1,
           })
    }

    /// Binds an image view with a sampler as the next element in the array.
    ///
    /// An error is returned if the image view isn't compatible with the descriptor.
    ///
    /// # Panic
    ///
    /// Panics if the image or the sampler doesn't have the same device as the pipeline layout.
    ///
    pub fn add_sampled_image<T>(mut self, image_view: T, sampler: Arc<Sampler>)
        -> Result<PersistentDescriptorSetBuilderArray<L, ((R, PersistentDescriptorSetImg<T>), PersistentDescriptorSetSampler)>, PersistentDescriptorSetError>
        where T: ImageViewAccess
    {
        assert_eq!(self.builder.layout.device().internal_object(),
                   image_view.parent().inner().image.device().internal_object());
        assert_eq!(self.builder.layout.device().internal_object(),
                   sampler.device().internal_object());

        if self.array_element as u32 >= self.desc.array_count {
            return Err(PersistentDescriptorSetError::ArrayOutOfBounds);
        }

        let desc = match self.builder
            .layout
            .descriptor(self.builder.set_id, self.builder.binding_id) {
            Some(d) => d,
            None => return Err(PersistentDescriptorSetError::EmptyExpected),
        };

        if !image_view.can_be_sampled(&sampler) {
            return Err(PersistentDescriptorSetError::IncompatibleImageViewSampler);
        }

        self.builder.writes.push(match desc.ty {
            DescriptorDescTy::CombinedImageSampler(ref desc) => {
                image_match_desc(&image_view, &desc)?;
                DescriptorWrite::combined_image_sampler(self.builder.binding_id as u32,
                                                        self.array_element as u32,
                                                        &sampler,
                                                        &image_view)
            },
            ty => {
                return Err(PersistentDescriptorSetError::WrongDescriptorTy {
                               expected: ty.ty().unwrap(),
                           });
            },
        });

        Ok(PersistentDescriptorSetBuilderArray {
               builder: PersistentDescriptorSetBuilder {
                   layout: self.builder.layout,
                   set_id: self.builder.set_id,
                   binding_id: self.builder.binding_id,
                   writes: self.builder.writes,
                   resources: ((self.builder.resources,
                                PersistentDescriptorSetImg {
                                    image: image_view,
                                    descriptor_num: self.builder.binding_id as u32,
                                }),
                               PersistentDescriptorSetSampler { sampler: sampler }),
               },
               desc: self.desc,
               array_element: self.array_element + 1,
           })
    }

    /// Binds a sampler as the next element in the array.
    ///
    /// An error is returned if the sampler isn't compatible with the descriptor.
    ///
    /// # Panic
    ///
    /// Panics if the sampler doesn't have the same device as the pipeline layout.
    ///
    pub fn add_sampler(mut self, sampler: Arc<Sampler>)
        -> Result<PersistentDescriptorSetBuilderArray<L, (R, PersistentDescriptorSetSampler)>, PersistentDescriptorSetError>
    {
        assert_eq!(self.builder.layout.device().internal_object(),
                   sampler.device().internal_object());

        if self.array_element as u32 >= self.desc.array_count {
            return Err(PersistentDescriptorSetError::ArrayOutOfBounds);
        }

        let desc = match self.builder
            .layout
            .descriptor(self.builder.set_id, self.builder.binding_id) {
            Some(d) => d,
            None => return Err(PersistentDescriptorSetError::EmptyExpected),
        };

        self.builder.writes.push(match desc.ty {
            DescriptorDescTy::Sampler => {
                DescriptorWrite::sampler(self.builder.binding_id as u32,
                                         self.array_element as u32,
                                         &sampler)
            },
            ty => {
                return Err(PersistentDescriptorSetError::WrongDescriptorTy {
                               expected: ty.ty().unwrap(),
                           });
            },
        });

        Ok(PersistentDescriptorSetBuilderArray {
               builder: PersistentDescriptorSetBuilder {
                   layout: self.builder.layout,
                   set_id: self.builder.set_id,
                   binding_id: self.builder.binding_id,
                   writes: self.builder.writes,
                   resources: (self.builder.resources,
                               PersistentDescriptorSetSampler { sampler: sampler }),
               },
               desc: self.desc,
               array_element: self.array_element + 1,
           })
    }
}

// Checks whether an image view matches the descriptor.
fn image_match_desc<I>(image_view: &I, desc: &DescriptorImageDesc)
                       -> Result<(), PersistentDescriptorSetError>
    where I: ?Sized + ImageViewAccess
{
    if desc.sampled && !image_view.parent().inner().image.usage_sampled() {
        return Err(PersistentDescriptorSetError::MissingImageUsage(
                       MissingImageUsage::Sampled));
    } else if !desc.sampled && !image_view.parent().inner().image.usage_storage() {
        return Err(PersistentDescriptorSetError::MissingImageUsage(
                       MissingImageUsage::Storage));
    }

    let image_view_ty = DescriptorImageDescDimensions::from_dimensions(image_view.dimensions());
    if image_view_ty != desc.dimensions {
        return Err(PersistentDescriptorSetError::ImageViewTypeMismatch {
                       expected: desc.dimensions,
                       obtained: image_view_ty,
                   });
    }

    if let Some(format) = desc.format {
        if image_view.format() != format {
            return Err(PersistentDescriptorSetError::ImageViewFormatMismatch {
                           expected: format,
                           obtained: image_view.format(),
                       });
        }
    }

    if desc.multisampled && image_view.samples() == 1 {
        return Err(PersistentDescriptorSetError::ExpectedMultisampled);
    } else if !desc.multisampled && image_view.samples() != 1 {
        return Err(PersistentDescriptorSetError::UnexpectedMultisampled);
    }

    let image_layers = image_view.dimensions().array_layers();

    match desc.array_layers {
        DescriptorImageDescArray::NonArrayed => {
            // TODO: when a non-array is expected, can we pass an image view that is in fact an
            // array with one layer? need to check
            if image_layers != 1 {
                return Err(PersistentDescriptorSetError::ArrayLayersMismatch {
                               expected: 1,
                               obtained: image_layers,
                           });
            }
        },
        DescriptorImageDescArray::Arrayed { max_layers: Some(max_layers) } => {
            if image_layers > max_layers {
                // TODO: is this correct? "max" layers? or is it in fact min layers?
                return Err(PersistentDescriptorSetError::ArrayLayersMismatch {
                               expected: max_layers,
                               obtained: image_layers,
                           });
            }
        },
        DescriptorImageDescArray::Arrayed { max_layers: None } => {},
    };

    Ok(())
}

pub unsafe trait PersistentDescriptorSetResources {
    fn num_buffers(&self) -> usize;
    fn buffer(&self, index: usize) -> Option<(&BufferAccess, u32)>;
    fn num_images(&self) -> usize;
    fn image(&self, index: usize) -> Option<(&ImageViewAccess, u32)>;
}

unsafe impl PersistentDescriptorSetResources for () {
    #[inline]
    fn num_buffers(&self) -> usize {
        0
    }

    #[inline]
    fn buffer(&self, _: usize) -> Option<(&BufferAccess, u32)> {
        None
    }

    #[inline]
    fn num_images(&self) -> usize {
        0
    }

    #[inline]
    fn image(&self, _: usize) -> Option<(&ImageViewAccess, u32)> {
        None
    }
}

/// Internal object related to the `PersistentDescriptorSet` system.
pub struct PersistentDescriptorSetBuf<B> {
    buffer: B,
    descriptor_num: u32,
}

unsafe impl<R, B> PersistentDescriptorSetResources for (R, PersistentDescriptorSetBuf<B>)
    where R: PersistentDescriptorSetResources,
          B: BufferAccess
{
    #[inline]
    fn num_buffers(&self) -> usize {
        self.0.num_buffers() + 1
    }

    #[inline]
    fn buffer(&self, index: usize) -> Option<(&BufferAccess, u32)> {
        if let Some(buf) = self.0.buffer(index) {
            Some(buf)
        } else if index == self.0.num_buffers() {
            Some((&self.1.buffer, self.1.descriptor_num))
        } else {
            None
        }
    }

    #[inline]
    fn num_images(&self) -> usize {
        self.0.num_images()
    }

    #[inline]
    fn image(&self, index: usize) -> Option<(&ImageViewAccess, u32)> {
        self.0.image(index)
    }
}

/// Internal object related to the `PersistentDescriptorSet` system.
pub struct PersistentDescriptorSetBufView<V>
    where V: BufferViewRef
{
    view: V,
    descriptor_num: u32,
}

unsafe impl<R, V> PersistentDescriptorSetResources for (R, PersistentDescriptorSetBufView<V>)
    where R: PersistentDescriptorSetResources,
          V: BufferViewRef
{
    #[inline]
    fn num_buffers(&self) -> usize {
        self.0.num_buffers() + 1
    }

    #[inline]
    fn buffer(&self, index: usize) -> Option<(&BufferAccess, u32)> {
        if let Some(buf) = self.0.buffer(index) {
            Some(buf)
        } else if index == self.0.num_buffers() {
            Some((self.1.view.view().buffer(), self.1.descriptor_num))
        } else {
            None
        }
    }

    #[inline]
    fn num_images(&self) -> usize {
        self.0.num_images()
    }

    #[inline]
    fn image(&self, index: usize) -> Option<(&ImageViewAccess, u32)> {
        self.0.image(index)
    }
}

/// Internal object related to the `PersistentDescriptorSet` system.
pub struct PersistentDescriptorSetImg<I> {
    image: I,
    descriptor_num: u32,
}

unsafe impl<R, I> PersistentDescriptorSetResources for (R, PersistentDescriptorSetImg<I>)
    where R: PersistentDescriptorSetResources,
          I: ImageViewAccess
{
    #[inline]
    fn num_buffers(&self) -> usize {
        self.0.num_buffers()
    }

    #[inline]
    fn buffer(&self, index: usize) -> Option<(&BufferAccess, u32)> {
        self.0.buffer(index)
    }

    #[inline]
    fn num_images(&self) -> usize {
        self.0.num_images() + 1
    }

    #[inline]
    fn image(&self, index: usize) -> Option<(&ImageViewAccess, u32)> {
        if let Some(img) = self.0.image(index) {
            Some(img)
        } else if index == self.0.num_images() {
            Some((&self.1.image, self.1.descriptor_num))
        } else {
            None
        }
    }
}

/// Internal object related to the `PersistentDescriptorSet` system.
pub struct PersistentDescriptorSetSampler {
    sampler: Arc<Sampler>,
}

unsafe impl<R> PersistentDescriptorSetResources for (R, PersistentDescriptorSetSampler)
    where R: PersistentDescriptorSetResources
{
    #[inline]
    fn num_buffers(&self) -> usize {
        self.0.num_buffers()
    }

    #[inline]
    fn buffer(&self, index: usize) -> Option<(&BufferAccess, u32)> {
        self.0.buffer(index)
    }

    #[inline]
    fn num_images(&self) -> usize {
        self.0.num_images()
    }

    #[inline]
    fn image(&self, index: usize) -> Option<(&ImageViewAccess, u32)> {
        self.0.image(index)
    }
}

// Part of the PersistentDescriptorSetError for the case
// of missing usage on a buffer.
#[derive(Debug, Clone)]
pub enum MissingBufferUsage {
    StorageBuffer, UniformBuffer, StorageTexelBuffer, UniformTexelBuffer
}

// Part of the PersistentDescriptorSetError for the case
// of missing usage on an image.
#[derive(Debug, Clone)]
pub enum MissingImageUsage {
    InputAttachment, Sampled, Storage
}

/// Error related to the persistent descriptor set.
#[derive(Debug, Clone)]
pub enum PersistentDescriptorSetError {
    /// Expected one type of resource but got another.
    WrongDescriptorTy {
        /// The expected descriptor type.
        expected: DescriptorType,
    },

    /// Expected nothing.
    EmptyExpected,

    /// Tried to add too many elements to an array.
    ArrayOutOfBounds,

    /// Didn't fill all the elements of an array before leaving.
    MissingArrayElements {
        /// Number of expected elements.
        expected: u32,
        /// Number of elements that were added.
        obtained: u32,
    },

    /// The image view isn't compatible with the sampler.
    IncompatibleImageViewSampler,

    /// The buffer is missing the correct usage.
    MissingBufferUsage(MissingBufferUsage),

    /// The image is missing the correct usage.
    MissingImageUsage(MissingImageUsage),

    /// Expected a multisampled image, but got a single-sampled image.
    ExpectedMultisampled,

    /// Expected a single-sampled image, but got a multisampled image.
    UnexpectedMultisampled,

    /// The number of array layers of an image doesn't match what was expected.
    ArrayLayersMismatch {
        /// Number of expected array layers for the image.
        expected: u32,
        /// Number of array layers of the image that was added.
        obtained: u32,
    },

    /// The format of an image view doesn't match what was expected.
    ImageViewFormatMismatch {
        /// Expected format.
        expected: Format,
        /// Format of the image view that was passed.
        obtained: Format,
    },

    /// The type of an image view doesn't match what was expected.
    ImageViewTypeMismatch {
        /// Expected type.
        expected: DescriptorImageDescDimensions,
        /// Type of the image view that was passed.
        obtained: DescriptorImageDescDimensions,
    },
}

impl error::Error for PersistentDescriptorSetError {
    #[inline]
    fn description(&self) -> &str {
        match *self {
            PersistentDescriptorSetError::WrongDescriptorTy { .. } => {
                "expected one type of resource but got another"
            },
            PersistentDescriptorSetError::EmptyExpected => {
                "expected an empty descriptor but got something"
            },
            PersistentDescriptorSetError::ArrayOutOfBounds => {
                "tried to add too many elements to an array"
            },
            PersistentDescriptorSetError::MissingArrayElements { .. } => {
                "didn't fill all the elements of an array before leaving"
            },
            PersistentDescriptorSetError::IncompatibleImageViewSampler => {
                "the image view isn't compatible with the sampler"
            },
            PersistentDescriptorSetError::MissingBufferUsage { .. } => {
                "the buffer is missing the correct usage"
            },
            PersistentDescriptorSetError::MissingImageUsage { .. } => {
                "the image is missing the correct usage"
            },
            PersistentDescriptorSetError::ExpectedMultisampled => {
                "expected a multisampled image, but got a single-sampled image"
            },
            PersistentDescriptorSetError::UnexpectedMultisampled => {
                "expected a single-sampled image, but got a multisampled image"
            },
            PersistentDescriptorSetError::ArrayLayersMismatch { .. } => {
                "the number of array layers of an image doesn't match what was expected"
            },
            PersistentDescriptorSetError::ImageViewFormatMismatch { .. } => {
                "the format of an image view doesn't match what was expected"
            },
            PersistentDescriptorSetError::ImageViewTypeMismatch { .. } => {
                "the type of an image view doesn't match what was expected"
            },
        }
    }
}

impl fmt::Display for PersistentDescriptorSetError {
    #[inline]
    fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        write!(fmt, "{}", error::Error::description(self))
    }
}

/// Error when building a persistent descriptor set.
#[derive(Debug, Clone)]
pub enum PersistentDescriptorSetBuildError {
    /// Out of memory.
    OomError(OomError),

    /// Didn't fill all the descriptors before building.
    MissingDescriptors {
        /// Number of expected descriptors.
        expected: u32,
        /// Number of descriptors that were added.
        obtained: u32,
    },
}

impl error::Error for PersistentDescriptorSetBuildError {
    #[inline]
    fn description(&self) -> &str {
        match *self {
            PersistentDescriptorSetBuildError::MissingDescriptors { .. } => {
                "didn't fill all the descriptors before building"
            },
            PersistentDescriptorSetBuildError::OomError(_) => {
                "not enough memory available"
            },
        }
    }
}

impl From<OomError> for PersistentDescriptorSetBuildError {
    #[inline]
    fn from(err: OomError) -> PersistentDescriptorSetBuildError {
        PersistentDescriptorSetBuildError::OomError(err)
    }
}

impl fmt::Display for PersistentDescriptorSetBuildError {
    #[inline]
    fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        write!(fmt, "{}", error::Error::description(self))
    }
}