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
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
// Copyright (c) 2016 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::RenderPass;
use crate::{
    device::{Device, DeviceOwned},
    format::Format,
    image::{view::ImageViewType, ImageDimensions, ImageViewAbstract, SampleCount},
    OomError, VulkanError, VulkanObject,
};
use smallvec::SmallVec;
use std::{
    error::Error,
    fmt::{Display, Error as FmtError, Formatter},
    hash::{Hash, Hasher},
    mem::MaybeUninit,
    ops::Range,
    ptr,
    sync::Arc,
};

/// The image views that are attached to a render pass during drawing.
///
/// A framebuffer is a collection of images, and supplies the actual inputs and outputs of each
/// attachment within a render pass. Each attachment point in the render pass must have a matching
/// image in the framebuffer.
///
/// ```
/// # use std::sync::Arc;
/// # use vulkano::render_pass::RenderPass;
/// # use vulkano::image::AttachmentImage;
/// # use vulkano::image::view::ImageView;
/// use vulkano::render_pass::{Framebuffer, FramebufferCreateInfo};
///
/// # let render_pass: Arc<RenderPass> = return;
/// # let view: Arc<ImageView<AttachmentImage>> = return;
/// // let render_pass: Arc<_> = ...;
/// let framebuffer = Framebuffer::new(
///     render_pass.clone(),
///     FramebufferCreateInfo {
///         attachments: vec![view],
///         ..Default::default()
///     },
/// ).unwrap();
/// ```
#[derive(Debug)]
pub struct Framebuffer {
    handle: ash::vk::Framebuffer,
    render_pass: Arc<RenderPass>,

    attachments: Vec<Arc<dyn ImageViewAbstract>>,
    extent: [u32; 2],
    layers: u32,
}

