upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/runtime/src/vulkan_bindless.h
diff options
context:
space:
mode:
authorJan Trencansky <jan.trencansky@protonmail.com>2026-11-24 22:12:48 -0500
committerJan Trencansky <jan.trencansky@protonmail.com>2026-11-24 22:13:02 -0500
commit3ee0037fd3accba459d0d5ecd8acad831174d4d7 (patch)
tree55953ce44091103e4f7c4a2f45490be961282b27 /runtime/src/vulkan_bindless.h
parent9b8707c03dabb59ba2e29b9b0749d3c3eb1f3903 (diff)
parent5115f0887940595aa0f46fed7fc9db28b64151ff (diff)
Merge main into RT-DIRECT-HEAP-GRAPHICS (#1232)
This merges #1064 as prepared (its head + a merge of main), so it brings #1232 up to date with main and with #1064. #1232's branch carried #974 (merged into main since) and an older head of #1064 (7c47fd946). main already supplies the directly indexed heaps to graphics draws (integration #984): graphics_user_data() on DrawInstanced, DrawIndexedInstanced and DispatchMesh, at RootArgumentLayout::graphics_arguments_end (pack_stage(Stage::Pixel)'s end_sgpr, set when the console layout places the signature), LEONIDA_GRAPHICS_DIRECT_HEAPS=0, its notes for a signature on the s0 layout or one that fills s31, and d3d12_graphics_direct_heaps_test (recorded draws and the VS/PS GPU reads). That form stays. What this pull request adds beyond it is carried onto it: the mesh case. Conflicts (all taken from #1064's merged branch, then the PR's mesh parts carried over): - runtime/shims/d3d12_com.cpp: main's graphics_user_data()/with_direct_heaps() and notes. The PR's own graphics_user_data(), GetEnvironmentVariableA switch and no-room notes are main's in another form and dropped. Carried: the comment says a mesh shader reads push dword d as s(d + 8) through #974's window, so it gets the heaps after its arguments from s16 (main's comment still said the mesh stage gets none); and DispatchMesh reports once when a heap falls past the mesh window (push dword 24 and up, s32 for the mesh shader), the case raised in the review of #1232 (mesh_ok accepts arguments up to push dword 24). - runtime/shims/d3d12_com.h, runtime/shims/d3d12_vulkan_device.cpp: main's (graphics_arguments_end from pixel.end_sgpr; the PR set it from its Spill::block form, which main did not take from #974). - runtime/test/glsl/cs_user_data.comp: main's (identical direct-indexing mode). - docs/d3d12_vulkan.md: main's section 3.4 with #1064's compute paragraph; the graphics paragraph's "a mesh shader ... is not modelled" replaced by the mesh window position, cited to issue #14 comment 7143020922 as a report not reproduced here, the window-overflow note and the mesh test. - runtime/test/d3d12_mesh_test.cpp (no conflict): the PR's recorded-argument checks kept (vertex and mesh draw with 4 constants, resource-only rebind, 23 constants, 30 constants); the 30-constant comment now says it keeps pack()'s s0 layout on main. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'runtime/src/vulkan_bindless.h')
-rw-r--r--runtime/src/vulkan_bindless.h396
1 files changed, 309 insertions, 87 deletions
diff --git a/runtime/src/vulkan_bindless.h b/runtime/src/vulkan_bindless.h
index cb5b61f65..589cadffd 100644
--- a/runtime/src/vulkan_bindless.h
+++ b/runtime/src/vulkan_bindless.h
@@ -8,11 +8,13 @@
8// 2 the descriptor hash table 1 7 3D r32ui storage images 256 8// 2 the descriptor hash table 1 7 3D r32ui storage images 256
9// 3 sampled 2D-array images 1024 8 + 3 * dimension + class 256 each: 9// 3 sampled 2D-array images 1024 8 + 3 * dimension + class 256 each:
10// 4 2D r32ui storage images 1024 storage images by component class 10// 4 2D r32ui storage images 1024 storage images by component class
11// dimension: 0 = 2D, 1 = 2D array, 2 = 3D, 3 = 1D (the translator's STORE_DIMS); class: 0 = float, 1 = uint, 2 = sint. 11// dimension: 0 = 2D, 1 = 2D array, 2 = 3D, 3 = 1D (the first four STORE_DIMS); class: 0 = float, 1 = uint, 2 = sint.
12// bindings 20/21: sampled multisample 2D images / 2D arrays, 256 each (runtime SRVs). 12// bindings 20/21: sampled multisample 2D images / 2D arrays, 256 each (runtime SRVs).
13// bindings 22/23 and 24/25 are their UINT and SINT equivalents on devices supporting those classes. 13// bindings 22/23 and 24/25 are their UINT and SINT equivalents on devices supporting those classes.
14// These are the default counts (BindlessFeatures::counts). size_bindings() sizes the 2D, sampler and storage arrays 14// bindings 26-28: storage-only 1D-array images by component class, 256 each (STORE_DIMS index 4).
15// from the device's limits instead; the shaders declare runtime arrays, so any count works for them. 15// These are the default counts (BindlessFeatures::counts). size_bindings() sizes the sampled arrays of every
16// single-sample dimension, the samplers and the storage arrays from the device's limits instead; the shaders declare
17// runtime arrays, so any count works for them.
16// 18//
17// A shader turns a T# or S# into an index through the hash table (descriptor_table.h) and uses that index in 19// A shader turns a T# or S# into an index through the hash table (descriptor_table.h) and uses that index in
18// whichever binding the instruction calls for: the sampled array of the image's dimension, or one of its storage 20// whichever binding the instruction calls for: the sampled array of the image's dimension, or one of its storage
@@ -37,12 +39,22 @@
37// flush() takes the command buffer that will use the set: it uploads only the slots that changed, from a mapped 39// flush() takes the command buffer that will use the set: it uploads only the slots that changed, from a mapped
38// staging buffer, and barriers the copy before the draws. The table at creation is empty until that first flush. 40// staging buffer, and barriers the copy before the draws. The table at creation is empty until that first flush.
39// 41//
42// When device-local memory runs out (a title that fills VRAM), a new generation's table goes to HOST_VISIBLE memory
43// instead: slower lookups beat no table. Released generations are kept as spares (at most max_spares) and reused,
44// pool and buffers, by the next replacing flush, so steady churn allocates nothing. If a generation still cannot be
45// made, flush() rewrites the current table in place when every submission that could read it is done, and otherwise
46// degrades: the descriptors are written, the table keeps its last uploaded contents (keys added since find the
47// fallback, index 0; keys rebound since keep their previous index, whose views stay alive; removed indices are not
48// given out again meanwhile) and the change waits for a later flush. A flush never fails the submission for want of
49// memory (last_flush_degraded(), degraded_flushes()).
50//
40// Not thread-safe: the owner serialises calls. 51// Not thread-safe: the owner serialises calls.
41 52
42#ifndef VK_NO_PROTOTYPES 53#ifndef VK_NO_PROTOTYPES
43#define VK_NO_PROTOTYPES 54#define VK_NO_PROTOTYPES
44#endif 55#endif
45#include "descriptor_table.h" 56#include "descriptor_table.h"
57#include "queue_families.h"
46 58
47#include <vulkan/vulkan.h> 59#include <vulkan/vulkan.h>
48 60
@@ -52,12 +64,13 @@
52#include <cstring> 64#include <cstring>
53#include <functional> 65#include <functional>
54#include <unordered_map> 66#include <unordered_map>
67#include <utility>
55#include <vector> 68#include <vector>
56 69
57namespace leonida { 70namespace leonida {
58 71
59// The first four dimensions are the translator's STORE_DIMS indices. A cube is a 2D array of six layers. 72// The first five dimensions are the translator's STORE_DIMS indices. A cube is a 2D array of six layers.
60enum class ImageDimension : std::uint32_t { dim_2d, dim_2d_array, dim_3d, dim_1d, dim_2d_ms, dim_2d_ms_array }; 73enum class ImageDimension : std::uint32_t { dim_2d, dim_2d_array, dim_3d, dim_1d, dim_1d_array, dim_2d_ms, dim_2d_ms_array };
61 74
62// Storage views of one image by the component type a shader reads or writes it with (the translator picks by the 75// Storage views of one image by the component type a shader reads or writes it with (the translator picks by the
63// T# format at run time). r32ui is for the atomic instructions, whose image type is R32ui (2D and 3D only). 76// T# format at run time). r32ui is for the atomic instructions, whose image type is R32ui (2D and 3D only).
@@ -70,7 +83,7 @@ struct StorageViews {
70}; 83};
71 84
72namespace bindless { 85namespace bindless {
73inline constexpr std::uint32_t binding_count = 26; 86inline constexpr std::uint32_t binding_count = 29;
74constexpr std::array<std::uint32_t, binding_count> default_counts(); 87constexpr std::array<std::uint32_t, binding_count> default_counts();
75} // namespace bindless 88} // namespace bindless
76 89
@@ -94,10 +107,12 @@ struct Binding {
94inline constexpr std::uint32_t table_binding = 2; 107inline constexpr std::uint32_t table_binding = 2;
95inline constexpr std::uint32_t sampler_binding = 1; 108inline constexpr std::uint32_t sampler_binding = 1;
96inline constexpr std::uint32_t first_ms_binding = 20; 109inline constexpr std::uint32_t first_ms_binding = 20;
110inline constexpr std::uint32_t ms_binding_count = 6;
111inline constexpr std::uint32_t first_1d_array_storage_binding = first_ms_binding + ms_binding_count;
97inline constexpr std::uint32_t no_binding = 0xffffffffu; 112inline constexpr std::uint32_t no_binding = 0xffffffffu;
98 113
99// Indexed by binding number. 114// Indexed by binding number. Keep the literal extent for tools/spirv_metal_set0.py.
100inline constexpr std::array<Binding, 26> bindings = {{ 115inline constexpr std::array<Binding, 29> bindings = {{
101 {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 4096}, {VK_DESCRIPTOR_TYPE_SAMPLER, 1024}, 116 {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 4096}, {VK_DESCRIPTOR_TYPE_SAMPLER, 1024},
102 {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1024}, 117 {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1024},
103 {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1024}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, 118 {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1024}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256},
@@ -111,6 +126,8 @@ inline constexpr std::array<Binding, 26> bindings = {{
111 {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, 126 {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256},
112 {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, 127 {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256},
113 {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, 128 {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256},
129 {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 256}, {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 256},
130 {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 256},
114}}; 131}};
115 132
116static_assert(bindings.size() == binding_count); 133static_assert(bindings.size() == binding_count);
@@ -121,8 +138,12 @@ constexpr std::array<std::uint32_t, binding_count> default_counts() {
121 return counts; 138 return counts;
122} 139}
123 140
141constexpr bool ms_binding(std::uint32_t binding) {
142 return binding >= first_ms_binding && binding < first_ms_binding + ms_binding_count;
143}
144
124constexpr bool binding_enabled(std::uint32_t binding, const BindlessFeatures& features) { 145constexpr bool binding_enabled(std::uint32_t binding, const BindlessFeatures& features) {
125 return binding < first_ms_binding || features.ms_samples[(binding - first_ms_binding) / 2] != VK_SAMPLE_COUNT_1_BIT; 146 return !ms_binding(binding) || features.ms_samples[(binding - first_ms_binding) / 2] != VK_SAMPLE_COUNT_1_BIT;
126} 147}
127 148
128// Every binding is visible to every shader stage. Preserve the single-sample layout on devices whose 149// Every binding is visible to every shader stage. Preserve the single-sample layout on devices whose
@@ -131,7 +152,8 @@ constexpr void limit_ms_bindings(BindlessFeatures& features, std::uint32_t sampl
131 std::uint32_t resource_limit) { 152 std::uint32_t resource_limit) {
132 const auto& counts = features.counts; 153 const auto& counts = features.counts;
133 std::uint32_t sampled = 0, total = 0; 154 std::uint32_t sampled = 0, total = 0;
134 for (std::uint32_t b = 0; b < first_ms_binding; ++b) { 155 for (std::uint32_t b = 0; b < binding_count; ++b) {
156 if (ms_binding(b)) continue;
135 if (bindings[b].type == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE) sampled += counts[b]; 157 if (bindings[b].type == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE) sampled += counts[b];
136 if (bindings[b].type != VK_DESCRIPTOR_TYPE_SAMPLER) total += counts[b]; 158 if (bindings[b].type != VK_DESCRIPTOR_TYPE_SAMPLER) total += counts[b];
137 } 159 }
@@ -153,12 +175,13 @@ constexpr bool multisampled(ImageDimension dimension) {
153} 175}
154 176
155constexpr std::uint32_t sampled_binding(ImageDimension dimension, std::uint32_t component_class = 0) { 177constexpr std::uint32_t sampled_binding(ImageDimension dimension, std::uint32_t component_class = 0) {
156 constexpr std::uint32_t by_dimension[] = {0, 3, 6, 5, first_ms_binding, first_ms_binding + 1}; 178 constexpr std::uint32_t by_dimension[] = {0, 3, 6, 5, no_binding, first_ms_binding, first_ms_binding + 1};
157 return by_dimension[std::uint32_t(dimension)] + (multisampled(dimension) ? component_class * 2 : 0); 179 return by_dimension[std::uint32_t(dimension)] + (multisampled(dimension) ? component_class * 2 : 0);
158} 180}
159 181
160// component_class: 0 = float, 1 = uint, 2 = sint. 182// component_class: 0 = float, 1 = uint, 2 = sint.
161constexpr std::uint32_t storage_binding(ImageDimension dimension, std::uint32_t component_class) { 183constexpr std::uint32_t storage_binding(ImageDimension dimension, std::uint32_t component_class) {
184 if (dimension == ImageDimension::dim_1d_array) return first_1d_array_storage_binding + component_class;
162 return multisampled(dimension) ? no_binding : 8 + 3 * std::uint32_t(dimension) + component_class; 185 return multisampled(dimension) ? no_binding : 8 + 3 * std::uint32_t(dimension) + component_class;
163} 186}
164 187
@@ -196,8 +219,13 @@ struct SetLayout {
196}; 219};
197 220
198// What size_bindings() grows to where the device's limits allow. At 32-64 bytes a descriptor the whole set is then 221// What size_bindings() grows to where the device's limits allow. At 32-64 bytes a descriptor the whole set is then
199// 3-6 MiB (93793 descriptors on an RTX 5070). 222// 5-10 MiB with 153697 descriptors when all MS classes and array bindings reach their limits (an RTX 5070).
200inline constexpr std::uint32_t max_2d_images = 65536; 223inline constexpr std::uint32_t max_2d_images = 65536;
224// The other single-sample dimensions: a title streams far more cube maps and texture arrays (and 1D lookup
225// textures) than the 1024 and 256 of the defaults, each distinct T# of one taking its own index.
226inline constexpr std::uint32_t max_2d_array_images = 16384;
227inline constexpr std::uint32_t max_3d_images = 4096;
228inline constexpr std::uint32_t max_1d_images = 4096;
201inline constexpr std::uint32_t max_storage_indices = 4096; // in each storage array, at most its dimension's images 229inline constexpr std::uint32_t max_storage_indices = 4096; // in each storage array, at most its dimension's images
202// A full D3D12 shader-visible sampler heap (2048) and room for literal and static S#s, within what the device can 230// A full D3D12 shader-visible sampler heap (2048) and room for literal and static S#s, within what the device can
203// create (maxSamplerAllocationCount, at least 4000) less the samplers that are not in the set. 231// create (maxSamplerAllocationCount, at least 4000) less the samplers that are not in the set.
@@ -212,10 +240,12 @@ inline constexpr std::uint32_t growth_headroom = 64;
212// standalone samplers do not, though they count in an update-after-bind pool. 240// standalone samplers do not, though they count in an update-after-bind pool.
213// 1. The default counts, or as much of them as the device holds: samplers, then storage, then 2D images. 241// 1. The default counts, or as much of them as the device holds: samplers, then storage, then 2D images.
214// 2. The MS pairs that fit beside them (limit_ms_bindings, which may turn classes off). 242// 2. The MS pairs that fit beside them (limit_ms_bindings, which may turn classes off).
215// 3. Growth towards the maximums above, in the same order, within maxPerSetDescriptors. That limit only says 243// 3. Growth towards the maximums above, in the same order, then the 2D-array, 3D and 1D images, within
216// what is sure to work (vkGetDescriptorSetLayoutSupport may allow more), so it never shrinks step 1. 244// maxPerSetDescriptors. That limit only says what is sure to work (vkGetDescriptorSetLayoutSupport may allow
217// A storage array holds the smaller of the storage count and its dimension's images: add_image never gives a 245// more), so it never shrinks step 1.
218// storage view an index past the sampled array. The other bindings keep their default counts. 246// A storage array holds the smaller of the storage count and its dimension's sampled count: add_image never
247// gives a storage view an index past the sampled array. The storage-only 1D array is capped at its default of 256.
248// The other bindings keep their default counts.
219// layout_supported, when given, answers vkGetDescriptorSetLayoutSupport for set 0 at the counts in its argument: 249// layout_supported, when given, answers vkGetDescriptorSetLayoutSupport for set 0 at the counts in its argument:
220// step 3 then also grows past maxPerSetDescriptors where the device says the layout works (Intel's Xe-LP reports 250// step 3 then also grows past maxPerSetDescriptors where the device says the layout works (Intel's Xe-LP reports
221// 6159 and supports the full sizes, D3D-219). It is asked only once the sum is above maxPerSetDescriptors. 251// 6159 and supports the full sizes, D3D-219). It is asked only once the sum is above maxPerSetDescriptors.
@@ -243,15 +273,24 @@ inline bool size_bindings(BindlessFeatures& features, const VkPhysicalDeviceLimi
243 auto& counts = features.counts; 273 auto& counts = features.counts;
244 counts = default_counts(); 274 counts = default_counts();
245 std::uint32_t images = 1, samplers = 1, storage = 1; 275 std::uint32_t images = 1, samplers = 1, storage = 1;
276 std::uint32_t arrays = counts[sampled_binding(ImageDimension::dim_2d_array)];
277 std::uint32_t volumes = counts[sampled_binding(ImageDimension::dim_3d)];
278 std::uint32_t lines = counts[sampled_binding(ImageDimension::dim_1d)];
246 // Until the end the 2D storage arrays are not capped by the 2D images, which grow after them: capping can only 279 // Until the end the 2D storage arrays are not capped by the 2D images, which grow after them: capping can only
247 // take descriptors away. 280 // take descriptors away.
248 const auto apply = [&](bool final) { 281 const auto apply = [&](bool final) {
249 counts[sampled_binding(ImageDimension::dim_2d)] = images; 282 counts[sampled_binding(ImageDimension::dim_2d)] = images;
283 counts[sampled_binding(ImageDimension::dim_2d_array)] = arrays;
284 counts[sampled_binding(ImageDimension::dim_3d)] = volumes;
285 counts[sampled_binding(ImageDimension::dim_1d)] = lines;
250 counts[sampler_binding] = samplers; 286 counts[sampler_binding] = samplers;
251 for (std::uint32_t d = 0; d < 4; ++d) { 287 for (std::uint32_t d = 0; d <= std::uint32_t(ImageDimension::dim_1d_array); ++d) {
252 const auto dimension = ImageDimension(d); 288 const auto dimension = ImageDimension(d);
289 const auto sampled_at = sampled_binding(dimension);
290 const auto capacity = sampled_at == no_binding ? bindings[storage_binding(dimension, 0)].count
291 : counts[sampled_at];
253 const bool capped = final || dimension != ImageDimension::dim_2d; 292 const bool capped = final || dimension != ImageDimension::dim_2d;
254 const std::uint32_t held = capped ? std::min(storage, counts[sampled_binding(dimension)]) : storage; 293 const std::uint32_t held = capped ? std::min(storage, capacity) : storage;
255 for (std::uint32_t c = 0; c < 3; ++c) counts[storage_binding(dimension, c)] = held; 294 for (std::uint32_t c = 0; c < 3; ++c) counts[storage_binding(dimension, c)] = held;
256 if (r32ui_binding(dimension) != no_binding) counts[r32ui_binding(dimension)] = held; 295 if (r32ui_binding(dimension) != no_binding) counts[r32ui_binding(dimension)] = held;
257 } 296 }
@@ -305,6 +344,9 @@ inline bool size_bindings(BindlessFeatures& features, const VkPhysicalDeviceLimi
305 grow(samplers, std::max(samplers, std::min(max_samplers, creatable)), growth_headroom, set_limit); 344 grow(samplers, std::max(samplers, std::min(max_samplers, creatable)), growth_headroom, set_limit);
306 grow(images, std::max(images, max_2d_images), growth_headroom, set_limit); 345 grow(images, std::max(images, max_2d_images), growth_headroom, set_limit);
307 grow(storage, std::max(storage, max_storage_indices), growth_headroom, set_limit); 346 grow(storage, std::max(storage, max_storage_indices), growth_headroom, set_limit);
347 grow(arrays, std::max(arrays, max_2d_array_images), growth_headroom, set_limit);
348 grow(volumes, std::max(volumes, max_3d_images), growth_headroom, set_limit);
349 grow(lines, std::max(lines, max_1d_images), growth_headroom, set_limit);
308 apply(true); 350 apply(true);
309 return full; 351 return full;
310} 352}
@@ -313,14 +355,20 @@ inline bool size_bindings(BindlessFeatures& features, const VkPhysicalDeviceLimi
313 355
314class BindlessSet { 356class BindlessSet {
315public: 357public:
358 // `descriptor_hash` is the finalizer the shaders of this device probe the table with (descriptor_table.h); it is
359 // handed to the table before its first key is inserted, so every insert, lookup and rehash agrees with them.
316 BindlessSet(PFN_vkGetDeviceProcAddr get, VkDevice device, const VkPhysicalDeviceMemoryProperties& memory, 360 BindlessSet(PFN_vkGetDeviceProcAddr get, VkDevice device, const VkPhysicalDeviceMemoryProperties& memory,
317 BindlessFeatures features = {}) 361 BindlessFeatures features = {}, DescriptorHashKind descriptor_hash = DescriptorHashKind::fnv1a,
318 : device_(device), memory_(memory), features_(features) { 362 std::vector<std::uint32_t> families = {})
363 : device_(device), memory_(memory), features_(features), families_(std::move(families)),
364 table_(64, descriptor_hash) {
319 ok_ = vk_.load(get, device) && create_layout() && create_fallbacks() && create_table_buffers() && fill(); 365 ok_ = vk_.load(get, device) && create_layout() && create_fallbacks() && create_table_buffers() && fill();
320 } 366 }
321 367
322 ~BindlessSet() { 368 ~BindlessSet() {
323 release_retired(); 369 release_retired();
370 for (Generation& spare : spares_) destroy(spare);
371 spares_.clear();
324 destroy(table_buffers_); 372 destroy(table_buffers_);
325 if (fallback_sampler_) vk_.vkDestroySampler(device_, fallback_sampler_, nullptr); 373 if (fallback_sampler_) vk_.vkDestroySampler(device_, fallback_sampler_, nullptr);
326 for (const VkImageView view : fallback_views_) vk_.vkDestroyImageView(device_, view, nullptr); 374 for (const VkImageView view : fallback_views_) vk_.vkDestroyImageView(device_, view, nullptr);
@@ -342,7 +390,8 @@ public:
342 // How many images of a dimension the set holds, the fallback included, and how many of the lowest of those 390 // How many images of a dimension the set holds, the fallback included, and how many of the lowest of those
343 // indices its storage arrays hold (0 for the MS dimensions, which have none). The same for samplers. 391 // indices its storage arrays hold (0 for the MS dimensions, which have none). The same for samplers.
344 std::uint32_t image_capacity(ImageDimension dimension) const { 392 std::uint32_t image_capacity(ImageDimension dimension) const {
345 return features_.counts[bindless::sampled_binding(dimension)]; 393 const auto binding = bindless::sampled_binding(dimension);
394 return binding == bindless::no_binding ? storage_capacity(dimension) : features_.counts[binding];
346 } 395 }
347 std::uint32_t storage_capacity(ImageDimension dimension) const { 396 std::uint32_t storage_capacity(ImageDimension dimension) const {
348 return bindless::multisampled(dimension) ? 0 : features_.counts[bindless::storage_binding(dimension, 0)]; 397 return bindless::multisampled(dimension) ? 0 : features_.counts[bindless::storage_binding(dimension, 0)];
@@ -401,6 +450,7 @@ public:
401 std::uint32_t add_image(ImageDimension dimension, VkImageView sampled, VkImageLayout sampled_layout, 450 std::uint32_t add_image(ImageDimension dimension, VkImageView sampled, VkImageLayout sampled_layout,
402 const StorageViews& storage = {}, std::uint32_t sampled_class = 0) { 451 const StorageViews& storage = {}, std::uint32_t sampled_class = 0) {
403 const bool stores = storage.as_float || storage.as_uint || storage.as_sint || storage.r32ui; 452 const bool stores = storage.as_float || storage.as_uint || storage.as_sint || storage.r32ui;
453 if (!stores && bindless::sampled_binding(dimension) == bindless::no_binding) return 0;
404 if (bindless::multisampled(dimension) && (stores || !supports_ms_class(sampled_class))) return 0; 454 if (bindless::multisampled(dimension) && (stores || !supports_ms_class(sampled_class))) return 0;
405 auto& used = image_used_[std::uint32_t(dimension)]; 455 auto& used = image_used_[std::uint32_t(dimension)];
406 const std::uint32_t low_end = std::min(std::uint32_t(used.size()), storage_capacity(dimension)); 456 const std::uint32_t low_end = std::min(std::uint32_t(used.size()), storage_capacity(dimension));
@@ -414,16 +464,20 @@ public:
414 void update_image(ImageDimension dimension, std::uint32_t index, VkImageView sampled, VkImageLayout sampled_layout, 464 void update_image(ImageDimension dimension, std::uint32_t index, VkImageView sampled, VkImageLayout sampled_layout,
415 const StorageViews& storage = {}, std::uint32_t sampled_class = 0) { 465 const StorageViews& storage = {}, std::uint32_t sampled_class = 0) {
416 const auto& used = image_used_[std::uint32_t(dimension)]; 466 const auto& used = image_used_[std::uint32_t(dimension)];
417 if (index && index < used.size() && used[index]) 467 if (index && index < used.size() && used[index] == in_use)
418 write_image(dimension, index, sampled, sampled_layout, storage, sampled_class); 468 write_image(dimension, index, sampled, sampled_layout, storage, sampled_class);
419 } 469 }
420 470
421 // Returns the index to the fallback and frees it. The caller removes the image's keys with erase_key() first. 471 // Returns the index to the fallback and frees it. The caller removes the image's keys with erase_key() first.
472 // While the table has changes the GPU's copy lacks (an erased key may still name the index there), the index is
473 // held until a flush has brought the table up to date (one that did not degrade), so that no new image answers
474 // that key; otherwise it is free at once.
422 void remove_image(ImageDimension dimension, std::uint32_t index) { 475 void remove_image(ImageDimension dimension, std::uint32_t index) {
423 auto& used = image_used_[std::uint32_t(dimension)]; 476 auto& used = image_used_[std::uint32_t(dimension)];
424 if (!index || index >= used.size() || !used[index]) return; 477 if (!index || index >= used.size() || used[index] != in_use) return;
425 write_image(dimension, index, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_GENERAL, {}, 0); 478 write_image(dimension, index, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_GENERAL, {}, 0);
426 used[index] = 0; 479 used[index] = table_dirty_ ? held : 0;
480 if (table_dirty_) held_images_.push_back({dimension, index});
427 } 481 }
428 482
429 // 0 when the sampler array is full. 483 // 0 when the sampler array is full.
@@ -434,9 +488,10 @@ public:
434 } 488 }
435 489
436 void remove_sampler(std::uint32_t index) { 490 void remove_sampler(std::uint32_t index) {
437 if (!index || index >= sampler_used_.size() || !sampler_used_[index]) return; 491 if (!index || index >= sampler_used_.size() || sampler_used_[index] != in_use) return;
438 write_sampler(index, fallback_sampler_); 492 write_sampler(index, fallback_sampler_);
439 sampler_used_[index] = 0; 493 sampler_used_[index] = table_dirty_ ? held : 0;
494 if (table_dirty_) held_samplers_.push_back(index);
440 } 495 }
441 496
442 // T# and S# keys to the indices above: the table of binding 2 (descriptor_table.h). Changes reach the shaders 497 // T# and S# keys to the indices above: the table of binding 2 (descriptor_table.h). Changes reach the shaders
@@ -479,7 +534,10 @@ public:
479 void table_upload_result(bool submitted) { 534 void table_upload_result(bool submitted) {
480 if (!upload_in_flight_) return; 535 if (!upload_in_flight_) return;
481 upload_in_flight_ = false; 536 upload_in_flight_ = false;
482 if (submitted) return; 537 if (submitted) {
538 table_on_gpu_ = true; // the current buffers hold a table the GPU was given
539 return;
540 }
483 table_dirty_ = true; 541 table_dirty_ = true;
484 force_full_upload_ = true; 542 force_full_upload_ = true;
485 } 543 }
@@ -488,17 +546,42 @@ public:
488 // the set are recorded after it. When flush_replaces_table() was true this starts a new generation (table 546 // the set are recorded after it. When flush_replaces_table() was true this starts a new generation (table
489 // buffers, descriptor set, binding 2 and every descriptor written so far) and puts the previous one on the retire 547 // buffers, descriptor set, binding 2 and every descriptor written so far) and puts the previous one on the retire
490 // list, stamped `retire_ticket`: the owner's number for "every submission made so far", which release_retired() 548 // list, stamped `retire_ticket`: the owner's number for "every submission made so far", which release_retired()
491 // compares with what has completed. False when the new generation cannot be made: the set then still has the 549 // compares with what has completed.
492 // table as of the last flush. 550 // When the new generation cannot be made (no memory for its buffers or descriptor pool) and `completed_ticket` is
493 bool flush(VkCommandBuffer command_buffer, std::uint64_t retire_ticket = 0) { 551 // given, it is asked what has completed: the generations retired up to there are released (to the spares) and
552 // the generation is tried again; when everything up to `retire_ticket` is done, nothing reads the current table
553 // and it is rewritten in place if it is large enough. Failing both, the flush degrades instead of failing: the
554 // descriptors are written in place, as on a flush that does not replace the table (add_image writes new indices,
555 // which no key of the GPU's table reaches; remove_image writes the fallback, and the index stays held until a
556 // flush that does not degrade), the table keeps what it had, and its changes wait for a later flush
557 // (last_flush_degraded()). False only without a command buffer, when nothing can be recorded.
558 bool flush(VkCommandBuffer command_buffer, std::uint64_t retire_ticket = 0,
559 const std::function<std::uint64_t()>& completed_ticket = {}) {
560 if (!command_buffer) return false;
494 bool replaced = false; 561 bool replaced = false;
495 bool written = true; 562 bool written = true;
496 const bool must_replace = flush_replaces_table(); 563 const bool must_replace = flush_replaces_table();
564 last_flush_degraded_ = false;
497 if (table_dirty_ || !table_uploaded_) written = upload_table(command_buffer, retire_ticket, replaced); 565 if (table_dirty_ || !table_uploaded_) written = upload_table(command_buffer, retire_ticket, replaced);
566 if (!written && must_replace && completed_ticket) {
567 const std::uint64_t completed = completed_ticket();
568 if (!retired_.empty()) {
569 release_retired(completed);
570 written = upload_table(command_buffer, retire_ticket, replaced);
571 }
572 if (!written && completed >= retire_ticket) written = rewrite_table_in_place(command_buffer);
573 }
498 last_flush_replaced_ = replaced; 574 last_flush_replaced_ = replaced;
499 // The new generation could not be made: the current set is the one running work reads, so its descriptors are 575 // Degrading keeps what the current buffers hold, so only once they hold a table that reached the queue: a
500 // not written in place either. The pending writes and the table's changes stay for the next flush. 576 // first flush under full memory, or one after a failed submission of the only upload, has nothing on the GPU
501 if (!written && must_replace) return false; 577 // (word 0 is the probe mask) and refuses as before (review of #64).
578 if (!written && must_replace && !table_on_gpu_) return false;
579 if (!written && must_replace) {
580 // The current set is the one running work reads, and the table's changes may move or rebind live keys:
581 // they stay for a later flush, and keys added since find the fallback until then.
582 ++degraded_flushes_;
583 last_flush_degraded_ = true;
584 }
502 for (const Pending& pending : pending_) { 585 for (const Pending& pending : pending_) {
503 if (pending.binding >= shadow_.size() || pending.index >= shadow_[pending.binding].size()) continue; 586 if (pending.binding >= shadow_.size() || pending.index >= shadow_[pending.binding].size()) continue;
504 shadow_[pending.binding][pending.index] = pending.info; 587 shadow_[pending.binding][pending.index] = pending.info;
@@ -521,17 +604,29 @@ public:
521 } 604 }
522 pending_.clear(); 605 pending_.clear();
523 pending_slots_.clear(); 606 pending_slots_.clear();
524 return written; 607 if (!last_flush_degraded_) {
608 // The table this flush leaves on the GPU names no removed index any more: they can be given out again.
609 for (const auto& [dimension, index] : held_images_) image_used_[std::uint32_t(dimension)][index] = 0;
610 for (const std::uint32_t index : held_samplers_) sampler_used_[index] = 0;
611 held_images_.clear();
612 held_samplers_.clear();
613 }
614 return true;
525 } 615 }
526 616
527 // Frees the generations (table buffers and descriptor set) that flush() retired with a ticket up to `completed`. 617 // Releases the generations (table buffers and descriptor set) that flush() retired with a ticket up to
528 // The default frees all of them: when nothing submitted before the last flush() still runs. 618 // `completed`: up to max_spares of them, large enough for the table, are kept for the next replacing flush to
619 // reuse; the others are freed. The default releases all of them: when nothing submitted before the last flush()
620 // still runs.
529 void release_retired(std::uint64_t completed = UINT64_MAX) { 621 void release_retired(std::uint64_t completed = UINT64_MAX) {
530 std::size_t kept = 0; 622 std::size_t kept = 0;
531 for (auto& generation : retired_) { 623 for (auto& generation : retired_) {
532 if (generation.ticket <= completed) { 624 if (generation.ticket <= completed) {
533 destroy(generation.buffers); 625 if (spares_.size() < max_spares && generation.pool && generation.buffers.staging.mapped &&
534 if (generation.pool) vk_.vkDestroyDescriptorPool(device_, generation.pool, nullptr); 626 generation.buffers.table.size >= table_.size_bytes())
627 spares_.push_back(generation);
628 else
629 destroy(generation);
535 } else { 630 } else {
536 retired_[kept++] = generation; 631 retired_[kept++] = generation;
537 } 632 }
@@ -548,11 +643,32 @@ public:
548 std::uint64_t generations_made() const { return generations_made_; } 643 std::uint64_t generations_made() const { return generations_made_; }
549 std::size_t retired_count() const { return retired_.size(); } 644 std::size_t retired_count() const { return retired_.size(); }
550 645
646 // Released generations kept for reuse, and how many replacing flushes reused one instead of allocating. One: the
647 // current generation and a spare are the two a replacing flush has at its peak anyway (the new one, and the one
648 // retired until its work completes), and a grown table can be large (64 MiB at a million slots).
649 static constexpr std::size_t max_spares = 1;
650 std::size_t spare_count() const { return spares_.size(); }
651 std::uint64_t spares_reused() const { return spares_reused_; }
652 // Flushes that could not make the generation they needed and kept the previous table (see flush()), and whether
653 // the last one did; flushes that rewrote the table in place instead, every submission being done.
654 std::uint64_t degraded_flushes() const { return degraded_flushes_; }
655 bool last_flush_degraded() const { return last_flush_degraded_; }
656 std::uint64_t in_place_rewrites() const { return in_place_rewrites_; }
657 // Table buffers placed in HOST_VISIBLE memory because the DEVICE_LOCAL allocation failed.
658 std::uint64_t table_host_fallbacks() const { return table_host_fallbacks_; }
659 // What the last generation that could not be made failed to get: "table buffer", "staging buffer" or
660 // "descriptor set" (nullptr before any failure), and the Vulkan result of that call.
661 const char* last_failure() const { return last_failure_; }
662 VkResult last_failure_result() const { return last_failure_result_; }
663 // Bytes of the current table buffer (the table grows by doubling its slots: size_bytes() of table()).
664 std::size_t table_buffer_bytes() const { return table_buffers_.table.size; }
665
551private: 666private:
552 struct Functions { 667 struct Functions {
553#define LEONIDA_BINDLESS_FUNCTIONS(X) \ 668#define LEONIDA_BINDLESS_FUNCTIONS(X) \
554 X(vkCreateDescriptorSetLayout) X(vkDestroyDescriptorSetLayout) X(vkCreateDescriptorPool) \ 669 X(vkCreateDescriptorSetLayout) X(vkDestroyDescriptorSetLayout) X(vkCreateDescriptorPool) \
555 X(vkDestroyDescriptorPool) X(vkAllocateDescriptorSets) X(vkUpdateDescriptorSets) X(vkCreateBuffer) \ 670 X(vkDestroyDescriptorPool) X(vkResetDescriptorPool) X(vkAllocateDescriptorSets) X(vkUpdateDescriptorSets) \
671 X(vkCreateBuffer) \
556 X(vkDestroyBuffer) X(vkGetBufferMemoryRequirements) X(vkBindBufferMemory) X(vkAllocateMemory) \ 672 X(vkDestroyBuffer) X(vkGetBufferMemoryRequirements) X(vkBindBufferMemory) X(vkAllocateMemory) \
557 X(vkFreeMemory) X(vkMapMemory) X(vkCreateImage) X(vkDestroyImage) X(vkGetImageMemoryRequirements) \ 673 X(vkFreeMemory) X(vkMapMemory) X(vkCreateImage) X(vkDestroyImage) X(vkGetImageMemoryRequirements) \
558 X(vkBindImageMemory) X(vkCreateImageView) X(vkDestroyImageView) X(vkCreateSampler) X(vkDestroySampler) \ 674 X(vkBindImageMemory) X(vkCreateImageView) X(vkDestroyImageView) X(vkCreateSampler) X(vkDestroySampler) \
@@ -583,6 +699,7 @@ private:
583 VkDeviceMemory memory = VK_NULL_HANDLE; 699 VkDeviceMemory memory = VK_NULL_HANDLE;
584 void* mapped = nullptr; 700 void* mapped = nullptr;
585 std::size_t size = 0; 701 std::size_t size = 0;
702 bool device_local = false; // the memory is DEVICE_LOCAL
586 }; 703 };
587 704
588 // The table and the mapped staging copy the CPU writes before vkCmdCopyBuffer moves the changes. 705 // The table and the mapped staging copy the CPU writes before vkCmdCopyBuffer moves the changes.
@@ -591,13 +708,23 @@ private:
591 TableBuffer staging; // HOST_VISIBLE | HOST_COHERENT 708 TableBuffer staging; // HOST_VISIBLE | HOST_COHERENT
592 }; 709 };
593 710
711 struct Generation { // what a replaced table leaves for release_retired()
712 TableBuffers buffers;
713 VkDescriptorPool pool = VK_NULL_HANDLE; // owns the descriptor set
714 VkDescriptorSet set = VK_NULL_HANDLE;
715 std::uint64_t ticket = 0;
716 };
717
594 struct Pending { 718 struct Pending {
595 std::uint32_t binding; 719 std::uint32_t binding;
596 std::uint32_t index; 720 std::uint32_t index;
597 VkDescriptorImageInfo info; 721 VkDescriptorImageInfo info;
598 }; 722 };
599 723
600 static constexpr std::uint32_t dimensions = 6, classes = 3; 724 static constexpr std::uint32_t dimensions = 7, classes = 3;
725 // image_used_ and sampler_used_: 0 free, in_use, or held (removed while the table was dirty: free after the next
726 // flush that does not degrade).
727 static constexpr std::uint8_t in_use = 1, held = 2;
601 728
602 // The first free index in [begin, end), marked used; 0 when there is none. 729 // The first free index in [begin, end), marked used; 0 when there is none.
603 static std::uint32_t allocate(std::vector<std::uint8_t>& used, std::uint32_t begin, std::uint32_t end) { 730 static std::uint32_t allocate(std::vector<std::uint8_t>& used, std::uint32_t begin, std::uint32_t end) {
@@ -645,21 +772,35 @@ private:
645 pool_info.maxSets = 1; 772 pool_info.maxSets = 1;
646 pool_info.poolSizeCount = pool_size_count_; 773 pool_info.poolSizeCount = pool_size_count_;
647 pool_info.pPoolSizes = pool_sizes_.data(); 774 pool_info.pPoolSizes = pool_sizes_.data();
648 if (vk_.vkCreateDescriptorPool(device_, &pool_info, nullptr, &pool) != VK_SUCCESS) { 775 if (const VkResult result = vk_.vkCreateDescriptorPool(device_, &pool_info, nullptr, &pool);
776 result != VK_SUCCESS) {
649 pool = VK_NULL_HANDLE; 777 pool = VK_NULL_HANDLE;
778 note_failure("descriptor set", result);
650 return false; 779 return false;
651 } 780 }
781 if (allocate_set(pool, set)) return true;
782 vk_.vkDestroyDescriptorPool(device_, pool, nullptr);
783 pool = VK_NULL_HANDLE;
784 return false;
785 }
786
787 bool allocate_set(VkDescriptorPool pool, VkDescriptorSet& set) const {
652 VkDescriptorSetAllocateInfo set_info{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO}; 788 VkDescriptorSetAllocateInfo set_info{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO};
653 set_info.descriptorPool = pool; 789 set_info.descriptorPool = pool;
654 set_info.descriptorSetCount = 1; 790 set_info.descriptorSetCount = 1;
655 set_info.pSetLayouts = &layout_; 791 set_info.pSetLayouts = &layout_;
656 if (vk_.vkAllocateDescriptorSets(device_, &set_info, &set) == VK_SUCCESS) return true; 792 const VkResult result = vk_.vkAllocateDescriptorSets(device_, &set_info, &set);
657 vk_.vkDestroyDescriptorPool(device_, pool, nullptr); 793 if (result == VK_SUCCESS) return true;
658 pool = VK_NULL_HANDLE;
659 set = VK_NULL_HANDLE; 794 set = VK_NULL_HANDLE;
795 note_failure("descriptor set", result);
660 return false; 796 return false;
661 } 797 }
662 798
799 void note_failure(const char* what, VkResult result) const {
800 last_failure_ = what;
801 last_failure_result_ = result;
802 }
803
663 // Writes every descriptor written so far (the shadow) into the current set, one update per run of written 804 // Writes every descriptor written so far (the shadow) into the current set, one update per run of written
664 // elements: the set was just made, and unwritten elements stay unwritten, as partially_bound allows. 805 // elements: the set was just made, and unwritten elements stay unwritten, as partially_bound allows.
665 void write_shadow() const { 806 void write_shadow() const {
@@ -695,10 +836,11 @@ private:
695 constexpr std::uint32_t ms_type = 3; 836 constexpr std::uint32_t ms_type = 3;
696 constexpr VkFormat formats[classes] = {VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R32_UINT, VK_FORMAT_R32_SINT}; 837 constexpr VkFormat formats[classes] = {VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R32_UINT, VK_FORMAT_R32_SINT};
697 // dimension -> (index into types, view type) 838 // dimension -> (index into types, view type)
698 constexpr std::uint32_t type_of[dimensions] = {0, 0, 1, 2, ms_type, ms_type}; 839 constexpr std::uint32_t type_of[dimensions] = {0, 0, 1, 2, 2, ms_type, ms_type};
699 constexpr VkImageViewType view_types[dimensions] = {VK_IMAGE_VIEW_TYPE_2D, VK_IMAGE_VIEW_TYPE_2D_ARRAY, 840 constexpr VkImageViewType view_types[dimensions] = {VK_IMAGE_VIEW_TYPE_2D, VK_IMAGE_VIEW_TYPE_2D_ARRAY,
700 VK_IMAGE_VIEW_TYPE_3D, VK_IMAGE_VIEW_TYPE_1D, 841 VK_IMAGE_VIEW_TYPE_3D, VK_IMAGE_VIEW_TYPE_1D,
701 VK_IMAGE_VIEW_TYPE_2D, VK_IMAGE_VIEW_TYPE_2D_ARRAY}; 842 VK_IMAGE_VIEW_TYPE_1D_ARRAY,
843 VK_IMAGE_VIEW_TYPE_2D, VK_IMAGE_VIEW_TYPE_2D_ARRAY};
702 for (std::uint32_t t = 0; t < std::size(types); ++t) { 844 for (std::uint32_t t = 0; t < std::size(types); ++t) {
703 for (std::uint32_t c = 0; c < classes; ++c) { 845 for (std::uint32_t c = 0; c < classes; ++c) {
704 if (t == ms_type && !supports_ms_class(c)) continue; 846 if (t == ms_type && !supports_ms_class(c)) continue;
@@ -713,6 +855,7 @@ private:
713 if (t != ms_type) info.usage |= VK_IMAGE_USAGE_STORAGE_BIT; 855 if (t != ms_type) info.usage |= VK_IMAGE_USAGE_STORAGE_BIT;
714 if (t == ms_type || c == 0) info.usage |= VK_IMAGE_USAGE_SAMPLED_BIT; 856 if (t == ms_type || c == 0) info.usage |= VK_IMAGE_USAGE_SAMPLED_BIT;
715 FallbackImage& image = fallback_images_[t * classes + c]; 857 FallbackImage& image = fallback_images_[t * classes + c];
858 share_across_queue_families(info, families_);
716 if (vk_.vkCreateImage(device_, &info, nullptr, &image.image) != VK_SUCCESS) return false; 859 if (vk_.vkCreateImage(device_, &info, nullptr, &image.image) != VK_SUCCESS) return false;
717 VkMemoryRequirements requirements{}; 860 VkMemoryRequirements requirements{};
718 vk_.vkGetImageMemoryRequirements(device_, image.image, &requirements); 861 vk_.vkGetImageMemoryRequirements(device_, image.image, &requirements);
@@ -737,8 +880,9 @@ private:
737 VkImageView view = VK_NULL_HANDLE; 880 VkImageView view = VK_NULL_HANDLE;
738 if (vk_.vkCreateImageView(device_, &info, nullptr, &view) != VK_SUCCESS) return false; 881 if (vk_.vkCreateImageView(device_, &info, nullptr, &view) != VK_SUCCESS) return false;
739 fallback_views_.push_back(view); 882 fallback_views_.push_back(view);
740 if (c == 0 || bindless::multisampled(dimension)) 883 const auto sampled_at = bindless::sampled_binding(dimension, c);
741 fallback_by_binding_[bindless::sampled_binding(dimension, c)] = view; 884 if (sampled_at != bindless::no_binding && (c == 0 || bindless::multisampled(dimension)))
885 fallback_by_binding_[sampled_at] = view;
742 const auto storage_at = bindless::storage_binding(dimension, c); 886 const auto storage_at = bindless::storage_binding(dimension, c);
743 if (storage_at != bindless::no_binding) fallback_by_binding_[storage_at] = view; 887 if (storage_at != bindless::no_binding) fallback_by_binding_[storage_at] = view;
744 const auto r32ui_at = bindless::r32ui_binding(dimension); 888 const auto r32ui_at = bindless::r32ui_binding(dimension);
@@ -753,36 +897,54 @@ private:
753 return vk_.vkCreateSampler(device_, &sampler, nullptr, &fallback_sampler_) == VK_SUCCESS; 897 return vk_.vkCreateSampler(device_, &sampler, nullptr, &fallback_sampler_) == VK_SUCCESS;
754 } 898 }
755 899
756 bool create(TableBuffer& out, std::size_t bytes, bool device_local, bool* got_device_local = nullptr) const { 900 // device_local: the table (DEVICE_LOCAL, else HOST_VISIBLE when the device has no such type or that heap is out
901 // of memory); otherwise the mapped staging buffer (HOST_VISIBLE | HOST_COHERENT).
902 bool create(TableBuffer& out, std::size_t bytes, bool device_local) {
903 constexpr VkMemoryPropertyFlags host = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
904 const char* what = device_local ? "table buffer" : "staging buffer";
757 VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; 905 VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
758 info.size = bytes; 906 info.size = bytes;
759 info.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | 907 info.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT |
760 (device_local ? VK_BUFFER_USAGE_TRANSFER_DST_BIT : VK_BUFFER_USAGE_TRANSFER_SRC_BIT); 908 (device_local ? VK_BUFFER_USAGE_TRANSFER_DST_BIT : VK_BUFFER_USAGE_TRANSFER_SRC_BIT);
761 TableBuffer made; 909 TableBuffer made;
762 made.size = bytes; 910 made.size = bytes;
763 if (vk_.vkCreateBuffer(device_, &info, nullptr, &made.buffer) != VK_SUCCESS) return false; 911 share_across_queue_families(info, families_);
912 if (const VkResult result = vk_.vkCreateBuffer(device_, &info, nullptr, &made.buffer); result != VK_SUCCESS) {
913 made.buffer = VK_NULL_HANDLE;
914 note_failure(what, result);
915 return false;
916 }
764 VkMemoryRequirements requirements{}; 917 VkMemoryRequirements requirements{};
765 vk_.vkGetBufferMemoryRequirements(device_, made.buffer, &requirements); 918 vk_.vkGetBufferMemoryRequirements(device_, made.buffer, &requirements);
766 VkMemoryAllocateInfo allocation{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; 919 VkMemoryAllocateInfo allocation{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};
767 allocation.allocationSize = requirements.size; 920 allocation.allocationSize = requirements.size;
768 allocation.memoryTypeIndex = 921 const auto allocate = [&](std::uint32_t type) {
769 device_local ? memory_type(requirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) 922 if (type == 0xffffffffu) return VK_ERROR_OUT_OF_DEVICE_MEMORY;
770 : memory_type(requirements.memoryTypeBits, 923 allocation.memoryTypeIndex = type;
771 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); 924 const VkResult result = vk_.vkAllocateMemory(device_, &allocation, nullptr, &made.memory);
772 if (device_local && allocation.memoryTypeIndex == 0xffffffffu) 925 if (result != VK_SUCCESS) made.memory = VK_NULL_HANDLE;
773 allocation.memoryTypeIndex = memory_type(requirements.memoryTypeBits, 926 return result;
774 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | 927 };
775 VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); 928 const std::uint32_t local = device_local
776 if (got_device_local) 929 ? memory_type(requirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)
777 *got_device_local = allocation.memoryTypeIndex != 0xffffffffu && 930 : 0xffffffffu;
778 (memory_.memoryTypes[allocation.memoryTypeIndex].propertyFlags & 931 VkResult result = device_local ? allocate(local) : allocate(memory_type(requirements.memoryTypeBits, host));
932 if (result != VK_SUCCESS && device_local) {
933 const std::uint32_t fallback = memory_type(requirements.memoryTypeBits, host);
934 if (fallback != local) {
935 result = allocate(fallback);
936 if (result == VK_SUCCESS && local != 0xffffffffu) ++table_host_fallbacks_;
937 }
938 }
939 if (result == VK_SUCCESS) {
940 made.device_local = (memory_.memoryTypes[allocation.memoryTypeIndex].propertyFlags &
779 VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) != 0; 941 VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) != 0;
780 bool ready = allocation.memoryTypeIndex != 0xffffffffu && 942 result = vk_.vkBindBufferMemory(device_, made.buffer, made.memory, 0);
781 vk_.vkAllocateMemory(device_, &allocation, nullptr, &made.memory) == VK_SUCCESS && 943 }
782 vk_.vkBindBufferMemory(device_, made.buffer, made.memory, 0) == VK_SUCCESS; 944 if (result == VK_SUCCESS && !device_local)
783 if (ready && !device_local) 945 result = vk_.vkMapMemory(device_, made.memory, 0, VK_WHOLE_SIZE, 0, &made.mapped);
784 ready = vk_.vkMapMemory(device_, made.memory, 0, VK_WHOLE_SIZE, 0, &made.mapped) == VK_SUCCESS; 946 if (result != VK_SUCCESS) {
785 if (!ready) { 947 note_failure(what, result);
786 destroy(made); 948 destroy(made);
787 return false; 949 return false;
788 } 950 }
@@ -801,17 +963,55 @@ private:
801 destroy(buffers.table); 963 destroy(buffers.table);
802 } 964 }
803 965
966 void destroy(Generation& generation) const {
967 destroy(generation.buffers);
968 if (generation.pool) vk_.vkDestroyDescriptorPool(device_, generation.pool, nullptr); // frees the set
969 generation.pool = VK_NULL_HANDLE;
970 generation.set = VK_NULL_HANDLE;
971 }
972
973 // A generation for a table of `bytes`: a spare when one is large enough (its pool reset for a fresh set), else
974 // new buffers and a new pool. Spares too small for the table are freed: the table never shrinks.
975 bool make_generation(std::size_t bytes, TableBuffers& buffers, VkDescriptorPool& pool, VkDescriptorSet& set) {
976 std::size_t kept = 0;
977 bool found = false;
978 for (Generation& spare : spares_) {
979 if (spare.buffers.table.size < bytes || spare.buffers.staging.size < bytes) {
980 destroy(spare);
981 continue;
982 }
983 if (!found && vk_.vkResetDescriptorPool(device_, spare.pool, 0) == VK_SUCCESS &&
984 allocate_set(spare.pool, set)) {
985 buffers = spare.buffers;
986 pool = spare.pool;
987 found = true;
988 ++spares_reused_;
989 continue;
990 }
991 spares_[kept++] = spare;
992 }
993 spares_.resize(kept);
994 if (found) return true;
995 TableBuffers made;
996 if (!create(made.table, bytes, true) || !create(made.staging, bytes, false) || !make_set(pool, set)) {
997 destroy(made);
998 return false;
999 }
1000 buffers = made;
1001 return true;
1002 }
1003
804 bool create_table_buffers() { 1004 bool create_table_buffers() {
805 const std::size_t bytes = table_.size_bytes(); 1005 const std::size_t bytes = table_.size_bytes();
806 TableBuffers made; 1006 TableBuffers made;
807 bool device_local = false; 1007 if (!create(made.table, bytes, true) || !create(made.staging, bytes, false)) {
808 if (!create(made.table, bytes, true, &device_local) || !create(made.staging, bytes, false)) {
809 destroy(made); 1008 destroy(made);
810 return false; 1009 return false;
811 } 1010 }
812 table_buffers_ = made; 1011 table_buffers_ = made;
813 table_device_local_ = device_local; 1012 table_device_local_ = made.table.device_local;
814 table_uploaded_ = false; // the first flush() uploads it, in the command buffer that will use it 1013 table_uploaded_ = false; // the first flush() uploads it, in the command buffer that will use it
1014 table_on_gpu_ = false;
815 table_dirty_ = existing_entries_changed_ = false; 1015 table_dirty_ = existing_entries_changed_ = false;
816 return true; 1016 return true;
817 } 1017 }
@@ -829,15 +1029,11 @@ private:
829 TableBuffers larger; 1029 TableBuffers larger;
830 VkDescriptorPool pool = VK_NULL_HANDLE; 1030 VkDescriptorPool pool = VK_NULL_HANDLE;
831 VkDescriptorSet set = VK_NULL_HANDLE; 1031 VkDescriptorSet set = VK_NULL_HANDLE;
832 bool device_local = false; 1032 if (!make_generation(bytes, larger, pool, set)) return false;
833 if (!create(larger.table, bytes, true, &device_local) || !create(larger.staging, bytes, false) || 1033 table_device_local_ = larger.table.device_local;
834 !make_set(pool, set)) {
835 destroy(larger);
836 return false;
837 }
838 table_device_local_ = device_local;
839 retired_.push_back({table_buffers_, pool_, set_, retire_ticket}); 1034 retired_.push_back({table_buffers_, pool_, set_, retire_ticket});
840 table_buffers_ = larger; 1035 table_buffers_ = larger;
1036 table_on_gpu_ = false; // until this generation's upload is submitted (table_upload_result)
841 pool_ = pool; 1037 pool_ = pool;
842 set_ = set; 1038 set_ = set;
843 write_table_binding(table_buffers_.table.buffer); 1039 write_table_binding(table_buffers_.table.buffer);
@@ -893,6 +1089,25 @@ private:
893 return true; 1089 return true;
894 } 1090 }
895 1091
1092 // The whole table into the current generation's buffers, for a flush whose new generation could not be made,
1093 // once every submission that could read the current table is done (flush()). False when the table outgrew them.
1094 bool rewrite_table_in_place(VkCommandBuffer command_buffer) {
1095 const std::size_t bytes = table_.size_bytes();
1096 if (bytes > table_buffers_.table.size || bytes > table_buffers_.staging.size || !table_buffers_.staging.mapped)
1097 return false;
1098 table_.take_changes(); // all of it goes
1099 // Nothing still runs that copies from the staging buffer or reads the table.
1100 table_.write_to_buffer(table_buffers_.staging.mapped);
1101 copy_table_range(command_buffer, 0, bytes);
1102 record_table_barrier(command_buffer);
1103 upload_in_flight_ = true;
1104 table_dirty_ = existing_entries_changed_ = false;
1105 table_uploaded_ = true;
1106 force_full_upload_ = false;
1107 ++in_place_rewrites_;
1108 return true;
1109 }
1110
896 // Copies the data into the command buffer while recording (64 KiB per call, the Vulkan limit), so no staging 1111 // Copies the data into the command buffer while recording (64 KiB per call, the Vulkan limit), so no staging
897 // buffer is read at execution: a later flush can rewrite its own staging without racing a pending copy. 1112 // buffer is read at execution: a later flush can rewrite its own staging without racing a pending copy.
898 void update_table_range(VkCommandBuffer command_buffer, VkDeviceSize offset, const void* data, 1113 void update_table_range(VkCommandBuffer command_buffer, VkDeviceSize offset, const void* data,
@@ -998,8 +1213,9 @@ private:
998 return; 1213 return;
999 } 1214 }
1000 const std::uint32_t sampled_at = bindless::sampled_binding(dimension); 1215 const std::uint32_t sampled_at = bindless::sampled_binding(dimension);
1001 queue(sampled_at, index, 1216 if (sampled_at != bindless::no_binding)
1002 sampled ? VkDescriptorImageInfo{VK_NULL_HANDLE, sampled, sampled_layout} : fallback_info(sampled_at)); 1217 queue(sampled_at, index,
1218 sampled ? VkDescriptorImageInfo{VK_NULL_HANDLE, sampled, sampled_layout} : fallback_info(sampled_at));
1003 const auto store = [&](std::uint32_t binding, VkImageView view) { 1219 const auto store = [&](std::uint32_t binding, VkImageView view) {
1004 if (binding == bindless::no_binding || index >= features_.counts[binding]) return; 1220 if (binding == bindless::no_binding || index >= features_.counts[binding]) return;
1005 queue(binding, index, 1221 queue(binding, index,
@@ -1014,6 +1230,7 @@ private:
1014 VkDevice device_; 1230 VkDevice device_;
1015 VkPhysicalDeviceMemoryProperties memory_; 1231 VkPhysicalDeviceMemoryProperties memory_;
1016 BindlessFeatures features_; 1232 BindlessFeatures features_;
1233 std::vector<std::uint32_t> families_;
1017 Functions vk_; 1234 Functions vk_;
1018 bool ok_ = false; 1235 bool ok_ = false;
1019 VkDescriptorSetLayout layout_ = VK_NULL_HANDLE; 1236 VkDescriptorSetLayout layout_ = VK_NULL_HANDLE;
@@ -1026,25 +1243,30 @@ private:
1026 bool fallbacks_ready_ = false; 1243 bool fallbacks_ready_ = false;
1027 std::array<std::vector<std::uint8_t>, dimensions> image_used_; 1244 std::array<std::vector<std::uint8_t>, dimensions> image_used_;
1028 std::vector<std::uint8_t> sampler_used_; 1245 std::vector<std::uint8_t> sampler_used_;
1246 std::vector<std::pair<ImageDimension, std::uint32_t>> held_images_; // removed, not yet free (remove_image)
1247 std::vector<std::uint32_t> held_samplers_;
1029 std::vector<Pending> pending_; 1248 std::vector<Pending> pending_;
1030 std::unordered_map<std::uint64_t, std::size_t> pending_slots_; // binding and index -> place in pending_ 1249 std::unordered_map<std::uint64_t, std::size_t> pending_slots_; // binding and index -> place in pending_
1031 DescriptorTable table_{64}; 1250 DescriptorTable table_; // 64 slots, and the device's hash kind, from the constructor
1032 TableBuffers table_buffers_; 1251 TableBuffers table_buffers_;
1033 bool table_uploaded_ = false; // the table's current contents are in table_buffers_.table 1252 bool table_uploaded_ = false; // the table's current contents are in table_buffers_.table
1253 bool table_on_gpu_ = false; // an upload into the current table buffers reached the queue (degrading is safe)
1034 bool table_device_local_ = false; 1254 bool table_device_local_ = false;
1035 bool table_dirty_ = false; // the table differs from the buffer 1255 bool table_dirty_ = false; // the table differs from the buffer
1036 bool existing_entries_changed_ = false; // ... and not only by entries added 1256 bool existing_entries_changed_ = false; // ... and not only by entries added
1037 bool upload_in_flight_ = false; // a copy is recorded, not yet known to have reached the queue 1257 bool upload_in_flight_ = false; // a copy is recorded, not yet known to have reached the queue
1038 bool force_full_upload_ = false; // the last submit failed: rebuild the whole table on the next flush 1258 bool force_full_upload_ = false; // the last submit failed: rebuild the whole table on the next flush
1039 struct Generation { // what a replaced table leaves for release_retired()
1040 TableBuffers buffers;
1041 VkDescriptorPool pool = VK_NULL_HANDLE; // owns the descriptor set
1042 VkDescriptorSet set = VK_NULL_HANDLE;
1043 std::uint64_t ticket = 0;
1044 };
1045 std::vector<Generation> retired_; 1259 std::vector<Generation> retired_;
1260 std::vector<Generation> spares_; // released generations kept for reuse (release_retired)
1046 std::uint64_t generations_made_ = 0; 1261 std::uint64_t generations_made_ = 0;
1047 bool last_flush_replaced_ = false; 1262 bool last_flush_replaced_ = false;
1263 bool last_flush_degraded_ = false;
1264 std::uint64_t spares_reused_ = 0;
1265 std::uint64_t degraded_flushes_ = 0;
1266 std::uint64_t in_place_rewrites_ = 0;
1267 std::uint64_t table_host_fallbacks_ = 0;
1268 mutable const char* last_failure_ = nullptr;
1269 mutable VkResult last_failure_result_ = VK_SUCCESS;
1048 std::array<VkDescriptorPoolSize, bindless::bindings.size()> pool_sizes_{}; 1270 std::array<VkDescriptorPoolSize, bindless::bindings.size()> pool_sizes_{};
1049 std::uint32_t pool_size_count_ = 0; 1271 std::uint32_t pool_size_count_ = 0;
1050 // Every descriptor written to the set (the table's binding aside), to fill the next generation's set. 1272 // Every descriptor written to the set (the table's binding aside), to fill the next generation's set.