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 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438
//! Shader resource types
use {
super::{device::Device, DescriptorSetLayout, DriverError, VertexInputState},
ash::vk,
derive_builder::{Builder, UninitializedFieldError},
log::{debug, error, trace, warn},
ordered_float::OrderedFloat,
spirq::{
entry_point::EntryPoint,
ty::{DescriptorType, ScalarType, SpirvType, Type},
var::Variable,
ReflectConfig,
},
std::{
collections::{BTreeMap, HashMap},
fmt::{Debug, Formatter},
iter::repeat,
mem::size_of_val,
ops::Deref,
sync::Arc,
thread::panicking,
},
};
pub(crate) type DescriptorBindingMap =
HashMap<DescriptorBinding, (DescriptorInfo, vk::ShaderStageFlags)>;
#[profiling::function]
fn guess_immutable_sampler(binding_name: &str) -> SamplerInfo {
const INVALID_ERR: &str = "Invalid sampler specification";
let (texel_filter, mipmap_mode, address_modes) = if binding_name.contains("_sampler_") {
let spec = &binding_name[binding_name.len() - 3..];
let texel_filter = match &spec[0..1] {
"n" => vk::Filter::NEAREST,
"l" => vk::Filter::LINEAR,
_ => panic!("{INVALID_ERR}: {}", &spec[0..1]),
};
let mipmap_mode = match &spec[1..2] {
"n" => vk::SamplerMipmapMode::NEAREST,
"l" => vk::SamplerMipmapMode::LINEAR,
_ => panic!("{INVALID_ERR}: {}", &spec[1..2]),
};
let address_modes = match &spec[2..3] {
"b" => vk::SamplerAddressMode::CLAMP_TO_BORDER,
"e" => vk::SamplerAddressMode::CLAMP_TO_EDGE,
"m" => vk::SamplerAddressMode::MIRRORED_REPEAT,
"r" => vk::SamplerAddressMode::REPEAT,
_ => panic!("{INVALID_ERR}: {}", &spec[2..3]),
};
(texel_filter, mipmap_mode, address_modes)
} else {
debug!("image binding {binding_name} using default sampler");
(
vk::Filter::LINEAR,
vk::SamplerMipmapMode::LINEAR,
vk::SamplerAddressMode::REPEAT,
)
};
let anisotropy_enable = texel_filter == vk::Filter::LINEAR;
let mut info = SamplerInfoBuilder::default()
.mag_filter(texel_filter)
.min_filter(texel_filter)
.mipmap_mode(mipmap_mode)
.address_mode_u(address_modes)
.address_mode_v(address_modes)
.address_mode_w(address_modes)
.max_lod(vk::LOD_CLAMP_NONE)
.anisotropy_enable(anisotropy_enable);
if anisotropy_enable {
info = info.max_anisotropy(16.0);
}
info.build()
}
/// Tuple of descriptor set index and binding index.
///
/// This is a generic representation of the descriptor binding point within the shader and not a
/// bound descriptor reference.
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct DescriptorBinding(pub u32, pub u32);
impl From<u32> for DescriptorBinding {
fn from(binding_idx: u32) -> Self {
Self(0, binding_idx)
}
}
impl From<(u32, u32)> for DescriptorBinding {
fn from((descriptor_set_idx, binding_idx): (u32, u32)) -> Self {
Self(descriptor_set_idx, binding_idx)
}
}
#[derive(Debug)]
pub(crate) enum DescriptorInfo {
AccelerationStructure(u32),
CombinedImageSampler(u32, Sampler, bool), //count, sampler, is-manually-defined?
InputAttachment(u32, u32), //count, input index,
SampledImage(u32),
Sampler(u32),
StorageBuffer(u32),
StorageImage(u32),
StorageTexelBuffer(u32),
UniformBuffer(u32),
UniformTexelBuffer(u32),
}
impl DescriptorInfo {
pub fn binding_count(&self) -> u32 {
match *self {
Self::AccelerationStructure(binding_count) => binding_count,
Self::CombinedImageSampler(binding_count, ..) => binding_count,
Self::InputAttachment(binding_count, _) => binding_count,
Self::SampledImage(binding_count) => binding_count,
Self::Sampler(binding_count) => binding_count,
Self::StorageBuffer(binding_count) => binding_count,
Self::StorageImage(binding_count) => binding_count,
Self::StorageTexelBuffer(binding_count) => binding_count,
Self::UniformBuffer(binding_count) => binding_count,
Self::UniformTexelBuffer(binding_count) => binding_count,
}
}
pub fn descriptor_type(&self) -> vk::DescriptorType {
match self {
Self::AccelerationStructure(_) => vk::DescriptorType::ACCELERATION_STRUCTURE_KHR,
Self::CombinedImageSampler(..) => vk::DescriptorType::COMBINED_IMAGE_SAMPLER,
Self::InputAttachment(..) => vk::DescriptorType::INPUT_ATTACHMENT,
Self::SampledImage(_) => vk::DescriptorType::SAMPLED_IMAGE,
Self::Sampler(_) => vk::DescriptorType::SAMPLER,
Self::StorageBuffer(_) => vk::DescriptorType::STORAGE_BUFFER,
Self::StorageImage(_) => vk::DescriptorType::STORAGE_IMAGE,
Self::StorageTexelBuffer(_) => vk::DescriptorType::STORAGE_TEXEL_BUFFER,
Self::UniformBuffer(_) => vk::DescriptorType::UNIFORM_BUFFER,
Self::UniformTexelBuffer(_) => vk::DescriptorType::UNIFORM_TEXEL_BUFFER,
}
}
pub fn sampler(&self) -> Option<&Sampler> {
match self {
Self::CombinedImageSampler(_, sampler, _) => Some(sampler),
_ => None,
}
}
pub fn set_binding_count(&mut self, binding_count: u32) {
*match self {
Self::AccelerationStructure(binding_count) => binding_count,
Self::CombinedImageSampler(binding_count, ..) => binding_count,
Self::InputAttachment(binding_count, _) => binding_count,
Self::SampledImage(binding_count) => binding_count,
Self::Sampler(binding_count) => binding_count,
Self::StorageBuffer(binding_count) => binding_count,
Self::StorageImage(binding_count) => binding_count,
Self::StorageTexelBuffer(binding_count) => binding_count,
Self::UniformBuffer(binding_count) => binding_count,
Self::UniformTexelBuffer(binding_count) => binding_count,
} = binding_count;
}
}
#[derive(Debug)]
pub(crate) struct PipelineDescriptorInfo {
pub layouts: BTreeMap<u32, DescriptorSetLayout>,
pub pool_sizes: HashMap<u32, HashMap<vk::DescriptorType, u32>>,
}
impl PipelineDescriptorInfo {
#[profiling::function]
pub fn create(
device: &Arc<Device>,
descriptor_bindings: &DescriptorBindingMap,
) -> Result<Self, DriverError> {
let descriptor_set_count = descriptor_bindings
.keys()
.max()
.copied()
.map(|descriptor_binding| descriptor_binding.0 + 1)
.unwrap_or_default();
let mut layouts = BTreeMap::new();
let mut pool_sizes = HashMap::new();
//trace!("descriptor_bindings: {:#?}", &descriptor_bindings);
for descriptor_set_idx in 0..descriptor_set_count {
// HACK: We need to keep the immutable samplers alive until create, could be cleaner..
let mut immutable_samplers = vec![];
let mut binding_counts = HashMap::<vk::DescriptorType, u32>::new();
let mut bindings = vec![];
for (descriptor_binding, (descriptor_info, stage_flags)) in descriptor_bindings
.iter()
.filter(|(descriptor_binding, _)| descriptor_binding.0 == descriptor_set_idx)
{
let descriptor_ty: vk::DescriptorType = descriptor_info.descriptor_type();
*binding_counts.entry(descriptor_ty).or_default() +=
descriptor_info.binding_count();
let mut binding = vk::DescriptorSetLayoutBinding::builder()
.binding(descriptor_binding.1)
.descriptor_count(descriptor_info.binding_count())
.descriptor_type(descriptor_ty)
.stage_flags(*stage_flags);
if let Some(sampler) = descriptor_info.sampler() {
let start = immutable_samplers.len();
immutable_samplers
.extend(repeat(**sampler).take(descriptor_info.binding_count() as _));
binding = binding.immutable_samplers(&immutable_samplers[start..]);
}
bindings.push(binding.build());
}
let pool_size = pool_sizes
.entry(descriptor_set_idx)
.or_insert_with(HashMap::new);
for (descriptor_ty, binding_count) in binding_counts.into_iter() {
*pool_size.entry(descriptor_ty).or_default() += binding_count;
}
//trace!("bindings: {:#?}", &bindings);
let mut create_info =
vk::DescriptorSetLayoutCreateInfo::builder().bindings(bindings.as_slice());
// The bindless flags have to be created for every descriptor set layout binding.
// [vulkan spec](https://www.khronos.org/registry/vulkan/specs/1.3-extensions/man/html/VkDescriptorSetLayoutBindingFlagsCreateInfo.html)
// Maybe using one vector and updating it would be more efficient.
let bindless_flags = vec![vk::DescriptorBindingFlags::PARTIALLY_BOUND; bindings.len()];
let mut bindless_flags = if device
.physical_device
.features_v1_2
.descriptor_binding_partially_bound
{
let bindless_flags = vk::DescriptorSetLayoutBindingFlagsCreateInfo::builder()
.binding_flags(&bindless_flags);
Some(bindless_flags)
} else {
None
};
if let Some(bindless_flags) = bindless_flags.as_mut() {
create_info = create_info.push_next(bindless_flags);
}
layouts.insert(
descriptor_set_idx,
DescriptorSetLayout::create(device, &create_info)?,
);
}
//trace!("layouts {:#?}", &layouts);
// trace!("pool_sizes {:#?}", &pool_sizes);
Ok(Self {
layouts,
pool_sizes,
})
}
}
pub(crate) struct Sampler {
device: Arc<Device>,
sampler: vk::Sampler,
}
impl Sampler {
#[profiling::function]
pub fn create(device: &Arc<Device>, info: impl Into<SamplerInfo>) -> Result<Self, DriverError> {
let device = Arc::clone(device);
let info = info.into();
let sampler = unsafe {
device
.create_sampler(
&vk::SamplerCreateInfo::builder()
.flags(info.flags)
.mag_filter(info.mag_filter)
.min_filter(info.min_filter)
.mipmap_mode(info.mipmap_mode)
.address_mode_u(info.address_mode_u)
.address_mode_v(info.address_mode_v)
.address_mode_w(info.address_mode_w)
.mip_lod_bias(info.mip_lod_bias.0)
.anisotropy_enable(info.anisotropy_enable)
.max_anisotropy(info.max_anisotropy.0)
.compare_enable(info.compare_enable)
.compare_op(info.compare_op)
.min_lod(info.min_lod.0)
.max_lod(info.max_lod.0)
.border_color(info.border_color)
.unnormalized_coordinates(info.unnormalized_coordinates)
.push_next(
&mut vk::SamplerReductionModeCreateInfo::builder()
.reduction_mode(info.reduction_mode),
),
None,
)
.map_err(|err| {
warn!("{err}");
match err {
vk::Result::ERROR_OUT_OF_HOST_MEMORY
| vk::Result::ERROR_OUT_OF_DEVICE_MEMORY => DriverError::OutOfMemory,
_ => DriverError::Unsupported,
}
})?
};
Ok(Self { device, sampler })
}
}
impl Debug for Sampler {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}", self.sampler)
}
}
impl Deref for Sampler {
type Target = vk::Sampler;
fn deref(&self) -> &Self::Target {
&self.sampler
}
}
impl Drop for Sampler {
#[profiling::function]
fn drop(&mut self) {
if panicking() {
return;
}
unsafe {
self.device.destroy_sampler(self.sampler, None);
}
}
}
/// Information used to create a [`vk::Sampler`] instance.
#[derive(Builder, Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[builder(
build_fn(private, name = "fallible_build", error = "SamplerInfoBuilderError"),
derive(Clone, Copy, Debug),
pattern = "owned"
)]
#[non_exhaustive]
pub struct SamplerInfo {
/// Bitmask specifying additional parameters of a sampler.
#[builder(default)]
pub flags: vk::SamplerCreateFlags,
/// Specify the magnification filter to apply to texture lookups.
///
/// The default value is [`vk::Filter::NEAREST`]
#[builder(default)]
pub mag_filter: vk::Filter,
/// Specify the minification filter to apply to texture lookups.
///
/// The default value is [`vk::Filter::NEAREST`]
#[builder(default)]
pub min_filter: vk::Filter,
/// A value specifying the mipmap filter to apply to lookups.
///
/// The default value is [`vk::SamplerMipmapMode::NEAREST`]
#[builder(default)]
pub mipmap_mode: vk::SamplerMipmapMode,
/// A value specifying the addressing mode for U coordinates outside `[0, 1)`.
///
/// The default value is [`vk::SamplerAddressMode::REPEAT`]
#[builder(default)]
pub address_mode_u: vk::SamplerAddressMode,
/// A value specifying the addressing mode for V coordinates outside `[0, 1)`.
///
/// The default value is [`vk::SamplerAddressMode::REPEAT`]
#[builder(default)]
pub address_mode_v: vk::SamplerAddressMode,
/// A value specifying the addressing mode for W coordinates outside `[0, 1)`.
///
/// The default value is [`vk::SamplerAddressMode::REPEAT`]
#[builder(default)]
pub address_mode_w: vk::SamplerAddressMode,
/// The bias to be added to mipmap LOD calculation and bias provided by image sampling functions
/// in SPIR-V, as described in the
/// [LOD Operation](https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#textures-level-of-detail-operation)
/// section.
#[builder(default, setter(into))]
pub mip_lod_bias: OrderedFloat<f32>,
/// Enables anisotropic filtering, as described in the
/// [Texel Anisotropic Filtering](https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#textures-texel-anisotropic-filtering)
/// section
#[builder(default)]
pub anisotropy_enable: bool,
/// The anisotropy value clamp used by the sampler when `anisotropy_enable` is `true`.
///
/// If `anisotropy_enable` is `false`, max_anisotropy is ignored.
#[builder(default, setter(into))]
pub max_anisotropy: OrderedFloat<f32>,
/// Enables comparison against a reference value during lookups.
#[builder(default)]
pub compare_enable: bool,
/// Specifies the comparison operator to apply to fetched data before filtering as described in
/// the
/// [Depth Compare Operation](https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#textures-depth-compare-operation)
/// section.
#[builder(default)]
pub compare_op: vk::CompareOp,
/// Used to clamp the
/// [minimum of the computed LOD value](https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#textures-level-of-detail-operation).
#[builder(default, setter(into))]
pub min_lod: OrderedFloat<f32>,
/// Used to clamp the
/// [maximum of the computed LOD value](https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#textures-level-of-detail-operation).
///
/// To avoid clamping the maximum value, set maxLod to the constant `vk::LOD_CLAMP_NONE`.
#[builder(default, setter(into))]
pub max_lod: OrderedFloat<f32>,
/// Secifies the predefined border color to use.
///
/// The default value is [`vk::BorderColor::FLOAT_TRANSPARENT_BLACK`]
#[builder(default)]
pub border_color: vk::BorderColor,
/// Controls whether to use unnormalized or normalized texel coordinates to address texels of
/// the image.
///
/// When set to `true`, the range of the image coordinates used to lookup the texel is in the
/// range of zero to the image size in each dimension.
///
/// When set to `false` the range of image coordinates is zero to one.
///
/// See
/// [requirements](https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VkSamplerCreateInfo.html).
#[builder(default)]
pub unnormalized_coordinates: bool,
/// Specifies sampler reduction mode.
///
/// Setting magnification filter ([`mag_filter`](Self::mag_filter)) to [`vk::Filter::NEAREST`]
/// disables sampler reduction mode.
///
/// The default value is [`vk::SamplerReductionMode::WEIGHTED_AVERAGE`]
///
/// See
/// [requirements](https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VkSamplerCreateInfo.html).
#[builder(default)]
pub reduction_mode: vk::SamplerReductionMode,
}
impl SamplerInfo {
/// Default sampler information with `mag_filter`, `min_filter` and `mipmap_mode` set to linear.
pub const LINEAR: SamplerInfoBuilder = SamplerInfoBuilder {
flags: None,
mag_filter: Some(vk::Filter::LINEAR),
min_filter: Some(vk::Filter::LINEAR),
mipmap_mode: Some(vk::SamplerMipmapMode::LINEAR),
address_mode_u: None,
address_mode_v: None,
address_mode_w: None,
mip_lod_bias: None,
anisotropy_enable: None,
max_anisotropy: None,
compare_enable: None,
compare_op: None,
min_lod: None,
max_lod: None,
border_color: None,
unnormalized_coordinates: None,
reduction_mode: None,
};
/// Default sampler information with `mag_filter`, `min_filter` and `mipmap_mode` set to
/// nearest.
pub const NEAREST: SamplerInfoBuilder = SamplerInfoBuilder {
flags: None,
mag_filter: Some(vk::Filter::NEAREST),
min_filter: Some(vk::Filter::NEAREST),
mipmap_mode: Some(vk::SamplerMipmapMode::NEAREST),
address_mode_u: None,
address_mode_v: None,
address_mode_w: None,
mip_lod_bias: None,
anisotropy_enable: None,
max_anisotropy: None,
compare_enable: None,
compare_op: None,
min_lod: None,
max_lod: None,
border_color: None,
unnormalized_coordinates: None,
reduction_mode: None,
};
/// Creates a default `SamplerInfoBuilder`.
#[allow(clippy::new_ret_no_self)]
#[deprecated = "Use SamplerInfo::default()"]
#[doc(hidden)]
pub fn new() -> SamplerInfoBuilder {
Self::default().to_builder()
}
/// Converts a `SamplerInfo` into a `SamplerInfoBuilder`.
#[inline(always)]
pub fn to_builder(self) -> SamplerInfoBuilder {
SamplerInfoBuilder {
flags: Some(self.flags),
mag_filter: Some(self.mag_filter),
min_filter: Some(self.min_filter),
mipmap_mode: Some(self.mipmap_mode),
address_mode_u: Some(self.address_mode_u),
address_mode_v: Some(self.address_mode_v),
address_mode_w: Some(self.address_mode_w),
mip_lod_bias: Some(self.mip_lod_bias),
anisotropy_enable: Some(self.anisotropy_enable),
max_anisotropy: Some(self.max_anisotropy),
compare_enable: Some(self.compare_enable),
compare_op: Some(self.compare_op),
min_lod: Some(self.min_lod),
max_lod: Some(self.max_lod),
border_color: Some(self.border_color),
unnormalized_coordinates: Some(self.unnormalized_coordinates),
reduction_mode: Some(self.reduction_mode),
}
}
}
impl Default for SamplerInfo {
fn default() -> Self {
Self {
flags: vk::SamplerCreateFlags::empty(),
mag_filter: vk::Filter::NEAREST,
min_filter: vk::Filter::NEAREST,
mipmap_mode: vk::SamplerMipmapMode::NEAREST,
address_mode_u: vk::SamplerAddressMode::REPEAT,
address_mode_v: vk::SamplerAddressMode::REPEAT,
address_mode_w: vk::SamplerAddressMode::REPEAT,
mip_lod_bias: OrderedFloat(0.0),
anisotropy_enable: false,
max_anisotropy: OrderedFloat(0.0),
compare_enable: false,
compare_op: vk::CompareOp::NEVER,
min_lod: OrderedFloat(0.0),
max_lod: OrderedFloat(0.0),
border_color: vk::BorderColor::FLOAT_TRANSPARENT_BLACK,
unnormalized_coordinates: false,
reduction_mode: vk::SamplerReductionMode::WEIGHTED_AVERAGE,
}
}
}
impl SamplerInfoBuilder {
/// Builds a new `SamplerInfo`.
#[inline(always)]
pub fn build(self) -> SamplerInfo {
let res = self.fallible_build();
#[cfg(test)]
let res = res.unwrap();
#[cfg(not(test))]
let res = unsafe { res.unwrap_unchecked() };
res
}
}
impl From<SamplerInfoBuilder> for SamplerInfo {
fn from(info: SamplerInfoBuilder) -> Self {
info.build()
}
}
#[derive(Debug)]
struct SamplerInfoBuilderError;
impl From<UninitializedFieldError> for SamplerInfoBuilderError {
fn from(_: UninitializedFieldError) -> Self {
Self
}
}
/// Describes a shader program which runs on some pipeline stage.
#[allow(missing_docs)]
#[derive(Builder, Clone)]
#[builder(
build_fn(private, name = "fallible_build", error = "ShaderBuilderError"),
derive(Clone, Debug),
pattern = "owned"
)]
pub struct Shader {
/// The name of the entry point which will be executed by this shader.
///
/// The default value is `main`.
#[builder(default = "\"main\".to_owned()")]
pub entry_name: String,
/// Data about Vulkan specialization constants.
///
/// # Examples
///
/// Basic usage (GLSL):
///
/// ```
/// # inline_spirv::inline_spirv!(r#"
/// #version 460 core
///
/// // Defaults to 6 if not set using Shader specialization_info!
/// layout(constant_id = 0) const uint MY_COUNT = 6;
///
/// layout(set = 0, binding = 0) uniform sampler2D my_samplers[MY_COUNT];
///
/// void main()
/// {
/// // Code uses MY_COUNT number of my_samplers here
/// }
/// # "#, comp);
/// ```
///
/// ```no_run
/// # use std::sync::Arc;
/// # use ash::vk;
/// # use screen_13::driver::DriverError;
/// # use screen_13::driver::device::{Device, DeviceInfo};
/// # use screen_13::driver::shader::{Shader, SpecializationInfo};
/// # fn main() -> Result<(), DriverError> {
/// # let device = Arc::new(Device::create_headless(DeviceInfo::new())?);
/// # let my_shader_code = [0u8; 1];
/// // We instead specify 42 for MY_COUNT:
/// let shader = Shader::new_fragment(my_shader_code.as_slice())
/// .specialization_info(SpecializationInfo::new(
/// [vk::SpecializationMapEntry {
/// constant_id: 0,
/// offset: 0,
/// size: 4,
/// }],
/// 42u32.to_ne_bytes()
/// ));
/// # Ok(()) }
/// ```
#[builder(default, setter(strip_option))]
pub specialization_info: Option<SpecializationInfo>,
/// Shader code.
///
/// Although SPIR-V code is specified as `u32` values, this field uses `u8` in order to make
/// loading from file simpler. You should always have a SPIR-V code length which is a multiple
/// of four bytes, or a panic will happen during pipeline creation.
pub spirv: Vec<u8>,
/// The shader stage this structure applies to.
pub stage: vk::ShaderStageFlags,
#[builder(private)]
entry_point: EntryPoint,
#[builder(default, private)]
image_samplers: HashMap<DescriptorBinding, SamplerInfo>,
#[builder(default, private, setter(strip_option))]
vertex_input_state: Option<VertexInputState>,
}
impl Shader {
/// Specifies a shader with the given `stage` and shader code values.
#[allow(clippy::new_ret_no_self)]
pub fn new(stage: vk::ShaderStageFlags, spirv: impl ShaderCode) -> ShaderBuilder {
ShaderBuilder::default()
.spirv(spirv.into_vec())
.stage(stage)
}
/// Creates a new ray trace shader.
///
/// # Panics
///
/// If the shader code is invalid or not a multiple of four bytes in length.
pub fn new_any_hit(spirv: impl ShaderCode) -> ShaderBuilder {
Self::new(vk::ShaderStageFlags::ANY_HIT_KHR, spirv)
}
/// Creates a new ray trace shader.
///
/// # Panics
///
/// If the shader code is invalid or not a multiple of four bytes in length.
pub fn new_callable(spirv: impl ShaderCode) -> ShaderBuilder {
Self::new(vk::ShaderStageFlags::CALLABLE_KHR, spirv)
}
/// Creates a new ray trace shader.
///
/// # Panics
///
/// If the shader code is invalid or not a multiple of four bytes in length.
pub fn new_closest_hit(spirv: impl ShaderCode) -> ShaderBuilder {
Self::new(vk::ShaderStageFlags::CLOSEST_HIT_KHR, spirv)
}
/// Creates a new compute shader.
///
/// # Panics
///
/// If the shader code is invalid or not a multiple of four bytes in length.
pub fn new_compute(spirv: impl ShaderCode) -> ShaderBuilder {
Self::new(vk::ShaderStageFlags::COMPUTE, spirv)
}
/// Creates a new fragment shader.
///
/// # Panics
///
/// If the shader code is invalid or not a multiple of four bytes in length.
pub fn new_fragment(spirv: impl ShaderCode) -> ShaderBuilder {
Self::new(vk::ShaderStageFlags::FRAGMENT, spirv)
}
/// Creates a new geometry shader.
///
/// # Panics
///
/// If the shader code is invalid or not a multiple of four bytes in length.
pub fn new_geometry(spirv: impl ShaderCode) -> ShaderBuilder {
Self::new(vk::ShaderStageFlags::GEOMETRY, spirv)
}
/// Creates a new ray trace shader.
///
/// # Panics
///
/// If the shader code is invalid or not a multiple of four bytes in length.
pub fn new_intersection(spirv: impl ShaderCode) -> ShaderBuilder {
Self::new(vk::ShaderStageFlags::INTERSECTION_KHR, spirv)
}
/// Creates a new mesh shader.
///
/// # Panics
///
/// If the shader code is invalid.
pub fn new_mesh(spirv: impl ShaderCode) -> ShaderBuilder {
Self::new(vk::ShaderStageFlags::MESH_EXT, spirv)
}
/// Creates a new ray trace shader.
///
/// # Panics
///
/// If the shader code is invalid or not a multiple of four bytes in length.
pub fn new_miss(spirv: impl ShaderCode) -> ShaderBuilder {
Self::new(vk::ShaderStageFlags::MISS_KHR, spirv)
}
/// Creates a new ray trace shader.
///
/// # Panics
///
/// If the shader code is invalid or not a multiple of four bytes in length.
pub fn new_ray_gen(spirv: impl ShaderCode) -> ShaderBuilder {
Self::new(vk::ShaderStageFlags::RAYGEN_KHR, spirv)
}
/// Creates a new mesh task shader.
///
/// # Panics
///
/// If the shader code is invalid.
pub fn new_task(spirv: impl ShaderCode) -> ShaderBuilder {
Self::new(vk::ShaderStageFlags::TASK_EXT, spirv)
}
/// Creates a new tesselation control shader.
///
/// # Panics
///
/// If the shader code is invalid or not a multiple of four bytes in length.
pub fn new_tesselation_ctrl(spirv: impl ShaderCode) -> ShaderBuilder {
Self::new(vk::ShaderStageFlags::TESSELLATION_CONTROL, spirv)
}
/// Creates a new tesselation evaluation shader.
///
/// # Panics
///
/// If the shader code is invalid or not a multiple of four bytes in length.
pub fn new_tesselation_eval(spirv: impl ShaderCode) -> ShaderBuilder {
Self::new(vk::ShaderStageFlags::TESSELLATION_EVALUATION, spirv)
}
/// Creates a new vertex shader.
///
/// # Panics
///
/// If the shader code is invalid or not a multiple of four bytes in length.
pub fn new_vertex(spirv: impl ShaderCode) -> ShaderBuilder {
Self::new(vk::ShaderStageFlags::VERTEX, spirv)
}
/// Returns the input and write attachments of a shader.
#[profiling::function]
pub(super) fn attachments(
&self,
) -> (
impl Iterator<Item = u32> + '_,
impl Iterator<Item = u32> + '_,
) {
(
self.entry_point.vars.iter().filter_map(|var| match var {
Variable::Descriptor {
desc_ty: DescriptorType::InputAttachment(attachment),
..
} => Some(*attachment),
_ => None,
}),
self.entry_point.vars.iter().filter_map(|var| match var {
Variable::Output { location, .. } => Some(location.loc()),
_ => None,
}),
)
}
#[profiling::function]
pub(super) fn descriptor_bindings(
&self,
device: &Arc<Device>,
) -> Result<DescriptorBindingMap, DriverError> {
let mut res = DescriptorBindingMap::default();
for (name, binding, desc_ty, binding_count) in
self.entry_point.vars.iter().filter_map(|var| match var {
Variable::Descriptor {
name,
desc_bind,
desc_ty,
nbind,
..
} => Some((name, desc_bind, desc_ty, *nbind)),
_ => None,
})
{
trace!(
"binding {}: {}.{} = {:?}[{}]",
name.as_deref().unwrap_or_default(),
binding.set(),
binding.bind(),
*desc_ty,
binding_count
);
let descriptor_info = match desc_ty {
DescriptorType::AccelStruct() => {
DescriptorInfo::AccelerationStructure(binding_count)
}
DescriptorType::CombinedImageSampler() => {
let (sampler_info, is_manually_defined) = self
.image_samplers
.get(&DescriptorBinding(binding.set(), binding.bind()))
.copied()
.map(|sampler_info| (sampler_info, true))
.unwrap_or_else(|| {
(
guess_immutable_sampler(name.as_deref().unwrap_or_default()),
false,
)
});
DescriptorInfo::CombinedImageSampler(
binding_count,
Sampler::create(device, sampler_info)?,
is_manually_defined,
)
}
DescriptorType::InputAttachment(attachment) => {
DescriptorInfo::InputAttachment(binding_count, *attachment)
}
DescriptorType::SampledImage() => DescriptorInfo::SampledImage(binding_count),
DescriptorType::Sampler() => DescriptorInfo::Sampler(binding_count),
DescriptorType::StorageBuffer(_access_ty) => {
DescriptorInfo::StorageBuffer(binding_count)
}
DescriptorType::StorageImage(_access_ty) => {
DescriptorInfo::StorageImage(binding_count)
}
DescriptorType::StorageTexelBuffer(_access_ty) => {
DescriptorInfo::StorageTexelBuffer(binding_count)
}
DescriptorType::UniformBuffer() => DescriptorInfo::UniformBuffer(binding_count),
DescriptorType::UniformTexelBuffer() => {
DescriptorInfo::UniformTexelBuffer(binding_count)
}
};
res.insert(
DescriptorBinding(binding.set(), binding.bind()),
(descriptor_info, self.stage),
);
}
Ok(res)
}
#[profiling::function]
pub(super) fn merge_descriptor_bindings(
descriptor_bindings: impl IntoIterator<Item = DescriptorBindingMap>,
) -> DescriptorBindingMap {
fn merge_info(lhs: &mut DescriptorInfo, rhs: DescriptorInfo) -> bool {
let (lhs_count, rhs_count) = match lhs {
DescriptorInfo::AccelerationStructure(lhs) => {
if let DescriptorInfo::AccelerationStructure(rhs) = rhs {
(lhs, rhs)
} else {
return false;
}
}
DescriptorInfo::CombinedImageSampler(lhs, lhs_sampler, lhs_is_manually_defined) => {
if let DescriptorInfo::CombinedImageSampler(
rhs,
rhs_sampler,
rhs_is_manually_defined,
) = rhs
{
// Allow one of the samplers to be manually defined (only one!)
if *lhs_is_manually_defined && rhs_is_manually_defined {
return false;
} else if rhs_is_manually_defined {
*lhs_sampler = rhs_sampler;
}
(lhs, rhs)
} else {
return false;
}
}
DescriptorInfo::InputAttachment(lhs, lhs_idx) => {
if let DescriptorInfo::InputAttachment(rhs, rhs_idx) = rhs {
if *lhs_idx != rhs_idx {
return false;
}
(lhs, rhs)
} else {
return false;
}
}
DescriptorInfo::SampledImage(lhs) => {
if let DescriptorInfo::SampledImage(rhs) = rhs {
(lhs, rhs)
} else {
return false;
}
}
DescriptorInfo::Sampler(lhs) => {
if let DescriptorInfo::Sampler(rhs) = rhs {
(lhs, rhs)
} else {
return false;
}
}
DescriptorInfo::StorageBuffer(lhs) => {
if let DescriptorInfo::StorageBuffer(rhs) = rhs {
(lhs, rhs)
} else {
return false;
}
}
DescriptorInfo::StorageImage(lhs) => {
if let DescriptorInfo::StorageImage(rhs) = rhs {
(lhs, rhs)
} else {
return false;
}
}
DescriptorInfo::StorageTexelBuffer(lhs) => {
if let DescriptorInfo::StorageTexelBuffer(rhs) = rhs {
(lhs, rhs)
} else {
return false;
}
}
DescriptorInfo::UniformBuffer(lhs) => {
if let DescriptorInfo::UniformBuffer(rhs) = rhs {
(lhs, rhs)
} else {
return false;
}
}
DescriptorInfo::UniformTexelBuffer(lhs) => {
if let DescriptorInfo::UniformTexelBuffer(rhs) = rhs {
(lhs, rhs)
} else {
return false;
}
}
};
*lhs_count = rhs_count.max(*lhs_count);
true
}
#[profiling::function]
fn merge_pair(src: DescriptorBindingMap, dst: &mut DescriptorBindingMap) {
for (descriptor_binding, (descriptor_info, descriptor_flags)) in src.into_iter() {
if let Some((existing_info, existing_flags)) = dst.get_mut(&descriptor_binding) {
if !merge_info(existing_info, descriptor_info) {
panic!("Inconsistent shader descriptors ({descriptor_binding:?})");
}
*existing_flags |= descriptor_flags;
} else {
dst.insert(descriptor_binding, (descriptor_info, descriptor_flags));
}
}
}
let mut descriptor_bindings = descriptor_bindings.into_iter();
let mut res = descriptor_bindings.next().unwrap_or_default();
for descriptor_binding in descriptor_bindings {
merge_pair(descriptor_binding, &mut res);
}
res
}
#[profiling::function]
pub(super) fn push_constant_range(&self) -> Option<vk::PushConstantRange> {
self.entry_point
.vars
.iter()
.filter_map(|var| match var {
Variable::PushConstant {
ty: Type::Struct(ty),
..
} => Some(ty.members.clone()),
_ => None,
})
.flatten()
.map(|push_const| {
let offset = push_const.offset.unwrap_or_default();
let size = push_const.ty.nbyte().unwrap_or_default();
offset..offset + size
})
.reduce(|a, b| a.start.min(b.start)..a.end.max(b.end))
.map(|push_const| vk::PushConstantRange {
stage_flags: self.stage,
size: (push_const.end - push_const.start) as _,
offset: push_const.start as _,
})
}
#[profiling::function]
fn reflect_entry_point(
entry_name: &str,
spirv: &[u8],
specialization_info: Option<&SpecializationInfo>,
) -> Result<EntryPoint, DriverError> {
let mut config = ReflectConfig::new();
config.ref_all_rscs(true).spv(spirv);
if let Some(spec_info) = specialization_info {
for spec in &spec_info.map_entries {
config.specialize(
spec.constant_id,
spec_info.data[spec.offset as usize..spec.offset as usize + spec.size].into(),
);
}
}
let entry_points = config.reflect().map_err(|err| {
error!("Unable to reflect spirv: {err}");
DriverError::InvalidData
})?;
let entry_point = entry_points
.into_iter()
.find(|entry_point| entry_point.name == entry_name)
.ok_or_else(|| {
error!("Entry point not found");
DriverError::InvalidData
})?;
Ok(entry_point)
}
#[profiling::function]
pub(super) fn vertex_input(&self) -> VertexInputState {
// Check for manually-specified vertex layout descriptions
if let Some(vertex_input) = &self.vertex_input_state {
return vertex_input.clone();
}
fn scalar_format(ty: &ScalarType, byte_len: u32) -> vk::Format {
match ty {
ScalarType::Float { .. } => match byte_len {
4 => vk::Format::R32_SFLOAT,
8 => vk::Format::R32G32_SFLOAT,
12 => vk::Format::R32G32B32_SFLOAT,
16 => vk::Format::R32G32B32A32_SFLOAT,
_ => unimplemented!("byte_len {byte_len}"),
},
ScalarType::Integer {
is_signed: true, ..
} => match byte_len {
4 => vk::Format::R32_SINT,
8 => vk::Format::R32G32_SINT,
12 => vk::Format::R32G32B32_SINT,
16 => vk::Format::R32G32B32A32_SINT,
_ => unimplemented!("byte_len {byte_len}"),
},
ScalarType::Integer {
is_signed: false, ..
} => match byte_len {
4 => vk::Format::R32_UINT,
8 => vk::Format::R32G32_UINT,
12 => vk::Format::R32G32B32_UINT,
16 => vk::Format::R32G32B32A32_UINT,
_ => unimplemented!("byte_len {byte_len}"),
},
_ => unimplemented!("{:?}", ty),
}
}
let mut input_rates_strides = HashMap::new();
let mut vertex_attribute_descriptions = vec![];
for (name, location, ty) in self.entry_point.vars.iter().filter_map(|var| match var {
Variable::Input { name, location, ty } => Some((name, location, ty)),
_ => None,
}) {
let (binding, guessed_rate) = name
.as_ref()
.filter(|name| name.contains("_ibind") || name.contains("_vbind"))
.map(|name| {
let binding = name[name.rfind("bind").unwrap()..]
.parse()
.unwrap_or_default();
let rate = if name.contains("_ibind") {
vk::VertexInputRate::INSTANCE
} else {
vk::VertexInputRate::VERTEX
};
(binding, rate)
})
.unwrap_or_default();
let (location, _) = location.into_inner();
if let Some((input_rate, _)) = input_rates_strides.get(&binding) {
assert_eq!(*input_rate, guessed_rate);
}
let byte_stride = ty.nbyte().unwrap_or_default() as u32;
let (input_rate, stride) = input_rates_strides.entry(binding).or_default();
*input_rate = guessed_rate;
*stride += byte_stride;
//trace!("{location} {:?} is {byte_stride} bytes", name);
vertex_attribute_descriptions.push(vk::VertexInputAttributeDescription {
location,
binding,
format: match ty {
Type::Scalar(ty) => scalar_format(ty, ty.nbyte().unwrap_or_default() as _),
Type::Vector(ty) => scalar_format(&ty.scalar_ty, byte_stride),
_ => unimplemented!("{:?}", ty),
},
offset: byte_stride, // Figured out below - this data is iter'd in an unknown order
});
}
vertex_attribute_descriptions.sort_unstable_by(|lhs, rhs| {
let binding = lhs.binding.cmp(&rhs.binding);
if binding.is_lt() {
return binding;
}
lhs.location.cmp(&rhs.location)
});
let mut offset = 0;
let mut offset_binding = 0;
for vertex_attribute_description in &mut vertex_attribute_descriptions {
if vertex_attribute_description.binding != offset_binding {
offset_binding = vertex_attribute_description.binding;
offset = 0;
}
let stride = vertex_attribute_description.offset;
vertex_attribute_description.offset = offset;
offset += stride;
debug!(
"vertex attribute {}.{}: {:?} (offset={})",
vertex_attribute_description.binding,
vertex_attribute_description.location,
vertex_attribute_description.format,
vertex_attribute_description.offset,
);
}
let mut vertex_binding_descriptions = vec![];
for (binding, (input_rate, stride)) in input_rates_strides.into_iter() {
vertex_binding_descriptions.push(vk::VertexInputBindingDescription {
binding,
input_rate,
stride,
});
}
VertexInputState {
vertex_attribute_descriptions,
vertex_binding_descriptions,
}
}
}
impl Debug for Shader {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
// We don't want the default formatter bc vec u8
// TODO: Better output message
f.write_str("Shader")
}
}
impl From<ShaderBuilder> for Shader {
fn from(shader: ShaderBuilder) -> Self {
shader.build()
}
}
// HACK: https://github.com/colin-kiegel/rust-derive-builder/issues/56
impl ShaderBuilder {
/// Specifies a shader with the given `stage` and shader code values.
pub fn new(stage: vk::ShaderStageFlags, spirv: Vec<u8>) -> Self {
Self::default().stage(stage).spirv(spirv)
}
/// Builds a new `Shader`.
pub fn build(mut self) -> Shader {
let entry_name = self.entry_name.as_deref().unwrap_or("main");
self.entry_point = Some(
Shader::reflect_entry_point(
entry_name,
self.spirv.as_deref().unwrap(),
self.specialization_info
.as_ref()
.map(|opt| opt.as_ref())
.unwrap_or_default(),
)
.unwrap_or_else(|_| panic!("invalid shader code for entry name \'{entry_name}\'")),
);
self.fallible_build()
.expect("All required fields set at initialization")
}
/// Specifies a manually-defined image sampler.
///
/// Sampled images, by default, use reflection to automatically assign image samplers. Each
/// sampled image may use a suffix such as `_llr` or `_nne` for common linear/linear repeat or
/// nearest/nearest clamp-to-edge samplers, respectively.
///
/// See the [main documentation] for more information about automatic image samplers.
///
/// Descriptor bindings may be specified as `(1, 2)` for descriptor set index `1` and binding
/// index `2`, or if the descriptor set index is `0` simply specify `2` for the same case.
///
/// _NOTE:_ When defining image samplers which are used in multiple stages of a single pipeline
/// you must only call this function on one of the shader stages, it does not matter which one.
///
/// # Panics
///
/// Panics if two shader stages of the same pipeline define individual calls to `image_sampler`.
///
/// [main documentation]: crate
#[profiling::function]
pub fn image_sampler(
mut self,
binding: impl Into<DescriptorBinding>,
info: impl Into<SamplerInfo>,
) -> Self {
let binding = binding.into();
let info = info.into();
if self.image_samplers.is_none() {
self.image_samplers = Some(Default::default());
}
self.image_samplers.as_mut().unwrap().insert(binding, info);
self
}
/// Specifies a manually-defined vertex input layout.
///
/// The vertex input layout, by default, uses reflection to automatically define vertex binding
/// and attribute descriptions. Each vertex location is inferred to have 32-bit channels and be
/// tightly packed in the vertex buffer. In this mode, a location with `_ibind_0` or `_vbind3`
/// suffixes is inferred to use instance-rate on vertex buffer binding `0` or vertex rate on
/// binding `3`, respectively.
///
/// See the [main documentation] for more information about automatic vertex input layout.
///
/// [main documentation]: crate
#[profiling::function]
pub fn vertex_input(
mut self,
bindings: &[vk::VertexInputBindingDescription],
attributes: &[vk::VertexInputAttributeDescription],
) -> Self {
self.vertex_input_state = Some(Some(VertexInputState {
vertex_binding_descriptions: bindings.to_vec(),
vertex_attribute_descriptions: attributes.to_vec(),
}));
self
}
}
#[derive(Debug)]
struct ShaderBuilderError;
impl From<UninitializedFieldError> for ShaderBuilderError {
fn from(_: UninitializedFieldError) -> Self {
Self
}
}
/// Trait for types which can be converted into shader code.
pub trait ShaderCode {
/// Converts the instance into SPIR-V shader code specified as a byte array.
fn into_vec(self) -> Vec<u8>;
}
impl ShaderCode for &[u8] {
fn into_vec(self) -> Vec<u8> {
debug_assert_eq!(self.len() % 4, 0, "invalid spir-v code");
self.to_vec()
}
}
impl ShaderCode for &[u32] {
fn into_vec(self) -> Vec<u8> {
pub fn into_u8_slice<T>(t: &[T]) -> &[u8]
where
T: Sized,
{
use std::slice::from_raw_parts;
unsafe { from_raw_parts(t.as_ptr() as *const _, size_of_val(t)) }
}
into_u8_slice(self).into_vec()
}
}
impl ShaderCode for Vec<u8> {
fn into_vec(self) -> Vec<u8> {
debug_assert_eq!(self.len() % 4, 0, "invalid spir-v code");
self
}
}
impl ShaderCode for Vec<u32> {
fn into_vec(self) -> Vec<u8> {
self.as_slice().into_vec()
}
}
/// Describes specialized constant values.
#[derive(Clone, Debug)]
pub struct SpecializationInfo {
/// A buffer of data which holds the constant values.
pub data: Vec<u8>,
/// Mapping of locations within the constant value data which describe each individual constant.
pub map_entries: Vec<vk::SpecializationMapEntry>,
}
impl SpecializationInfo {
/// Constructs a new `SpecializationInfo`.
pub fn new(
map_entries: impl Into<Vec<vk::SpecializationMapEntry>>,
data: impl Into<Vec<u8>>,
) -> Self {
Self {
data: data.into(),
map_entries: map_entries.into(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
type Info = SamplerInfo;
type Builder = SamplerInfoBuilder;
#[test]
pub fn sampler_info() {
let info = Info::default();
let builder = info.to_builder().build();
assert_eq!(info, builder);
}
#[test]
pub fn sampler_info_builder() {
let info = Info::default();
let builder = Builder::default().build();
assert_eq!(info, builder);
}
}