upleb.uk

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

summaryrefslogtreecommitdiff
path: root/runtime/src
diff options
context:
space:
mode:
authorEmma <47298336+zzEmmazz@users.noreply.github.com>2026-11-23 05:49:06 +0200
committerEmma <47298336+zzEmmazz@users.noreply.github.com>2026-11-23 05:49:06 +0200
commitdddf6aaa9af4d16227955ecf0c632ff3690bb13e (patch)
tree80d5abaaed2fd119b5d9f22fc65645690fa9bc90 /runtime/src
parentd2e6b31db24e7ca93a34f0b53b063d32ff944070 (diff)
parent7b7d73f890f9fbbf5967bbb694390bbc99e33ba6 (diff)
Merge main 7b7d73f8: the device function list keeps main's pipeline cache entries and the render pass ones
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Diffstat (limited to 'runtime/src')
-rw-r--r--runtime/src/active_input.h146
-rw-r--r--runtime/src/buffer_va_index.h31
-rw-r--r--runtime/src/command_list.h27
-rw-r--r--runtime/src/depth24_fragment.h445
-rw-r--r--runtime/src/gfx10_descriptors.h9
-rw-r--r--runtime/src/indirect_dispatch_count.comp34
-rw-r--r--runtime/src/indirect_dispatch_count_spv.h84
-rw-r--r--runtime/src/pe_loader.cpp28
-rw-r--r--runtime/src/pe_loader.h17
-rw-r--r--runtime/src/queue_families.h20
-rw-r--r--runtime/src/shader_library.h11
-rw-r--r--runtime/src/vulkan_backend.h71
-rw-r--r--runtime/src/vulkan_indirect_dispatch_count.h199
-rw-r--r--runtime/src/vulkan_memory.h9
-rw-r--r--runtime/src/vulkan_present.h26
-rw-r--r--runtime/src/vulkan_replay.h132
16 files changed, 1231 insertions, 58 deletions
diff --git a/runtime/src/active_input.h b/runtime/src/active_input.h
new file mode 100644
index 000000000..c0f7451b1
--- /dev/null
+++ b/runtime/src/active_input.h
@@ -0,0 +1,146 @@
1#pragma once
2
3// Which kind of input device the player used last: an Xbox-style pad, a PlayStation pad, a Nintendo pad or the
4// keyboard pad (docs/gameinput.md). The GameInput shim reports every pad to the title as an Xbox One pad, so the title
5// itself cannot tell; this is the port's own record, for whatever wants to follow the device in use (button prompt
6// glyphs first). No SDL, no Windows headers: the shim feeds it one sample per device per poll, and tests feed it
7// synthetic samples with their own times.
8//
9// The rules, chosen so that only deliberate input changes the answer:
10// * Only an edge counts: a button going down, a trigger rising past `trigger`, a stick leaving the `stick` radius.
11// A button held down, a trigger held, a stick held over, stick drift that stays inside the radius and analog
12// noise never count, so a pad lying on the desk cannot take over. The keyboard pad's right stick follows the
13// mouse, so a real mouse movement counts as keyboard input through the same stick rule.
14// * A device's first sample is its baseline and counts for nothing: a pad that connects with a button held or a
15// worn stick resting past the radius does not switch anything until it produces a new edge.
16// * After a change, another change waits until `min_switch_us` has passed. An edge from another family inside that
17// window is ignored (not queued), so two devices used at once cannot make the answer flicker.
18// * Edges from a device of the family already active change nothing.
19// * Before any edge the answer is `initial` (Xbox unless the caller says otherwise).
20// * A forced family (LEONIDA_PROMPTS) wins over all of this; the tracking still runs underneath, so clearing the
21// force goes straight back to the device in use.
22// `generation` counts changes of the answer (tracked or forced), so a reader can tell that something changed without
23// comparing families.
24
25#include <cmath>
26#include <cstdint>
27#include <optional>
28#include <unordered_map>
29
30namespace leonida {
31
32enum class InputFamily : std::uint8_t {
33 Xbox, // Xbox One/Series, Xbox 360, and any pad SDL does not know better (generic, unknown)
34 PlayStation5, // DualSense, DualSense Edge
35 PlayStation4, // DualShock 4
36 PlayStation3, // DualShock 3
37 Nintendo, // Switch Pro controller and Joy-Cons
38 Keyboard, // the keyboard pad: keyboard and mouse
39};
40
41inline const char* input_family_name(InputFamily f) {
42 switch (f) {
43 case InputFamily::Xbox: return "Xbox";
44 case InputFamily::PlayStation5: return "PlayStation 5";
45 case InputFamily::PlayStation4: return "PlayStation 4";
46 case InputFamily::PlayStation3: return "PlayStation 3";
47 case InputFamily::Nintendo: return "Nintendo";
48 case InputFamily::Keyboard: return "keyboard and mouse";
49 }
50 return "unknown";
51}
52
53// One device's state at one poll, in GameInput's units: sticks -1..1, triggers 0..1. `buttons` is any bit set per
54// pressed button (the shim passes the GameInput gamepad bits plus one bit for the guide button); only its changes
55// matter.
56struct InputSample {
57 std::uint32_t buttons = 0;
58 float left_trigger = 0, right_trigger = 0;
59 float left_x = 0, left_y = 0, right_x = 0, right_y = 0;
60};
61
62// What made the answer change, for the log line.
63enum class InputEdge : std::uint8_t { None, Button, Trigger, Stick };
64
65inline const char* input_edge_name(InputEdge e) {
66 switch (e) {
67 case InputEdge::None: return "none";
68 case InputEdge::Button: return "button press";
69 case InputEdge::Trigger: return "trigger pull";
70 case InputEdge::Stick: return "stick movement";
71 }
72 return "unknown";
73}
74
75class ActiveInputTracker {
76public:
77 struct Thresholds {
78 float stick = 0.35f; // radius a stick has to leave
79 float trigger = 0.3f; // a trigger has to rise past this
80 std::uint64_t min_switch_us = 300'000; // shortest time between two changes
81 };
82
83 explicit ActiveInputTracker(InputFamily initial = InputFamily::Xbox) : tracked_(initial) {}
84 ActiveInputTracker(InputFamily initial, Thresholds t) : thresholds_(t), tracked_(initial) {}
85
86 // One sample of one device (`device` is any key that stays the same while the device is connected). Returns the
87 // edge that changed the tracked family, or None when it did not change. With a family forced, the tracked family
88 // still follows the devices, but active() does not move.
89 InputEdge observe(std::uint64_t device, InputFamily family, const InputSample& now, std::uint64_t time_us) {
90 auto it = devices_.find(device);
91 if (it == devices_.end()) {
92 devices_.emplace(device, now); // the baseline: counts for nothing
93 return InputEdge::None;
94 }
95 const InputEdge edge = edge_between(it->second, now);
96 it->second = now;
97 if (edge == InputEdge::None || family == tracked_) return InputEdge::None;
98 if (changed_once_ && time_us - changed_at_ < thresholds_.min_switch_us) return InputEdge::None;
99 const InputFamily before = active();
100 tracked_ = family;
101 changed_at_ = time_us;
102 changed_once_ = true;
103 if (active() != before) ++generation_;
104 return edge;
105 }
106
107 // The device disconnected: its next sample, if it comes back, is a baseline again.
108 void forget(std::uint64_t device) { devices_.erase(device); }
109
110 // Forces the answer (a family) or returns to tracking (nullopt). Changing what active() returns bumps generation.
111 void force(std::optional<InputFamily> family) {
112 const InputFamily before = active();
113 forced_ = family;
114 if (active() != before) ++generation_;
115 }
116
117 InputFamily active() const { return forced_ ? *forced_ : tracked_; }
118 InputFamily tracked() const { return tracked_; }
119 bool forced() const { return forced_.has_value(); }
120 std::uint64_t generation() const { return generation_; }
121 const Thresholds& thresholds() const { return thresholds_; }
122 void set_thresholds(const Thresholds& t) { thresholds_ = t; }
123
124private:
125 InputEdge edge_between(const InputSample& was, const InputSample& now) const {
126 if (now.buttons & ~was.buttons) return InputEdge::Button;
127 const float t = thresholds_.trigger;
128 if ((was.left_trigger <= t && now.left_trigger > t) || (was.right_trigger <= t && now.right_trigger > t))
129 return InputEdge::Trigger;
130 const auto out = [this](float x, float y) { return std::hypot(x, y) > thresholds_.stick; };
131 if ((!out(was.left_x, was.left_y) && out(now.left_x, now.left_y)) ||
132 (!out(was.right_x, was.right_y) && out(now.right_x, now.right_y)))
133 return InputEdge::Stick;
134 return InputEdge::None;
135 }
136
137 Thresholds thresholds_{};
138 InputFamily tracked_;
139 std::optional<InputFamily> forced_;
140 std::uint64_t generation_ = 0;
141 std::uint64_t changed_at_ = 0;
142 bool changed_once_ = false;
143 std::unordered_map<std::uint64_t, InputSample> devices_;
144};
145
146} // namespace leonida
diff --git a/runtime/src/buffer_va_index.h b/runtime/src/buffer_va_index.h
index 5abab65df..5096771c7 100644
--- a/runtime/src/buffer_va_index.h
+++ b/runtime/src/buffer_va_index.h
@@ -5,9 +5,13 @@
5// every registered resource. No Vulkan or Windows dependency; not thread-safe (VulkanContext guards it with 5// every registered resource. No Vulkan or Windows dependency; not thread-safe (VulkanContext guards it with
6// resource_mutex_, like the bindings themselves). 6// resource_mutex_, like the bindings themselves).
7// 7//
8// D3D12 lets placed buffers alias, so ranges may overlap. A lookup then returns the containing range that starts 8// D3D12 lets placed buffers alias, so ranges may overlap. A lookup names the bytes it needs, [va, va + bytes), and
9// closest below the VA (the larger ID on a tie): the walk goes down from the nearest start and stops once no range can 9// returns, among the ranges that hold va, the one that starts closest below it (the larger ID on a tie) that also
10// still reach the VA, which `longest_` bounds. Without overlaps the first range it looks at is the answer, or none is. 10// holds all of those bytes; when none does, the closest one that holds va. So a view that starts in a small placed
11// buffer and runs past its end resolves to a larger buffer that aliases the same memory and holds all of it, instead
12// of being cut at the small one's end (found in review of #2823). The walk goes down from the nearest start and stops
13// once no range can still reach the VA, or, with a fallback found, once no range can still hold all the bytes; both
14// are bounded by `longest_`. Without overlaps the first range it looks at is the answer, or none is.
11// `longest_` is the longest range indexed now, not the longest ever: a large buffer that is freed stops lengthening 15// `longest_` is the longest range indexed now, not the longest ever: a large buffer that is freed stops lengthening
12// later misses. A miss still walks every start within the longest live range below the VA. 16// later misses. A miss still walks every start within the longest live range below the VA.
13 17
@@ -49,20 +53,29 @@ public:
49 std::uint64_t size; 53 std::uint64_t size;
50 }; 54 };
51 55
52 // The range that holds `va`; false when none does. 56 // The range that holds `va`, preferring one that holds [va, va + bytes) (bytes 0 counts as 1); false when none
53 bool find(std::uint64_t va, Hit& out) const { 57 // holds va.
58 bool find(std::uint64_t va, Hit& out, std::uint64_t bytes = 1) const {
59 if (!bytes) bytes = 1;
60 bool found = false; // `out` holds the closest range that holds va, though not all the bytes
54 auto it = ranges_.upper_bound({va, max_id()}); 61 auto it = ranges_.upper_bound({va, max_id()});
55 while (it != ranges_.begin()) { 62 while (it != ranges_.begin()) {
56 --it; 63 --it;
57 const std::uint64_t start = it->first.first; 64 const std::uint64_t start = it->first.first;
58 const std::uint64_t offset = va - start; // start <= va here 65 const std::uint64_t offset = va - start; // start <= va here; it only grows as the walk goes down
59 if (offset >= longest_) return false; // no range that starts this low reaches va 66 if (offset >= longest_) break; // no range that starts this low reaches va
60 if (offset < it->second) { 67 if (found && bytes > longest_ - offset) break; // nor holds all the bytes
68 if (offset >= it->second) continue;
69 if (bytes <= it->second - offset) {
61 out = {it->first.second, start, it->second}; 70 out = {it->first.second, start, it->second};
62 return true; 71 return true;
63 } 72 }
73 if (!found) {
74 out = {it->first.second, start, it->second};
75 found = true;
76 }
64 } 77 }
65 return false; 78 return found;
66 } 79 }
67 80
68 std::size_t size() const { return ranges_.size(); } 81 std::size_t size() const { return ranges_.size(); }
diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h
index fcdc1ca33..7e612e1eb 100644
--- a/runtime/src/command_list.h
+++ b/runtime/src/command_list.h
@@ -12,6 +12,7 @@
12#include <cstdint> 12#include <cstdint>
13#include <optional> 13#include <optional>
14#include <span> 14#include <span>
15#include <memory>
15#include <string> 16#include <string>
16#include <utility> 17#include <utility>
17#include <variant> 18#include <variant>
@@ -179,6 +180,11 @@ inline constexpr std::uint32_t video_decode_statistics = 8;
179inline constexpr std::uint32_t pipeline_statistics1 = 10; 180inline constexpr std::uint32_t pipeline_statistics1 = 10;
180} // namespace d3d12_query 181} // namespace d3d12_query
181 182
183// A stream-output statistics query (SO_STATISTICS_STREAM0..3).
184constexpr bool is_so_statistics(std::uint32_t query_type) {
185 return query_type >= d3d12_query::so_statistics_stream0 && query_type <= d3d12_query::so_statistics_stream3;
186}
187
182// Whether a heap of `heap_type` holds queries of `query_type` (the D3D12 pairing rules). 188// Whether a heap of `heap_type` holds queries of `query_type` (the D3D12 pairing rules).
183constexpr bool query_fits_heap(std::uint32_t heap_type, std::uint32_t query_type) { 189constexpr bool query_fits_heap(std::uint32_t heap_type, std::uint32_t query_type) {
184 namespace h = d3d12_query_heap; 190 namespace h = d3d12_query_heap;
@@ -196,7 +202,8 @@ constexpr bool query_fits_heap(std::uint32_t heap_type, std::uint32_t query_type
196} 202}
197 203
198// Bytes one resolved query takes: a UINT64 for occlusion and timestamps, D3D12_QUERY_DATA_PIPELINE_STATISTICS 204// Bytes one resolved query takes: a UINT64 for occlusion and timestamps, D3D12_QUERY_DATA_PIPELINE_STATISTICS
199// (11 UINT64s) for pipeline statistics. 0 for the types this layer does not resolve. 205// (11 UINT64s) for pipeline statistics, D3D12_QUERY_DATA_SO_STATISTICS (2 UINT64s) for stream output. 0 for the
206// types this layer does not resolve.
200constexpr std::uint32_t query_result_size(std::uint32_t query_type) { 207constexpr std::uint32_t query_result_size(std::uint32_t query_type) {
201 namespace q = d3d12_query; 208 namespace q = d3d12_query;
202 switch (query_type) { 209 switch (query_type) {
@@ -204,6 +211,11 @@ constexpr std::uint32_t query_result_size(std::uint32_t query_type) {
204 case q::binary_occlusion: 211 case q::binary_occlusion:
205 case q::timestamp: return 8; 212 case q::timestamp: return 8;
206 case q::pipeline_statistics: return 11 * 8; 213 case q::pipeline_statistics: return 11 * 8;
214 // D3D12_QUERY_DATA_SO_STATISTICS: NumPrimitivesWritten, PrimitivesStorageNeeded.
215 case q::so_statistics_stream0:
216 case q::so_statistics_stream0 + 1:
217 case q::so_statistics_stream0 + 2:
218 case q::so_statistics_stream3: return 2 * 8;
207 default: return 0; 219 default: return 0;
208 } 220 }
209} 221}
@@ -392,6 +404,15 @@ struct IndexBufferView {
392 std::uint32_t format; // DXGI_FORMAT_R16_UINT (57) or DXGI_FORMAT_R32_UINT (42) 404 std::uint32_t format; // DXGI_FORMAT_R16_UINT (57) or DXGI_FORMAT_R32_UINT (42)
393}; 405};
394 406
407// The views a draw captured, at the D3D12 maxima. Kept by value because the CPU descriptor slots and the bound
408// views can change after the draw is recorded, and out of line because the command variant is sized by its largest
409// member: inline they made every recorded command, barriers included, 976 bytes.
410struct DrawViews {
411 std::array<TargetView, 8> render_targets{};
412 std::array<VertexBufferView, 32> vertex_buffers{}; // by input slot
413 std::uint32_t render_target_count = 8;
414};
415
395// DrawInstanced / DrawIndexedInstanced, with everything they use captured when they are recorded: D3D12 reads 416// DrawInstanced / DrawIndexedInstanced, with everything they use captured when they are recorded: D3D12 reads
396// render-target and depth descriptors at OMSetRenderTargets, and every other piece of state is the list's state at 417// render-target and depth descriptors at OMSetRenderTargets, and every other piece of state is the list's state at
397// the draw. resource 0 marks an unbound render-target slot or no depth buffer. 418// the draw. resource 0 marks an unbound render-target slot or no depth buffer.
@@ -400,9 +421,8 @@ struct IndexBufferView {
400struct Draw { 421struct Draw {
401 std::uintptr_t pipeline = 0; 422 std::uintptr_t pipeline = 0;
402 std::array<std::uint32_t, 32> user_data{}; 423 std::array<std::uint32_t, 32> user_data{};
403 std::array<TargetView, 8> render_targets{}; 424 std::shared_ptr<const DrawViews> views; // null: no render targets or vertex buffers captured
404 TargetView depth{}; 425 TargetView depth{};
405 std::array<VertexBufferView, 32> vertex_buffers{}; // by input slot
406 IndexBufferView index{}; 426 IndexBufferView index{};
407 std::uint32_t topology = 0; // D3D_PRIMITIVE_TOPOLOGY 427 std::uint32_t topology = 0; // D3D_PRIMITIVE_TOPOLOGY
408 Viewport viewport{}; // the first; more viewports are not modelled yet 428 Viewport viewport{}; // the first; more viewports are not modelled yet
@@ -416,7 +436,6 @@ struct Draw {
416 std::uint32_t first = 0; // first vertex or first index 436 std::uint32_t first = 0; // first vertex or first index
417 std::int32_t base_vertex = 0; 437 std::int32_t base_vertex = 0;
418 std::uint32_t first_instance = 0; 438 std::uint32_t first_instance = 0;
419 std::uint32_t render_target_count = 8;
420}; 439};
421 440
422// D3D12_TEXTURE_DATA_PITCH_ALIGNMENT and D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT. 441// D3D12_TEXTURE_DATA_PITCH_ALIGNMENT and D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT.
diff --git a/runtime/src/depth24_fragment.h b/runtime/src/depth24_fragment.h
new file mode 100644
index 000000000..10f0dada8
--- /dev/null
+++ b/runtime/src/depth24_fragment.h
@@ -0,0 +1,445 @@
1#pragma once
2
3// D24_UNORM_S8_UINT on a GPU without D24 (the layer stores D32_SFLOAT_S8_UINT, depth24.h) in draws (D3D-309).
4//
5// Two D3D rules break when the depth attachment is float (found by @marquezinii, measured by @Vonsek on #291):
6// * the integer RasterizerState.DepthBias is in fixed D24 units, r = 1 / (2^24 - 1) ("the minimum representable
7// value > 0 in the depth-buffer format"), while Vulkan scales a float attachment's constant bias by the
8// primitive's exponent;
9// * clears are quantised to the D24 code (depth24_clear_value), fragment depth is not, so an EQUAL test at a
10// cleared value fails where D24 hardware passes.
11// The fix moves both into the pixel stage: the fragment writes FragDepth = quantise(z + bias), with z the rasterised
12// depth, bias = DepthBias * r + SlopeScaledDepthBias * max(|dz/dx|, |dz/dy|) clamped by DepthBiasClamp (D3D's
13// formula), and quantise = depth24_to_float(depth24_quantize(.)) from depth24_convert.comp, so a fragment holds
14// exactly the float a D24 code reads back as. The rasterizer's own bias is then turned off for the pipeline.
15// A shader that writes its own depth (SV_Depth) keeps its value, quantised; D3D applies no bias to it.
16//
17// depth24_patch_fragment edits a translated pixel shader's SPIR-V; depth24_depth_only_fragment builds the stage
18// for a pipeline without a pixel shader (depth-only passes such as shadow maps). Both are plain word editing with
19// no dependency beyond the standard library; d3d12_depth24_draw_test runs them (with LEONIDA_VK_VALIDATION=1 the
20// validation layer checks the modules).
21//
22// Not covered (logged by the caller): a pixel shader with EarlyFragmentTests (its FragDepth write would be ignored),
23// multisampled targets (FragDepth is per pixel, which would flatten per-sample depth), and a viewport depth range
24// narrower than the biased depth (D3D clamps to MinDepth..MaxDepth before quantising; the quantisation here clamps
25// to 0..1 and Vulkan's clamp to the viewport range follows it).
26
27#include <array>
28#include <cmath>
29#include <cstdint>
30#include <cstring>
31#include <string>
32#include <vector>
33
34namespace leonida {
35
36struct Depth24Bias {
37 int constant = 0; // D3D12_RASTERIZER_DESC::DepthBias
38 float slope = 0.0f; // SlopeScaledDepthBias
39 float clamp = 0.0f; // DepthBiasClamp: > 0 caps the bias, < 0 floors it, 0 leaves it
40 bool any() const { return constant != 0 || slope != 0.0f; }
41};
42
43// D3D's constant term in float: (float)DepthBias * r, with r the float nearest 1 / (2^24 - 1).
44inline float depth24_bias_constant(int bias) {
45 return float(bias) * float(1.0 / 16777215.0);
46}
47
48namespace spirv24 {
49
50enum : std::uint32_t {
51 op_name = 5, op_line = 8, op_ext_inst_import = 11, op_ext_inst = 12, op_memory_model = 14, op_entry_point = 15,
52 op_execution_mode = 16, op_capability = 17, op_type_void = 19, op_type_bool = 20, op_type_int = 21,
53 op_type_float = 22, op_type_vector = 23, op_type_pointer = 32, op_type_function = 33, op_constant = 43,
54 op_function = 54, op_function_end = 56, op_variable = 59, op_load = 61, op_store = 62, op_decorate = 71,
55 op_composite_extract = 81, op_convert_f_to_u = 109, op_convert_u_to_f = 112, op_bitcast = 124, op_i_add = 128,
56 op_f_add = 129, op_i_sub = 130, op_f_mul = 133, op_select = 169, op_i_equal = 170, op_u_greater_than = 172,
57 op_u_greater_than_equal = 174, op_shift_left_logical = 196, op_dpdx = 207, op_dpdy = 208, op_label = 248,
58 op_return = 253, op_no_line = 317, op_execution_mode_id = 331,
59};
60enum : std::uint32_t { storage_input = 1, storage_output = 3 };
61enum : std::uint32_t { decoration_builtin = 11, builtin_frag_coord = 15, builtin_frag_depth = 22 };
62enum : std::uint32_t { model_fragment = 4 };
63enum : std::uint32_t {
64 mode_origin_upper_left = 7, mode_early_fragment_tests = 9, mode_depth_replacing = 12, mode_depth_greater = 14,
65 mode_depth_less = 15, mode_depth_unchanged = 16,
66};
67enum : std::uint32_t { glsl_round_even = 2, glsl_fabs = 4, glsl_fmin = 37, glsl_fmax = 40, glsl_find_umsb = 75 };
68
69using Inst = std::vector<std::uint32_t>; // a whole instruction, word 0 included
70
71inline std::uint32_t opcode(const Inst& i) { return i[0] & 0xffffu; }
72inline Inst make(std::uint32_t op, std::initializer_list<std::uint32_t> operands) {
73 Inst i;
74 i.reserve(operands.size() + 1);
75 i.push_back(std::uint32_t(operands.size() + 1) << 16 | op);
76 i.insert(i.end(), operands.begin(), operands.end());
77 return i;
78}
79inline void append_string(Inst& i, const char* s) {
80 const std::size_t n = std::strlen(s) + 1, words = (n + 3) / 4;
81 const std::size_t at = i.size();
82 i.resize(at + words, 0);
83 std::memcpy(&i[at], s, n);
84}
85inline void fix_length(Inst& i) { i[0] = std::uint32_t(i.size()) << 16 | opcode(i); }
86inline std::uint32_t bits(float f) {
87 std::uint32_t u;
88 std::memcpy(&u, &f, 4);
89 return u;
90}
91// Words a literal string takes in an instruction, starting at `at`.
92inline std::size_t string_words(const Inst& i, std::size_t at) {
93 std::size_t w = at;
94 while (w < i.size()) {
95 const std::uint32_t word = i[w++];
96 if ((word & 0xff000000u) == 0 || (word & 0x00ff0000u) == 0 || (word & 0x0000ff00u) == 0 ||
97 (word & 0x000000ffu) == 0)
98 break;
99 }
100 return w - at;
101}
102
103inline bool is_global_decl(std::uint32_t op) {
104 return op == 1 /* OpUndef */ || (op >= op_type_void && op <= 39) || (op >= 41 && op <= 52) || op == op_variable;
105}
106
107class Module {
108public:
109 bool parse(const std::vector<std::uint32_t>& words, std::string& why) {
110 if (words.size() < 5 || words[0] != 0x07230203u) {
111 why = "not a SPIR-V module";
112 return false;
113 }
114 header_.assign(words.begin(), words.begin() + 5);
115 for (std::size_t w = 5; w < words.size();) {
116 const std::uint32_t count = words[w] >> 16;
117 if (count == 0 || w + count > words.size()) {
118 why = "truncated instruction";
119 return false;
120 }
121 insts_.emplace_back(words.begin() + std::ptrdiff_t(w), words.begin() + std::ptrdiff_t(w + count));
122 w += count;
123 }
124 return true;
125 }
126 std::vector<std::uint32_t> words() const {
127 std::vector<std::uint32_t> out = header_;
128 for (const Inst& i : insts_) out.insert(out.end(), i.begin(), i.end());
129 return out;
130 }
131 std::uint32_t fresh() { return header_[3]++; }
132 std::uint32_t version() const { return header_[1]; }
133 std::vector<Inst>& insts() { return insts_; }
134 std::vector<std::uint32_t>& header() { return header_; }
135
136private:
137 std::vector<std::uint32_t> header_;
138 std::vector<Inst> insts_;
139};
140
141// The edit, on a parsed module. Globals are collected first and spliced in at their section's end.
142class Patch {
143public:
144 Patch(Module& m, std::uint32_t entry) : m_(m), entry_(entry) {
145 // Copies: apply() moves the module's instructions while the code at returns still looks types up.
146 for (const Inst& i : m.insts()) {
147 if (opcode(i) == op_function) break;
148 existing_.push_back(i);
149 }
150 }
151
152 // A type, reused when the module already declares it (SPIR-V forbids duplicate non-aggregate types).
153 std::uint32_t type(std::uint32_t op, std::initializer_list<std::uint32_t> operands) {
154 auto same = [&](const Inst& i) {
155 if (opcode(i) != op || i.size() != operands.size() + 2) return false;
156 std::size_t k = 2;
157 for (std::uint32_t o : operands)
158 if (i[k++] != o) return false;
159 return true;
160 };
161 for (const Inst& ex : existing_)
162 if (same(ex)) return ex[1];
163 for (const Inst& i : globals_)
164 if (same(i)) return i[1];
165 const std::uint32_t id = m_.fresh();
166 Inst i = make(op, {id});
167 i.insert(i.end(), operands.begin(), operands.end());
168 fix_length(i);
169 globals_.push_back(std::move(i));
170 return id;
171 }
172 std::uint32_t t_float() { return type(op_type_float, {32}); }
173 std::uint32_t t_uint() { return type(op_type_int, {32, 0}); }
174 std::uint32_t t_bool() { return type(op_type_bool, {}); }
175 // Constants are cached by type and value: all of them are declared before apply() writes the globals out.
176 std::uint32_t constant(std::uint32_t t, std::uint32_t value) {
177 for (const auto& c : constants_)
178 if (c[0] == t && c[1] == value) return c[2];
179 const std::uint32_t id = m_.fresh();
180 globals_.push_back(make(op_constant, {t, id, value}));
181 constants_.push_back({t, value, id});
182 return id;
183 }
184 // Declares what quantise() uses, so it can run inside apply() (at returns) without adding globals.
185 void prime_quantise() {
186 t_bool();
187 glsl();
188 for (float f : {16777215.0f, 0.0f}) f32(f);
189 for (std::uint32_t u : {0x3f800000u, 0xffffffu, 0x7f800000u, 0u, 23u, 1u, 80u}) u32(u);
190 }
191 std::uint32_t f32(float f) { return constant(t_float(), bits(f)); }
192 std::uint32_t u32(std::uint32_t u) { return constant(t_uint(), u); }
193
194 std::uint32_t glsl() {
195 if (glsl_) return glsl_;
196 for (const Inst& ex : existing_) {
197 if (opcode(ex) != op_ext_inst_import || ex.size() < 3) continue;
198 std::string name((ex.size() - 2) * 4, '\0');
199 std::memcpy(name.data(), &ex[2], name.size());
200 if (std::strcmp(name.c_str(), "GLSL.std.450") == 0) return glsl_ = ex[1];
201 }
202 glsl_ = m_.fresh();
203 Inst i = make(op_ext_inst_import, {glsl_});
204 append_string(i, "GLSL.std.450");
205 fix_length(i);
206 import_ = std::move(i);
207 return glsl_;
208 }
209
210 // A built-in variable already decorated in the module, or 0.
211 std::uint32_t builtin_variable(std::uint32_t builtin) const {
212 for (const Inst& ex : existing_)
213 if (opcode(ex) == op_decorate && ex.size() == 4 && ex[2] == decoration_builtin && ex[3] == builtin)
214 return ex[1];
215 return 0;
216 }
217 std::uint32_t variable(std::uint32_t pointer_type, std::uint32_t storage, std::uint32_t builtin) {
218 const std::uint32_t id = m_.fresh();
219 globals_.push_back(make(op_variable, {pointer_type, id, storage}));
220 decorations_.push_back(make(op_decorate, {id, decoration_builtin, builtin}));
221 interface_.push_back(id);
222 return id;
223 }
224 void ensure_interface(std::uint32_t id) { interface_.push_back(id); }
225 void mode(std::uint32_t m) { modes_.push_back(make(op_execution_mode, {entry_, m})); }
226
227 // Instructions in a function body: emit returns the result id.
228 std::uint32_t emit(std::vector<Inst>& code, std::uint32_t op, std::uint32_t type,
229 std::initializer_list<std::uint32_t> operands) {
230 const std::uint32_t id = m_.fresh();
231 Inst i = make(op, {type, id});
232 i.insert(i.end(), operands.begin(), operands.end());
233 fix_length(i);
234 code.push_back(std::move(i));
235 return id;
236 }
237 std::uint32_t ext(std::vector<Inst>& code, std::uint32_t type, std::uint32_t inst,
238 std::initializer_list<std::uint32_t> operands) {
239 const std::uint32_t id = m_.fresh();
240 Inst i = make(op_ext_inst, {type, id, glsl(), inst});
241 i.insert(i.end(), operands.begin(), operands.end());
242 fix_length(i);
243 code.push_back(std::move(i));
244 return id;
245 }
246
247 // depth24_to_float(depth24_from_bits(z)) of depth24_convert.comp, branch-free.
248 std::uint32_t quantise(std::vector<Inst>& code, std::uint32_t z) {
249 const std::uint32_t tf = t_float(), tu = t_uint(), tb = t_bool();
250 const std::uint32_t b = emit(code, op_bitcast, tu, {z});
251 const std::uint32_t product = emit(code, op_f_mul, tf, {z, f32(16777215.0f)});
252 const std::uint32_t rounded = ext(code, tf, glsl_round_even, {product});
253 // Clamped before the conversion so an out-of-range float never reaches OpConvertFToU (undefined there).
254 const std::uint32_t safe = ext(code, tf, glsl_fmin, {ext(code, tf, glsl_fmax, {rounded, f32(0.0f)}),
255 f32(16777215.0f)});
256 const std::uint32_t code_mid = emit(code, op_convert_f_to_u, tu, {safe});
257 const std::uint32_t at_least_one = emit(code, op_u_greater_than_equal, tb, {b, u32(0x3f800000u)});
258 const std::uint32_t code_hi = emit(code, op_select, tu, {at_least_one, u32(0xffffffu), code_mid});
259 const std::uint32_t negative_or_nan = emit(code, op_u_greater_than, tb, {b, u32(0x7f800000u)});
260 const std::uint32_t d = emit(code, op_select, tu, {negative_or_nan, u32(0), code_hi});
261 // float(m + 1) * 2^(e - 47) with e = findMSB(d) and m = d << (23 - e); d == 0 gives 0.
262 const std::uint32_t e = ext(code, tu, glsl_find_umsb, {d});
263 const std::uint32_t m = emit(code, op_shift_left_logical, tu, {d, emit(code, op_i_sub, tu, {u32(23), e})});
264 const std::uint32_t mf = emit(code, op_convert_u_to_f, tf, {emit(code, op_i_add, tu, {m, u32(1)})});
265 const std::uint32_t exponent = emit(code, op_shift_left_logical, tu, {emit(code, op_i_add, tu, {e, u32(80)}),
266 u32(23)});
267 const std::uint32_t scale = emit(code, op_bitcast, tf, {exponent});
268 const std::uint32_t value = emit(code, op_f_mul, tf, {mf, scale});
269 const std::uint32_t zero = emit(code, op_i_equal, tb, {d, u32(0)});
270 return emit(code, op_select, tf, {zero, f32(0.0f), value});
271 }
272
273 // Splices everything into the module.
274 void apply(std::vector<Inst> entry_code, std::vector<Inst> (*at_return)(Patch&, void*), void* ctx,
275 bool drop_conservative_modes) {
276 auto& in = m_.insts();
277 std::size_t last_entry_point = 0;
278 for (std::size_t k = 0; k < in.size(); ++k)
279 if (opcode(in[k]) == op_entry_point) last_entry_point = k;
280 std::vector<Inst> out;
281 out.reserve(in.size() + globals_.size() + entry_code.size() + 16);
282 bool imported = import_.empty(), decorated = false, declared = false;
283 bool in_main = false, entry_done = false;
284 for (std::size_t k = 0; k < in.size(); ++k) {
285 Inst& i = in[k];
286 const std::uint32_t op = opcode(i);
287 if (!imported && op == op_memory_model) {
288 out.push_back(std::move(import_));
289 imported = true;
290 }
291 if (op == op_execution_mode && i.size() >= 3 && i[1] == entry_ && drop_conservative_modes &&
292 (i[2] == mode_depth_greater || i[2] == mode_depth_less || i[2] == mode_depth_unchanged ||
293 i[2] == mode_depth_replacing))
294 continue; // replaced by the DepthReplacing in modes_
295 if (op == op_entry_point && i.size() > 2 && i[2] == entry_) {
296 const std::size_t names = 3 + string_words(i, 3);
297 for (std::uint32_t id : interface_) {
298 bool listed = false;
299 for (std::size_t w = names; w < i.size(); ++w) listed |= i[w] == id;
300 if (!listed) i.push_back(id);
301 }
302 fix_length(i);
303 }
304 if (!decorated && (is_global_decl(op) || op == op_function)) {
305 for (Inst& d : decorations_) out.push_back(std::move(d));
306 decorated = true;
307 }
308 if (!declared && op == op_function) {
309 for (const Inst& g : globals_) out.push_back(g); // copies: type() may still read them
310 declared = true;
311 }
312 if (op == op_function && i.size() > 2 && i[2] == entry_) in_main = true;
313 if (in_main && !entry_done && op != op_function && op != op_label && op != op_variable &&
314 op != op_line && op != op_no_line && op != 55 /* OpFunctionParameter */) {
315 for (Inst& c : entry_code) out.push_back(std::move(c));
316 entry_done = true;
317 }
318 if (in_main && op == op_return && at_return) {
319 for (Inst& c : at_return(*this, ctx)) out.push_back(std::move(c));
320 }
321 if (op == op_function_end) in_main = false;
322 out.push_back(std::move(i));
323 if (k == last_entry_point) // execution modes follow the entry points
324 for (Inst& mo : modes_) out.push_back(std::move(mo));
325 }
326 in = std::move(out);
327 }
328
329private:
330 Module& m_;
331 std::uint32_t entry_;
332 std::vector<Inst> existing_;
333 std::vector<Inst> globals_, decorations_, modes_;
334 Inst import_;
335 std::vector<std::uint32_t> interface_;
336 std::vector<std::array<std::uint32_t, 3>> constants_; // type, value, id
337 std::uint32_t glsl_ = 0;
338};
339
340} // namespace spirv24
341
342// Edits a pixel shader so it writes the D24-quantised (and, unless it writes depth itself, D3D-biased) depth.
343// Returns the new words, or an empty vector with `why` set when the shader can't take the edit.
344inline std::vector<std::uint32_t> depth24_patch_fragment(const std::vector<std::uint32_t>& words,
345 const Depth24Bias& bias, std::string& why) {
346 using namespace spirv24;
347 Module m;
348 if (!m.parse(words, why)) return {};
349 std::uint32_t entry = 0;
350 for (const Inst& i : m.insts()) {
351 if (opcode(i) == op_entry_point && i.size() > 2 && i[1] == model_fragment) {
352 if (entry) {
353 why = "more than one fragment entry point";
354 return {};
355 }
356 entry = i[2];
357 }
358 if (opcode(i) == op_function) break;
359 }
360 if (!entry) {
361 why = "no fragment entry point";
362 return {};
363 }
364 for (const Inst& i : m.insts()) {
365 if (opcode(i) == op_execution_mode && i.size() >= 3 && i[1] == entry && i[2] == mode_early_fragment_tests) {
366 why = "the shader forces early fragment tests, which ignore a FragDepth write";
367 return {};
368 }
369 if (opcode(i) == op_function) break;
370 }
371
372 Patch p(m, entry);
373 const std::uint32_t tf = p.t_float();
374 p.prime_quantise();
375 std::uint32_t frag_depth = p.builtin_variable(builtin_frag_depth);
376 const bool shader_writes_depth = frag_depth != 0;
377 if (!shader_writes_depth)
378 frag_depth = p.variable(p.type(op_type_pointer, {storage_output, tf}), storage_output, builtin_frag_depth);
379 else
380 p.ensure_interface(frag_depth);
381 p.mode(mode_depth_replacing);
382
383 std::vector<Inst> entry_code;
384 if (!shader_writes_depth) {
385 std::uint32_t frag_coord = p.builtin_variable(builtin_frag_coord);
386 const std::uint32_t tv4 = p.type(op_type_vector, {tf, 4});
387 if (!frag_coord)
388 frag_coord = p.variable(p.type(op_type_pointer, {storage_input, tv4}), storage_input, builtin_frag_coord);
389 else
390 p.ensure_interface(frag_coord);
391 const std::uint32_t coord = p.emit(entry_code, op_load, tv4, {frag_coord});
392 std::uint32_t z = p.emit(entry_code, op_composite_extract, tf, {coord, 2});
393 if (bias.any()) {
394 // In the entry block: uniform control flow, so the derivatives are defined.
395 const std::uint32_t dx = p.ext(entry_code, tf, glsl_fabs, {p.emit(entry_code, op_dpdx, tf, {z})});
396 const std::uint32_t dy = p.ext(entry_code, tf, glsl_fabs, {p.emit(entry_code, op_dpdy, tf, {z})});
397 const std::uint32_t max_slope = p.ext(entry_code, tf, glsl_fmax, {dx, dy});
398 std::uint32_t amount = p.emit(entry_code, op_f_mul, tf, {p.f32(bias.slope), max_slope});
399 amount = p.emit(entry_code, op_f_add, tf, {amount, p.f32(depth24_bias_constant(bias.constant))});
400 if (bias.clamp > 0.0f) amount = p.ext(entry_code, tf, glsl_fmin, {amount, p.f32(bias.clamp)});
401 if (bias.clamp < 0.0f) amount = p.ext(entry_code, tf, glsl_fmax, {amount, p.f32(bias.clamp)});
402 z = p.emit(entry_code, op_f_add, tf, {z, amount});
403 }
404 const std::uint32_t q = p.quantise(entry_code, z);
405 entry_code.push_back(make(op_store, {frag_depth, q}));
406 p.apply(std::move(entry_code), nullptr, nullptr, true);
407 } else {
408 struct Ctx { std::uint32_t var, tf; } ctx{frag_depth, tf};
409 p.apply({}, [](Patch& patch, void* c) {
410 const auto& x = *static_cast<Ctx*>(c);
411 std::vector<Inst> code;
412 const std::uint32_t written = patch.emit(code, op_load, x.tf, {x.var});
413 code.push_back(make(op_store, {x.var, patch.quantise(code, written)}));
414 return code;
415 }, &ctx, true);
416 }
417 return m.words();
418}
419
420// A pixel stage for a pipeline without one: no colour output, only the biased, quantised depth.
421inline std::vector<std::uint32_t> depth24_depth_only_fragment(const Depth24Bias& bias) {
422 using namespace spirv24;
423 // OpCapability Shader; OpMemoryModel Logical GLSL450; OpEntryPoint Fragment %main "main";
424 // OpExecutionMode %main OriginUpperLeft; %void; %fn = void(); %main = function { label; return }
425 enum : std::uint32_t { id_main = 1, id_void = 2, id_fn = 3, id_label = 4, bound = 5 };
426 std::vector<std::uint32_t> w = {0x07230203u, 0x00010000u, 0, bound, 0};
427 auto put = [&](Inst i) { w.insert(w.end(), i.begin(), i.end()); };
428 put(make(op_capability, {1}));
429 put(make(op_memory_model, {0, 1}));
430 Inst ep = make(op_entry_point, {model_fragment, id_main});
431 append_string(ep, "main");
432 fix_length(ep);
433 put(ep);
434 put(make(op_execution_mode, {id_main, mode_origin_upper_left}));
435 put(make(op_type_void, {id_void}));
436 put(make(op_type_function, {id_fn, id_void}));
437 put(make(op_function, {id_void, id_main, 0, id_fn}));
438 put(make(op_label, {id_label}));
439 put(make(op_return, {}));
440 put(make(op_function_end, {}));
441 std::string why;
442 return depth24_patch_fragment(w, bias, why);
443}
444
445} // namespace leonida
diff --git a/runtime/src/gfx10_descriptors.h b/runtime/src/gfx10_descriptors.h
index 537f81623..b225cddef 100644
--- a/runtime/src/gfx10_descriptors.h
+++ b/runtime/src/gfx10_descriptors.h
@@ -630,6 +630,15 @@ inline VkSamplerCreateInfo vulkan_sampler(const Sampler& sampler, float max_lod_
630 } 630 }
631 if (sampler.unnormalized) { 631 if (sampler.unnormalized) {
632 info.unnormalizedCoordinates = VK_TRUE; 632 info.unnormalizedCoordinates = VK_TRUE;
633 // VUID-VkSamplerCreateInfo-unnormalizedCoordinates-01075: U and V clamp to the edge or the border (a
634 // repeating mode would wrap at a texel count the sampler cannot know); -01072: one filter for min and mag.
635 // The S# allows any address mode with FORCE_UNNORMALIZED, and WRAP is its default (word 0 = 0).
636 const auto clamp_or_border = [](VkSamplerAddressMode m) {
637 return m == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ? m : VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
638 };
639 info.addressModeU = clamp_or_border(info.addressModeU);
640 info.addressModeV = clamp_or_border(info.addressModeV);
641 info.minFilter = info.magFilter;
633 info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST; 642 info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST;
634 info.minLod = info.maxLod = 0.0f; 643 info.minLod = info.maxLod = 0.0f;
635 info.anisotropyEnable = VK_FALSE; 644 info.anisotropyEnable = VK_FALSE;
diff --git a/runtime/src/indirect_dispatch_count.comp b/runtime/src/indirect_dispatch_count.comp
new file mode 100644
index 000000000..9cbc371d9
--- /dev/null
+++ b/runtime/src/indirect_dispatch_count.comp
@@ -0,0 +1,34 @@
1// Clamp a GPU-written D3D12 ExecuteIndirect DISPATCH count without reading it on the CPU.
2// Each record is a VkDispatchIndirectCommand (three uints); disabled records are zero.
3#version 460
4#extension GL_EXT_buffer_reference : require
5layout(local_size_x = 64) in;
6layout(buffer_reference, std430, buffer_reference_align = 4) readonly buffer WordsIn {
7 uint data[];
8};
9layout(buffer_reference, std430, buffer_reference_align = 4) buffer WordsOut {
10 uint data[];
11};
12layout(push_constant) uniform Params {
13 WordsIn arguments;
14 WordsIn count;
15 WordsOut output_words;
16 uint stride_words;
17 uint first_record;
18 uint records;
19} p;
20void main() {
21 const uint local_record = gl_GlobalInvocationID.x;
22 if (local_record >= p.records) return;
23 const uint target = local_record * 3u;
24 if (p.first_record + local_record < p.count.data[0]) {
25 const uint source = local_record * p.stride_words;
26 p.output_words.data[target] = p.arguments.data[source];
27 p.output_words.data[target + 1u] = p.arguments.data[source + 1u];
28 p.output_words.data[target + 2u] = p.arguments.data[source + 2u];
29 } else {
30 p.output_words.data[target] = 0u;
31 p.output_words.data[target + 1u] = 0u;
32 p.output_words.data[target + 2u] = 0u;
33 }
34}
diff --git a/runtime/src/indirect_dispatch_count_spv.h b/runtime/src/indirect_dispatch_count_spv.h
new file mode 100644
index 000000000..9cf7bbae5
--- /dev/null
+++ b/runtime/src/indirect_dispatch_count_spv.h
@@ -0,0 +1,84 @@
1// Generated with glslangValidator -V --target-env vulkan1.2 -Os --spirv-val indirect_dispatch_count.comp
2#pragma once
3#include <cstdint>
4namespace leonida {
5inline constexpr std::uint32_t indirect_dispatch_count_spirv[] = {
6 0x07230203u, 0x00010500u, 0x0008000bu, 0x00000074u, 0x00000000u, 0x00020011u, 0x00000001u, 0x00020011u,
7 0x000014e3u, 0x0006000bu, 0x00000001u, 0x4c534c47u, 0x6474732eu, 0x3035342eu, 0x00000000u, 0x0003000eu,
8 0x000014e4u, 0x00000001u, 0x0007000fu, 0x00000005u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x0000000bu,
9 0x00000019u, 0x00060010u, 0x00000004u, 0x00000011u, 0x00000040u, 0x00000001u, 0x00000001u, 0x00030003u,
10 0x00000002u, 0x000001ccu, 0x00070004u, 0x455f4c47u, 0x625f5458u, 0x65666675u, 0x65725f72u, 0x65726566u,
11 0x0065636eu, 0x00040005u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x00080005u, 0x0000000bu, 0x475f6c67u,
12 0x61626f6cu, 0x766e496cu, 0x7461636fu, 0x496e6f69u, 0x00000044u, 0x00040005u, 0x00000013u, 0x61726150u,
13 0x0000736du, 0x00060006u, 0x00000013u, 0x00000000u, 0x75677261u, 0x746e656du, 0x00000073u, 0x00050006u,
14 0x00000013u, 0x00000001u, 0x6e756f63u, 0x00000074u, 0x00070006u, 0x00000013u, 0x00000002u, 0x7074756fu,
15 0x775f7475u, 0x7364726fu, 0x00000000u, 0x00070006u, 0x00000013u, 0x00000003u, 0x69727473u, 0x775f6564u,
16 0x7364726fu, 0x00000000u, 0x00070006u, 0x00000013u, 0x00000004u, 0x73726966u, 0x65725f74u, 0x64726f63u,
17 0x00000000u, 0x00050006u, 0x00000013u, 0x00000005u, 0x6f636572u, 0x00736472u, 0x00040005u, 0x00000015u,
18 0x64726f57u, 0x006e4973u, 0x00050006u, 0x00000015u, 0x00000000u, 0x61746164u, 0x00000000u, 0x00050005u,
19 0x00000017u, 0x64726f57u, 0x74754f73u, 0x00000000u, 0x00050006u, 0x00000017u, 0x00000000u, 0x61746164u,
20 0x00000000u, 0x00030005u, 0x00000019u, 0x00000070u, 0x00040047u, 0x0000000bu, 0x0000000bu, 0x0000001cu,
21 0x00030047u, 0x00000013u, 0x00000002u, 0x00050048u, 0x00000013u, 0x00000000u, 0x00000023u, 0x00000000u,
22 0x00050048u, 0x00000013u, 0x00000001u, 0x00000023u, 0x00000008u, 0x00050048u, 0x00000013u, 0x00000002u,
23 0x00000023u, 0x00000010u, 0x00050048u, 0x00000013u, 0x00000003u, 0x00000023u, 0x00000018u, 0x00050048u,
24 0x00000013u, 0x00000004u, 0x00000023u, 0x0000001cu, 0x00050048u, 0x00000013u, 0x00000005u, 0x00000023u,
25 0x00000020u, 0x00040047u, 0x00000014u, 0x00000006u, 0x00000004u, 0x00030047u, 0x00000015u, 0x00000002u,
26 0x00040048u, 0x00000015u, 0x00000000u, 0x00000018u, 0x00050048u, 0x00000015u, 0x00000000u, 0x00000023u,
27 0x00000000u, 0x00040047u, 0x00000016u, 0x00000006u, 0x00000004u, 0x00030047u, 0x00000017u, 0x00000002u,
28 0x00050048u, 0x00000017u, 0x00000000u, 0x00000023u, 0x00000000u, 0x00040047u, 0x00000071u, 0x0000000bu,
29 0x00000019u, 0x00020013u, 0x00000002u, 0x00030021u, 0x00000003u, 0x00000002u, 0x00040015u, 0x00000006u,
30 0x00000020u, 0x00000000u, 0x00040017u, 0x00000009u, 0x00000006u, 0x00000003u, 0x00040020u, 0x0000000au,
31 0x00000001u, 0x00000009u, 0x0004003bu, 0x0000000au, 0x0000000bu, 0x00000001u, 0x0004002bu, 0x00000006u,
32 0x0000000cu, 0x00000000u, 0x00040020u, 0x0000000du, 0x00000001u, 0x00000006u, 0x00030027u, 0x00000011u,
33 0x000014e5u, 0x00030027u, 0x00000012u, 0x000014e5u, 0x0008001eu, 0x00000013u, 0x00000011u, 0x00000011u,
34 0x00000012u, 0x00000006u, 0x00000006u, 0x00000006u, 0x0003001du, 0x00000014u, 0x00000006u, 0x0003001eu,
35 0x00000015u, 0x00000014u, 0x00040020u, 0x00000011u, 0x000014e5u, 0x00000015u, 0x0003001du, 0x00000016u,
36 0x00000006u, 0x0003001eu, 0x00000017u, 0x00000016u, 0x00040020u, 0x00000012u, 0x000014e5u, 0x00000017u,
37 0x00040020u, 0x00000018u, 0x00000009u, 0x00000013u, 0x0004003bu, 0x00000018u, 0x00000019u, 0x00000009u,
38 0x00040015u, 0x0000001au, 0x00000020u, 0x00000001u, 0x0004002bu, 0x0000001au, 0x0000001bu, 0x00000005u,
39 0x00040020u, 0x0000001cu, 0x00000009u, 0x00000006u, 0x00020014u, 0x0000001fu, 0x0004002bu, 0x00000006u,
40 0x00000026u, 0x00000003u, 0x0004002bu, 0x0000001au, 0x00000028u, 0x00000004u, 0x0004002bu, 0x0000001au,
41 0x0000002du, 0x00000001u, 0x00040020u, 0x0000002eu, 0x00000009u, 0x00000011u, 0x0004002bu, 0x0000001au,
42 0x00000031u, 0x00000000u, 0x00040020u, 0x00000032u, 0x000014e5u, 0x00000006u, 0x0004002bu, 0x0000001au,
43 0x0000003au, 0x00000003u, 0x0004002bu, 0x0000001au, 0x0000003eu, 0x00000002u, 0x00040020u, 0x0000003fu,
44 0x00000009u, 0x00000012u, 0x0004002bu, 0x00000006u, 0x0000004cu, 0x00000001u, 0x0004002bu, 0x00000006u,
45 0x00000058u, 0x00000002u, 0x0004002bu, 0x00000006u, 0x00000070u, 0x00000040u, 0x0006002cu, 0x00000009u,
46 0x00000071u, 0x00000070u, 0x0000004cu, 0x0000004cu, 0x00050036u, 0x00000002u, 0x00000004u, 0x00000000u,
47 0x00000003u, 0x000200f8u, 0x00000005u, 0x000300f7u, 0x00000072u, 0x00000000u, 0x000300fbu, 0x0000000cu,
48 0x00000073u, 0x000200f8u, 0x00000073u, 0x00050041u, 0x0000000du, 0x0000000eu, 0x0000000bu, 0x0000000cu,
49 0x0004003du, 0x00000006u, 0x0000000fu, 0x0000000eu, 0x00050041u, 0x0000001cu, 0x0000001du, 0x00000019u,
50 0x0000001bu, 0x0004003du, 0x00000006u, 0x0000001eu, 0x0000001du, 0x000500aeu, 0x0000001fu, 0x00000020u,
51 0x0000000fu, 0x0000001eu, 0x000300f7u, 0x00000022u, 0x00000000u, 0x000400fau, 0x00000020u, 0x00000021u,
52 0x00000022u, 0x000200f8u, 0x00000021u, 0x000200f9u, 0x00000072u, 0x000200f8u, 0x00000022u, 0x00050084u,
53 0x00000006u, 0x00000027u, 0x0000000fu, 0x00000026u, 0x00050041u, 0x0000001cu, 0x00000029u, 0x00000019u,
54 0x00000028u, 0x0004003du, 0x00000006u, 0x0000002au, 0x00000029u, 0x00050080u, 0x00000006u, 0x0000002cu,
55 0x0000002au, 0x0000000fu, 0x00050041u, 0x0000002eu, 0x0000002fu, 0x00000019u, 0x0000002du, 0x0004003du,
56 0x00000011u, 0x00000030u, 0x0000002fu, 0x00060041u, 0x00000032u, 0x00000033u, 0x00000030u, 0x00000031u,
57 0x00000031u, 0x0006003du, 0x00000006u, 0x00000034u, 0x00000033u, 0x00000002u, 0x00000004u, 0x000500b0u,
58 0x0000001fu, 0x00000035u, 0x0000002cu, 0x00000034u, 0x000300f7u, 0x00000037u, 0x00000000u, 0x000400fau,
59 0x00000035u, 0x00000036u, 0x00000061u, 0x000200f8u, 0x00000036u, 0x00050041u, 0x0000001cu, 0x0000003bu,
60 0x00000019u, 0x0000003au, 0x0004003du, 0x00000006u, 0x0000003cu, 0x0000003bu, 0x00050084u, 0x00000006u,
61 0x0000003du, 0x0000000fu, 0x0000003cu, 0x00050041u, 0x0000003fu, 0x00000040u, 0x00000019u, 0x0000003eu,
62 0x0004003du, 0x00000012u, 0x00000041u, 0x00000040u, 0x00050041u, 0x0000002eu, 0x00000043u, 0x00000019u,
63 0x00000031u, 0x0004003du, 0x00000011u, 0x00000044u, 0x00000043u, 0x00060041u, 0x00000032u, 0x00000046u,
64 0x00000044u, 0x00000031u, 0x0000003du, 0x0006003du, 0x00000006u, 0x00000047u, 0x00000046u, 0x00000002u,
65 0x00000004u, 0x00060041u, 0x00000032u, 0x00000048u, 0x00000041u, 0x00000031u, 0x00000027u, 0x0005003eu,
66 0x00000048u, 0x00000047u, 0x00000002u, 0x00000004u, 0x00050080u, 0x00000006u, 0x0000004du, 0x00000027u,
67 0x0000004cu, 0x00050080u, 0x00000006u, 0x00000051u, 0x0000003du, 0x0000004cu, 0x00060041u, 0x00000032u,
68 0x00000052u, 0x00000044u, 0x00000031u, 0x00000051u, 0x0006003du, 0x00000006u, 0x00000053u, 0x00000052u,
69 0x00000002u, 0x00000004u, 0x00060041u, 0x00000032u, 0x00000054u, 0x00000041u, 0x00000031u, 0x0000004du,
70 0x0005003eu, 0x00000054u, 0x00000053u, 0x00000002u, 0x00000004u, 0x00050080u, 0x00000006u, 0x00000059u,
71 0x00000027u, 0x00000058u, 0x00050080u, 0x00000006u, 0x0000005du, 0x0000003du, 0x00000058u, 0x00060041u,
72 0x00000032u, 0x0000005eu, 0x00000044u, 0x00000031u, 0x0000005du, 0x0006003du, 0x00000006u, 0x0000005fu,
73 0x0000005eu, 0x00000002u, 0x00000004u, 0x00060041u, 0x00000032u, 0x00000060u, 0x00000041u, 0x00000031u,
74 0x00000059u, 0x0005003eu, 0x00000060u, 0x0000005fu, 0x00000002u, 0x00000004u, 0x000200f9u, 0x00000037u,
75 0x000200f8u, 0x00000061u, 0x00050041u, 0x0000003fu, 0x00000062u, 0x00000019u, 0x0000003eu, 0x0004003du,
76 0x00000012u, 0x00000063u, 0x00000062u, 0x00060041u, 0x00000032u, 0x00000065u, 0x00000063u, 0x00000031u,
77 0x00000027u, 0x0005003eu, 0x00000065u, 0x0000000cu, 0x00000002u, 0x00000004u, 0x00050080u, 0x00000006u,
78 0x00000069u, 0x00000027u, 0x0000004cu, 0x00060041u, 0x00000032u, 0x0000006au, 0x00000063u, 0x00000031u,
79 0x00000069u, 0x0005003eu, 0x0000006au, 0x0000000cu, 0x00000002u, 0x00000004u, 0x00050080u, 0x00000006u,
80 0x0000006eu, 0x00000027u, 0x00000058u, 0x00060041u, 0x00000032u, 0x0000006fu, 0x00000063u, 0x00000031u,
81 0x0000006eu, 0x0005003eu, 0x0000006fu, 0x0000000cu, 0x00000002u, 0x00000004u, 0x000200f9u, 0x00000037u,
82 0x000200f8u, 0x00000037u, 0x000200f9u, 0x00000072u, 0x000200f8u, 0x00000072u, 0x000100fdu, 0x00010038u,
83};
84} // namespace leonida
diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp
index f4ecc0de2..f3323e4c0 100644
--- a/runtime/src/pe_loader.cpp
+++ b/runtime/src/pe_loader.cpp
@@ -529,15 +529,7 @@ void cleanup_tls_clones() { cleanup_tls_clones_internal(); }
529 529
530namespace { 530namespace {
531bool lookup_in_loader(void* ctx, uint64_t address, std::string& module, uint32_t& rva) { 531bool lookup_in_loader(void* ctx, uint64_t address, std::string& module, uint32_t& rva) {
532 for (const Module* m : static_cast<Loader*>(ctx)->modules()) { 532 return static_cast<Loader*>(ctx)->find_address(address, module, rva);
533 const auto base = reinterpret_cast<uint64_t>(m->base);
534 if (m->base && address >= base && address - base < m->size) {
535 module = m->name;
536 rva = static_cast<uint32_t>(address - base);
537 return true;
538 }
539 }
540 return false;
541} 533}
542 534
543void* bundled_find_loaded(void* ctx, const std::string& dll_lower) { 535void* bundled_find_loaded(void* ctx, const std::string& dll_lower) {
@@ -722,6 +714,18 @@ void* Loader::resolve_module_export(void* module_handle, const std::string& sym,
722 return nullptr; 714 return nullptr;
723} 715}
724 716
717bool Loader::find_address(uint64_t address, std::string& module, uint32_t& rva) const {
718 std::shared_lock lock(ranges_mutex_);
719 for (const MappedRange& r : ranges_) {
720 if (address >= r.base && address - r.base < r.size) {
721 module = r.name;
722 rva = static_cast<uint32_t>(address - r.base);
723 return true;
724 }
725 }
726 return false;
727}
728
725bool Loader::owns_module_handle(void* module_handle) const { 729bool Loader::owns_module_handle(void* module_handle) const {
726 if (!module_handle) return false; 730 if (!module_handle) return false;
727 std::lock_guard lock(mutex_); 731 std::lock_guard lock(mutex_);
@@ -850,6 +854,12 @@ Module& Loader::map_image(const std::filesystem::path& path) {
850 m->base = static_cast<uint8_t*>(VirtualAlloc(nullptr, oh.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); 854 m->base = static_cast<uint8_t*>(VirtualAlloc(nullptr, oh.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE));
851 if (!m->base) throw std::runtime_error(m->name + ": VirtualAlloc failed"); 855 if (!m->base) throw std::runtime_error(m->name + ": VirtualAlloc failed");
852 } 856 }
857 {
858 // From here an address inside the image names it. The memory stays until ~Loader, which unregisters the
859 // lookup first.
860 std::unique_lock lock(ranges_mutex_);
861 ranges_.push_back({reinterpret_cast<uint64_t>(m->base), m->size, m->name});
862 }
853 863
854 std::memcpy(m->base, file.data(), oh.SizeOfHeaders); 864 std::memcpy(m->base, file.data(), oh.SizeOfHeaders);
855 auto* sec = IMAGE_FIRST_SECTION(nt); 865 auto* sec = IMAGE_FIRST_SECTION(nt);
diff --git a/runtime/src/pe_loader.h b/runtime/src/pe_loader.h
index 8fb24349f..c87f157a4 100644
--- a/runtime/src/pe_loader.h
+++ b/runtime/src/pe_loader.h
@@ -9,6 +9,7 @@
9#include <filesystem> 9#include <filesystem>
10#include <map> 10#include <map>
11#include <mutex> 11#include <mutex>
12#include <shared_mutex>
12#include <string> 13#include <string>
13#include <vector> 14#include <vector>
14 15
@@ -79,6 +80,11 @@ public:
79 80
80 const std::vector<Module*>& modules() const { return order_; } 81 const std::vector<Module*>& modules() const { return order_; }
81 82
83 // The mapped module `address` lies in, with its RVA there. Safe from any thread at any time, also while another
84 // thread is in load(): it is what the shim registry asks for a caller's module (rt::shims::mapped_image_base on
85 // every C++ throw from a mapped image, and the trace and stop lines), and it reads its own table, not modules().
86 bool find_address(uint64_t address, std::string& module, uint32_t& rva) const;
87
82 // The order initialise() runs modules in: each module after every module it imports (a cycle is broken at the 88 // The order initialise() runs modules in: each module after every module it imports (a cycle is broken at the
83 // module that closed it). modules() is mapping order, which puts an importer before its imports. 89 // module that closed it). modules() is mapping order, which puts an importer before its imports.
84 const std::vector<Module*>& initialisation_order() const { return init_order_; } 90 const std::vector<Module*>& initialisation_order() const { return init_order_; }
@@ -129,6 +135,17 @@ private:
129 std::map<std::string, Module*> by_name_; // lower-case file name 135 std::map<std::string, Module*> by_name_; // lower-case file name
130 std::vector<Module*> order_; // mapping order; owns the modules 136 std::vector<Module*> order_; // mapping order; owns the modules
131 std::vector<Module*> init_order_; // dependencies first, see initialisation_order() 137 std::vector<Module*> init_order_; // dependencies first, see initialisation_order()
138
139 // What find_address reads: one entry per mapped image, added once its memory exists. Under ranges_mutex_, a leaf
140 // lock: mutex_ is held while image code runs and the registry holds its own lock around the lookup, so the
141 // lookup must not wait for either.
142 struct MappedRange {
143 uint64_t base = 0;
144 uint32_t size = 0;
145 std::string name;
146 };
147 mutable std::shared_mutex ranges_mutex_; // shared in find_address: lookups on different threads do not queue
148 std::vector<MappedRange> ranges_;
132}; 149};
133 150
134// Frees the TLS helper clones load() created and deletes their files (Module::tls_index background). load() 151// Frees the TLS helper clones load() created and deletes their files (Module::tls_index background). load()
diff --git a/runtime/src/queue_families.h b/runtime/src/queue_families.h
index 32ef1eb1d..e7dd50fe6 100644
--- a/runtime/src/queue_families.h
+++ b/runtime/src/queue_families.h
@@ -45,4 +45,24 @@ inline QueueFamilies pick_queue_families(std::span<const VkQueueFamilyProperties
45 return out; 45 return out;
46} 46}
47 47
48// A D3D12 COPY/COMPUTE queue may call UpdateTileMappings at any time. Vulkan binds sparse
49// pages on the VkQueue itself, so a family without SPARSE_BINDING cannot back that D3D12
50// queue when reserved buffers are offered. Use the graphics family (already checked for
51// sparse support by the device) rather than submitting an invalid vkQueueBindSparse.
52// Kept separate from the preference-only picker so devices without sparse resources keep
53// their dedicated async families unchanged.
54inline QueueFamilies sparse_capable_queue_families(std::span<const VkQueueFamilyProperties> families,
55 QueueFamilies chosen, bool sparse_buffers) {
56 if (!sparse_buffers || chosen.direct >= families.size() ||
57 !(families[chosen.direct].queueFlags & VK_QUEUE_SPARSE_BINDING_BIT))
58 return chosen;
59 if (chosen.compute >= families.size() ||
60 !(families[chosen.compute].queueFlags & VK_QUEUE_SPARSE_BINDING_BIT))
61 chosen.compute = chosen.direct;
62 if (chosen.copy >= families.size() ||
63 !(families[chosen.copy].queueFlags & VK_QUEUE_SPARSE_BINDING_BIT))
64 chosen.copy = chosen.direct;
65 return chosen;
66}
67
48} // namespace leonida 68} // namespace leonida
diff --git a/runtime/src/shader_library.h b/runtime/src/shader_library.h
index 528fd013d..69572ccd0 100644
--- a/runtime/src/shader_library.h
+++ b/runtime/src/shader_library.h
@@ -642,6 +642,9 @@ struct ShaderEntry {
642 std::vector<std::uint32_t> outputs; // pixel/vertex shaders: output locations written 642 std::vector<std::uint32_t> outputs; // pixel/vertex shaders: output locations written
643 // --f16-interp-fallback: param/attr index -> {low_half_location, high_half_location} (SHADER-378). 643 // --f16-interp-fallback: param/attr index -> {low_half_location, high_half_location} (SHADER-378).
644 std::map<std::uint32_t, std::array<std::uint32_t, 2>> f16_halves; 644 std::map<std::uint32_t, std::array<std::uint32_t, 2>> f16_halves;
645 // The S#s the shader builds from immediates (the index's literal_samplers): no heap slot names them, so a
646 // pipeline that uses the shader registers them in the bindless set itself (docs/design.md, Literal samplers).
647 std::vector<std::array<std::uint32_t, 4>> literal_samplers;
645}; 648};
646 649
647class ShaderLibrary { 650class ShaderLibrary {
@@ -813,6 +816,14 @@ private:
813 e.f16_halves[std::uint32_t(param)] = {u32(&val.array[0]), u32(&val.array[1])}; 816 e.f16_halves[std::uint32_t(param)] = {u32(&val.array[0]), u32(&val.array[1])};
814 } 817 }
815 } 818 }
819 if (const Json* l = meta.find("literal_samplers"); l && l->kind == Json::Kind::array) {
820 for (const Json& item : l->array) {
821 if (item.kind != Json::Kind::array || item.array.size() != 4) continue;
822 std::array<std::uint32_t, 4> words{};
823 for (std::size_t i = 0; i < 4; ++i) words[i] = u32(&item.array[i]);
824 e.literal_samplers.push_back(words);
825 }
826 }
816 if (by_fspx) fspx_entries_[{e.stage, e.fspx_code_sha256}].push_back(e); 827 if (by_fspx) fspx_entries_[{e.stage, e.fspx_code_sha256}].push_back(e);
817 if (by_fssm) entries_[{e.stage, e.fssm_sha256}].push_back(std::move(e)); 828 if (by_fssm) entries_[{e.stage, e.fssm_sha256}].push_back(std::move(e));
818 if (by_fspx && prefix == "fspx/") ++fspx_count_; 829 if (by_fspx && prefix == "fspx/") ++fspx_count_;
diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h
index 24a2155c5..644fbd9c3 100644
--- a/runtime/src/vulkan_backend.h
+++ b/runtime/src/vulkan_backend.h
@@ -17,6 +17,7 @@
17#include "statistics_sum_spirv.h" 17#include "statistics_sum_spirv.h"
18#include "vulkan13_features.h" 18#include "vulkan13_features.h"
19#include "vulkan_depth24.h" 19#include "vulkan_depth24.h"
20#include "vulkan_indirect_dispatch_count.h"
20#include "vulkan_scratch.h" 21#include "vulkan_scratch.h"
21#include "vulkan_replay.h" 22#include "vulkan_replay.h"
22#include "queue_families.h" 23#include "queue_families.h"
@@ -85,6 +86,7 @@ struct VulkanDeviceFunctions {
85 X(vkCmdSetPrimitiveTopology) X(vkCmdSetPrimitiveRestartEnable) X(vkCmdSetStencilReference) \ 86 X(vkCmdSetPrimitiveTopology) X(vkCmdSetPrimitiveRestartEnable) X(vkCmdSetStencilReference) \
86 X(vkCmdSetBlendConstants) X(vkCmdDraw) \ 87 X(vkCmdSetBlendConstants) X(vkCmdDraw) \
87 X(vkCmdDrawIndexed) X(vkCreateGraphicsPipelines) X(vkQueueBindSparse) \ 88 X(vkCmdDrawIndexed) X(vkCreateGraphicsPipelines) X(vkQueueBindSparse) \
89 X(vkCreatePipelineCache) X(vkDestroyPipelineCache) \
88 X(vkCreateEvent) X(vkDestroyEvent) X(vkResetEvent) X(vkCmdSetEvent) X(vkCmdWaitEvents) \ 90 X(vkCreateEvent) X(vkDestroyEvent) X(vkResetEvent) X(vkCmdSetEvent) X(vkCmdWaitEvents) \
89 X(vkCreateRenderPass2) X(vkDestroyRenderPass) X(vkCreateFramebuffer) X(vkDestroyFramebuffer) \ 91 X(vkCreateRenderPass2) X(vkDestroyRenderPass) X(vkCreateFramebuffer) X(vkDestroyFramebuffer) \
90 X(vkCmdBeginRenderPass) X(vkCmdEndRenderPass) 92 X(vkCmdBeginRenderPass) X(vkCmdEndRenderPass)
@@ -872,7 +874,7 @@ public:
872 // buffer as out of bounds, which is no reason to drop the submission. 874 // buffer as out of bounds, which is no reason to drop the submission.
873 replay_.buffer_at = [this](std::uint64_t va, std::uint64_t& size, VkBuffer& buffer, VkDeviceSize& offset) { 875 replay_.buffer_at = [this](std::uint64_t va, std::uint64_t& size, VkBuffer& buffer, VkDeviceSize& offset) {
874 BufferVaIndex<ResourceId>::Hit hit{}; 876 BufferVaIndex<ResourceId>::Hit hit{};
875 if (!buffer_vas_.find(va, hit)) return false; 877 if (!buffer_vas_.find(va, hit, size)) return false; // prefers an aliasing buffer that holds all of it
876 const ResourceBinding* b = resolve(hit.id); 878 const ResourceBinding* b = resolve(hit.id);
877 if (!b) return false; 879 if (!b) return false;
878 buffer = b->buffer; 880 buffer = b->buffer;
@@ -974,6 +976,13 @@ public:
974 std::unique_lock lock(resource_mutex_); 976 std::unique_lock lock(resource_mutex_);
975 predicated_copier_ = std::make_unique<PredicatedBufferCopier>(get, device_, limits); 977 predicated_copier_ = std::make_unique<PredicatedBufferCopier>(get, device_, limits);
976 } 978 }
979 // Counts for DISPATCH-only ExecuteIndirect are read by a helper compute shader from GPU memory.
980 // Requires Vulkan bufferDeviceAddress, already enabled for the D3D12 address arena.
981 void configure_counted_dispatch(PFN_vkGetDeviceProcAddr get, const VkPhysicalDeviceMemoryProperties& memory,
982 const VkPhysicalDeviceLimits& limits) {
983 std::unique_lock lock(resource_mutex_);
984 counted_dispatch_ = std::make_unique<IndirectDispatchCounter>(get, device_, memory, limits);
985 }
977 VkDevice device() const { return device_; } 986 VkDevice device() const { return device_; }
978 987
979 // Debug markers become labels from here on; call before any queue or list uses the context. Incomplete sets 988 // Debug markers become labels from here on; call before any queue or list uses the context. Incomplete sets
@@ -1011,6 +1020,14 @@ public:
1011 storage_pending_.insert(id); 1020 storage_pending_.insert(id);
1012 } 1021 }
1013 1022
1023 // A device-local buffer D3D12 says starts zeroed (D3D-71): the host cannot write it, so the next submission on
1024 // any queue fills it with zeros ahead of its lists. That submission publishes the same initialisation semaphore as
1025 // the storage images above, so a list on another queue that uses the buffer first waits for the fill.
1026 void zero_on_next_submit(ResourceId id, VkBuffer buffer) {
1027 std::lock_guard lock(storage_mutex_);
1028 zero_pending_.push_back({id, buffer});
1029 }
1030
1014 void add_sparse_buffer(ResourceId id, const ResourceBinding& binding, std::shared_ptr<SparseBuffer> buffer) { 1031 void add_sparse_buffer(ResourceId id, const ResourceBinding& binding, std::shared_ptr<SparseBuffer> buffer) {
1015 std::unique_lock lock(resource_mutex_); 1032 std::unique_lock lock(resource_mutex_);
1016 set_resource_locked(id, binding); 1033 set_resource_locked(id, binding);
@@ -1028,6 +1045,10 @@ public:
1028 resources_.erase(it); 1045 resources_.erase(it);
1029 sparse_buffers_.erase(id); 1046 sparse_buffers_.erase(id);
1030 } 1047 }
1048 {
1049 std::lock_guard lock(storage_mutex_); // a buffer destroyed before any submission is not filled
1050 std::erase_if(zero_pending_, [id](const PendingZero& zero) { return zero.id == id; });
1051 }
1031 if (img) { 1052 if (img) {
1032 std::lock_guard vlock(views_mutex_); 1053 std::lock_guard vlock(views_mutex_);
1033 for (auto f = resolve_framebuffers_.begin(); f != resolve_framebuffers_.end();) { 1054 for (auto f = resolve_framebuffers_.begin(); f != resolve_framebuffers_.end();) {
@@ -1437,8 +1458,13 @@ private:
1437 std::unordered_map<std::uintptr_t, GraphicsPipeline> graphics_pipelines_; 1458 std::unordered_map<std::uintptr_t, GraphicsPipeline> graphics_pipelines_;
1438 std::unordered_map<std::uint64_t, VkAccelerationStructureKHR> acceleration_structures_; 1459 std::unordered_map<std::uint64_t, VkAccelerationStructureKHR> acceleration_structures_;
1439 LayoutTracker tracker_; 1460 LayoutTracker tracker_;
1440 std::mutex storage_mutex_; // a leaf lock: guards storage_pending_ only 1461 std::mutex storage_mutex_; // a leaf lock: guards storage_pending_ and zero_pending_ only
1441 std::unordered_set<ResourceId> storage_pending_; 1462 std::unordered_set<ResourceId> storage_pending_;
1463 struct PendingZero {
1464 ResourceId id;
1465 VkBuffer buffer;
1466 };
1467 std::vector<PendingZero> zero_pending_; // zero_on_next_submit
1442 // The last submission that initialized storage images (its queue's progress semaphore and ticket) and a counter 1468 // The last submission that initialized storage images (its queue's progress semaphore and ticket) and a counter
1443 // that says which one: every other queue's next submission waits for it, so no queue uses such an image before 1469 // that says which one: every other queue's next submission waits for it, so no queue uses such an image before
1444 // the zero-fill that put it in GENERAL has run. 1470 // the zero-fill that put it in GENERAL has run.
@@ -1461,6 +1487,7 @@ private:
1461 ReplayFunctions replay_; 1487 ReplayFunctions replay_;
1462 std::unique_ptr<PredicateReducer> predicate_reducer_; 1488 std::unique_ptr<PredicateReducer> predicate_reducer_;
1463 std::unique_ptr<PredicatedBufferCopier> predicated_copier_; 1489 std::unique_ptr<PredicatedBufferCopier> predicated_copier_;
1490 std::unique_ptr<IndirectDispatchCounter> counted_dispatch_;
1464 std::uint32_t predicate_family_ = UINT32_MAX; 1491 std::uint32_t predicate_family_ = UINT32_MAX;
1465 std::uint32_t transfer_only_family_ = UINT32_MAX; 1492 std::uint32_t transfer_only_family_ = UINT32_MAX;
1466 DebugLabelFunctions labels_; 1493 DebugLabelFunctions labels_;
@@ -1584,6 +1611,12 @@ public:
1584 if (context_.depth24_) context_.depth24_->forget(progress_); // its scratch is idle now 1611 if (context_.depth24_) context_.depth24_->forget(progress_); // its scratch is idle now
1585 if (context_.scratch_) context_.scratch_->forget(progress_); 1612 if (context_.scratch_) context_.scratch_->forget(progress_);
1586 } 1613 }
1614 if (progress_) {
1615 // This queue is idle, so whatever initialisation it published (storage images, zero-filled buffers) has
1616 // finished: the next submission on another queue must not wait on a semaphore that is about to go.
1617 std::lock_guard lock(context_.storage_mutex_);
1618 if (context_.storage_init_semaphore_ == progress_) context_.storage_init_semaphore_ = VK_NULL_HANDLE;
1619 }
1587 if (pool_) vk.vkDestroyCommandPool(context_.device(), pool_, nullptr); 1620 if (pool_) vk.vkDestroyCommandPool(context_.device(), pool_, nullptr);
1588 if (progress_) vk.vkDestroySemaphore(context_.device(), progress_, nullptr); 1621 if (progress_) vk.vkDestroySemaphore(context_.device(), progress_, nullptr);
1589 for (auto& slot : buffers_) free_events_.insert(free_events_.end(), slot.events.begin(), slot.events.end()); 1622 for (auto& slot : buffers_) free_events_.insert(free_events_.end(), slot.events.begin(), slot.events.end());
@@ -1785,6 +1818,7 @@ private:
1785 if (const auto* p = std::get_if<Predication>(&command); p && p->buffer) ++captures; 1818 if (const auto* p = std::get_if<Predication>(&command); p && p->buffer) ++captures;
1786 std::unique_ptr<PredicateReducer::Batch> batch; 1819 std::unique_ptr<PredicateReducer::Batch> batch;
1787 std::unique_ptr<PredicatedBufferCopier::Batch> copy_batch; 1820 std::unique_ptr<PredicatedBufferCopier::Batch> copy_batch;
1821 std::unique_ptr<IndirectDispatchCounter::Batch> counted_batch;
1788 if (captures) { 1822 if (captures) {
1789 if (kind_ == QueueKind::copy || !context_.predicate_reducer_ || family_ != context_.predicate_family_) 1823 if (kind_ == QueueKind::copy || !context_.predicate_reducer_ || family_ != context_.predicate_family_)
1790 return ReplayResult::unsupported; 1824 return ReplayResult::unsupported;
@@ -1822,6 +1856,19 @@ private:
1822 return context_.scratch_->get(bytes, buffer, offset); 1856 return context_.scratch_->get(bytes, buffer, offset);
1823 }; 1857 };
1824 } 1858 }
1859 if (kind_ != QueueKind::copy && context_.counted_dispatch_) {
1860 replay.prepare_counted_dispatch = [this, &tracker_lock, &counted_batch](
1861 VkBuffer args, VkDeviceSize args_offset, VkBuffer count, VkDeviceSize count_offset,
1862 std::uint32_t stride, std::uint32_t maximum, CountedDispatch& out) {
1863 // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation.
1864 if (!tracker_lock.owns_lock()) tracker_lock.lock();
1865 if (!counted_batch) counted_batch = context_.counted_dispatch_->batch();
1866 return counted_batch->prepare(args, args_offset, count, count_offset, stride, maximum, out);
1867 };
1868 replay.emit_counted_dispatch = [this](VkCommandBuffer cb, const CountedDispatch& job) {
1869 context_.counted_dispatch_->emit(cb, job);
1870 };
1871 }
1825 if (context_.depth24_ && !transfer_only) { 1872 if (context_.depth24_ && !transfer_only) {
1826 replay.depth24_prepare = [this, &tracker_lock, &depth24_guard](Depth24Job& job, 1873 replay.depth24_prepare = [this, &tracker_lock, &depth24_guard](Depth24Job& job,
1827 std::vector<Depth24Job>& parts) { 1874 std::vector<Depth24Job>& parts) {
@@ -1966,6 +2013,7 @@ private:
1966 runs_shaders |= std::holds_alternative<Dispatch>(command) || std::holds_alternative<Draw>(command) || 2013 runs_shaders |= std::holds_alternative<Dispatch>(command) || std::holds_alternative<Draw>(command) ||
1967 std::holds_alternative<ExecuteIndirect>(command); 2014 std::holds_alternative<ExecuteIndirect>(command);
1968 std::vector<ResourceId> storage_images; 2015 std::vector<ResourceId> storage_images;
2016 std::vector<VulkanContext::PendingZero> zero_buffers;
1969 { 2017 {
1970 std::lock_guard lock(context_.storage_mutex_); 2018 std::lock_guard lock(context_.storage_mutex_);
1971 if (context_.storage_init_semaphore_ && context_.storage_init_semaphore_ != progress_ && 2019 if (context_.storage_init_semaphore_ && context_.storage_init_semaphore_ != progress_ &&
@@ -1977,6 +2025,16 @@ private:
1977 if (kind_ != QueueKind::copy && runs_shaders) 2025 if (kind_ != QueueKind::copy && runs_shaders)
1978 storage_images.assign(context_.storage_pending_.begin(), context_.storage_pending_.end()); 2026 storage_images.assign(context_.storage_pending_.begin(), context_.storage_pending_.end());
1979 if (!storage_images.empty()) context_.storage_pending_.clear(); 2027 if (!storage_images.empty()) context_.storage_pending_.clear();
2028 zero_buffers.swap(context_.zero_pending_); // any queue can fill a buffer
2029 }
2030 for (const auto& zero : zero_buffers)
2031 context_.vk.vkCmdFillBuffer(command_buffer, zero.buffer, 0, VK_WHOLE_SIZE, 0);
2032 if (!zero_buffers.empty()) {
2033 VkMemoryBarrier filled{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
2034 filled.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
2035 filled.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
2036 context_.vk.vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT,
2037 VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 1, &filled, 0, nullptr, 0, nullptr);
1980 } 2038 }
1981 for (const ResourceId id : storage_images) { 2039 for (const ResourceId id : storage_images) {
1982 const ResourceBinding* image = context_.resolve(id); 2040 const ResourceBinding* image = context_.resolve(id);
@@ -2032,11 +2090,13 @@ private:
2032 wait_values_.push_back(submitted_); 2090 wait_values_.push_back(submitted_);
2033 } 2091 }
2034 const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0); 2092 const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0);
2035 if (!submitted && !storage_images.empty()) { // not initialized after all: try again with the next submission 2093 if (!submitted && (!storage_images.empty() || !zero_buffers.empty())) {
2094 // not initialized after all: try again with the next submission
2036 std::lock_guard lock(context_.storage_mutex_); 2095 std::lock_guard lock(context_.storage_mutex_);
2037 context_.storage_pending_.insert(storage_images.begin(), storage_images.end()); 2096 context_.storage_pending_.insert(storage_images.begin(), storage_images.end());
2097 context_.zero_pending_.insert(context_.zero_pending_.end(), zero_buffers.begin(), zero_buffers.end());
2038 } 2098 }
2039 if (submitted && !storage_images.empty()) { 2099 if (submitted && (!storage_images.empty() || !zero_buffers.empty())) {
2040 std::lock_guard lock(context_.storage_mutex_); 2100 std::lock_guard lock(context_.storage_mutex_);
2041 context_.storage_init_semaphore_ = progress_; 2101 context_.storage_init_semaphore_ = progress_;
2042 context_.storage_init_value_ = submitted_; 2102 context_.storage_init_value_ = submitted_;
@@ -2051,6 +2111,7 @@ private:
2051 context_.tracker_ = std::move(next_tracker); 2111 context_.tracker_ = std::move(next_tracker);
2052 slot->predicate = std::move(batch); 2112 slot->predicate = std::move(batch);
2053 slot->predicated_copy = std::move(copy_batch); 2113 slot->predicated_copy = std::move(copy_batch);
2114 slot->counted_dispatch = std::move(counted_batch);
2054 queries.commit(); 2115 queries.commit();
2055 slot->segments = std::move(queries.retained); 2116 slot->segments = std::move(queries.retained);
2056 } else { 2117 } else {
@@ -2205,6 +2266,7 @@ private:
2205 std::vector<std::shared_ptr<const OcclusionSegmentPool>> segments; 2266 std::vector<std::shared_ptr<const OcclusionSegmentPool>> segments;
2206 std::vector<VkEvent> events; // order_timestamp_copy's, reset and reused once the slot completes 2267 std::vector<VkEvent> events; // order_timestamp_copy's, reset and reused once the slot completes
2207 std::unique_ptr<PredicatedBufferCopier::Batch> predicated_copy; 2268 std::unique_ptr<PredicatedBufferCopier::Batch> predicated_copy;
2269 std::unique_ptr<IndirectDispatchCounter::Batch> counted_dispatch;
2208 std::unique_ptr<PredicateReducer::Batch> predicate; // retained until this slot completes 2270 std::unique_ptr<PredicateReducer::Batch> predicate; // retained until this slot completes
2209 }; 2271 };
2210 2272
@@ -2323,6 +2385,7 @@ private:
2323 if (context_.vk.vkResetCommandBuffer(reuse->buffer, 0) != VK_SUCCESS) return nullptr; 2385 if (context_.vk.vkResetCommandBuffer(reuse->buffer, 0) != VK_SUCCESS) return nullptr;
2324 reuse->predicate.reset(); 2386 reuse->predicate.reset();
2325 reuse->predicated_copy.reset(); 2387 reuse->predicated_copy.reset();
2388 reuse->counted_dispatch.reset();
2326 reuse->ticket = UINT64_MAX; // in use until submitted 2389 reuse->ticket = UINT64_MAX; // in use until submitted
2327 return reuse; 2390 return reuse;
2328 } 2391 }
diff --git a/runtime/src/vulkan_indirect_dispatch_count.h b/runtime/src/vulkan_indirect_dispatch_count.h
new file mode 100644
index 000000000..225f7c1fc
--- /dev/null
+++ b/runtime/src/vulkan_indirect_dispatch_count.h
@@ -0,0 +1,199 @@
1// GPU-only count gating for simple D3D12 ExecuteIndirect(DISPATCH) signatures.
2// Vulkan has vkCmdDispatchIndirect but no vkCmdDispatchIndirectCount. We prepare a private indirect
3// buffer with zero-group records past the GPU count, then execute all MaxCommandCount records.
4#pragma once
5#ifndef VK_NO_PROTOTYPES
6#define VK_NO_PROTOTYPES
7#endif
8#include <vulkan/vulkan.h>
9#include <algorithm>
10#include <cstdint>
11#include <limits>
12#include <memory>
13#include <vector>
14#include "indirect_dispatch_count_spv.h"
15
16namespace leonida {
17
18struct CountedDispatch {
19 VkBuffer indirect = VK_NULL_HANDLE;
20 VkDeviceSize offset = 0;
21 VkDeviceAddress arguments = 0;
22 VkDeviceAddress count = 0;
23 VkDeviceAddress output = 0;
24 std::uint32_t stride = 0;
25 std::uint32_t max_count = 0;
26};
27
28class IndirectDispatchCounter {
29public:
30 IndirectDispatchCounter(PFN_vkGetDeviceProcAddr get, VkDevice device,
31 const VkPhysicalDeviceMemoryProperties& memory, const VkPhysicalDeviceLimits& limits)
32 : get_(get), device_(device), memory_(memory), limits_(limits) {}
33 ~IndirectDispatchCounter() {
34 if (pipeline_) fn<PFN_vkDestroyPipeline>("vkDestroyPipeline")(device_, pipeline_, nullptr);
35 if (layout_) fn<PFN_vkDestroyPipelineLayout>("vkDestroyPipelineLayout")(device_, layout_, nullptr);
36 }
37 IndirectDispatchCounter(const IndirectDispatchCounter&) = delete;
38 IndirectDispatchCounter& operator=(const IndirectDispatchCounter&) = delete;
39
40 // Retained by the command-buffer slot until its submission's timeline ticket completes.
41 struct Batch {
42 IndirectDispatchCounter& owner;
43 struct Allocation {
44 VkBuffer buffer = VK_NULL_HANDLE;
45 VkDeviceMemory memory = VK_NULL_HANDLE;
46 };
47 std::vector<Allocation> allocations;
48 explicit Batch(IndirectDispatchCounter& value) : owner(value) {}
49 ~Batch() {
50 for (auto& a : allocations) {
51 if (a.buffer) owner.fn<PFN_vkDestroyBuffer>("vkDestroyBuffer")(owner.device_, a.buffer, nullptr);
52 if (a.memory) owner.fn<PFN_vkFreeMemory>("vkFreeMemory")(owner.device_, a.memory, nullptr);
53 }
54 }
55 Batch(const Batch&) = delete;
56 Batch& operator=(const Batch&) = delete;
57
58 bool prepare(VkBuffer arguments, VkDeviceSize argument_offset, VkBuffer count,
59 VkDeviceSize count_offset, std::uint32_t stride, std::uint32_t max_count,
60 CountedDispatch& out) {
61 out = {};
62 if (!arguments || !count || !stride || stride % 4 || !max_count ||
63 !owner.limits_.maxComputeWorkGroupCount[0] || !owner.make_pipeline()) return false;
64 constexpr VkDeviceSize record_bytes = 3 * sizeof(std::uint32_t);
65 if (VkDeviceSize(max_count) > std::numeric_limits<VkDeviceSize>::max() / record_bytes)
66 return false;
67 const VkDeviceSize bytes = VkDeviceSize(max_count) * record_bytes;
68 VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
69 info.size = bytes;
70 info.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT |
71 VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT;
72 Allocation scratch{};
73 if (owner.fn<PFN_vkCreateBuffer>("vkCreateBuffer")(owner.device_, &info, nullptr, &scratch.buffer) != VK_SUCCESS)
74 return false;
75 allocations.push_back(scratch); // all failure paths free it with the batch
76 auto& a = allocations.back();
77 VkMemoryRequirements requirements{};
78 owner.fn<PFN_vkGetBufferMemoryRequirements>("vkGetBufferMemoryRequirements")(
79 owner.device_, a.buffer, &requirements);
80 std::uint32_t memory_type = UINT32_MAX;
81 for (std::uint32_t i = 0; i < owner.memory_.memoryTypeCount; ++i) {
82 if (!(requirements.memoryTypeBits & (1u << i))) continue;
83 if (memory_type == UINT32_MAX) memory_type = i;
84 if (owner.memory_.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) {
85 memory_type = i;
86 break;
87 }
88 }
89 if (memory_type == UINT32_MAX) return false;
90 VkMemoryAllocateFlagsInfo flags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO};
91 flags.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT;
92 VkMemoryAllocateInfo allocation{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, &flags};
93 allocation.allocationSize = requirements.size;
94 allocation.memoryTypeIndex = memory_type;
95 if (owner.fn<PFN_vkAllocateMemory>("vkAllocateMemory")(owner.device_, &allocation, nullptr, &a.memory) != VK_SUCCESS ||
96 owner.fn<PFN_vkBindBufferMemory>("vkBindBufferMemory")(owner.device_, a.buffer, a.memory, 0) != VK_SUCCESS)
97 return false;
98 const auto address = owner.fn<PFN_vkGetBufferDeviceAddress>("vkGetBufferDeviceAddress");
99 VkBufferDeviceAddressInfo addr{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO};
100 addr.buffer = arguments;
101 const VkDeviceAddress args_va = address(owner.device_, &addr);
102 addr.buffer = count;
103 const VkDeviceAddress count_va = address(owner.device_, &addr);
104 addr.buffer = a.buffer;
105 const VkDeviceAddress output_va = address(owner.device_, &addr);
106 if (!args_va || !count_va || !output_va ||
107 argument_offset > UINT64_MAX - args_va || count_offset > UINT64_MAX - count_va)
108 return false;
109 out = {a.buffer, 0, args_va + argument_offset, count_va + count_offset,
110 output_va, stride, max_count};
111 return true;
112 }
113 };
114
115 std::unique_ptr<Batch> batch() { return std::make_unique<Batch>(*this); }
116
117 void emit(VkCommandBuffer cb, const CountedDispatch& job) const {
118 const auto barrier = fn<PFN_vkCmdPipelineBarrier>("vkCmdPipelineBarrier");
119 VkMemoryBarrier before{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
120 before.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT;
121 before.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
122 barrier(cb, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
123 0, 1, &before, 0, nullptr, 0, nullptr);
124 fn<PFN_vkCmdBindPipeline>("vkCmdBindPipeline")(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_);
125 struct Push {
126 VkDeviceAddress arguments, count, output;
127 std::uint32_t stride_words, first_record, records;
128 };
129 static_assert(sizeof(Push) == 40);
130 const VkDeviceSize dispatch_limit = VkDeviceSize(limits_.maxComputeWorkGroupCount[0]) * 64;
131 // Bound per-dispatch indexing to 32 bits, even when the D3D12 stride is very large.
132 // The shader loads three consecutive dwords, so leave room for the final +2.
133 const VkDeviceSize index_limit = (UINT32_MAX - 2u) / (job.stride / 4);
134 const VkDeviceSize chunk_limit = std::min(dispatch_limit, index_limit + 1);
135 for (VkDeviceSize first = 0; first < job.max_count;) {
136 const std::uint32_t count = std::uint32_t(std::min<VkDeviceSize>(chunk_limit, job.max_count - first));
137 const Push push{job.arguments + first * job.stride, job.count, job.output + first * 12,
138 job.stride / 4, std::uint32_t(first), count};
139 fn<PFN_vkCmdPushConstants>("vkCmdPushConstants")(cb, layout_, VK_SHADER_STAGE_COMPUTE_BIT,
140 0, sizeof(push), &push);
141 fn<PFN_vkCmdDispatch>("vkCmdDispatch")(cb, (count + 63u) / 64u, 1, 1);
142 first += count;
143 }
144 VkMemoryBarrier after{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
145 after.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_SHADER_READ_BIT;
146 after.dstAccessMask = VK_ACCESS_INDIRECT_COMMAND_READ_BIT | VK_ACCESS_MEMORY_READ_BIT |
147 VK_ACCESS_MEMORY_WRITE_BIT;
148 barrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
149 0, 1, &after, 0, nullptr, 0, nullptr);
150 }
151
152private:
153 template<typename T> T fn(const char* name) const { return reinterpret_cast<T>(get_(device_, name)); }
154 bool make_pipeline() {
155 if (pipeline_) return true;
156 for (const char* name : {"vkCreateBuffer", "vkDestroyBuffer", "vkGetBufferMemoryRequirements",
157 "vkAllocateMemory", "vkFreeMemory", "vkBindBufferMemory", "vkGetBufferDeviceAddress",
158 "vkCreateShaderModule", "vkDestroyShaderModule", "vkCreatePipelineLayout",
159 "vkDestroyPipelineLayout", "vkCreateComputePipelines", "vkDestroyPipeline",
160 "vkCmdPipelineBarrier", "vkCmdBindPipeline", "vkCmdPushConstants", "vkCmdDispatch"})
161 if (!get_(device_, name)) return false;
162 VkShaderModule module = VK_NULL_HANDLE;
163 VkPipelineLayout layout = VK_NULL_HANDLE;
164 VkPipeline pipeline = VK_NULL_HANDLE;
165 VkShaderModuleCreateInfo shader{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO};
166 shader.codeSize = sizeof(indirect_dispatch_count_spirv);
167 shader.pCode = indirect_dispatch_count_spirv;
168 bool ok = fn<PFN_vkCreateShaderModule>("vkCreateShaderModule")(device_, &shader, nullptr, &module) == VK_SUCCESS;
169 const VkPushConstantRange range{VK_SHADER_STAGE_COMPUTE_BIT, 0, 40};
170 VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO};
171 layout_info.pushConstantRangeCount = 1;
172 layout_info.pPushConstantRanges = &range;
173 ok = ok && fn<PFN_vkCreatePipelineLayout>("vkCreatePipelineLayout")(device_, &layout_info, nullptr, &layout) == VK_SUCCESS;
174 VkComputePipelineCreateInfo info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO};
175 info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO};
176 info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT;
177 info.stage.module = module;
178 info.stage.pName = "main";
179 info.layout = layout;
180 ok = ok && fn<PFN_vkCreateComputePipelines>("vkCreateComputePipelines")(
181 device_, VK_NULL_HANDLE, 1, &info, nullptr, &pipeline) == VK_SUCCESS;
182 if (module) fn<PFN_vkDestroyShaderModule>("vkDestroyShaderModule")(device_, module, nullptr);
183 if (!ok) {
184 if (pipeline) fn<PFN_vkDestroyPipeline>("vkDestroyPipeline")(device_, pipeline, nullptr);
185 if (layout) fn<PFN_vkDestroyPipelineLayout>("vkDestroyPipelineLayout")(device_, layout, nullptr);
186 return false;
187 }
188 layout_ = layout;
189 pipeline_ = pipeline;
190 return true;
191 }
192 PFN_vkGetDeviceProcAddr get_;
193 VkDevice device_;
194 VkPhysicalDeviceMemoryProperties memory_;
195 VkPhysicalDeviceLimits limits_;
196 VkPipelineLayout layout_ = VK_NULL_HANDLE;
197 VkPipeline pipeline_ = VK_NULL_HANDLE;
198};
199} // namespace leonida
diff --git a/runtime/src/vulkan_memory.h b/runtime/src/vulkan_memory.h
index c89a68575..08c764d33 100644
--- a/runtime/src/vulkan_memory.h
+++ b/runtime/src/vulkan_memory.h
@@ -56,4 +56,13 @@ inline std::vector<std::uint32_t> memory_type_order(const VkPhysicalDeviceMemory
56 return order; 56 return order;
57} 57}
58 58
59// D3D-299: true when an allocation that preferred DEVICE_LOCAL without needing host access (a texture, a default-heap
60// buffer outside the arena) got a type without it, so the GPU now reads it from system memory. A host-visible
61// allocation (the arena, an upload heap) in system memory is the memory type policy without Resizable BAR, not this.
62inline bool spilled_to_host(VkMemoryPropertyFlags required, VkMemoryPropertyFlags preferred,
63 VkMemoryPropertyFlags chosen) {
64 return (preferred & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) && !(required & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) &&
65 !(chosen & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
66}
67
59} // namespace leonida 68} // namespace leonida
diff --git a/runtime/src/vulkan_present.h b/runtime/src/vulkan_present.h
index fc6d1699e..a29cce3fa 100644
--- a/runtime/src/vulkan_present.h
+++ b/runtime/src/vulkan_present.h
@@ -166,8 +166,10 @@ public:
166 { 166 {
167 std::lock_guard lock(context_.submit_mutex()); 167 std::lock_guard lock(context_.submit_mutex());
168 vk.vkQueueWaitIdle(queue_); 168 vk.vkQueueWaitIdle(queue_);
169 // A WSI layer may perform a device-wide idle while destroying the swapchain.
170 // Keep that implicit idle serialized with submits from every context queue.
171 release(swapchain_);
169 } 172 }
170 release(swapchain_);
171 swapchain_ = VK_NULL_HANDLE; 173 swapchain_ = VK_NULL_HANDLE;
172 release_capture(); 174 release_capture();
173 composer_.reset(); 175 composer_.reset();
@@ -299,7 +301,9 @@ public:
299 } 301 }
300 302
301 // The last presented frame as the swapchain stores it (4 bytes a texel, rows tightly packed, format() order). 303 // The last presented frame as the swapchain stores it (4 bytes a texel, rows tightly packed, format() order).
302 // Waits for the frame to finish. False if no captured frame is available or the wait fails. 304 // Waits for the frame to finish. False when nothing was presented since enable_capture(), after a present
305 // that was skipped because the window is minimised (it returned VK_SUCCESS but showed nothing), until the next
306 // frame that is shown (the frame before it is not what the window was last asked to show), or when the wait fails.
303 bool read_back(std::vector<std::uint8_t>& pixels, VkExtent2D* extent, VkFormat* format) { 307 bool read_back(std::vector<std::uint8_t>& pixels, VkExtent2D* extent, VkFormat* format) {
304 if (!capture_ || !capture_ptr_ || !captured_) return false; 308 if (!capture_ || !capture_ptr_ || !captured_) return false;
305 const Frame& frame = frames_[(frame_index_ + frames_.size() - 1) % frames_.size()]; 309 const Frame& frame = frames_[(frame_index_ + frames_.size() - 1) % frames_.size()];
@@ -331,6 +335,7 @@ public:
331 } 335 }
332 if (!swapchain_) { // minimised: try again next frame 336 if (!swapchain_) { // minimised: try again next frame
333 stale_ = true; 337 stale_ = true;
338 captured_ = false; // nothing was shown: read_back() must not hand out the frame before
334 return VK_SUCCESS; 339 return VK_SUCCESS;
335 } 340 }
336 if (binding && !presentable(source)) return VK_ERROR_UNKNOWN; // checked before an image is acquired for it 341 if (binding && !presentable(source)) return VK_ERROR_UNKNOWN; // checked before an image is acquired for it
@@ -347,7 +352,10 @@ public:
347 VkResult acquired = acquire(frame.acquired, &image); 352 VkResult acquired = acquire(frame.acquired, &image);
348 if (acquired == VK_ERROR_OUT_OF_DATE_KHR) { 353 if (acquired == VK_ERROR_OUT_OF_DATE_KHR) {
349 if (!recreate(vsync, swapchain_srgb_, swapchain_hdr_req_)) return acquired; 354 if (!recreate(vsync, swapchain_srgb_, swapchain_hdr_req_)) return acquired;
350 if (!swapchain_) return VK_SUCCESS; 355 if (!swapchain_) { // minimised since the last present: skipped, as above
356 captured_ = false;
357 return VK_SUCCESS;
358 }
351 acquired = acquire(frame.acquired, &image); 359 acquired = acquire(frame.acquired, &image);
352 } 360 }
353 if (acquired != VK_SUCCESS && acquired != VK_SUBOPTIMAL_KHR) return acquired; // nothing was acquired 361 if (acquired != VK_SUCCESS && acquired != VK_SUBOPTIMAL_KHR) return acquired; // nothing was acquired
@@ -873,7 +881,10 @@ private:
873 } 881 }
874 } 882 }
875 if (extent.width == 0 || extent.height == 0) { 883 if (extent.width == 0 || extent.height == 0) {
876 release(swapchain_); 884 {
885 std::lock_guard lock(context_.submit_mutex());
886 release(swapchain_);
887 }
877 swapchain_ = VK_NULL_HANDLE; 888 swapchain_ = VK_NULL_HANDLE;
878 vsync_ = vsync; 889 vsync_ = vsync;
879 swapchain_srgb_ = srgb; 890 swapchain_srgb_ = srgb;
@@ -985,13 +996,18 @@ private:
985 info.oldSwapchain = old; 996 info.oldSwapchain = old;
986 VkSwapchainKHR fresh = VK_NULL_HANDLE; 997 VkSwapchainKHR fresh = VK_NULL_HANDLE;
987 const VkResult created = vkCreateSwapchainKHR_(device, &info, nullptr, &fresh); 998 const VkResult created = vkCreateSwapchainKHR_(device, &info, nullptr, &fresh);
988 release(old); // retired by the creation attempt, whether or not it succeeded 999 {
1000 std::lock_guard lock(context_.submit_mutex());
1001 release(old); // retired by the creation attempt, whether or not it succeeded
1002 }
989 if (created != VK_SUCCESS) return false; 1003 if (created != VK_SUCCESS) return false;
990 1004
991 std::vector<VkImage> images; 1005 std::vector<VkImage> images;
992 std::vector<VkSemaphore> ready; 1006 std::vector<VkSemaphore> ready;
993 const auto discard = [&] { 1007 const auto discard = [&] {
994 for (VkSemaphore semaphore : ready) vk.vkDestroySemaphore(device, semaphore, nullptr); 1008 for (VkSemaphore semaphore : ready) vk.vkDestroySemaphore(device, semaphore, nullptr);
1009 // The WSI implementation may block on the device here too.
1010 std::lock_guard lock(context_.submit_mutex());
995 vkDestroySwapchainKHR_(device, fresh, nullptr); 1011 vkDestroySwapchainKHR_(device, fresh, nullptr);
996 return false; 1012 return false;
997 }; 1013 };
diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h
index 330969799..46c867242 100644
--- a/runtime/src/vulkan_replay.h
+++ b/runtime/src/vulkan_replay.h
@@ -37,6 +37,7 @@
37#include <vulkan/vulkan.h> 37#include <vulkan/vulkan.h>
38#include "vulkan_predicate.h" 38#include "vulkan_predicate.h"
39#include "vulkan_predicated_copy.h" 39#include "vulkan_predicated_copy.h"
40#include "vulkan_indirect_dispatch_count.h"
40 41
41#include <algorithm> 42#include <algorithm>
42#include <array> 43#include <array>
@@ -721,6 +722,8 @@ struct OcclusionResult {
721// A D3D12 query heap on Vulkan. The host tracks which queries hold a result. A resolve of a query that 722// A D3D12 query heap on Vulkan. The host tracks which queries hold a result. A resolve of a query that
722// was never ended writes zeros instead of waiting on it. 723// was never ended writes zeros instead of waiting on it.
723struct QueryPool { 724struct QueryPool {
725 // Null for a stream-output statistics heap: the layer has no stream output (PSOs with StreamOutput entries are
726 // refused), so every SO_STATISTICS_STREAMn query counts 0 written and 0 needed, and a resolve fills zeros.
724 VkQueryPool pool = VK_NULL_HANDLE; 727 VkQueryPool pool = VK_NULL_HANDLE;
725 std::uint32_t heap_type = 0; // d3d12_query_heap 728 std::uint32_t heap_type = 0; // d3d12_query_heap
726 std::uint32_t count = 0; 729 std::uint32_t count = 0;
@@ -799,6 +802,10 @@ struct ReplayFunctions {
799 std::function<void(VkCommandBuffer)> order_timestamp_copy; 802 std::function<void(VkCommandBuffer)> order_timestamp_copy;
800 std::function<void(VkCommandBuffer, VkQueryPool, std::uint32_t, std::uint32_t, VkBuffer, VkDeviceSize)> 803 std::function<void(VkCommandBuffer, VkQueryPool, std::uint32_t, std::uint32_t, VkBuffer, VkDeviceSize)>
801 sum_occlusion; 804 sum_occlusion;
805 // Creates a query pool of `count` queries of that type for the single-list replay()'s occlusion and
806 // pipeline-statistics segments (D3D-399); the batched path creates its own. Unset, or with any sum helper unset,
807 // replay() refuses a list whose queries overlap, as before.
808 std::function<std::shared_ptr<const OcclusionSegmentPool>(VkQueryType, std::uint32_t count)> create_segment_pool;
802 PFN_vkCmdBindPipeline bind_pipeline = nullptr; // dispatches 809 PFN_vkCmdBindPipeline bind_pipeline = nullptr; // dispatches
803 PFN_vkCmdPushConstants push_constants = nullptr; 810 PFN_vkCmdPushConstants push_constants = nullptr;
804 PFN_vkCmdBindDescriptorSets bind_descriptor_sets = nullptr; // set 0 of pipelines that declare bindings 811 PFN_vkCmdBindDescriptorSets bind_descriptor_sets = nullptr; // set 0 of pipelines that declare bindings
@@ -845,6 +852,11 @@ struct ReplayFunctions {
845 PFN_vkCmdDrawIndirectCount draw_indirect_count = nullptr; 852 PFN_vkCmdDrawIndirectCount draw_indirect_count = nullptr;
846 PFN_vkCmdDrawIndexedIndirectCount draw_indexed_indirect_count = nullptr; 853 PFN_vkCmdDrawIndexedIndirectCount draw_indexed_indirect_count = nullptr;
847 PFN_vkCmdDispatchIndirect dispatch_indirect = nullptr; 854 PFN_vkCmdDispatchIndirect dispatch_indirect = nullptr;
855 // A DISPATCH-only ExecuteIndirect signature with a GPU count buffer needs a compute prepass to clamp
856 // the number of commands. The resulting scratch buffer is owned by the queue's timeline-retained batch.
857 std::function<bool(VkBuffer, VkDeviceSize, VkBuffer, VkDeviceSize, std::uint32_t, std::uint32_t,
858 CountedDispatch&)> prepare_counted_dispatch;
859 std::function<void(VkCommandBuffer, const CountedDispatch&)> emit_counted_dispatch;
848 // Optional VK_KHR_acceleration_structure: BuildRaytracingAccelerationStructure. 860 // Optional VK_KHR_acceleration_structure: BuildRaytracingAccelerationStructure.
849 PFN_vkCmdBuildAccelerationStructuresKHR build_acceleration_structures = nullptr; 861 PFN_vkCmdBuildAccelerationStructuresKHR build_acceleration_structures = nullptr;
850 // XDXR BVH4 builds (xdxr_build.h), used instead of the KHR ones when set: `xdxr_check` refuses inputs the builder 862 // XDXR BVH4 builds (xdxr_build.h), used instead of the KHR ones when set: `xdxr_check` refuses inputs the builder
@@ -934,6 +946,7 @@ struct Prepared {
934 std::uint32_t statistics_begin = PreparedQuery::no_segment; 946 std::uint32_t statistics_begin = PreparedQuery::no_segment;
935 PredicateCapture predicate; 947 PredicateCapture predicate;
936 std::vector<PredicatedCopyDispatch> predicated_copy; 948 std::vector<PredicatedCopyDispatch> predicated_copy;
949 CountedDispatch counted_dispatch;
937 ResourceBinding binding; 950 ResourceBinding binding;
938 VkImageSubresourceRange range{}; // the barrier range, or the cleared view (cleared aspects only) 951 VkImageSubresourceRange range{}; // the barrier range, or the cleared view (cleared aspects only)
939 VkImageView view = VK_NULL_HANDLE; 952 VkImageView view = VK_NULL_HANDLE;
@@ -945,6 +958,7 @@ struct Prepared {
945 std::vector<VkBufferCopy> buffer_copies; 958 std::vector<VkBufferCopy> buffer_copies;
946 std::vector<VkBufferImageCopy> buffer_image_copies; // one direction, given by which side is an image 959 std::vector<VkBufferImageCopy> buffer_image_copies; // one direction, given by which side is an image
947 std::vector<VkImageCopy> image_copies; 960 std::vector<VkImageCopy> image_copies;
961 bool same_copy_subresource = false;
948 VkImageResolve resolve{}; // resolves 962 VkImageResolve resolve{}; // resolves
949 // Depth or stencil resolves: the mode, and the destination view (`view` is the source's). 963 // Depth or stencil resolves: the mode, and the destination view (`view` is the source's).
950 VkResolveModeFlagBits resolve_mode = VK_RESOLVE_MODE_NONE; 964 VkResolveModeFlagBits resolve_mode = VK_RESOLVE_MODE_NONE;
@@ -1555,6 +1569,8 @@ inline ReplayResult prepare_texture_copy(const CopyTexture& copy, Prepared& p) {
1555 p.binding.volume != p.source.volume || p.binding.samples != p.source.samples || 1569 p.binding.volume != p.source.volume || p.binding.samples != p.source.samples ||
1556 p.binding.rgb96 != p.source.rgb96) 1570 p.binding.rgb96 != p.source.rgb96)
1557 return ReplayResult::invalid_copy; 1571 return ReplayResult::invalid_copy;
1572 p.same_copy_subresource = p.source.image == p.binding.image && src.aspectMask == dst.aspectMask &&
1573 src.baseMipLevel == dst.baseMipLevel && src.baseArrayLayer == dst.baseArrayLayer;
1558 const VkExtent2D from = mip_extent(p.source, src.baseMipLevel), to = mip_extent(p.binding, dst.baseMipLevel); 1574 const VkExtent2D from = mip_extent(p.source, src.baseMipLevel), to = mip_extent(p.binding, dst.baseMipLevel);
1559 const auto from_depth = std::max(1u, p.source.depth >> src.baseMipLevel); 1575 const auto from_depth = std::max(1u, p.source.depth >> src.baseMipLevel);
1560 const auto to_depth = std::max(1u, p.binding.depth >> dst.baseMipLevel); 1576 const auto to_depth = std::max(1u, p.binding.depth >> dst.baseMipLevel);
@@ -1579,21 +1595,37 @@ inline ReplayResult prepare_texture_copy(const CopyTexture& copy, Prepared& p) {
1579 return ReplayResult::invalid_copy; 1595 return ReplayResult::invalid_copy;
1580 const std::uint32_t w = std::min(padded(box.right - box.left), from.width - box.left); 1596 const std::uint32_t w = std::min(padded(box.right - box.left), from.width - box.left);
1581 const std::uint32_t h = std::min(padded(box.bottom - box.top), from.height - box.top); 1597 const std::uint32_t h = std::min(padded(box.bottom - box.top), from.height - box.top);
1582 // shortcut: into a BC mip whose edge block is partial, Vulkan's extent cannot reach the padded edge; such 1598 const VkImageCopy region{{src.aspectMask, src.baseMipLevel, src.baseArrayLayer, 1},
1583 // a copy is refused until it is staged through a buffer. 1599 {std::int32_t(box.left), std::int32_t(box.top), std::int32_t(box.front)},
1584 if (dst_block > 1 && (copy.x + w * dst_block > to.width || copy.y + h * dst_block > to.height)) 1600 {dst.aspectMask, dst.baseMipLevel, dst.baseArrayLayer, 1},
1585 return ReplayResult::invalid_copy; 1601 {std::int32_t(copy.x), std::int32_t(copy.y), std::int32_t(copy.z)},
1586 p.image_copies.push_back({{src.aspectMask, src.baseMipLevel, src.baseArrayLayer, 1}, 1602 {w, h, box.back - box.front}};
1587 {std::int32_t(box.left), std::int32_t(box.top), std::int32_t(box.front)}, 1603 const std::uint32_t dst_w = w * dst_block, dst_h = h * dst_block;
1588 {dst.aspectMask, dst.baseMipLevel, dst.baseArrayLayer, 1}, 1604 if (dst_block > 1 && (copy.x + dst_w > to.width || copy.y + dst_h > to.height)) {
1589 {std::int32_t(copy.x), std::int32_t(copy.y), std::int32_t(copy.z)}, 1605 // Each uncompressed texel supplies a whole BC block. Keep the same scratch row and slice strides
1590 {w, h, box.back - box.front}}); 1606 // in bytes on both sides, with a destination extent clipped to the actual mip.
1607 const VkBufferImageCopy read{0, w, h, region.srcSubresource, region.srcOffset, region.extent};
1608 const VkBufferImageCopy write{0, dst_w, dst_h, region.dstSubresource, region.dstOffset,
1609 {std::min(dst_w, to.width - copy.x), std::min(dst_h, to.height - copy.y), region.extent.depth}};
1610 p.staged_reads.push_back(read);
1611 p.staged_writes.push_back(write);
1612 } else {
1613 p.image_copies.push_back(region);
1614 }
1591 p.range = dst; 1615 p.range = dst;
1592 p.source_range = src; 1616 p.source_range = src;
1593 return ReplayResult::success; 1617 return ReplayResult::success;
1594 } 1618 }
1595 std::uint32_t w = box.right - box.left, h = box.bottom - box.top; 1619 std::uint32_t w = box.right - box.left, h = box.bottom - box.top;
1596 const std::uint32_t d = box.back - box.front; 1620 const std::uint32_t d = box.back - box.front;
1621 if (p.same_copy_subresource) {
1622 const auto intersects = [](std::uint32_t a, std::uint32_t b, std::uint32_t size) {
1623 return (a < b ? b - a : a - b) < size;
1624 };
1625 if (intersects(box.left, copy.x, padded(w)) && intersects(box.top, copy.y, padded(h)) &&
1626 intersects(box.front, copy.z, d))
1627 return ReplayResult::invalid_copy;
1628 }
1597 if (block > 1) { 1629 if (block > 1) {
1598 // D3D12 copies whole blocks: the box is rounded up to blocks and must fit the destination's padded mip. 1630 // D3D12 copies whole blocks: the box is rounded up to blocks and must fit the destination's padded mip.
1599 // Vulkan takes an extent that is a block multiple or reaches the edge of each image separately, so the 1631 // Vulkan takes an extent that is a block multiple or reaches the edge of each image separately, so the
@@ -1945,8 +1977,9 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct
1945 }; 1977 };
1946 1978
1947 p.colors.assign(pipeline->color_formats.size(), {}); 1979 p.colors.assign(pipeline->color_formats.size(), {});
1948 for (std::size_t slot = 0; slot < draw.render_target_count && slot < draw.render_targets.size() && slot < p.colors.size(); ++slot) { 1980 const std::uint32_t render_target_count = draw.views ? draw.views->render_target_count : 0;
1949 const TargetView& target = draw.render_targets[slot]; 1981 for (std::size_t slot = 0; slot < render_target_count && slot < p.colors.size(); ++slot) {
1982 const TargetView& target = draw.views->render_targets[slot];
1950 if (!target.resource) continue; 1983 if (!target.resource) continue;
1951 const ResourceBinding* binding = resolve(target.resource); 1984 const ResourceBinding* binding = resolve(target.resource);
1952 if (!binding) return ReplayResult::unresolved_resource; 1985 if (!binding) return ReplayResult::unresolved_resource;
@@ -2004,7 +2037,8 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct
2004 p.vertex_offsets.resize(slot + 1, 0); 2037 p.vertex_offsets.resize(slot + 1, 0);
2005 p.vertex_sizes.resize(slot + 1, VK_WHOLE_SIZE); 2038 p.vertex_sizes.resize(slot + 1, VK_WHOLE_SIZE);
2006 p.vertex_strides.resize(slot + 1, 0); 2039 p.vertex_strides.resize(slot + 1, 0);
2007 const bool bound = slot < draw.vertex_buffers.size() && draw.vertex_buffers[slot].va; 2040 const bool bound = draw.views && slot < draw.views->vertex_buffers.size() &&
2041 draw.views->vertex_buffers[slot].va;
2008 if (!bound) { 2042 if (!bound) {
2009 if (!vk.zero_buffer) return ReplayResult::unresolved_resource; 2043 if (!vk.zero_buffer) return ReplayResult::unresolved_resource;
2010 p.vertex_buffers[slot] = vk.zero_buffer; 2044 p.vertex_buffers[slot] = vk.zero_buffer;
@@ -2013,7 +2047,7 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct
2013 p.vertex_strides[slot] = 0; 2047 p.vertex_strides[slot] = 0;
2014 continue; 2048 continue;
2015 } 2049 }
2016 const VertexBufferView& view = draw.vertex_buffers[slot]; 2050 const VertexBufferView& view = draw.views->vertex_buffers[slot];
2017 std::uint64_t size = view.size; 2051 std::uint64_t size = view.size;
2018 if (!vk.buffer_at(view.va, size, p.vertex_buffers[slot], p.vertex_offsets[slot])) 2052 if (!vk.buffer_at(view.va, size, p.vertex_buffers[slot], p.vertex_offsets[slot]))
2019 return ReplayResult::unresolved_resource; 2053 return ReplayResult::unresolved_resource;
@@ -2174,14 +2208,16 @@ inline void plan_statistics_segments(PreparedList& out) {
2174 std::size_t next_query = 0; 2208 std::size_t next_query = 0;
2175 for (std::size_t i = 0; i < out.commands.size(); ++i) { 2209 for (std::size_t i = 0; i < out.commands.size(); ++i) {
2176 auto& p = out.commands[i]; 2210 auto& p = out.commands[i];
2177 if (begin && (p.predicate.scratch || !p.predicated_copy.empty() || p.has_depth24)) 2211 if (begin && (p.predicate.scratch || !p.predicated_copy.empty() || p.has_depth24 ||
2212 p.counted_dispatch.indirect))
2178 inner.push_back({&p.statistics_end, &p.statistics_begin}); 2213 inner.push_back({&p.statistics_end, &p.statistics_begin});
2179 if (next_query == out.queries.size() || out.queries[next_query].command != i) continue; 2214 if (next_query == out.queries.size() || out.queries[next_query].command != i) continue;
2180 auto& query = out.queries[next_query++]; 2215 auto& query = out.queries[next_query++];
2181 const Command& command = out.list->commands()[i]; 2216 const Command& command = out.list->commands()[i];
2182 const auto range = query_range(command); 2217 const auto range = query_range(command);
2183 if (std::holds_alternative<ResolveQueries>(command)) { 2218 if (std::holds_alternative<ResolveQueries>(command)) {
2184 if (begin && range.type != d3d12_query::timestamp) 2219 // A stream-output resolve only fills zeros (no dispatch), so it needs no split.
2220 if (begin && range.type != d3d12_query::timestamp && !is_so_statistics(range.type))
2185 inner.push_back({&query.statistics_end, &query.statistics_begin}); 2221 inner.push_back({&query.statistics_end, &query.statistics_begin});
2186 } else if (range.type == d3d12_query::pipeline_statistics) { 2222 } else if (range.type == d3d12_query::pipeline_statistics) {
2187 if (std::holds_alternative<BeginQuery>(command)) { 2223 if (std::holds_alternative<BeginQuery>(command)) {
@@ -2223,7 +2259,8 @@ inline ReplayResult plan_overlapping_statistics_segments(PreparedList& out) {
2223 if (!query) { 2259 if (!query) {
2224 // A helper dispatch while a query runs would be counted into it (D3D-162): close the shared physical 2260 // A helper dispatch while a query runs would be counted into it (D3D-162): close the shared physical
2225 // segment before it and open a new one after, the way resolves do. 2261 // segment before it and open a new one after, the way resolves do.
2226 if (!active.empty() && (p.predicate.scratch || !p.predicated_copy.empty() || p.has_depth24)) { 2262 if (!active.empty() && (p.predicate.scratch || !p.predicated_copy.empty() || p.has_depth24 ||
2263 p.counted_dispatch.indirect)) {
2227 p.statistics_end = current; 2264 p.statistics_end = current;
2228 current = out.statistics_segment_count++; 2265 current = out.statistics_segment_count++;
2229 p.statistics_begin = current; 2266 p.statistics_begin = current;
@@ -2731,6 +2768,8 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2731 } else if (range.type == d3d12_query::binary_occlusion) { 2768 } else if (range.type == d3d12_query::binary_occlusion) {
2732 overlaps |= begin && (ordinary_active || binary_active); 2769 overlaps |= begin && (ordinary_active || binary_active);
2733 if (begin) ++binary_active; else --binary_active; 2770 if (begin) ++binary_active; else --binary_active;
2771 } else if (is_so_statistics(range.type)) {
2772 // No Vulkan query runs for it (QueryPool::pool is null), so it overlaps nothing.
2734 } else { 2773 } else {
2735 statistics_overlaps |= begin && statistics_active_count; 2774 statistics_overlaps |= begin && statistics_active_count;
2736 if (begin) ++statistics_active_count; else --statistics_active_count; 2775 if (begin) ++statistics_active_count; else --statistics_active_count;
@@ -2770,10 +2809,19 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2770 if (!detail::indirect_range(*cnt, ind->count_offset, sizeof(std::uint32_t))) 2809 if (!detail::indirect_range(*cnt, ind->count_offset, sizeof(std::uint32_t)))
2771 return ReplayResult::invalid_indirect_arguments; 2810 return ReplayResult::invalid_indirect_arguments;
2772 p.source = *cnt; 2811 p.source = *cnt;
2773 if ((ind->kind == IndirectKind::draw && !vk.draw_indirect_count) || 2812 if (ind->kind == IndirectKind::dispatch) {
2774 (ind->kind == IndirectKind::draw_indexed && !vk.draw_indexed_indirect_count) || 2813 // Vulkan lacks vkCmdDispatchIndirectCount. Copy the GPU-visible commands to private scratch
2775 ind->kind == IndirectKind::dispatch) 2814 // and replace commands past min(count, max_count) with zero-group dispatches.
2815 if (!ind->pipeline || !vk.dispatch_indirect || !vk.prepare_counted_dispatch ||
2816 !vk.emit_counted_dispatch || (statistics_active && !statistics_helpers) ||
2817 !vk.prepare_counted_dispatch(p.binding.buffer, p.binding.buffer_offset + ind->argument_offset,
2818 p.source.buffer, p.source.buffer_offset + ind->count_offset,
2819 ind->stride, ind->max_count, p.counted_dispatch))
2820 return ReplayResult::unsupported;
2821 } else if ((ind->kind == IndirectKind::draw && !vk.draw_indirect_count) ||
2822 (ind->kind == IndirectKind::draw_indexed && !vk.draw_indexed_indirect_count)) {
2776 return ReplayResult::unsupported; 2823 return ReplayResult::unsupported;
2824 }
2777 } else { 2825 } else {
2778 if ((ind->kind == IndirectKind::draw && !vk.draw_indirect) || 2826 if ((ind->kind == IndirectKind::draw && !vk.draw_indirect) ||
2779 (ind->kind == IndirectKind::draw_indexed && !vk.draw_indexed_indirect) || 2827 (ind->kind == IndirectKind::draw_indexed && !vk.draw_indexed_indirect) ||
@@ -3008,6 +3056,9 @@ inline void emit_query(const PreparedList& list, const detail::PreparedQuery& qu
3008 begin_statistics(); 3056 begin_statistics();
3009 return; 3057 return;
3010 } 3058 }
3059 // A heap without a Vulkan pool (stream-output statistics: the layer has no stream output) runs nothing for
3060 // BeginQuery and EndQuery; its resolves were planned as zero fills.
3061 if (!heap.pool && !std::holds_alternative<ResolveQueries>(command)) return;
3011 if (const auto* begin = std::get_if<BeginQuery>(&command)) { 3062 if (const auto* begin = std::get_if<BeginQuery>(&command)) {
3012 vk.reset_query_pool(cb, heap.pool, begin->index, 1); 3063 vk.reset_query_pool(cb, heap.pool, begin->index, 1);
3013 const bool precise = begin->type == d3d12_query::occlusion && heap.precise; 3064 const bool precise = begin->type == d3d12_query::occlusion && heap.precise;
@@ -3374,10 +3425,14 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
3374 vk.copy_buffer_to_image(command_buffer, p.staged, p.binding.image, dst_layout, 3425 vk.copy_buffer_to_image(command_buffer, p.staged, p.binding.image, dst_layout,
3375 std::uint32_t(p.staged_writes.size()), p.staged_writes.data()); 3426 std::uint32_t(p.staged_writes.size()), p.staged_writes.data());
3376 } else if (!p.image_copies.empty()) { 3427 } else if (!p.image_copies.empty()) {
3428 // A subresource can be both the source and destination only in a shared layout.
3429 const bool self = p.same_copy_subresource;
3377 const VkImageLayout src_layout = detail::copy_layout( 3430 const VkImageLayout src_layout = detail::copy_layout(
3378 vk, command_buffer, p.source, src_id, detail::planes_for_layout(p.source, p.source_range, separate), 3431 vk, command_buffer, p.source, src_id, detail::planes_for_layout(p.source, p.source_range, separate),
3379 VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_TRANSFER_READ_BIT, tracker); 3432 self ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
3380 const VkImageLayout dst_layout = detail::copy_layout( 3433 self ? VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT : VK_ACCESS_TRANSFER_READ_BIT,
3434 tracker);
3435 const VkImageLayout dst_layout = self ? src_layout : detail::copy_layout(
3381 vk, command_buffer, p.binding, dst_id, detail::planes_for_layout(p.binding, p.range, separate), 3436 vk, command_buffer, p.binding, dst_id, detail::planes_for_layout(p.binding, p.range, separate),
3382 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, tracker); 3437 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, tracker);
3383 const auto count = std::uint32_t(p.image_copies.size()); 3438 const auto count = std::uint32_t(p.image_copies.size());
@@ -3600,7 +3655,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
3600 vk.copy_buffer(command_buffer, p.source.buffer, p.binding.buffer, 1, p.buffer_copies.data()); 3655 vk.copy_buffer(command_buffer, p.source.buffer, p.binding.buffer, 1, p.buffer_copies.data());
3601 } else if (const auto* ind = std::get_if<ExecuteIndirect>(&command)) { 3656 } else if (const auto* ind = std::get_if<ExecuteIndirect>(&command)) {
3602 const VkDeviceSize arguments = p.binding.buffer_offset + ind->argument_offset; 3657 const VkDeviceSize arguments = p.binding.buffer_offset + ind->argument_offset;
3603 if (ind->count_buffer) { 3658 if (ind->count_buffer && ind->kind != IndirectKind::dispatch) {
3604 const VkDeviceSize count = p.source.buffer_offset + ind->count_offset; 3659 const VkDeviceSize count = p.source.buffer_offset + ind->count_offset;
3605 if (ind->kind == IndirectKind::draw) { 3660 if (ind->kind == IndirectKind::draw) {
3606 vk.draw_indirect_count(command_buffer, p.binding.buffer, arguments, p.source.buffer, 3661 vk.draw_indirect_count(command_buffer, p.binding.buffer, arguments, p.source.buffer,
@@ -3615,6 +3670,12 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
3615 } else if (ind->kind == IndirectKind::draw_indexed) { 3670 } else if (ind->kind == IndirectKind::draw_indexed) {
3616 vk.draw_indexed_indirect(command_buffer, p.binding.buffer, arguments, ind->max_count, ind->stride); 3671 vk.draw_indexed_indirect(command_buffer, p.binding.buffer, arguments, ind->max_count, ind->stride);
3617 } else if (ind->kind == IndirectKind::dispatch) { 3672 } else if (ind->kind == IndirectKind::dispatch) {
3673 if (ind->count_buffer) {
3674 // No D3D12 query must count this internal compute pass as an application dispatch.
3675 end_statistics();
3676 vk.emit_counted_dispatch(command_buffer, p.counted_dispatch);
3677 begin_statistics();
3678 }
3618 if (ind->pipeline) { 3679 if (ind->pipeline) {
3619 ShaderUserData data{}; 3680 ShaderUserData data{};
3620 std::copy(ind->user_data.begin(), ind->user_data.end(), data.s); 3681 std::copy(ind->user_data.begin(), ind->user_data.end(), data.s);
@@ -3628,8 +3689,10 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
3628 &data); 3689 &data);
3629 } 3690 }
3630 for (std::uint32_t k = 0; k < ind->max_count; ++k) { 3691 for (std::uint32_t k = 0; k < ind->max_count; ++k) {
3631 vk.dispatch_indirect(command_buffer, p.binding.buffer, 3692 vk.dispatch_indirect(command_buffer,
3632 arguments + VkDeviceSize(k) * ind->stride); 3693 ind->count_buffer ? p.counted_dispatch.indirect : p.binding.buffer,
3694 (ind->count_buffer ? p.counted_dispatch.offset + VkDeviceSize(k) * 12
3695 : arguments + VkDeviceSize(k) * ind->stride));
3633 } 3696 }
3634 } 3697 }
3635 } 3698 }
@@ -3796,18 +3859,33 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
3796} 3859}
3797 3860
3798// prepare + emit for one list. A failed replay leaves the command buffer and the tracker untouched. 3861// prepare + emit for one list. A failed replay leaves the command buffer and the tracker untouched.
3862// With `keep` and vk.create_segment_pool (and the sum helpers) set, overlapping occlusion or statistics queries get
3863// segment pools as in the batched path; the caller holds `keep` until the command buffer has completed.
3799template<typename Resolve> 3864template<typename Resolve>
3800ReplayResult replay(const CommandList& list, VkCommandBuffer command_buffer, Resolve&& resolve, 3865ReplayResult replay(const CommandList& list, VkCommandBuffer command_buffer, Resolve&& resolve,
3801 const ReplayFunctions& vk, LayoutTracker* tracker = nullptr) { 3866 const ReplayFunctions& vk, LayoutTracker* tracker = nullptr,
3867 std::vector<std::shared_ptr<const OcclusionSegmentPool>>* keep = nullptr) {
3802 if (tracker && tracker->separate_depth_stencil_layouts() != vk.separate_depth_stencil_layouts) 3868 if (tracker && tracker->separate_depth_stencil_layouts() != vk.separate_depth_stencil_layouts)
3803 return ReplayResult::unsupported; 3869 return ReplayResult::unsupported;
3870 const bool pools = keep && vk.create_segment_pool && vk.sum_occlusion && vk.resolve_binary_occlusion &&
3871 vk.sum_statistics && vk.sum_binary_occlusion;
3804 PreparedList prepared; 3872 PreparedList prepared;
3805 if (const auto result = prepare(list, resolve, vk, prepared); result != ReplayResult::success) return result; 3873 if (const auto result = prepare(list, resolve, vk, prepared, pools); result != ReplayResult::success)
3874 return result;
3806 if (tracker && zero_clear_unavailable(prepared, vk, *tracker)) return ReplayResult::unsupported; 3875 if (tracker && zero_clear_unavailable(prepared, vk, *tracker)) return ReplayResult::unsupported;
3876 std::shared_ptr<const OcclusionSegmentPool> physical, statistics;
3877 if (pools && prepared.segment_count &&
3878 !(physical = vk.create_segment_pool(VK_QUERY_TYPE_OCCLUSION, prepared.segment_count)))
3879 return ReplayResult::unsupported;
3880 if (pools && prepared.statistics_segment_count &&
3881 !(statistics = vk.create_segment_pool(VK_QUERY_TYPE_PIPELINE_STATISTICS, prepared.statistics_segment_count)))
3882 return ReplayResult::unsupported;
3807 QueryReplay queries; 3883 QueryReplay queries;
3808 if (const auto result = queries.plan(prepared); result != ReplayResult::success) return result; 3884 if (const auto result = queries.plan(prepared, physical, 0, pools, statistics, 0); result != ReplayResult::success)
3885 return result;
3809 emit(prepared, command_buffer, vk, tracker); 3886 emit(prepared, command_buffer, vk, tracker);
3810 queries.commit(); // the caller owns submission of the legacy command buffer 3887 queries.commit(); // the caller owns submission of the legacy command buffer
3888 if (keep) keep->insert(keep->end(), queries.retained.begin(), queries.retained.end());
3811 return ReplayResult::success; 3889 return ReplayResult::success;
3812} 3890}
3813 3891