impl Framebuffer {
    /// Creates a new `Framebuffer`.
    pub fn new(
        render_pass: Arc<RenderPass>,
        create_info: FramebufferCreateInfo,
    ) -> Result<Arc<Framebuffer>, FramebufferCreationError> {
        let FramebufferCreateInfo {
            attachments,
            mut extent,
            mut layers,
            _ne: _,
        } = create_info;

        let device = render_pass.device();

        // VUID-VkFramebufferCreateInfo-attachmentCount-00876
        if attachments.len() != render_pass.attachments().len() {
            return Err(FramebufferCreationError::AttachmentCountMismatch {
                provided: attachments.len() as u32,
                required: render_pass.attachments().len() as u32,
            });
        }

        let auto_extent = extent[0] == 0 || extent[1] == 0;
        let auto_layers = layers == 0;

        // VUID-VkFramebufferCreateInfo-width-00885
        // VUID-VkFramebufferCreateInfo-height-00887
        if auto_extent {
            if attachments.is_empty() {
                return Err(FramebufferCreationError::AutoExtentAttachmentsEmpty);
            }

            extent = [u32::MAX, u32::MAX];
        }

        // VUID-VkFramebufferCreateInfo-layers-00889
        if auto_layers {
            if attachments.is_empty() {
                return Err(FramebufferCreationError::AutoLayersAttachmentsEmpty);
            }

            if render_pass.views_used() != 0 {
                // VUID-VkFramebufferCreateInfo-renderPass-02531
                layers = 1;
            } else {
                layers = u32::MAX;
            }
        } else {
            // VUID-VkFramebufferCreateInfo-renderPass-02531
            if render_pass.views_used() != 0 && layers != 1 {
                return Err(FramebufferCreationError::MultiviewLayersInvalid);
            }
        }

        let attachments_vk = attachments
            .iter()
            .zip(render_pass.attachments())
            .enumerate()
            .map(|(attachment_num, (image_view, attachment_desc))| {
                let attachment_num = attachment_num as u32;
                assert_eq!(device, image_view.device());

                for subpass in render_pass.subpasses() {
                    // VUID-VkFramebufferCreateInfo-pAttachments-00877
                    if subpass
                        .color_attachments
                        .iter()
                        .flatten()
                        .any(|atch_ref| atch_ref.attachment == attachment_num)
                    {
                        if !image_view.usage().color_attachment {
                            return Err(FramebufferCreationError::AttachmentMissingUsage {
                                attachment: attachment_num,
                                usage: "color_attachment",
                            });
                        }
                    }

                    // VUID-VkFramebufferCreateInfo-pAttachments-02633
                    if let Some(atch_ref) = &subpass.depth_stencil_attachment {
                        if atch_ref.attachment == attachment_num {
                            if !image_view.usage().depth_stencil_attachment {
                                return Err(FramebufferCreationError::AttachmentMissingUsage {
                                    attachment: attachment_num,
                                    usage: "depth_stencil",
                                });
                            }
                        }
                    }

                    // VUID-VkFramebufferCreateInfo-pAttachments-00879
                    if subpass
                        .input_attachments
                        .iter()
                        .flatten()
                        .any(|atch_ref| atch_ref.attachment == attachment_num)
                    {
                        if !image_view.usage().input_attachment {
                            return Err(FramebufferCreationError::AttachmentMissingUsage {
                                attachment: attachment_num,
                                usage: "input_attachment",
                            });
                        }
                    }
                }

                // VUID-VkFramebufferCreateInfo-pAttachments-00880
                if image_view.format() != attachment_desc.format {
                    return Err(FramebufferCreationError::AttachmentFormatMismatch {
                        attachment: attachment_num,
                        provided: image_view.format(),
                        required: attachment_desc.format,
                    });
                }

                // VUID-VkFramebufferCreateInfo-pAttachments-00881
                if image_view.image().samples() != attachment_desc.samples {
                    return Err(FramebufferCreationError::AttachmentSamplesMismatch {
                        attachment: attachment_num,
                        provided: image_view.image().samples(),
                        required: attachment_desc.samples,
                    });
                }

                let image_view_extent = image_view.image().dimensions().width_height();
                let image_view_array_layers = image_view.subresource_range().array_layers.end
                    - image_view.subresource_range().array_layers.start;

                // VUID-VkFramebufferCreateInfo-renderPass-04536
                if image_view_array_layers < render_pass.views_used() {
                    return Err(
                        FramebufferCreationError::MultiviewAttachmentNotEnoughLayers {
                            attachment: attachment_num,
                            provided: image_view_array_layers,
                            min: render_pass.views_used(),
                        },
                    );
                }

                // VUID-VkFramebufferCreateInfo-flags-04533
                // VUID-VkFramebufferCreateInfo-flags-04534
                if auto_extent {
                    extent[0] = extent[0].min(image_view_extent[0]);
                    extent[1] = extent[1].min(image_view_extent[1]);
                } else if image_view_extent[0] < extent[0] || image_view_extent[1] < extent[1] {
                    return Err(FramebufferCreationError::AttachmentExtentTooSmall {
                        attachment: attachment_num,
                        provided: image_view_extent,
                        min: extent,
                    });
                }

                // VUID-VkFramebufferCreateInfo-flags-04535
                if auto_layers {
                    layers = layers.min(image_view_array_layers);
                } else if image_view_array_layers < layers {
                    return Err(FramebufferCreationError::AttachmentNotEnoughLayers {
                        attachment: attachment_num,
                        provided: image_view_array_layers,
                        min: layers,
                    });
                }

                // VUID-VkFramebufferCreateInfo-pAttachments-00883
                if image_view.subresource_range().mip_levels.end
                    - image_view.subresource_range().mip_levels.start
                    != 1
                {
                    return Err(FramebufferCreationError::AttachmentMultipleMipLevels {
                        attachment: attachment_num,
                    });
                }

                // VUID-VkFramebufferCreateInfo-pAttachments-00884
                if !image_view.component_mapping().is_identity() {
                    return Err(
                        FramebufferCreationError::AttachmentComponentMappingNotIdentity {
                            attachment: attachment_num,
                        },
                    );
                }

                // VUID-VkFramebufferCreateInfo-pAttachments-00891
                if matches!(
                    image_view.view_type(),
                    ImageViewType::Dim2d | ImageViewType::Dim2dArray
                ) && matches!(
                    image_view.image().dimensions(),
                    ImageDimensions::Dim3d { .. }
                ) && image_view.format().unwrap().type_color().is_none()
                {
                    return Err(
                        FramebufferCreationError::Attachment2dArrayCompatibleDepthStencil {
                            attachment: attachment_num,
                        },
                    );
                }

                // VUID-VkFramebufferCreateInfo-flags-04113
                if image_view.view_type() == ImageViewType::Dim3d {
                    return Err(FramebufferCreationError::AttachmentViewType3d {
                        attachment: attachment_num,
                    });
                }

                Ok(image_view.internal_object())
            })
            .collect::<Result<SmallVec<[_; 4]>, _>>()?;

        {
            let properties = device.physical_device().properties();

            // VUID-VkFramebufferCreateInfo-width-00886
            // VUID-VkFramebufferCreateInfo-height-00888
            if extent[0] > properties.max_framebuffer_width
                || extent[1] > properties.max_framebuffer_height
            {
                return Err(FramebufferCreationError::MaxFramebufferExtentExceeded {
                    provided: extent,
                    max: [
                        properties.max_framebuffer_width,
                        properties.max_framebuffer_height,
                    ],
                });
            }

            // VUID-VkFramebufferCreateInfo-layers-00890
            if layers > properties.max_framebuffer_layers {
                return Err(FramebufferCreationError::MaxFramebufferLayersExceeded {
                    provided: layers,
                    max: properties.max_framebuffer_layers,
                });
            }
        }

        let create_info = ash::vk::FramebufferCreateInfo {
            flags: ash::vk::FramebufferCreateFlags::empty(),
            render_pass: render_pass.internal_object(),
            attachment_count: attachments_vk.len() as u32,
            p_attachments: attachments_vk.as_ptr(),
            width: extent[0],
            height: extent[1],
            layers,
            ..Default::default()
        };

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

        Ok(Arc::new(Framebuffer {
            handle,
            render_pass,

            attachments,
            extent,
            layers,
        }))
    }

