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
use vk::*;
use std::rc::Rc as RefCounter;
use std::ops::Deref;
use {VkHandle, DeviceChild, Device};
#[cfg(feature = "Implements")] use VkResultHandler;
#[cfg(feature = "Implements")] use std::ptr::null;
#[cfg(feature = "Implements")] use std::mem::uninitialized as resv;
use std::borrow::Borrow; use std::mem::transmute;
struct DeviceMemoryCell(VkDeviceMemory, ::Device);
struct BufferCell(VkBuffer, ::Device);
#[cfg(feature = "VK_KHR_swapchain")]
pub enum ImageCell
{
DeviceChild { obj: VkImage, dev: ::Device, dim: VkImageType, fmt: VkFormat, size: ::Extent3D },
SwapchainChild { obj: VkImage, owner: ::Swapchain, fmt: VkFormat }
}
#[cfg(not(feature = "VK_KHR_swapchain"))] #[cfg_attr(not(feature = "Implements"), allow(dead_code))]
struct ImageCell { obj: VkImage, dev: ::Device, dim: VkImageType, fmt: VkFormat, size: ::Extent3D }
pub struct DeviceMemory(RefCounter<DeviceMemoryCell>);
#[derive(Clone)] pub struct Buffer(RefCounter<BufferCell>);
#[derive(Clone)] pub struct Image(RefCounter<ImageCell>);
pub struct BufferView(VkBufferView, Buffer);
struct ImageViewCell(VkImageView, Image);
#[derive(Clone)]
pub struct ImageView(RefCounter<ImageViewCell>);
impl Deref for BufferView { type Target = Buffer; fn deref(&self) -> &Buffer { &self.1 } }
impl Deref for ImageView { type Target = Image; fn deref(&self) -> &Image { &self.0 .1 } }
#[cfg(feature = "Implements")] DeviceChildCommonDrop! { for DeviceMemoryCell[vkFreeMemory], BufferCell[vkDestroyBuffer] }
#[cfg(feature = "Implements")] impl Drop for ImageCell
{
fn drop(&mut self)
{
#[cfg(feature = "VK_KHR_swapchain")]
match *self
{
ImageCell::DeviceChild { obj, ref dev, .. } => unsafe { vkDestroyImage(dev.native_ptr(), obj, null()); },
_ => ()
}
#[cfg(not(feature = "VK_KHR_swapchain"))]
unsafe { vkDestroyImage(self.dev.native_ptr(), self.obj, null()); }
}
}
#[cfg(feature = "Implements")]
impl Drop for BufferView { fn drop(&mut self) { unsafe { vkDestroyBufferView(self.device().native_ptr(), self.native_ptr(), null()) }; } }
#[cfg(feature = "Implements")]
impl Drop for ImageViewCell { fn drop(&mut self) { unsafe { vkDestroyImageView (self.1.device().native_ptr(), self.0, null()) }; } }
impl VkHandle for DeviceMemory { type Handle = VkDeviceMemory; fn native_ptr(&self) -> VkDeviceMemory { self.0 .0 } }
impl VkHandle for Buffer { type Handle = VkBuffer; fn native_ptr(&self) -> VkBuffer { self.0 .0 } }
impl VkHandle for BufferView { type Handle = VkBufferView; fn native_ptr(&self) -> VkBufferView { self.0 } }
impl VkHandle for ImageView { type Handle = VkImageView; fn native_ptr(&self) -> VkImageView { self.0 .0 } }
impl DeviceChild for DeviceMemory { fn device(&self) -> &::Device { &self.0 .1 } }
impl DeviceChild for Buffer { fn device(&self) -> &::Device { &self.0 .1 } }
impl DeviceChild for BufferView { fn device(&self) -> &::Device { self.deref().device() } }
impl DeviceChild for ImageView { fn device(&self) -> &::Device { self.deref().device() } }
impl VkHandle for Image
{
type Handle = VkImage;
#[cfg(feature = "VK_KHR_swapchain")]
fn native_ptr(&self) -> VkImage
{
match *self.0
{
ImageCell::DeviceChild { obj, .. } | ImageCell::SwapchainChild { obj, .. } => obj
}
}
#[cfg(not(feature = "VK_KHR_swapchain"))]
fn native_ptr(&self) -> VkImage { self.0.obj }
}
impl DeviceChild for Image
{
#[cfg(feature = "VK_KHR_swapchain")]
fn device(&self) -> &Device
{
match *self.0
{
ImageCell::DeviceChild { ref dev, .. } => dev,
ImageCell::SwapchainChild { ref owner, .. } => owner.device()
}
}
#[cfg(not(feature = "VK_KHR_swapchain"))]
fn device(&self) -> &Device { &self.0.dev }
}
#[cfg(feature = "Implements")]
impl DeviceMemory
{
pub fn allocate(device: &::Device, size: usize, type_index: u32) -> ::Result<Self>
{
let mut h = VK_NULL_HANDLE as _;
unsafe { vkAllocateMemory(device.native_ptr(), &VkMemoryAllocateInfo { allocationSize: size as _, memoryTypeIndex: type_index, .. Default::default() },
::std::ptr::null(), &mut h) }.into_result().map(|_| DeviceMemory(RefCounter::new(DeviceMemoryCell(h, device.clone()))))
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct BufferUsage(pub VkBufferUsageFlags);
impl BufferUsage
{
pub const TRANSFER_SRC: Self = BufferUsage(VK_BUFFER_USAGE_TRANSFER_SRC_BIT);
pub const TRANSFER_DEST: Self = BufferUsage(VK_BUFFER_USAGE_TRANSFER_DST_BIT);
pub const UNIFORM_TEXEL_BUFFER: Self = BufferUsage(VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT);
pub const STORAGE_TEXEL_BUFFER: Self = BufferUsage(VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT);
pub const UNIFORM_BUFFER: Self = BufferUsage(VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT);
pub const STORAGE_BUFFER: Self = BufferUsage(VK_BUFFER_USAGE_STORAGE_BUFFER_BIT);
pub const INDEX_BUFFER: Self = BufferUsage(VK_BUFFER_USAGE_INDEX_BUFFER_BIT);
pub const VERTEX_BUFFER: Self = BufferUsage(VK_BUFFER_USAGE_VERTEX_BUFFER_BIT);
pub const INDIRECT_BUFFER: Self = BufferUsage(VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT);
pub fn transfer_src(&self) -> Self { BufferUsage(self.0 | Self::TRANSFER_SRC.0) }
pub fn transfer_dest(&self) -> Self { BufferUsage(self.0 | Self::TRANSFER_DEST.0) }
pub fn uniform_texel_buffer(&self) -> Self { BufferUsage(self.0 | Self::UNIFORM_TEXEL_BUFFER.0) }
pub fn storage_texel_buffer(&self) -> Self { BufferUsage(self.0 | Self::STORAGE_TEXEL_BUFFER.0) }
pub fn uniform_buffer(&self) -> Self { BufferUsage(self.0 | Self::UNIFORM_BUFFER.0) }
pub fn storage_buffer(&self) -> Self { BufferUsage(self.0 | Self::STORAGE_BUFFER.0) }
pub fn index_buffer(&self) -> Self { BufferUsage(self.0 | Self::INDEX_BUFFER.0) }
pub fn vertex_buffer(&self) -> Self { BufferUsage(self.0 | Self::VERTEX_BUFFER.0) }
pub fn indirect_buffer(&self) -> Self { BufferUsage(self.0 | Self::INDIRECT_BUFFER.0) }
pub fn default_access_mask(&self) -> VkAccessFlags
{
let mut bits = 0;
if (self.0 & Self::TRANSFER_SRC.0) != 0 { bits |= VK_ACCESS_TRANSFER_READ_BIT; }
if (self.0 & Self::TRANSFER_DEST.0) != 0 { bits |= VK_ACCESS_TRANSFER_WRITE_BIT; }
if (self.0 & Self::UNIFORM_TEXEL_BUFFER.0) != 0 { bits |= VK_ACCESS_UNIFORM_READ_BIT; }
if (self.0 & Self::STORAGE_TEXEL_BUFFER.0) != 0 { bits |= VK_ACCESS_UNIFORM_READ_BIT; }
if (self.0 & Self::UNIFORM_BUFFER.0) != 0 { bits |= VK_ACCESS_UNIFORM_READ_BIT; }
if (self.0 & Self::STORAGE_BUFFER.0) != 0 { bits |= VK_ACCESS_UNIFORM_READ_BIT; }
if (self.0 & Self::INDEX_BUFFER.0) != 0 { bits |= VK_ACCESS_INDEX_READ_BIT; }
if (self.0 & Self::VERTEX_BUFFER.0) != 0 { bits |= VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT; }
if (self.0 & Self::INDIRECT_BUFFER.0) != 0 { bits |= VK_ACCESS_INDIRECT_COMMAND_READ_BIT; }
bits
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[repr(C)] pub enum BufferSparseBinding
{
None = 0,
Bound = VK_BUFFER_CREATE_SPARSE_BINDING_BIT as _,
Residency = (VK_BUFFER_CREATE_SPARSE_BINDING_BIT | VK_BUFFER_CREATE_SPARSE_RESIDENCY_BIT) as _,
Aliased = (VK_BUFFER_CREATE_SPARSE_BINDING_BIT | VK_BUFFER_CREATE_SPARSE_ALIASED_BIT) as _,
Both = (VK_BUFFER_CREATE_SPARSE_BINDING_BIT | VK_BUFFER_CREATE_SPARSE_RESIDENCY_BIT | VK_BUFFER_CREATE_SPARSE_ALIASED_BIT) as _
}
pub struct BufferDesc { cinfo: VkBufferCreateInfo }
impl BufferDesc
{
pub fn new(byte_size: usize, usage: BufferUsage) -> Self
{
BufferDesc
{
cinfo: VkBufferCreateInfo
{
size: byte_size as _, usage: usage.0, .. Default::default()
}
}
}
pub fn sharing_queue_families(&mut self, indices: &[u32]) -> &mut Self
{
self.cinfo.sharingMode = if indices.is_empty() { VK_SHARING_MODE_EXCLUSIVE } else { VK_SHARING_MODE_CONCURRENT };
self.cinfo.queueFamilyIndexCount = indices.len() as _;
self.cinfo.pQueueFamilyIndices = indices.as_ptr();
self
}
pub fn sparse_binding_opt(&mut self, opt: BufferSparseBinding) -> &mut Self
{
self.cinfo.flags = opt as _; self
}
#[cfg(feature = "Implements")]
pub fn create(&self, device: &::Device) -> ::Result<Buffer>
{
let mut h = VK_NULL_HANDLE as _;
unsafe { vkCreateBuffer(device.native_ptr(), &self.cinfo, ::std::ptr::null(), &mut h) }
.into_result().map(|_| Buffer(RefCounter::new(BufferCell(h, device.clone()))))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ImageUsage(pub VkImageUsageFlags);
impl ImageUsage
{
pub const TRANSFER_SRC: Self = ImageUsage(VK_IMAGE_USAGE_TRANSFER_SRC_BIT);
pub const TRANSFER_DEST: Self = ImageUsage(VK_IMAGE_USAGE_TRANSFER_DST_BIT);
pub const SAMPLED: Self = ImageUsage(VK_IMAGE_USAGE_SAMPLED_BIT);
pub const STORAGE: Self = ImageUsage(VK_IMAGE_USAGE_STORAGE_BIT);
pub const COLOR_ATTACHMENT: Self = ImageUsage(VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT);
pub const DEPTH_STENCIL_ATTACHMENT: Self = ImageUsage(VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT);
pub const TRANSIENT_ATTACHMENT: Self = ImageUsage(VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT);
pub const INPUT_ATTACHMENT: Self = ImageUsage(VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT);
pub fn transfer_src(&self) -> Self { ImageUsage(self.0 | Self::TRANSFER_SRC.0) }
pub fn transfer_dest(&self) -> Self { ImageUsage(self.0 | Self::TRANSFER_DEST.0) }
pub fn sampled(&self) -> Self { ImageUsage(self.0 | Self::SAMPLED.0) }
pub fn storage(&self) -> Self { ImageUsage(self.0 | Self::STORAGE.0) }
pub fn color_attachment(&self) -> Self { ImageUsage(self.0 | Self::COLOR_ATTACHMENT.0) }
pub fn depth_stencil_attachment(&self) -> Self { ImageUsage(self.0 | Self::DEPTH_STENCIL_ATTACHMENT.0) }
pub fn transient_attachment(&self) -> Self { ImageUsage(self.0 | Self::TRANSIENT_ATTACHMENT.0) }
pub fn input_attachment(&self) -> Self { ImageUsage(self.0 | Self::INPUT_ATTACHMENT.0) }
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ImageFlags(pub VkImageCreateFlags);
impl ImageFlags
{
pub const EMPTY: Self = ImageFlags(0);
pub const SPARSE_BINDING: Self = ImageFlags(VK_IMAGE_CREATE_SPARSE_BINDING_BIT);
pub const SPARSE_RESIDENCY: Self = ImageFlags(VK_IMAGE_CREATE_SPARSE_BINDING_BIT | VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT);
pub const SPARSE_ALIASED: Self = ImageFlags(VK_IMAGE_CREATE_SPARSE_BINDING_BIT | VK_IMAGE_CREATE_SPARSE_ALIASED_BIT);
pub const MUTABLE_FORMAT: Self = ImageFlags(VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT);
pub const CUBE_COMPATIBLE: Self = ImageFlags(VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT);
pub fn sparse_binding(&self) -> Self { ImageFlags(self.0 | Self::SPARSE_BINDING.0) }
pub fn sparse_residency(&self) -> Self { ImageFlags(self.0 | Self::SPARSE_RESIDENCY.0) }
pub fn sparse_aliased(&self) -> Self { ImageFlags(self.0 | Self::SPARSE_ALIASED.0) }
pub fn mutable_format(&self) -> Self { ImageFlags(self.0 | Self::MUTABLE_FORMAT.0) }
pub fn cube_compatible(&self) -> Self { ImageFlags(self.0 | Self::CUBE_COMPATIBLE.0) }
}
#[derive(Debug, Clone, PartialEq, Eq)] pub struct ImageDesc(VkImageCreateInfo);
impl ImageDesc
{
pub fn new<Size: ImageSize>(size: &Size, format: VkFormat, usage: ImageUsage, initial_layout: ImageLayout) -> Self
{
ImageDesc(VkImageCreateInfo
{
imageType: Size::DIMENSION, extent: size.conv(), format, usage: usage.0,
mipLevels: 1, arrayLayers:1, samples: 1, initialLayout: initial_layout as _,
.. Default::default()
})
}
pub fn sharing_queue_families(&mut self, indices: &[u32]) -> &mut Self
{
self.0.sharingMode = if indices.is_empty() { VK_SHARING_MODE_EXCLUSIVE } else { VK_SHARING_MODE_CONCURRENT };
self.0.queueFamilyIndexCount = indices.len() as _;
self.0.pQueueFamilyIndices = indices.as_ptr();
self
}
pub fn sample_counts(&mut self, count_bits: u32) -> &mut Self
{
self.0.samples = count_bits; self
}
pub fn use_linear_tiling(&mut self) -> &mut Self
{
self.0.tiling = VK_IMAGE_TILING_LINEAR; self
}
pub fn flags(&mut self, opt: ImageFlags) -> &mut Self
{
self.0.flags = opt.0; self
}
pub fn array_layers(&mut self, layers: u32) -> &mut Self { self.0.arrayLayers = layers; self }
pub fn mip_levels(&mut self, levels: u32) -> &mut Self { self.0.mipLevels = levels; self }
}
#[cfg(feature = "Implements")]
impl ImageDesc
{
#[cfg(not(feature = "VK_KHR_swapchain"))]
pub fn create(&self, device: &::Device) -> ::Result<Image>
{
let mut h = VK_NULL_HANDLE as _;
unsafe { vkCreateImage(device.native_ptr(), &self.0, ::std::ptr::null(), &mut h) }
.into_result().map(|_| Image(RefCounter::new(ImageCell
{
obj: h, dev: device.clone(), dim: self.0.imageType, fmt: self.0.format,
size: ::Extent3D(self.0.extent.width, self.0.extent.height, self.0.extent.depth)
})))
}
#[cfg(feature = "VK_KHR_swapchain")]
pub fn create(&self, device: &::Device) -> ::Result<Image>
{
let mut h = VK_NULL_HANDLE as _;
unsafe { vkCreateImage(device.native_ptr(), &self.0, ::std::ptr::null(), &mut h) }
.into_result().map(|_| Image(RefCounter::new(ImageCell::DeviceChild
{
obj: h, dev: device.clone(), dim: self.0.imageType, fmt: self.0.format,
size: ::Extent3D(self.0.extent.width, self.0.extent.height, self.0.extent.depth)
})))
}
}
impl Image
{
pub fn format(&self) -> VkFormat
{
#[cfg(feature = "VK_KHR_swapchain")]
match *self.0 { ImageCell::DeviceChild { fmt, .. } | ImageCell::SwapchainChild { fmt, .. } => fmt }
#[cfg(not(feature = "VK_KHR_swapchain"))]
{ self.0.fmt }
}
pub fn size(&self) -> &::Extent3D
{
#[cfg(feature = "VK_KHR_swapchain")]
match *self.0
{
ImageCell::DeviceChild { ref size, .. } => size,
ImageCell::SwapchainChild { ref owner, .. } => owner.size()
}
#[cfg(not(feature = "VK_KHR_swapchain"))]
&self.0.size
}
#[cfg(feature = "Implements")]
fn dimension(&self) -> VkImageViewType
{
#[cfg(feature = "VK_KHR_swapchain")]
let dim = match *self.0 { ImageCell::DeviceChild { dim, .. } => dim, ImageCell::SwapchainChild { .. } => VK_IMAGE_TYPE_2D };
#[cfg(not(feature = "VK_KHR_swapchain"))]
let dim = self.0.dim;
match dim
{
VK_IMAGE_TYPE_1D => VK_IMAGE_VIEW_TYPE_1D,
VK_IMAGE_TYPE_2D => VK_IMAGE_VIEW_TYPE_2D,
VK_IMAGE_TYPE_3D => VK_IMAGE_VIEW_TYPE_3D,
_ => unreachable!()
}
}
}
#[cfg(feature = "Implements")]
impl Buffer
{
pub fn create_view(&self, format: VkFormat, range: ::std::ops::Range<u64>) -> ::Result<BufferView>
{
let cinfo = VkBufferViewCreateInfo
{
buffer: self.native_ptr(), format, offset: range.start, range: range.end - range.start, .. Default::default()
};
let mut h = VK_NULL_HANDLE as _;
unsafe { vkCreateBufferView(self.device().native_ptr(), &cinfo, ::std::ptr::null(), &mut h) }
.into_result().map(|_| BufferView(h, self.clone()))
}
}
#[cfg(feature = "Implements")]
impl Image
{
pub fn create_view(&self, format: Option<VkFormat>, vtype: Option<VkImageViewType>,
cmap: &ComponentMapping, subresource_range: &ImageSubresourceRange) -> ::Result<ImageView>
{
let (format, vtype) = (format.unwrap_or(self.format()), vtype.unwrap_or(self.dimension()));
let cinfo = VkImageViewCreateInfo
{
image: self.native_ptr(), viewType: vtype, format, components: unsafe { ::std::mem::transmute_copy(cmap) },
subresourceRange: subresource_range.0.clone(), .. Default::default()
};
let mut h = VK_NULL_HANDLE as _;
unsafe { vkCreateImageView(self.device().native_ptr(), &cinfo, ::std::ptr::null(), &mut h) }
.into_result().map(|_| ImageView(RefCounter::new(ImageViewCell(h, self.clone()))))
}
pub fn image_subresource_layout(&self, subres_aspect: AspectMask, subres_mip_level: u32, subres_array_layer: u32) -> VkSubresourceLayout
{
let mut s = unsafe { resv() };
let subres = VkImageSubresource { aspectMask: subres_aspect.0, mipLevel: subres_mip_level, arrayLayer: subres_array_layer };
unsafe { vkGetImageSubresourceLayout(self.device().native_ptr(), self.native_ptr(), &subres, &mut s) }; s
}
}
#[cfg(feature = "Implements")]
impl DeviceMemory
{
pub fn map(&self, range: ::std::ops::Range<usize>) -> ::Result<MappedMemoryRange>
{
let mut p = ::std::ptr::null_mut();
unsafe { vkMapMemory(self.device().native_ptr(), self.native_ptr(), range.start as _, (range.end - range.start) as _,
0, &mut p) }.into_result().map(|_| MappedMemoryRange(self, p as *mut _, range.start as _ .. range.end as _))
}
pub unsafe fn unmap(&self)
{
vkUnmapMemory(self.0 .1.native_ptr(), self.native_ptr());
}
pub fn commitment_bytes(&self) -> VkDeviceSize
{
let mut b = 0;
unsafe { vkGetDeviceMemoryCommitment(self.device().native_ptr(), self.native_ptr(), &mut b) }; b
}
}
#[cfg(feature = "Implements")]
impl Device
{
pub fn bind_buffers(&self, bounds: &[(&Buffer, &DeviceMemory, VkDeviceSize)]) -> ::Result<()>
{
let infos: Vec<_> = bounds.iter().map(|&(b, m, offs)| VkBindBufferMemoryInfo
{
buffer: b.native_ptr(), memory: m.native_ptr(), memoryOffset: offs, .. Default::default()
}).collect();
unsafe
{
vkBindBufferMemory2(self.native_ptr(), infos.len() as _, infos.as_ptr()).into_result()
}
}
pub fn bind_images(&self, bounds: &[(&Image, &DeviceMemory, VkDeviceSize)]) -> ::Result<()>
{
let infos: Vec<_> = bounds.iter().map(|&(i, m, offs)| VkBindImageMemoryInfo
{
image: i.native_ptr(), memory: m.native_ptr(), memoryOffset: offs, .. Default::default()
}).collect();
unsafe
{
vkBindImageMemory2(self.native_ptr(), infos.len() as _, infos.as_ptr()).into_result()
}
}
pub fn bind_resources(&self, buf_bounds: &[(&Buffer, &DeviceMemory, VkDeviceSize)],
img_bounds: &[(&Image, &DeviceMemory, VkDeviceSize)]) -> ::Result<()>
{
self.bind_buffers(buf_bounds).and(self.bind_images(img_bounds))
}
}
#[cfg(feature = "Implements")]
pub trait MemoryBound
{
fn requirements(&self) -> VkMemoryRequirements;
fn bind(&self, memory: &DeviceMemory, offset: usize) -> ::Result<()>;
}
#[cfg(feature = "Implements")]
impl MemoryBound for Buffer
{
fn requirements(&self) -> VkMemoryRequirements
{
let mut p = unsafe { resv() };
unsafe { vkGetBufferMemoryRequirements(self.device().native_ptr(), self.native_ptr(), &mut p) }; p
}
fn bind(&self, memory: &DeviceMemory, offset: usize) -> ::Result<()>
{
unsafe { vkBindBufferMemory(self.device().native_ptr(), self.native_ptr(), memory.native_ptr(), offset as _) }.into_result()
}
}
#[cfg(feature = "Implements")]
impl MemoryBound for Image
{
fn requirements(&self) -> VkMemoryRequirements
{
let mut p = unsafe { resv() };
unsafe { vkGetImageMemoryRequirements(self.device().native_ptr(), self.native_ptr(), &mut p) }; p
}
fn bind(&self, memory: &DeviceMemory, offset: usize) -> ::Result<()>
{
unsafe { vkBindImageMemory(self.device().native_ptr(), self.native_ptr(), memory.native_ptr(), offset as _) }.into_result()
}
}
#[cfg(feature = "Implements")]
impl Image
{
pub fn sparse_requirements(&self) -> Vec<VkSparseImageMemoryRequirements>
{
let mut n = 0;
unsafe { vkGetImageSparseMemoryRequirements(self.device().native_ptr(), self.native_ptr(), &mut n, ::std::ptr::null_mut()) };
let mut v = Vec::with_capacity(n as _); unsafe { v.set_len(n as _) };
unsafe { vkGetImageSparseMemoryRequirements(self.device().native_ptr(), self.native_ptr(), &mut n, v.as_mut_ptr()) };
v
}
}
pub trait ImageSize
{
const DIMENSION: VkImageType;
fn conv(&self) -> VkExtent3D;
}
impl ImageSize for ::Extent1D
{
const DIMENSION: VkImageType = VK_IMAGE_TYPE_1D;
fn conv(&self) -> VkExtent3D { VkExtent3D { width: self.0, height: 1, depth: 1 } }
}
impl ImageSize for ::Extent2D
{
const DIMENSION: VkImageType = VK_IMAGE_TYPE_2D;
fn conv(&self) -> VkExtent3D { VkExtent3D { width: self.0, height: self.1, depth: 1 } }
}
impl ImageSize for ::Extent3D
{
const DIMENSION: VkImageType = VK_IMAGE_TYPE_3D;
fn conv(&self) -> VkExtent3D { AsRef::<VkExtent3D>::as_ref(self).clone() }
}
pub struct MappedMemoryRange<'m>(&'m DeviceMemory, *mut u8, ::std::ops::Range<VkDeviceSize>);
impl<'m> MappedMemoryRange<'m>
{
pub unsafe fn get<T>(&self, offset: usize) -> &T
{
::std::mem::transmute(self.1.offset(offset as _))
}
pub unsafe fn get_mut<T>(&self, offset: usize) -> &mut T
{
::std::mem::transmute(self.1.offset(offset as _))
}
pub unsafe fn slice<T>(&self, offset: usize, count: usize) -> &[T]
{
::std::slice::from_raw_parts(self.1.offset(offset as _) as *const T, count)
}
pub unsafe fn slice_mut<T>(&self, offset: usize, count: usize) -> &mut [T]
{
::std::slice::from_raw_parts_mut(self.1.offset(offset as _) as *mut T, count)
}
pub unsafe fn clone_from_slice_at<T: Clone>(&self, offset: usize, src: &[T])
{
self.slice_mut(offset, src.len()).clone_from_slice(src);
}
pub unsafe fn clone_at<T: Clone>(&self, offset: usize, src: &T)
{
*self.get_mut(offset) = src.clone();
}
pub fn manual_flush(self) -> VkMappedMemoryRange
{
let (m, r) = (self.0 .0 .0, self.2.clone()); ::std::mem::forget(self);
VkMappedMemoryRange
{
offset: r.start, size: r.end - r.start, memory: m, .. Default::default()
}
}
}
#[cfg(feature = "Implements")]
impl<'m> Drop for MappedMemoryRange<'m>
{
fn drop(&mut self)
{
unsafe { vkFlushMappedMemoryRanges(self.0 .0 .1.native_ptr(), 1, &::std::mem::replace(self, resv()).manual_flush()) }
.into_result().unwrap();
}
}
#[cfg(all(feature = "Implements", feature = "VK_KHR_swapchain"))]
impl ::Swapchain
{
pub fn get_images(&self) -> ::Result<Vec<Image>>
{
let mut n = 0;
unsafe { vkGetSwapchainImagesKHR(self.device().native_ptr(), self.native_ptr(), &mut n, ::std::ptr::null_mut()) }.into_result()?;
let mut v = Vec::with_capacity(n as _); unsafe { v.set_len(n as _) };
unsafe { vkGetSwapchainImagesKHR(self.device().native_ptr(), self.native_ptr(), &mut n, v.as_mut_ptr()) }.into_result()
.map(|_| v.into_iter().map(|r| Image(RefCounter::new(ImageCell::SwapchainChild { obj: r, owner: self.clone(), fmt: self.format() }))).collect())
}
}
#[repr(u32)] #[derive(Debug, Clone, PartialEq, Eq, Copy)]
pub enum ImageLayout
{
Undefined = VK_IMAGE_LAYOUT_UNDEFINED as _,
Preinitialized = VK_IMAGE_LAYOUT_PREINITIALIZED as _,
General = VK_IMAGE_LAYOUT_GENERAL as _,
ColorAttachmentOpt = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL as _,
DepthStencilAttachmentOpt = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL as _,
DepthStencilReadOnlyOpt = VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL as _,
ShaderReadOnlyOpt = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL as _,
TransferSrcOpt = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL as _,
TransferDestOpt = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL as _,
#[cfg(feature = "VK_KHR_swapchain")]
PresentSrc = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR as _
}
impl ImageLayout
{
pub fn default_access_mask(&self) -> VkAccessFlags
{
match *self
{
ImageLayout::Undefined | ImageLayout::Preinitialized => 0,
ImageLayout::General => VK_ACCESS_MEMORY_READ_BIT,
ImageLayout::ColorAttachmentOpt => VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
ImageLayout::DepthStencilAttachmentOpt => VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT,
ImageLayout::DepthStencilReadOnlyOpt => VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT,
ImageLayout::ShaderReadOnlyOpt => VK_ACCESS_SHADER_READ_BIT,
ImageLayout::TransferSrcOpt => VK_ACCESS_TRANSFER_READ_BIT,
ImageLayout::TransferDestOpt => VK_ACCESS_TRANSFER_WRITE_BIT,
#[cfg(feature = "VK_KHR_swapchain")]
ImageLayout::PresentSrc => VK_ACCESS_MEMORY_READ_BIT
}
}
}
#[repr(C)] #[derive(Debug, Clone, PartialEq, Eq)]
pub struct ComponentMapping(pub ComponentSwizzle, pub ComponentSwizzle, pub ComponentSwizzle, pub ComponentSwizzle);
#[repr(u32)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ComponentSwizzle
{
Identity = VK_COMPONENT_SWIZZLE_IDENTITY as _,
Zero = VK_COMPONENT_SWIZZLE_ZERO as _,
One = VK_COMPONENT_SWIZZLE_ONE as _,
R = VK_COMPONENT_SWIZZLE_R as _,
G = VK_COMPONENT_SWIZZLE_G as _,
B = VK_COMPONENT_SWIZZLE_B as _,
A = VK_COMPONENT_SWIZZLE_A as _
}
impl Default for ComponentMapping { fn default() -> Self { Self::all(ComponentSwizzle::Identity) } }
impl ComponentMapping
{
pub fn all(s: ComponentSwizzle) -> Self { ComponentMapping(s, s, s, s) }
pub fn set2(a: ComponentSwizzle, b: ComponentSwizzle) -> Self { ComponentMapping(a, b, a, b) }
}
#[derive(Debug, Clone, PartialEq, Eq, Copy)] #[repr(C)]
pub struct AspectMask(pub VkImageAspectFlags);
impl AspectMask
{
pub const COLOR: Self = AspectMask(VK_IMAGE_ASPECT_COLOR_BIT);
pub const DEPTH: Self = AspectMask(VK_IMAGE_ASPECT_DEPTH_BIT);
pub const STENCIL: Self = AspectMask(VK_IMAGE_ASPECT_STENCIL_BIT);
pub const METADATA: Self = AspectMask(VK_IMAGE_ASPECT_METADATA_BIT);
pub fn color(&self) -> Self { AspectMask(self.0 | Self::COLOR.0) }
pub fn depth(&self) -> Self { AspectMask(self.0 | Self::DEPTH.0) }
pub fn stencil(&self) -> Self { AspectMask(self.0 | Self::STENCIL.0) }
pub fn metadata(&self) -> Self { AspectMask(self.0 | Self::METADATA.0) }
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ImageSubresourceRange(VkImageSubresourceRange);
impl Borrow<VkImageSubresourceRange> for ImageSubresourceRange
{
fn borrow(&self) -> &VkImageSubresourceRange { unsafe { transmute(self) } }
}
impl ImageSubresourceRange
{
pub fn color<Levels, Layers>(mip_levels: Levels, array_layers: Layers) -> Self where
Levels: ::AnalogNumRange<u32>, Layers: ::AnalogNumRange<u32>
{
ImageSubresourceRange(VkImageSubresourceRange
{
aspectMask: AspectMask::COLOR.0,
baseMipLevel: mip_levels.begin(), baseArrayLayer: array_layers.begin(),
levelCount: mip_levels.count(), layerCount: array_layers.count()
})
}
pub fn stencil<Levels, Layers>(mip_levels: Levels, array_layers: Layers) -> Self where
Levels: ::AnalogNumRange<u32>, Layers: ::AnalogNumRange<u32>
{
ImageSubresourceRange(VkImageSubresourceRange
{
aspectMask: AspectMask::STENCIL.0,
baseMipLevel: mip_levels.begin(), baseArrayLayer: array_layers.begin(),
levelCount: mip_levels.count(), layerCount: array_layers.count()
})
}
}
pub struct Sampler(VkSampler, ::Device);
#[cfg(feature = "Implements")] DeviceChildCommonDrop!{ for Sampler[vkDestroySampler] }
impl VkHandle for Sampler { type Handle = VkSampler; fn native_ptr(&self) -> VkSampler { self.0 } }
impl DeviceChild for Sampler { fn device(&self) -> &::Device { &self.1 } }
#[repr(C)] #[derive(Debug, Clone, PartialEq, Eq, Copy)]
pub enum AddressingMode
{
Repeat = VK_SAMPLER_ADDRESS_MODE_REPEAT as _,
MirroredRepeat = VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT as _,
ClampToEdge = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE as _,
ClampToBorder = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER as _,
#[cfg(feature = "VK_KHR_mirror_clamp_to_edge")]
MirrorClampToEdge = VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE as _
}
#[repr(C)] #[derive(Debug, Clone, PartialEq, Eq, Copy)]
pub enum FilterMode
{
Nearest = VK_FILTER_NEAREST as _,
Linear = VK_FILTER_LINEAR as _
}
#[repr(C)] #[derive(Debug, Clone, PartialEq, Eq, Copy)]
pub enum MipmapFilterMode
{
Nearest = VK_SAMPLER_MIPMAP_MODE_NEAREST as _,
Linear = VK_SAMPLER_MIPMAP_MODE_LINEAR as _
}
#[repr(C)] #[derive(Debug, Clone, PartialEq, Eq, Copy)]
pub enum BorderColor
{
TransparentBlackF = VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK as _,
TransparentBlackI = VK_BORDER_COLOR_INT_TRANSPARENT_BLACK as _,
OpaqueBlackF = VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK as _,
OpaqueBlackI = VK_BORDER_COLOR_INT_OPAQUE_BLACK as _,
OpaqueWhiteF = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE as _,
OpaqueWhiteI = VK_BORDER_COLOR_INT_OPAQUE_WHITE as _
}
pub struct SamplerBuilder(VkSamplerCreateInfo);
impl SamplerBuilder
{
pub fn new() -> Self
{
SamplerBuilder(VkSamplerCreateInfo
{
magFilter: FilterMode::Linear as _, minFilter: FilterMode::Linear as _, mipmapMode: MipmapFilterMode::Linear as _,
addressModeU: AddressingMode::Repeat as _, addressModeV: AddressingMode::Repeat as _, addressModeW: AddressingMode::Repeat as _,
mipLodBias: 0.0, anisotropyEnable: false as _, compareEnable: false as _, compareOp: ::CompareOp::Always as _,
minLod: 0.0, maxLod: 0.0, borderColor: BorderColor::TransparentBlackF as _, unnormalizedCoordinates: false as _,
.. Default::default()
})
}
pub fn filter(&mut self, mag: FilterMode, min: FilterMode) -> &mut Self
{
self.0.magFilter = mag as _; self.0.minFilter = min as _; self
}
pub fn mip_filter(&mut self, f: MipmapFilterMode) -> &mut Self
{
self.0.mipmapMode = f as _; self
}
pub fn addressing(&mut self, u: AddressingMode, v: AddressingMode, w: AddressingMode) -> &mut Self
{
self.0.addressModeU = u as _; self.0.addressModeV = v as _; self.0.addressModeW = w as _; self
}
pub fn lod_bias(&mut self, bias: f32) -> &mut Self { self.0.mipLodBias = bias; self }
pub fn max_anisotropy(&mut self, level: Option<f32>) -> &mut Self
{
self.0.anisotropyEnable = level.is_some() as _;
self.0.maxAnisotropy = level.unwrap_or_default(); self
}
pub fn comparison(&mut self, op: Option<::CompareOp>) -> &mut Self
{
self.0.compareEnable = op.is_some() as _;
self.0.compareOp = op.unwrap_or(::CompareOp::Always) as _; self
}
pub fn lod_clamp(&mut self, min_lod: f32, max_lod: f32) -> &mut Self
{
assert!(max_lod >= min_lod);
self.0.minLod = min_lod; self.0.maxLod = max_lod; self
}
pub unsafe fn unnormalized_coordinates(&mut self, use_unnormalized: bool) -> &mut Self
{
self.0.unnormalizedCoordinates = use_unnormalized as _; self
}
#[cfg(feature = "Implements")]
pub fn create(&self, device: &::Device) -> ::Result<Sampler>
{
let mut h = VK_NULL_HANDLE as _;
unsafe { vkCreateSampler(device.native_ptr(), &self.0, ::std::ptr::null(), &mut h) }
.into_result().map(|_| Sampler(h, device.clone()))
}
}