    /// Creates a new `Framebuffer` from a raw object handle.
    ///
    /// # Safety
    ///
    /// - `handle` must be a valid Vulkan object handle created from `render_pass`.
    /// - `create_info` must match the info used to create the object.
    pub unsafe fn from_handle(
        render_pass: Arc<RenderPass>,
        handle: ash::vk::Framebuffer,
        create_info: FramebufferCreateInfo,
    ) -> Arc<Framebuffer> {
        let FramebufferCreateInfo {
            attachments,
            extent,
            layers,
            _ne: _,
        } = create_info;

        Arc::new(Framebuffer {
            handle,
            render_pass,

            attachments,
            extent,
            layers,
        })
    }
    /// Returns the renderpass that was used to create this framebuffer.
    #[inline]
    pub fn render_pass(&self) -> &Arc<RenderPass> {
        &self.render_pass
    }

    /// Returns the attachments of the framebuffer.
    #[inline]
    pub fn attachments(&self) -> &[Arc<dyn ImageViewAbstract>] {
        &self.attachments
    }

    /// Returns the extent (width and height) of the framebuffer.
    #[inline]
    pub fn extent(&self) -> [u32; 2] {
        self.extent
    }

    /// Returns the number of layers of the framebuffer.
    #[inline]
    pub fn layers(&self) -> u32 {
        self.layers
    }

    /// Returns the layer ranges for all attachments.
    #[inline]
    pub fn attached_layers_ranges(&self) -> SmallVec<[Range<u32>; 4]> {
        self.attachments
            .iter()
            .map(|img| img.subresource_range().array_layers.clone())
            .collect()
    }
}

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

unsafe impl VulkanObject for Framebuffer {
    type Object = ash::vk::Framebuffer;

    #[inline]
    fn internal_object(&self) -> ash::vk::Framebuffer {
        self.handle
    }
}

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

impl PartialEq for Framebuffer {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.handle == other.handle && self.device() == other.device()
    }
}

impl Eq for Framebuffer {}

impl Hash for Framebuffer {
    #[inline]
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.handle.hash(state);
        self.device().hash(state);
    }
}

/// Parameters to create a new `Framebuffer`.
#[derive(Clone, Debug)]
pub struct FramebufferCreateInfo {
    /// The attachment images that are to be used in the framebuffer.
    ///
    /// Attachments are specified in the same order as they are defined in the render pass, and
    /// there must be exactly as many. This implies that the list must be empty if the render pass
    /// specifies no attachments. Each image must have the correct usages set to be used for the
    /// types of attachment that the render pass will use it as.
    ///
    /// The attachment images must not be smaller than `extent` and `layers`, but can be larger and
    /// have different sizes from each other. Any leftover parts of an image will be left untouched
    /// during rendering.
    ///
    /// If the render pass has multiview enabled (`views_used` does not return 0), then each
    /// image must have at least `views_used` array layers.
    ///
    /// The default value is empty.
    pub attachments: Vec<Arc<dyn ImageViewAbstract>>,

    /// The extent (width and height) of the framebuffer.
    ///
    /// This must be no larger than the smallest width and height of the images in `attachments`.
    /// If one of the elements is set to 0, the extent will be calculated automatically from the
    /// extents of the attachment images to be the largest allowed. At least one attachment image
    /// must be specified in that case.
    ///
    /// The extent, whether automatically calculated or specified explicitly, must not be larger
    /// than the [`max_framebuffer_width`](crate::device::Properties::max_framebuffer_width) and
    /// [`max_framebuffer_height`](crate::device::Properties::max_framebuffer_height) limits.
    ///
    /// The default value is `[0, 0]`.
    pub extent: [u32; 2],

    /// The number of layers of the framebuffer.
    ///
    /// This must be no larger than the smallest number of array layers of the images in
    /// `attachments`. If set to 0, the number of layers will be calculated automatically from the
    /// layer ranges of the attachment images to be the largest allowed. At least one attachment
    /// image must be specified in that case.
    ///
    /// The number of layers, whether automatically calculated or specified explicitly, must not be
    /// larger than the
    /// [`max_framebuffer_layers`](crate::device::Properties::max_framebuffer_layers) limit.
    ///
    /// If the render pass has multiview enabled (`views_used` does not return 0), then this value
    /// must be 0 or 1.
    ///
    /// The default value is `0`.
    pub layers: u32,

    pub _ne: crate::NonExhaustive,
}

impl Default for FramebufferCreateInfo {
    #[inline]
    fn default() -> Self {
        Self {
            attachments: Vec::new(),
            extent: [0, 0],
            layers: 0,
            _ne: crate::NonExhaustive(()),
        }
    }
}

/// Error that can happen when creating a `Framebuffer`.
#[derive(Copy, Clone, Debug)]
pub enum FramebufferCreationError {
    /// Out of memory.
    OomError(OomError),

    /// An attachment image is a 2D image view created from a 3D image, and has a depth/stencil
    /// format.
    Attachment2dArrayCompatibleDepthStencil { attachment: u32 },

    /// An attachment image has a non-identity component mapping.
    AttachmentComponentMappingNotIdentity { attachment: u32 },

    /// The number of attachments doesn't match the number expected by the render pass.
    AttachmentCountMismatch { provided: u32, required: u32 },

    /// An attachment image has an extent smaller than the provided `extent`.
    AttachmentExtentTooSmall {
        attachment: u32,
        provided: [u32; 2],
        min: [u32; 2],
    },

    /// An attachment image has a `format` different from what the render pass requires.
    AttachmentFormatMismatch {
        attachment: u32,
        provided: Option<Format>,
        required: Option<Format>,
    },

    /// An attachment image is missing a usage that the render pass requires it to have.
    AttachmentMissingUsage {
        attachment: u32,
        usage: &'static str,
    },

    /// An attachment image has multiple mip levels.
    AttachmentMultipleMipLevels { attachment: u32 },

    /// An attachment image has less array layers than the provided `layers`.
    AttachmentNotEnoughLayers {
        attachment: u32,
        provided: u32,
        min: u32,
    },

    /// An attachment image has a `samples` different from what the render pass requires.
    AttachmentSamplesMismatch {
        attachment: u32,
        provided: SampleCount,
        required: SampleCount,
    },

    /// An attachment image has a `ty` of [`ImageViewType::Dim3d`].
    AttachmentViewType3d { attachment: u32 },

    /// One of the elements of `extent` is zero, but no attachment images were given to calculate
    /// the extent from.
    AutoExtentAttachmentsEmpty,

    /// `layers` is zero, but no attachment images were given to calculate the number of layers
    /// from.
    AutoLayersAttachmentsEmpty,

    /// The provided `extent` exceeds the `max_framebuffer_width` or `max_framebuffer_height`
    /// limits.
    MaxFramebufferExtentExceeded { provided: [u32; 2], max: [u32; 2] },

    /// The provided `layers` exceeds the `max_framebuffer_layers` limit.
    MaxFramebufferLayersExceeded { provided: u32, max: u32 },

    /// The render pass has multiview enabled, and an attachment image has less layers than the
    /// number of views in the render pass.
    MultiviewAttachmentNotEnoughLayers {
        attachment: u32,
        provided: u32,
        min: u32,
    },

    /// The render pass has multiview enabled, but `layers` was not 0 or 1.
    MultiviewLayersInvalid,
}

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

impl Error for FramebufferCreationError {
    #[inline]
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match *self {
            Self::OomError(ref err) => Some(err),
            _ => None,
        }
    }
}

impl Display for FramebufferCreationError {
    #[inline]
    fn fmt(&self, f: &mut Formatter) -> Result<(), FmtError> {
        match *self {
            Self::OomError(_) => write!(
                f,
                "no memory available",
            ),
            Self::Attachment2dArrayCompatibleDepthStencil { attachment } => write!(
                f,
                "attachment image {} is a 2D image view created from a 3D image, and has a depth/stencil format",
                attachment,
            ),
            Self::AttachmentComponentMappingNotIdentity { attachment } => write!(
                f,
                "attachment image {} has a non-identity component mapping",
                attachment,
            ),
            Self::AttachmentCountMismatch { .. } => write!(
                f,
                "the number of attachments doesn't match the number expected by the render pass",
            ),
            Self::AttachmentExtentTooSmall {
                attachment,
                provided,
                min,
            } => write!(
                f,
                "attachment image {} has an extent ({:?}) smaller than the provided `extent` ({:?})",
                attachment, provided, min,
            ),
            Self::AttachmentFormatMismatch {
                attachment,
                provided,
                required,
            } => write!(
                f,
                "attachment image {} has a `format` ({:?}) different from what the render pass requires ({:?})",
                attachment, provided, required,
            ),
            Self::AttachmentMissingUsage {
                attachment,
                usage,
            } => write!(
                f,
                "attachment image {} is missing usage `{}` that the render pass requires it to have",
                attachment, usage,
            ),
            Self::AttachmentMultipleMipLevels {
                attachment,
            } => write!(
                f,
                "attachment image {} has multiple mip levels",
                attachment,
            ),
            Self::AttachmentNotEnoughLayers {
                attachment,
                provided,
                min,
            } => write!(
                f,
                "attachment image {} has less layers ({}) than the provided `layers` ({})",
                attachment, provided, min,
            ),
            Self::AttachmentSamplesMismatch {
                attachment,
                provided,
                required,
            } => write!(
                f,
                "attachment image {} has a `samples` ({:?}) different from what the render pass requires ({:?})",
                attachment, provided, required,
            ),
            Self::AttachmentViewType3d {
                attachment,
            } => write!(
                f,
                "attachment image {} has a `ty` of `ImageViewType::Dim3d`",
                attachment,
            ),
            Self::AutoExtentAttachmentsEmpty => write!(
                f,
                "one of the elements of `extent` is zero, but no attachment images were given to calculate the extent from",
            ),
            Self::AutoLayersAttachmentsEmpty => write!(
                f,
                "`layers` is zero, but no attachment images were given to calculate the number of layers from",
            ),
            Self::MaxFramebufferExtentExceeded { provided, max } => write!(
                f,
                "the provided `extent` ({:?}) exceeds the `max_framebuffer_width` or `max_framebuffer_height` limits ({:?})",
                provided, max,
            ),
            Self::MaxFramebufferLayersExceeded { provided, max } => write!(
                f,
                "the provided `layers` ({}) exceeds the `max_framebuffer_layers` limit ({})",
                provided, max,
            ),
            Self::MultiviewAttachmentNotEnoughLayers {
                attachment,
                provided,
                min,
            } => write!(
                f,
                "the render pass has multiview enabled, and attachment image {} has less layers ({}) than the number of views in the render pass ({})",
                attachment, provided, min,
            ),
            Self::MultiviewLayersInvalid => write!(
                f,
                "the render pass has multiview enabled, but `layers` was not 0 or 1",
            ),
        }
    }
}

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

#[cfg(test)]
mod tests {
    use crate::{
        format::Format,
        image::{attachment::AttachmentImage, view::ImageView},
        render_pass::{Framebuffer, FramebufferCreateInfo, FramebufferCreationError, RenderPass},
    };

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

        let render_pass = single_pass_renderpass!(device.clone(),
            attachments: {
                color: {
                    load: Clear,
                    store: DontCare,
                    format: Format::R8G8B8A8_UNORM,
                    samples: 1,
                }
            },
            pass: {
                color: [color],
                depth_stencil: {}
            }
        )
        .unwrap();

        let view = ImageView::new_default(
            AttachmentImage::new(device, [1024, 768], Format::R8G8B8A8_UNORM).unwrap(),
        )
        .unwrap();
        let _ = Framebuffer::new(
            render_pass,
            FramebufferCreateInfo {
                attachments: vec![view],
                ..Default::default()
            },
        )
        .unwrap();
    }

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

        let render_pass = RenderPass::empty_single_pass(device).unwrap();
        let res = Framebuffer::new(
            render_pass.clone(),
            FramebufferCreateInfo {
                extent: [0xffffffff, 0xffffffff],
                layers: 1,
                ..Default::default()
            },
        );
        match res {
            Err(FramebufferCreationError::MaxFramebufferExtentExceeded { .. }) => (),
            _ => panic!(),
        }

        let res = Framebuffer::new(
            render_pass,
            FramebufferCreateInfo {
                extent: [1, 1],
                layers: 0xffffffff,
                ..Default::default()
            },
        );

        match res {
            Err(FramebufferCreationError::MaxFramebufferLayersExceeded { .. }) => (),
            _ => panic!(),
        }
    }

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

        let render_pass = single_pass_renderpass!(device.clone(),
            attachments: {
                color: {
                    load: Clear,
                    store: DontCare,
                    format: Format::R8G8B8A8_UNORM,
                    samples: 1,
                }
            },
            pass: {
                color: [color],
                depth_stencil: {}
            }
        )
        .unwrap();

        let view = ImageView::new_default(
            AttachmentImage::new(device, [1024, 768], Format::R8_UNORM).unwrap(),
        )
        .unwrap();

        match Framebuffer::new(
            render_pass,
            FramebufferCreateInfo {
                attachments: vec![view],
                ..Default::default()
            },
        ) {
            Err(FramebufferCreationError::AttachmentFormatMismatch { .. }) => (),
            _ => panic!(),
        }
    }

    // TODO: check samples mismatch

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

        let render_pass = single_pass_renderpass!(device.clone(),
            attachments: {
                color: {
                    load: Clear,
                    store: DontCare,
                    format: Format::R8G8B8A8_UNORM,
                    samples: 1,
                }
            },
            pass: {
                color: [color],
                depth_stencil: {}
            }
        )
        .unwrap();

        let view = ImageView::new_default(
            AttachmentImage::new(device, [600, 600], Format::R8G8B8A8_UNORM).unwrap(),
        )
        .unwrap();

        let _ = Framebuffer::new(
            render_pass,
            FramebufferCreateInfo {
                attachments: vec![view],
                extent: [512, 512],
                layers: 1,
                ..Default::default()
            },
        )
        .unwrap();
    }

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

        let render_pass = single_pass_renderpass!(device.clone(),
            attachments: {
                color: {
                    load: Clear,
                    store: DontCare,
                    format: Format::R8G8B8A8_UNORM,
                    samples: 1,
                }
            },
            pass: {
                color: [color],
                depth_stencil: {}
            }
        )
        .unwrap();

        let view = ImageView::new_default(
            AttachmentImage::new(device, [512, 700], Format::R8G8B8A8_UNORM).unwrap(),
        )
        .unwrap();

        match Framebuffer::new(
            render_pass,
            FramebufferCreateInfo {
                attachments: vec![view],
                extent: [600, 600],
                layers: 1,
                ..Default::default()
            },
        ) {
            Err(FramebufferCreationError::AttachmentExtentTooSmall { .. }) => (),
            _ => panic!(),
        }
    }

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

        let render_pass = single_pass_renderpass!(device.clone(),
            attachments: {
                a: {
                    load: Clear,
                    store: DontCare,
                    format: Format::R8G8B8A8_UNORM,
                    samples: 1,
                },
                b: {
                    load: Clear,
                    store: DontCare,
                    format: Format::R8G8B8A8_UNORM,
                    samples: 1,
                }
            },
            pass: {
                color: [a, b],
                depth_stencil: {}
            }
        )
        .unwrap();

        let a = ImageView::new_default(
            AttachmentImage::new(device.clone(), [256, 512], Format::R8G8B8A8_UNORM).unwrap(),
        )
        .unwrap();
        let b = ImageView::new_default(
            AttachmentImage::new(device, [512, 128], Format::R8G8B8A8_UNORM).unwrap(),
        )
        .unwrap();

        let framebuffer = Framebuffer::new(
            render_pass,
            FramebufferCreateInfo {
                attachments: vec![a, b],
                ..Default::default()
            },
        )
        .unwrap();

        match (framebuffer.extent(), framebuffer.layers()) {
            ([256, 128], 1) => (),
            _ => panic!(),
        }
    }

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

        let render_pass = single_pass_renderpass!(device.clone(),
            attachments: {
                a: {
                    load: Clear,
                    store: DontCare,
                    format: Format::R8G8B8A8_UNORM,
                    samples: 1,
                },
                b: {
                    load: Clear,
                    store: DontCare,
                    format: Format::R8G8B8A8_UNORM,
                    samples: 1,
                }
            },
            pass: {
                color: [a, b],
                depth_stencil: {}
            }
        )
        .unwrap();

        let view = ImageView::new_default(
            AttachmentImage::new(device, [256, 512], Format::R8G8B8A8_UNORM).unwrap(),
        )
        .unwrap();

        let res = Framebuffer::new(
            render_pass,
            FramebufferCreateInfo {
                attachments: vec![view],
                ..Default::default()
            },
        );

        match res {
            Err(FramebufferCreationError::AttachmentCountMismatch {
                required: 2,
                provided: 1,
            }) => (),
            _ => panic!(),
        }
    }

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

        let render_pass = single_pass_renderpass!(device.clone(),
            attachments: {
                a: {
                    load: Clear,
                    store: DontCare,
                    format: Format::R8G8B8A8_UNORM,
                    samples: 1,
                }
            },
            pass: {
                color: [a],
                depth_stencil: {}
            }
        )
        .unwrap();

        let a = ImageView::new_default(
            AttachmentImage::new(device.clone(), [256, 512], Format::R8G8B8A8_UNORM).unwrap(),
        )
        .unwrap();
        let b = ImageView::new_default(
            AttachmentImage::new(device, [256, 512], Format::R8G8B8A8_UNORM).unwrap(),
        )
        .unwrap();

        let res = Framebuffer::new(
            render_pass,
            FramebufferCreateInfo {
                attachments: vec![a, b],
                ..Default::default()
            },
        );

        match res {
            Err(FramebufferCreationError::AttachmentCountMismatch {
                required: 1,
                provided: 2,
            }) => (),
            _ => panic!(),
        }
    }

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

        let render_pass = RenderPass::empty_single_pass(device).unwrap();
        let _ = Framebuffer::new(
            render_pass,
            FramebufferCreateInfo {
                extent: [512, 512],
                layers: 1,
                ..Default::default()
            },
        )
        .unwrap();
    }

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

        let render_pass = RenderPass::empty_single_pass(device).unwrap();
        let res = Framebuffer::new(render_pass, FramebufferCreateInfo::default());
        match res {
            Err(FramebufferCreationError::AutoExtentAttachmentsEmpty) => (),
            _ => panic!(),
        }
    }
}