diff options
| author | Nolan Cotter <186326284+NolanCotter@users.noreply.github.com> | 2026-11-22 20:39:59 -0700 |
|---|---|---|
| committer | Nolan Cotter <186326284+NolanCotter@users.noreply.github.com> | 2026-11-22 20:39:59 -0700 |
| commit | fa5f26db8eafd2cc27f627b68c0a5a5949bcf2ff (patch) | |
| tree | fc57e238be829295fc216dff89a6d93e64c16b50 /runtime/src | |
| parent | 9b693ecd8a2f90799f6c47f8f06cf062feb9820c (diff) | |
| parent | 7b7d73f890f9fbbf5967bbb694390bbc99e33ba6 (diff) | |
Merge origin/main: DXGI device fields coexist with the console-ABI device state
Diffstat (limited to 'runtime/src')
| -rw-r--r-- | runtime/src/active_input.h | 146 | ||||
| -rw-r--r-- | runtime/src/buffer_va_index.h | 31 | ||||
| -rw-r--r-- | runtime/src/command_list.h | 27 | ||||
| -rw-r--r-- | runtime/src/depth24_fragment.h | 445 | ||||
| -rw-r--r-- | runtime/src/gfx10_descriptors.h | 9 | ||||
| -rw-r--r-- | runtime/src/indirect_dispatch_count.comp | 34 | ||||
| -rw-r--r-- | runtime/src/indirect_dispatch_count_spv.h | 84 | ||||
| -rw-r--r-- | runtime/src/pe_loader.cpp | 28 | ||||
| -rw-r--r-- | runtime/src/pe_loader.h | 17 | ||||
| -rw-r--r-- | runtime/src/queue_families.h | 20 | ||||
| -rw-r--r-- | runtime/src/shader_library.h | 11 | ||||
| -rw-r--r-- | runtime/src/vulkan_backend.h | 71 | ||||
| -rw-r--r-- | runtime/src/vulkan_indirect_dispatch_count.h | 199 | ||||
| -rw-r--r-- | runtime/src/vulkan_memory.h | 9 | ||||
| -rw-r--r-- | runtime/src/vulkan_present.h | 26 | ||||
| -rw-r--r-- | runtime/src/vulkan_replay.h | 132 |
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 | |||
| 30 | namespace leonida { | ||
| 31 | |||
| 32 | enum 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 | |||
| 41 | inline 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. | ||
| 56 | struct 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. | ||
| 63 | enum class InputEdge : std::uint8_t { None, Button, Trigger, Stick }; | ||
| 64 | |||
| 65 | inline 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 | |||
| 75 | class ActiveInputTracker { | ||
| 76 | public: | ||
| 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 | |||
| 124 | private: | ||
| 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; | |||
| 179 | inline constexpr std::uint32_t pipeline_statistics1 = 10; | 180 | inline 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). | ||
| 184 | constexpr 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). |
| 183 | constexpr bool query_fits_heap(std::uint32_t heap_type, std::uint32_t query_type) { | 189 | constexpr 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. | ||
| 200 | constexpr std::uint32_t query_result_size(std::uint32_t query_type) { | 207 | constexpr 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. | ||
| 410 | struct 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 { | |||
| 400 | struct Draw { | 421 | struct 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 | |||
| 34 | namespace leonida { | ||
| 35 | |||
| 36 | struct 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). | ||
| 44 | inline float depth24_bias_constant(int bias) { | ||
| 45 | return float(bias) * float(1.0 / 16777215.0); | ||
| 46 | } | ||
| 47 | |||
| 48 | namespace spirv24 { | ||
| 49 | |||
| 50 | enum : 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 | }; | ||
| 60 | enum : std::uint32_t { storage_input = 1, storage_output = 3 }; | ||
| 61 | enum : std::uint32_t { decoration_builtin = 11, builtin_frag_coord = 15, builtin_frag_depth = 22 }; | ||
| 62 | enum : std::uint32_t { model_fragment = 4 }; | ||
| 63 | enum : 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 | }; | ||
| 67 | enum : std::uint32_t { glsl_round_even = 2, glsl_fabs = 4, glsl_fmin = 37, glsl_fmax = 40, glsl_find_umsb = 75 }; | ||
| 68 | |||
| 69 | using Inst = std::vector<std::uint32_t>; // a whole instruction, word 0 included | ||
| 70 | |||
| 71 | inline std::uint32_t opcode(const Inst& i) { return i[0] & 0xffffu; } | ||
| 72 | inline 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 | } | ||
| 79 | inline 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 | } | ||
| 85 | inline void fix_length(Inst& i) { i[0] = std::uint32_t(i.size()) << 16 | opcode(i); } | ||
| 86 | inline 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`. | ||
| 92 | inline 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 | |||
| 103 | inline 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 | |||
| 107 | class Module { | ||
| 108 | public: | ||
| 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 | |||
| 136 | private: | ||
| 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. | ||
| 142 | class Patch { | ||
| 143 | public: | ||
| 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 | |||
| 329 | private: | ||
| 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. | ||
| 344 | inline 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. | ||
| 421 | inline 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 | ||
| 5 | layout(local_size_x = 64) in; | ||
| 6 | layout(buffer_reference, std430, buffer_reference_align = 4) readonly buffer WordsIn { | ||
| 7 | uint data[]; | ||
| 8 | }; | ||
| 9 | layout(buffer_reference, std430, buffer_reference_align = 4) buffer WordsOut { | ||
| 10 | uint data[]; | ||
| 11 | }; | ||
| 12 | layout(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; | ||
| 20 | void 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> | ||
| 4 | namespace leonida { | ||
| 5 | inline 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 278444c6f..3c7f9da08 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 | ||
| 530 | namespace { | 530 | namespace { |
| 531 | bool lookup_in_loader(void* ctx, uint64_t address, std::string& module, uint32_t& rva) { | 531 | bool 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 | ||
| 543 | void* bundled_find_loaded(void* ctx, const std::string& dll_lower) { | 535 | void* bundled_find_loaded(void* ctx, const std::string& dll_lower) { |
| @@ -732,6 +724,18 @@ void* Loader::resolve_module_export(void* module_handle, const std::string& sym, | |||
| 732 | return nullptr; | 724 | return nullptr; |
| 733 | } | 725 | } |
| 734 | 726 | ||
| 727 | bool Loader::find_address(uint64_t address, std::string& module, uint32_t& rva) const { | ||
| 728 | std::shared_lock lock(ranges_mutex_); | ||
| 729 | for (const MappedRange& r : ranges_) { | ||
| 730 | if (address >= r.base && address - r.base < r.size) { | ||
| 731 | module = r.name; | ||
| 732 | rva = static_cast<uint32_t>(address - r.base); | ||
| 733 | return true; | ||
| 734 | } | ||
| 735 | } | ||
| 736 | return false; | ||
| 737 | } | ||
| 738 | |||
| 735 | bool Loader::owns_module_handle(void* module_handle) const { | 739 | bool Loader::owns_module_handle(void* module_handle) const { |
| 736 | if (!module_handle) return false; | 740 | if (!module_handle) return false; |
| 737 | std::lock_guard lock(mutex_); | 741 | std::lock_guard lock(mutex_); |
| @@ -873,6 +877,12 @@ Module& Loader::map_image(const std::filesystem::path& path) { | |||
| 873 | m->base = static_cast<uint8_t*>(VirtualAlloc(nullptr, oh.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); | 877 | m->base = static_cast<uint8_t*>(VirtualAlloc(nullptr, oh.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); |
| 874 | if (!m->base) throw std::runtime_error(m->name + ": VirtualAlloc failed"); | 878 | if (!m->base) throw std::runtime_error(m->name + ": VirtualAlloc failed"); |
| 875 | } | 879 | } |
| 880 | { | ||
| 881 | // From here an address inside the image names it. The memory stays until ~Loader, which unregisters the | ||
| 882 | // lookup first. | ||
| 883 | std::unique_lock lock(ranges_mutex_); | ||
| 884 | ranges_.push_back({reinterpret_cast<uint64_t>(m->base), m->size, m->name}); | ||
| 885 | } | ||
| 876 | 886 | ||
| 877 | std::memcpy(m->base, file.data(), oh.SizeOfHeaders); | 887 | std::memcpy(m->base, file.data(), oh.SizeOfHeaders); |
| 878 | auto* sec = IMAGE_FIRST_SECTION(nt); | 888 | auto* sec = IMAGE_FIRST_SECTION(nt); |
diff --git a/runtime/src/pe_loader.h b/runtime/src/pe_loader.h index e73c36339..d7e5be91c 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_; } |
| @@ -133,6 +139,17 @@ private: | |||
| 133 | std::map<std::string, Module*> by_name_; // lower-case file name | 139 | std::map<std::string, Module*> by_name_; // lower-case file name |
| 134 | std::vector<Module*> order_; // mapping order; owns the modules | 140 | std::vector<Module*> order_; // mapping order; owns the modules |
| 135 | std::vector<Module*> init_order_; // dependencies first, see initialisation_order() | 141 | std::vector<Module*> init_order_; // dependencies first, see initialisation_order() |
| 142 | |||
| 143 | // What find_address reads: one entry per mapped image, added once its memory exists. Under ranges_mutex_, a leaf | ||
| 144 | // lock: mutex_ is held while image code runs and the registry holds its own lock around the lookup, so the | ||
| 145 | // lookup must not wait for either. | ||
| 146 | struct MappedRange { | ||
| 147 | uint64_t base = 0; | ||
| 148 | uint32_t size = 0; | ||
| 149 | std::string name; | ||
| 150 | }; | ||
| 151 | mutable std::shared_mutex ranges_mutex_; // shared in find_address: lookups on different threads do not queue | ||
| 152 | std::vector<MappedRange> ranges_; | ||
| 136 | }; | 153 | }; |
| 137 | 154 | ||
| 138 | // Frees the TLS helper clones load() created and deletes their files (Module::tls_index background). load() | 155 | // 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. | ||
| 54 | inline 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 | ||
| 647 | class ShaderLibrary { | 650 | class 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 03ab7ba26..d247b8cb0 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 | #define LEONIDA_VK_MEMBER(name) PFN_##name name = nullptr; | 91 | #define LEONIDA_VK_MEMBER(name) PFN_##name name = nullptr; |
| 90 | LEONIDA_VK_DEVICE_FUNCTIONS(LEONIDA_VK_MEMBER) | 92 | LEONIDA_VK_DEVICE_FUNCTIONS(LEONIDA_VK_MEMBER) |
| @@ -866,7 +868,7 @@ public: | |||
| 866 | // buffer as out of bounds, which is no reason to drop the submission. | 868 | // buffer as out of bounds, which is no reason to drop the submission. |
| 867 | replay_.buffer_at = [this](std::uint64_t va, std::uint64_t& size, VkBuffer& buffer, VkDeviceSize& offset) { | 869 | replay_.buffer_at = [this](std::uint64_t va, std::uint64_t& size, VkBuffer& buffer, VkDeviceSize& offset) { |
| 868 | BufferVaIndex<ResourceId>::Hit hit{}; | 870 | BufferVaIndex<ResourceId>::Hit hit{}; |
| 869 | if (!buffer_vas_.find(va, hit)) return false; | 871 | if (!buffer_vas_.find(va, hit, size)) return false; // prefers an aliasing buffer that holds all of it |
| 870 | const ResourceBinding* b = resolve(hit.id); | 872 | const ResourceBinding* b = resolve(hit.id); |
| 871 | if (!b) return false; | 873 | if (!b) return false; |
| 872 | buffer = b->buffer; | 874 | buffer = b->buffer; |
| @@ -953,6 +955,13 @@ public: | |||
| 953 | std::unique_lock lock(resource_mutex_); | 955 | std::unique_lock lock(resource_mutex_); |
| 954 | predicated_copier_ = std::make_unique<PredicatedBufferCopier>(get, device_, limits); | 956 | predicated_copier_ = std::make_unique<PredicatedBufferCopier>(get, device_, limits); |
| 955 | } | 957 | } |
| 958 | // Counts for DISPATCH-only ExecuteIndirect are read by a helper compute shader from GPU memory. | ||
| 959 | // Requires Vulkan bufferDeviceAddress, already enabled for the D3D12 address arena. | ||
| 960 | void configure_counted_dispatch(PFN_vkGetDeviceProcAddr get, const VkPhysicalDeviceMemoryProperties& memory, | ||
| 961 | const VkPhysicalDeviceLimits& limits) { | ||
| 962 | std::unique_lock lock(resource_mutex_); | ||
| 963 | counted_dispatch_ = std::make_unique<IndirectDispatchCounter>(get, device_, memory, limits); | ||
| 964 | } | ||
| 956 | VkDevice device() const { return device_; } | 965 | VkDevice device() const { return device_; } |
| 957 | 966 | ||
| 958 | // Debug markers become labels from here on; call before any queue or list uses the context. Incomplete sets | 967 | // Debug markers become labels from here on; call before any queue or list uses the context. Incomplete sets |
| @@ -990,6 +999,14 @@ public: | |||
| 990 | storage_pending_.insert(id); | 999 | storage_pending_.insert(id); |
| 991 | } | 1000 | } |
| 992 | 1001 | ||
| 1002 | // A device-local buffer D3D12 says starts zeroed (D3D-71): the host cannot write it, so the next submission on | ||
| 1003 | // any queue fills it with zeros ahead of its lists. That submission publishes the same initialisation semaphore as | ||
| 1004 | // the storage images above, so a list on another queue that uses the buffer first waits for the fill. | ||
| 1005 | void zero_on_next_submit(ResourceId id, VkBuffer buffer) { | ||
| 1006 | std::lock_guard lock(storage_mutex_); | ||
| 1007 | zero_pending_.push_back({id, buffer}); | ||
| 1008 | } | ||
| 1009 | |||
| 993 | void add_sparse_buffer(ResourceId id, const ResourceBinding& binding, std::shared_ptr<SparseBuffer> buffer) { | 1010 | void add_sparse_buffer(ResourceId id, const ResourceBinding& binding, std::shared_ptr<SparseBuffer> buffer) { |
| 994 | std::unique_lock lock(resource_mutex_); | 1011 | std::unique_lock lock(resource_mutex_); |
| 995 | set_resource_locked(id, binding); | 1012 | set_resource_locked(id, binding); |
| @@ -1007,6 +1024,10 @@ public: | |||
| 1007 | resources_.erase(it); | 1024 | resources_.erase(it); |
| 1008 | sparse_buffers_.erase(id); | 1025 | sparse_buffers_.erase(id); |
| 1009 | } | 1026 | } |
| 1027 | { | ||
| 1028 | std::lock_guard lock(storage_mutex_); // a buffer destroyed before any submission is not filled | ||
| 1029 | std::erase_if(zero_pending_, [id](const PendingZero& zero) { return zero.id == id; }); | ||
| 1030 | } | ||
| 1010 | if (img) { | 1031 | if (img) { |
| 1011 | std::lock_guard vlock(views_mutex_); | 1032 | std::lock_guard vlock(views_mutex_); |
| 1012 | for (auto v = views_.begin(); v != views_.end();) { | 1033 | for (auto v = views_.begin(); v != views_.end();) { |
| @@ -1346,8 +1367,13 @@ private: | |||
| 1346 | std::unordered_map<std::uintptr_t, GraphicsPipeline> graphics_pipelines_; | 1367 | std::unordered_map<std::uintptr_t, GraphicsPipeline> graphics_pipelines_; |
| 1347 | std::unordered_map<std::uint64_t, VkAccelerationStructureKHR> acceleration_structures_; | 1368 | std::unordered_map<std::uint64_t, VkAccelerationStructureKHR> acceleration_structures_; |
| 1348 | LayoutTracker tracker_; | 1369 | LayoutTracker tracker_; |
| 1349 | std::mutex storage_mutex_; // a leaf lock: guards storage_pending_ only | 1370 | std::mutex storage_mutex_; // a leaf lock: guards storage_pending_ and zero_pending_ only |
| 1350 | std::unordered_set<ResourceId> storage_pending_; | 1371 | std::unordered_set<ResourceId> storage_pending_; |
| 1372 | struct PendingZero { | ||
| 1373 | ResourceId id; | ||
| 1374 | VkBuffer buffer; | ||
| 1375 | }; | ||
| 1376 | std::vector<PendingZero> zero_pending_; // zero_on_next_submit | ||
| 1351 | // The last submission that initialized storage images (its queue's progress semaphore and ticket) and a counter | 1377 | // The last submission that initialized storage images (its queue's progress semaphore and ticket) and a counter |
| 1352 | // that says which one: every other queue's next submission waits for it, so no queue uses such an image before | 1378 | // that says which one: every other queue's next submission waits for it, so no queue uses such an image before |
| 1353 | // the zero-fill that put it in GENERAL has run. | 1379 | // the zero-fill that put it in GENERAL has run. |
| @@ -1366,6 +1392,7 @@ private: | |||
| 1366 | ReplayFunctions replay_; | 1392 | ReplayFunctions replay_; |
| 1367 | std::unique_ptr<PredicateReducer> predicate_reducer_; | 1393 | std::unique_ptr<PredicateReducer> predicate_reducer_; |
| 1368 | std::unique_ptr<PredicatedBufferCopier> predicated_copier_; | 1394 | std::unique_ptr<PredicatedBufferCopier> predicated_copier_; |
| 1395 | std::unique_ptr<IndirectDispatchCounter> counted_dispatch_; | ||
| 1369 | std::uint32_t predicate_family_ = UINT32_MAX; | 1396 | std::uint32_t predicate_family_ = UINT32_MAX; |
| 1370 | std::uint32_t transfer_only_family_ = UINT32_MAX; | 1397 | std::uint32_t transfer_only_family_ = UINT32_MAX; |
| 1371 | DebugLabelFunctions labels_; | 1398 | DebugLabelFunctions labels_; |
| @@ -1489,6 +1516,12 @@ public: | |||
| 1489 | if (context_.depth24_) context_.depth24_->forget(progress_); // its scratch is idle now | 1516 | if (context_.depth24_) context_.depth24_->forget(progress_); // its scratch is idle now |
| 1490 | if (context_.scratch_) context_.scratch_->forget(progress_); | 1517 | if (context_.scratch_) context_.scratch_->forget(progress_); |
| 1491 | } | 1518 | } |
| 1519 | if (progress_) { | ||
| 1520 | // This queue is idle, so whatever initialisation it published (storage images, zero-filled buffers) has | ||
| 1521 | // finished: the next submission on another queue must not wait on a semaphore that is about to go. | ||
| 1522 | std::lock_guard lock(context_.storage_mutex_); | ||
| 1523 | if (context_.storage_init_semaphore_ == progress_) context_.storage_init_semaphore_ = VK_NULL_HANDLE; | ||
| 1524 | } | ||
| 1492 | if (pool_) vk.vkDestroyCommandPool(context_.device(), pool_, nullptr); | 1525 | if (pool_) vk.vkDestroyCommandPool(context_.device(), pool_, nullptr); |
| 1493 | if (progress_) vk.vkDestroySemaphore(context_.device(), progress_, nullptr); | 1526 | if (progress_) vk.vkDestroySemaphore(context_.device(), progress_, nullptr); |
| 1494 | for (auto& slot : buffers_) free_events_.insert(free_events_.end(), slot.events.begin(), slot.events.end()); | 1527 | for (auto& slot : buffers_) free_events_.insert(free_events_.end(), slot.events.begin(), slot.events.end()); |
| @@ -1690,6 +1723,7 @@ private: | |||
| 1690 | if (const auto* p = std::get_if<Predication>(&command); p && p->buffer) ++captures; | 1723 | if (const auto* p = std::get_if<Predication>(&command); p && p->buffer) ++captures; |
| 1691 | std::unique_ptr<PredicateReducer::Batch> batch; | 1724 | std::unique_ptr<PredicateReducer::Batch> batch; |
| 1692 | std::unique_ptr<PredicatedBufferCopier::Batch> copy_batch; | 1725 | std::unique_ptr<PredicatedBufferCopier::Batch> copy_batch; |
| 1726 | std::unique_ptr<IndirectDispatchCounter::Batch> counted_batch; | ||
| 1693 | if (captures) { | 1727 | if (captures) { |
| 1694 | if (kind_ == QueueKind::copy || !context_.predicate_reducer_ || family_ != context_.predicate_family_) | 1728 | if (kind_ == QueueKind::copy || !context_.predicate_reducer_ || family_ != context_.predicate_family_) |
| 1695 | return ReplayResult::unsupported; | 1729 | return ReplayResult::unsupported; |
| @@ -1727,6 +1761,19 @@ private: | |||
| 1727 | return context_.scratch_->get(bytes, buffer, offset); | 1761 | return context_.scratch_->get(bytes, buffer, offset); |
| 1728 | }; | 1762 | }; |
| 1729 | } | 1763 | } |
| 1764 | if (kind_ != QueueKind::copy && context_.counted_dispatch_) { | ||
| 1765 | replay.prepare_counted_dispatch = [this, &tracker_lock, &counted_batch]( | ||
| 1766 | VkBuffer args, VkDeviceSize args_offset, VkBuffer count, VkDeviceSize count_offset, | ||
| 1767 | std::uint32_t stride, std::uint32_t maximum, CountedDispatch& out) { | ||
| 1768 | // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation. | ||
| 1769 | if (!tracker_lock.owns_lock()) tracker_lock.lock(); | ||
| 1770 | if (!counted_batch) counted_batch = context_.counted_dispatch_->batch(); | ||
| 1771 | return counted_batch->prepare(args, args_offset, count, count_offset, stride, maximum, out); | ||
| 1772 | }; | ||
| 1773 | replay.emit_counted_dispatch = [this](VkCommandBuffer cb, const CountedDispatch& job) { | ||
| 1774 | context_.counted_dispatch_->emit(cb, job); | ||
| 1775 | }; | ||
| 1776 | } | ||
| 1730 | if (context_.depth24_ && !transfer_only) { | 1777 | if (context_.depth24_ && !transfer_only) { |
| 1731 | replay.depth24_prepare = [this, &tracker_lock, &depth24_guard](Depth24Job& job, | 1778 | replay.depth24_prepare = [this, &tracker_lock, &depth24_guard](Depth24Job& job, |
| 1732 | std::vector<Depth24Job>& parts) { | 1779 | std::vector<Depth24Job>& parts) { |
| @@ -1871,6 +1918,7 @@ private: | |||
| 1871 | runs_shaders |= std::holds_alternative<Dispatch>(command) || std::holds_alternative<Draw>(command) || | 1918 | runs_shaders |= std::holds_alternative<Dispatch>(command) || std::holds_alternative<Draw>(command) || |
| 1872 | std::holds_alternative<ExecuteIndirect>(command); | 1919 | std::holds_alternative<ExecuteIndirect>(command); |
| 1873 | std::vector<ResourceId> storage_images; | 1920 | std::vector<ResourceId> storage_images; |
| 1921 | std::vector<VulkanContext::PendingZero> zero_buffers; | ||
| 1874 | { | 1922 | { |
| 1875 | std::lock_guard lock(context_.storage_mutex_); | 1923 | std::lock_guard lock(context_.storage_mutex_); |
| 1876 | if (context_.storage_init_semaphore_ && context_.storage_init_semaphore_ != progress_ && | 1924 | if (context_.storage_init_semaphore_ && context_.storage_init_semaphore_ != progress_ && |
| @@ -1882,6 +1930,16 @@ private: | |||
| 1882 | if (kind_ != QueueKind::copy && runs_shaders) | 1930 | if (kind_ != QueueKind::copy && runs_shaders) |
| 1883 | storage_images.assign(context_.storage_pending_.begin(), context_.storage_pending_.end()); | 1931 | storage_images.assign(context_.storage_pending_.begin(), context_.storage_pending_.end()); |
| 1884 | if (!storage_images.empty()) context_.storage_pending_.clear(); | 1932 | if (!storage_images.empty()) context_.storage_pending_.clear(); |
| 1933 | zero_buffers.swap(context_.zero_pending_); // any queue can fill a buffer | ||
| 1934 | } | ||
| 1935 | for (const auto& zero : zero_buffers) | ||
| 1936 | context_.vk.vkCmdFillBuffer(command_buffer, zero.buffer, 0, VK_WHOLE_SIZE, 0); | ||
| 1937 | if (!zero_buffers.empty()) { | ||
| 1938 | VkMemoryBarrier filled{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; | ||
| 1939 | filled.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; | ||
| 1940 | filled.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT; | ||
| 1941 | context_.vk.vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, | ||
| 1942 | VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 1, &filled, 0, nullptr, 0, nullptr); | ||
| 1885 | } | 1943 | } |
| 1886 | for (const ResourceId id : storage_images) { | 1944 | for (const ResourceId id : storage_images) { |
| 1887 | const ResourceBinding* image = context_.resolve(id); | 1945 | const ResourceBinding* image = context_.resolve(id); |
| @@ -1937,11 +1995,13 @@ private: | |||
| 1937 | wait_values_.push_back(submitted_); | 1995 | wait_values_.push_back(submitted_); |
| 1938 | } | 1996 | } |
| 1939 | const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0); | 1997 | const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0); |
| 1940 | if (!submitted && !storage_images.empty()) { // not initialized after all: try again with the next submission | 1998 | if (!submitted && (!storage_images.empty() || !zero_buffers.empty())) { |
| 1999 | // not initialized after all: try again with the next submission | ||
| 1941 | std::lock_guard lock(context_.storage_mutex_); | 2000 | std::lock_guard lock(context_.storage_mutex_); |
| 1942 | context_.storage_pending_.insert(storage_images.begin(), storage_images.end()); | 2001 | context_.storage_pending_.insert(storage_images.begin(), storage_images.end()); |
| 2002 | context_.zero_pending_.insert(context_.zero_pending_.end(), zero_buffers.begin(), zero_buffers.end()); | ||
| 1943 | } | 2003 | } |
| 1944 | if (submitted && !storage_images.empty()) { | 2004 | if (submitted && (!storage_images.empty() || !zero_buffers.empty())) { |
| 1945 | std::lock_guard lock(context_.storage_mutex_); | 2005 | std::lock_guard lock(context_.storage_mutex_); |
| 1946 | context_.storage_init_semaphore_ = progress_; | 2006 | context_.storage_init_semaphore_ = progress_; |
| 1947 | context_.storage_init_value_ = submitted_; | 2007 | context_.storage_init_value_ = submitted_; |
| @@ -1956,6 +2016,7 @@ private: | |||
| 1956 | context_.tracker_ = std::move(next_tracker); | 2016 | context_.tracker_ = std::move(next_tracker); |
| 1957 | slot->predicate = std::move(batch); | 2017 | slot->predicate = std::move(batch); |
| 1958 | slot->predicated_copy = std::move(copy_batch); | 2018 | slot->predicated_copy = std::move(copy_batch); |
| 2019 | slot->counted_dispatch = std::move(counted_batch); | ||
| 1959 | queries.commit(); | 2020 | queries.commit(); |
| 1960 | slot->segments = std::move(queries.retained); | 2021 | slot->segments = std::move(queries.retained); |
| 1961 | } else { | 2022 | } else { |
| @@ -2110,6 +2171,7 @@ private: | |||
| 2110 | std::vector<std::shared_ptr<const OcclusionSegmentPool>> segments; | 2171 | std::vector<std::shared_ptr<const OcclusionSegmentPool>> segments; |
| 2111 | std::vector<VkEvent> events; // order_timestamp_copy's, reset and reused once the slot completes | 2172 | std::vector<VkEvent> events; // order_timestamp_copy's, reset and reused once the slot completes |
| 2112 | std::unique_ptr<PredicatedBufferCopier::Batch> predicated_copy; | 2173 | std::unique_ptr<PredicatedBufferCopier::Batch> predicated_copy; |
| 2174 | std::unique_ptr<IndirectDispatchCounter::Batch> counted_dispatch; | ||
| 2113 | std::unique_ptr<PredicateReducer::Batch> predicate; // retained until this slot completes | 2175 | std::unique_ptr<PredicateReducer::Batch> predicate; // retained until this slot completes |
| 2114 | }; | 2176 | }; |
| 2115 | 2177 | ||
| @@ -2228,6 +2290,7 @@ private: | |||
| 2228 | if (context_.vk.vkResetCommandBuffer(reuse->buffer, 0) != VK_SUCCESS) return nullptr; | 2290 | if (context_.vk.vkResetCommandBuffer(reuse->buffer, 0) != VK_SUCCESS) return nullptr; |
| 2229 | reuse->predicate.reset(); | 2291 | reuse->predicate.reset(); |
| 2230 | reuse->predicated_copy.reset(); | 2292 | reuse->predicated_copy.reset(); |
| 2293 | reuse->counted_dispatch.reset(); | ||
| 2231 | reuse->ticket = UINT64_MAX; // in use until submitted | 2294 | reuse->ticket = UINT64_MAX; // in use until submitted |
| 2232 | return reuse; | 2295 | return reuse; |
| 2233 | } | 2296 | } |
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 | |||
| 16 | namespace leonida { | ||
| 17 | |||
| 18 | struct 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 | |||
| 28 | class IndirectDispatchCounter { | ||
| 29 | public: | ||
| 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 | |||
| 152 | private: | ||
| 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 = ⦥ | ||
| 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. | ||
| 62 | inline 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 4185d6ff8..d5effb830 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. |
| 723 | struct QueryPool { | 724 | struct 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 |
| @@ -926,6 +938,7 @@ struct Prepared { | |||
| 926 | std::uint32_t statistics_begin = PreparedQuery::no_segment; | 938 | std::uint32_t statistics_begin = PreparedQuery::no_segment; |
| 927 | PredicateCapture predicate; | 939 | PredicateCapture predicate; |
| 928 | std::vector<PredicatedCopyDispatch> predicated_copy; | 940 | std::vector<PredicatedCopyDispatch> predicated_copy; |
| 941 | CountedDispatch counted_dispatch; | ||
| 929 | ResourceBinding binding; | 942 | ResourceBinding binding; |
| 930 | VkImageSubresourceRange range{}; // the barrier range, or the cleared view (cleared aspects only) | 943 | VkImageSubresourceRange range{}; // the barrier range, or the cleared view (cleared aspects only) |
| 931 | VkImageView view = VK_NULL_HANDLE; | 944 | VkImageView view = VK_NULL_HANDLE; |
| @@ -937,6 +950,7 @@ struct Prepared { | |||
| 937 | std::vector<VkBufferCopy> buffer_copies; | 950 | std::vector<VkBufferCopy> buffer_copies; |
| 938 | std::vector<VkBufferImageCopy> buffer_image_copies; // one direction, given by which side is an image | 951 | std::vector<VkBufferImageCopy> buffer_image_copies; // one direction, given by which side is an image |
| 939 | std::vector<VkImageCopy> image_copies; | 952 | std::vector<VkImageCopy> image_copies; |
| 953 | bool same_copy_subresource = false; | ||
| 940 | VkImageResolve resolve{}; // resolves | 954 | VkImageResolve resolve{}; // resolves |
| 941 | // Depth or stencil resolves: the mode, and the destination view (`view` is the source's). | 955 | // Depth or stencil resolves: the mode, and the destination view (`view` is the source's). |
| 942 | VkResolveModeFlagBits resolve_mode = VK_RESOLVE_MODE_NONE; | 956 | VkResolveModeFlagBits resolve_mode = VK_RESOLVE_MODE_NONE; |
| @@ -1544,6 +1558,8 @@ inline ReplayResult prepare_texture_copy(const CopyTexture& copy, Prepared& p) { | |||
| 1544 | p.binding.volume != p.source.volume || p.binding.samples != p.source.samples || | 1558 | p.binding.volume != p.source.volume || p.binding.samples != p.source.samples || |
| 1545 | p.binding.rgb96 != p.source.rgb96) | 1559 | p.binding.rgb96 != p.source.rgb96) |
| 1546 | return ReplayResult::invalid_copy; | 1560 | return ReplayResult::invalid_copy; |
| 1561 | p.same_copy_subresource = p.source.image == p.binding.image && src.aspectMask == dst.aspectMask && | ||
| 1562 | src.baseMipLevel == dst.baseMipLevel && src.baseArrayLayer == dst.baseArrayLayer; | ||
| 1547 | const VkExtent2D from = mip_extent(p.source, src.baseMipLevel), to = mip_extent(p.binding, dst.baseMipLevel); | 1563 | const VkExtent2D from = mip_extent(p.source, src.baseMipLevel), to = mip_extent(p.binding, dst.baseMipLevel); |
| 1548 | const auto from_depth = std::max(1u, p.source.depth >> src.baseMipLevel); | 1564 | const auto from_depth = std::max(1u, p.source.depth >> src.baseMipLevel); |
| 1549 | const auto to_depth = std::max(1u, p.binding.depth >> dst.baseMipLevel); | 1565 | const auto to_depth = std::max(1u, p.binding.depth >> dst.baseMipLevel); |
| @@ -1568,21 +1584,37 @@ inline ReplayResult prepare_texture_copy(const CopyTexture& copy, Prepared& p) { | |||
| 1568 | return ReplayResult::invalid_copy; | 1584 | return ReplayResult::invalid_copy; |
| 1569 | const std::uint32_t w = std::min(padded(box.right - box.left), from.width - box.left); | 1585 | const std::uint32_t w = std::min(padded(box.right - box.left), from.width - box.left); |
| 1570 | const std::uint32_t h = std::min(padded(box.bottom - box.top), from.height - box.top); | 1586 | const std::uint32_t h = std::min(padded(box.bottom - box.top), from.height - box.top); |
| 1571 | // shortcut: into a BC mip whose edge block is partial, Vulkan's extent cannot reach the padded edge; such | 1587 | const VkImageCopy region{{src.aspectMask, src.baseMipLevel, src.baseArrayLayer, 1}, |
| 1572 | // a copy is refused until it is staged through a buffer. | 1588 | {std::int32_t(box.left), std::int32_t(box.top), std::int32_t(box.front)}, |
| 1573 | if (dst_block > 1 && (copy.x + w * dst_block > to.width || copy.y + h * dst_block > to.height)) | 1589 | {dst.aspectMask, dst.baseMipLevel, dst.baseArrayLayer, 1}, |
| 1574 | return ReplayResult::invalid_copy; | 1590 | {std::int32_t(copy.x), std::int32_t(copy.y), std::int32_t(copy.z)}, |
| 1575 | p.image_copies.push_back({{src.aspectMask, src.baseMipLevel, src.baseArrayLayer, 1}, | 1591 | {w, h, box.back - box.front}}; |
| 1576 | {std::int32_t(box.left), std::int32_t(box.top), std::int32_t(box.front)}, | 1592 | const std::uint32_t dst_w = w * dst_block, dst_h = h * dst_block; |
| 1577 | {dst.aspectMask, dst.baseMipLevel, dst.baseArrayLayer, 1}, | 1593 | if (dst_block > 1 && (copy.x + dst_w > to.width || copy.y + dst_h > to.height)) { |
| 1578 | {std::int32_t(copy.x), std::int32_t(copy.y), std::int32_t(copy.z)}, | 1594 | // Each uncompressed texel supplies a whole BC block. Keep the same scratch row and slice strides |
| 1579 | {w, h, box.back - box.front}}); | 1595 | // in bytes on both sides, with a destination extent clipped to the actual mip. |
| 1596 | const VkBufferImageCopy read{0, w, h, region.srcSubresource, region.srcOffset, region.extent}; | ||
| 1597 | const VkBufferImageCopy write{0, dst_w, dst_h, region.dstSubresource, region.dstOffset, | ||
| 1598 | {std::min(dst_w, to.width - copy.x), std::min(dst_h, to.height - copy.y), region.extent.depth}}; | ||
| 1599 | p.staged_reads.push_back(read); | ||
| 1600 | p.staged_writes.push_back(write); | ||
| 1601 | } else { | ||
| 1602 | p.image_copies.push_back(region); | ||
| 1603 | } | ||
| 1580 | p.range = dst; | 1604 | p.range = dst; |
| 1581 | p.source_range = src; | 1605 | p.source_range = src; |
| 1582 | return ReplayResult::success; | 1606 | return ReplayResult::success; |
| 1583 | } | 1607 | } |
| 1584 | std::uint32_t w = box.right - box.left, h = box.bottom - box.top; | 1608 | std::uint32_t w = box.right - box.left, h = box.bottom - box.top; |
| 1585 | const std::uint32_t d = box.back - box.front; | 1609 | const std::uint32_t d = box.back - box.front; |
| 1610 | if (p.same_copy_subresource) { | ||
| 1611 | const auto intersects = [](std::uint32_t a, std::uint32_t b, std::uint32_t size) { | ||
| 1612 | return (a < b ? b - a : a - b) < size; | ||
| 1613 | }; | ||
| 1614 | if (intersects(box.left, copy.x, padded(w)) && intersects(box.top, copy.y, padded(h)) && | ||
| 1615 | intersects(box.front, copy.z, d)) | ||
| 1616 | return ReplayResult::invalid_copy; | ||
| 1617 | } | ||
| 1586 | if (block > 1) { | 1618 | if (block > 1) { |
| 1587 | // D3D12 copies whole blocks: the box is rounded up to blocks and must fit the destination's padded mip. | 1619 | // D3D12 copies whole blocks: the box is rounded up to blocks and must fit the destination's padded mip. |
| 1588 | // Vulkan takes an extent that is a block multiple or reaches the edge of each image separately, so the | 1620 | // Vulkan takes an extent that is a block multiple or reaches the edge of each image separately, so the |
| @@ -1934,8 +1966,9 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct | |||
| 1934 | }; | 1966 | }; |
| 1935 | 1967 | ||
| 1936 | p.colors.assign(pipeline->color_formats.size(), {}); | 1968 | p.colors.assign(pipeline->color_formats.size(), {}); |
| 1937 | for (std::size_t slot = 0; slot < draw.render_target_count && slot < draw.render_targets.size() && slot < p.colors.size(); ++slot) { | 1969 | const std::uint32_t render_target_count = draw.views ? draw.views->render_target_count : 0; |
| 1938 | const TargetView& target = draw.render_targets[slot]; | 1970 | for (std::size_t slot = 0; slot < render_target_count && slot < p.colors.size(); ++slot) { |
| 1971 | const TargetView& target = draw.views->render_targets[slot]; | ||
| 1939 | if (!target.resource) continue; | 1972 | if (!target.resource) continue; |
| 1940 | const ResourceBinding* binding = resolve(target.resource); | 1973 | const ResourceBinding* binding = resolve(target.resource); |
| 1941 | if (!binding) return ReplayResult::unresolved_resource; | 1974 | if (!binding) return ReplayResult::unresolved_resource; |
| @@ -1993,7 +2026,8 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct | |||
| 1993 | p.vertex_offsets.resize(slot + 1, 0); | 2026 | p.vertex_offsets.resize(slot + 1, 0); |
| 1994 | p.vertex_sizes.resize(slot + 1, VK_WHOLE_SIZE); | 2027 | p.vertex_sizes.resize(slot + 1, VK_WHOLE_SIZE); |
| 1995 | p.vertex_strides.resize(slot + 1, 0); | 2028 | p.vertex_strides.resize(slot + 1, 0); |
| 1996 | const bool bound = slot < draw.vertex_buffers.size() && draw.vertex_buffers[slot].va; | 2029 | const bool bound = draw.views && slot < draw.views->vertex_buffers.size() && |
| 2030 | draw.views->vertex_buffers[slot].va; | ||
| 1997 | if (!bound) { | 2031 | if (!bound) { |
| 1998 | if (!vk.zero_buffer) return ReplayResult::unresolved_resource; | 2032 | if (!vk.zero_buffer) return ReplayResult::unresolved_resource; |
| 1999 | p.vertex_buffers[slot] = vk.zero_buffer; | 2033 | p.vertex_buffers[slot] = vk.zero_buffer; |
| @@ -2002,7 +2036,7 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct | |||
| 2002 | p.vertex_strides[slot] = 0; | 2036 | p.vertex_strides[slot] = 0; |
| 2003 | continue; | 2037 | continue; |
| 2004 | } | 2038 | } |
| 2005 | const VertexBufferView& view = draw.vertex_buffers[slot]; | 2039 | const VertexBufferView& view = draw.views->vertex_buffers[slot]; |
| 2006 | std::uint64_t size = view.size; | 2040 | std::uint64_t size = view.size; |
| 2007 | if (!vk.buffer_at(view.va, size, p.vertex_buffers[slot], p.vertex_offsets[slot])) | 2041 | if (!vk.buffer_at(view.va, size, p.vertex_buffers[slot], p.vertex_offsets[slot])) |
| 2008 | return ReplayResult::unresolved_resource; | 2042 | return ReplayResult::unresolved_resource; |
| @@ -2163,14 +2197,16 @@ inline void plan_statistics_segments(PreparedList& out) { | |||
| 2163 | std::size_t next_query = 0; | 2197 | std::size_t next_query = 0; |
| 2164 | for (std::size_t i = 0; i < out.commands.size(); ++i) { | 2198 | for (std::size_t i = 0; i < out.commands.size(); ++i) { |
| 2165 | auto& p = out.commands[i]; | 2199 | auto& p = out.commands[i]; |
| 2166 | if (begin && (p.predicate.scratch || !p.predicated_copy.empty() || p.has_depth24)) | 2200 | if (begin && (p.predicate.scratch || !p.predicated_copy.empty() || p.has_depth24 || |
| 2201 | p.counted_dispatch.indirect)) | ||
| 2167 | inner.push_back({&p.statistics_end, &p.statistics_begin}); | 2202 | inner.push_back({&p.statistics_end, &p.statistics_begin}); |
| 2168 | if (next_query == out.queries.size() || out.queries[next_query].command != i) continue; | 2203 | if (next_query == out.queries.size() || out.queries[next_query].command != i) continue; |
| 2169 | auto& query = out.queries[next_query++]; | 2204 | auto& query = out.queries[next_query++]; |
| 2170 | const Command& command = out.list->commands()[i]; | 2205 | const Command& command = out.list->commands()[i]; |
| 2171 | const auto range = query_range(command); | 2206 | const auto range = query_range(command); |
| 2172 | if (std::holds_alternative<ResolveQueries>(command)) { | 2207 | if (std::holds_alternative<ResolveQueries>(command)) { |
| 2173 | if (begin && range.type != d3d12_query::timestamp) | 2208 | // A stream-output resolve only fills zeros (no dispatch), so it needs no split. |
| 2209 | if (begin && range.type != d3d12_query::timestamp && !is_so_statistics(range.type)) | ||
| 2174 | inner.push_back({&query.statistics_end, &query.statistics_begin}); | 2210 | inner.push_back({&query.statistics_end, &query.statistics_begin}); |
| 2175 | } else if (range.type == d3d12_query::pipeline_statistics) { | 2211 | } else if (range.type == d3d12_query::pipeline_statistics) { |
| 2176 | if (std::holds_alternative<BeginQuery>(command)) { | 2212 | if (std::holds_alternative<BeginQuery>(command)) { |
| @@ -2212,7 +2248,8 @@ inline ReplayResult plan_overlapping_statistics_segments(PreparedList& out) { | |||
| 2212 | if (!query) { | 2248 | if (!query) { |
| 2213 | // A helper dispatch while a query runs would be counted into it (D3D-162): close the shared physical | 2249 | // A helper dispatch while a query runs would be counted into it (D3D-162): close the shared physical |
| 2214 | // segment before it and open a new one after, the way resolves do. | 2250 | // segment before it and open a new one after, the way resolves do. |
| 2215 | if (!active.empty() && (p.predicate.scratch || !p.predicated_copy.empty() || p.has_depth24)) { | 2251 | if (!active.empty() && (p.predicate.scratch || !p.predicated_copy.empty() || p.has_depth24 || |
| 2252 | p.counted_dispatch.indirect)) { | ||
| 2216 | p.statistics_end = current; | 2253 | p.statistics_end = current; |
| 2217 | current = out.statistics_segment_count++; | 2254 | current = out.statistics_segment_count++; |
| 2218 | p.statistics_begin = current; | 2255 | p.statistics_begin = current; |
| @@ -2703,6 +2740,8 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 2703 | } else if (range.type == d3d12_query::binary_occlusion) { | 2740 | } else if (range.type == d3d12_query::binary_occlusion) { |
| 2704 | overlaps |= begin && (ordinary_active || binary_active); | 2741 | overlaps |= begin && (ordinary_active || binary_active); |
| 2705 | if (begin) ++binary_active; else --binary_active; | 2742 | if (begin) ++binary_active; else --binary_active; |
| 2743 | } else if (is_so_statistics(range.type)) { | ||
| 2744 | // No Vulkan query runs for it (QueryPool::pool is null), so it overlaps nothing. | ||
| 2706 | } else { | 2745 | } else { |
| 2707 | statistics_overlaps |= begin && statistics_active_count; | 2746 | statistics_overlaps |= begin && statistics_active_count; |
| 2708 | if (begin) ++statistics_active_count; else --statistics_active_count; | 2747 | if (begin) ++statistics_active_count; else --statistics_active_count; |
| @@ -2742,10 +2781,19 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 2742 | if (!detail::indirect_range(*cnt, ind->count_offset, sizeof(std::uint32_t))) | 2781 | if (!detail::indirect_range(*cnt, ind->count_offset, sizeof(std::uint32_t))) |
| 2743 | return ReplayResult::invalid_indirect_arguments; | 2782 | return ReplayResult::invalid_indirect_arguments; |
| 2744 | p.source = *cnt; | 2783 | p.source = *cnt; |
| 2745 | if ((ind->kind == IndirectKind::draw && !vk.draw_indirect_count) || | 2784 | if (ind->kind == IndirectKind::dispatch) { |
| 2746 | (ind->kind == IndirectKind::draw_indexed && !vk.draw_indexed_indirect_count) || | 2785 | // Vulkan lacks vkCmdDispatchIndirectCount. Copy the GPU-visible commands to private scratch |
| 2747 | ind->kind == IndirectKind::dispatch) | 2786 | // and replace commands past min(count, max_count) with zero-group dispatches. |
| 2787 | if (!ind->pipeline || !vk.dispatch_indirect || !vk.prepare_counted_dispatch || | ||
| 2788 | !vk.emit_counted_dispatch || (statistics_active && !statistics_helpers) || | ||
| 2789 | !vk.prepare_counted_dispatch(p.binding.buffer, p.binding.buffer_offset + ind->argument_offset, | ||
| 2790 | p.source.buffer, p.source.buffer_offset + ind->count_offset, | ||
| 2791 | ind->stride, ind->max_count, p.counted_dispatch)) | ||
| 2792 | return ReplayResult::unsupported; | ||
| 2793 | } else if ((ind->kind == IndirectKind::draw && !vk.draw_indirect_count) || | ||
| 2794 | (ind->kind == IndirectKind::draw_indexed && !vk.draw_indexed_indirect_count)) { | ||
| 2748 | return ReplayResult::unsupported; | 2795 | return ReplayResult::unsupported; |
| 2796 | } | ||
| 2749 | } else { | 2797 | } else { |
| 2750 | if ((ind->kind == IndirectKind::draw && !vk.draw_indirect) || | 2798 | if ((ind->kind == IndirectKind::draw && !vk.draw_indirect) || |
| 2751 | (ind->kind == IndirectKind::draw_indexed && !vk.draw_indexed_indirect) || | 2799 | (ind->kind == IndirectKind::draw_indexed && !vk.draw_indexed_indirect) || |
| @@ -2980,6 +3028,9 @@ inline void emit_query(const PreparedList& list, const detail::PreparedQuery& qu | |||
| 2980 | begin_statistics(); | 3028 | begin_statistics(); |
| 2981 | return; | 3029 | return; |
| 2982 | } | 3030 | } |
| 3031 | // A heap without a Vulkan pool (stream-output statistics: the layer has no stream output) runs nothing for | ||
| 3032 | // BeginQuery and EndQuery; its resolves were planned as zero fills. | ||
| 3033 | if (!heap.pool && !std::holds_alternative<ResolveQueries>(command)) return; | ||
| 2983 | if (const auto* begin = std::get_if<BeginQuery>(&command)) { | 3034 | if (const auto* begin = std::get_if<BeginQuery>(&command)) { |
| 2984 | vk.reset_query_pool(cb, heap.pool, begin->index, 1); | 3035 | vk.reset_query_pool(cb, heap.pool, begin->index, 1); |
| 2985 | const bool precise = begin->type == d3d12_query::occlusion && heap.precise; | 3036 | const bool precise = begin->type == d3d12_query::occlusion && heap.precise; |
| @@ -3346,10 +3397,14 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c | |||
| 3346 | vk.copy_buffer_to_image(command_buffer, p.staged, p.binding.image, dst_layout, | 3397 | vk.copy_buffer_to_image(command_buffer, p.staged, p.binding.image, dst_layout, |
| 3347 | std::uint32_t(p.staged_writes.size()), p.staged_writes.data()); | 3398 | std::uint32_t(p.staged_writes.size()), p.staged_writes.data()); |
| 3348 | } else if (!p.image_copies.empty()) { | 3399 | } else if (!p.image_copies.empty()) { |
| 3400 | // A subresource can be both the source and destination only in a shared layout. | ||
| 3401 | const bool self = p.same_copy_subresource; | ||
| 3349 | const VkImageLayout src_layout = detail::copy_layout( | 3402 | const VkImageLayout src_layout = detail::copy_layout( |
| 3350 | vk, command_buffer, p.source, src_id, detail::planes_for_layout(p.source, p.source_range, separate), | 3403 | vk, command_buffer, p.source, src_id, detail::planes_for_layout(p.source, p.source_range, separate), |
| 3351 | VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_TRANSFER_READ_BIT, tracker); | 3404 | self ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, |
| 3352 | const VkImageLayout dst_layout = detail::copy_layout( | 3405 | self ? VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT : VK_ACCESS_TRANSFER_READ_BIT, |
| 3406 | tracker); | ||
| 3407 | const VkImageLayout dst_layout = self ? src_layout : detail::copy_layout( | ||
| 3353 | vk, command_buffer, p.binding, dst_id, detail::planes_for_layout(p.binding, p.range, separate), | 3408 | vk, command_buffer, p.binding, dst_id, detail::planes_for_layout(p.binding, p.range, separate), |
| 3354 | VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, tracker); | 3409 | VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, tracker); |
| 3355 | const auto count = std::uint32_t(p.image_copies.size()); | 3410 | const auto count = std::uint32_t(p.image_copies.size()); |
| @@ -3562,7 +3617,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c | |||
| 3562 | vk.copy_buffer(command_buffer, p.source.buffer, p.binding.buffer, 1, p.buffer_copies.data()); | 3617 | vk.copy_buffer(command_buffer, p.source.buffer, p.binding.buffer, 1, p.buffer_copies.data()); |
| 3563 | } else if (const auto* ind = std::get_if<ExecuteIndirect>(&command)) { | 3618 | } else if (const auto* ind = std::get_if<ExecuteIndirect>(&command)) { |
| 3564 | const VkDeviceSize arguments = p.binding.buffer_offset + ind->argument_offset; | 3619 | const VkDeviceSize arguments = p.binding.buffer_offset + ind->argument_offset; |
| 3565 | if (ind->count_buffer) { | 3620 | if (ind->count_buffer && ind->kind != IndirectKind::dispatch) { |
| 3566 | const VkDeviceSize count = p.source.buffer_offset + ind->count_offset; | 3621 | const VkDeviceSize count = p.source.buffer_offset + ind->count_offset; |
| 3567 | if (ind->kind == IndirectKind::draw) { | 3622 | if (ind->kind == IndirectKind::draw) { |
| 3568 | vk.draw_indirect_count(command_buffer, p.binding.buffer, arguments, p.source.buffer, | 3623 | vk.draw_indirect_count(command_buffer, p.binding.buffer, arguments, p.source.buffer, |
| @@ -3577,6 +3632,12 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c | |||
| 3577 | } else if (ind->kind == IndirectKind::draw_indexed) { | 3632 | } else if (ind->kind == IndirectKind::draw_indexed) { |
| 3578 | vk.draw_indexed_indirect(command_buffer, p.binding.buffer, arguments, ind->max_count, ind->stride); | 3633 | vk.draw_indexed_indirect(command_buffer, p.binding.buffer, arguments, ind->max_count, ind->stride); |
| 3579 | } else if (ind->kind == IndirectKind::dispatch) { | 3634 | } else if (ind->kind == IndirectKind::dispatch) { |
| 3635 | if (ind->count_buffer) { | ||
| 3636 | // No D3D12 query must count this internal compute pass as an application dispatch. | ||
| 3637 | end_statistics(); | ||
| 3638 | vk.emit_counted_dispatch(command_buffer, p.counted_dispatch); | ||
| 3639 | begin_statistics(); | ||
| 3640 | } | ||
| 3580 | if (ind->pipeline) { | 3641 | if (ind->pipeline) { |
| 3581 | ShaderUserData data{}; | 3642 | ShaderUserData data{}; |
| 3582 | std::copy(ind->user_data.begin(), ind->user_data.end(), data.s); | 3643 | std::copy(ind->user_data.begin(), ind->user_data.end(), data.s); |
| @@ -3590,8 +3651,10 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c | |||
| 3590 | &data); | 3651 | &data); |
| 3591 | } | 3652 | } |
| 3592 | for (std::uint32_t k = 0; k < ind->max_count; ++k) { | 3653 | for (std::uint32_t k = 0; k < ind->max_count; ++k) { |
| 3593 | vk.dispatch_indirect(command_buffer, p.binding.buffer, | 3654 | vk.dispatch_indirect(command_buffer, |
| 3594 | arguments + VkDeviceSize(k) * ind->stride); | 3655 | ind->count_buffer ? p.counted_dispatch.indirect : p.binding.buffer, |
| 3656 | (ind->count_buffer ? p.counted_dispatch.offset + VkDeviceSize(k) * 12 | ||
| 3657 | : arguments + VkDeviceSize(k) * ind->stride)); | ||
| 3595 | } | 3658 | } |
| 3596 | } | 3659 | } |
| 3597 | } | 3660 | } |
| @@ -3758,18 +3821,33 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c | |||
| 3758 | } | 3821 | } |
| 3759 | 3822 | ||
| 3760 | // prepare + emit for one list. A failed replay leaves the command buffer and the tracker untouched. | 3823 | // prepare + emit for one list. A failed replay leaves the command buffer and the tracker untouched. |
| 3824 | // With `keep` and vk.create_segment_pool (and the sum helpers) set, overlapping occlusion or statistics queries get | ||
| 3825 | // segment pools as in the batched path; the caller holds `keep` until the command buffer has completed. | ||
| 3761 | template<typename Resolve> | 3826 | template<typename Resolve> |
| 3762 | ReplayResult replay(const CommandList& list, VkCommandBuffer command_buffer, Resolve&& resolve, | 3827 | ReplayResult replay(const CommandList& list, VkCommandBuffer command_buffer, Resolve&& resolve, |
| 3763 | const ReplayFunctions& vk, LayoutTracker* tracker = nullptr) { | 3828 | const ReplayFunctions& vk, LayoutTracker* tracker = nullptr, |
| 3829 | std::vector<std::shared_ptr<const OcclusionSegmentPool>>* keep = nullptr) { | ||
| 3764 | if (tracker && tracker->separate_depth_stencil_layouts() != vk.separate_depth_stencil_layouts) | 3830 | if (tracker && tracker->separate_depth_stencil_layouts() != vk.separate_depth_stencil_layouts) |
| 3765 | return ReplayResult::unsupported; | 3831 | return ReplayResult::unsupported; |
| 3832 | const bool pools = keep && vk.create_segment_pool && vk.sum_occlusion && vk.resolve_binary_occlusion && | ||
| 3833 | vk.sum_statistics && vk.sum_binary_occlusion; | ||
| 3766 | PreparedList prepared; | 3834 | PreparedList prepared; |
| 3767 | if (const auto result = prepare(list, resolve, vk, prepared); result != ReplayResult::success) return result; | 3835 | if (const auto result = prepare(list, resolve, vk, prepared, pools); result != ReplayResult::success) |
| 3836 | return result; | ||
| 3768 | if (tracker && zero_clear_unavailable(prepared, vk, *tracker)) return ReplayResult::unsupported; | 3837 | if (tracker && zero_clear_unavailable(prepared, vk, *tracker)) return ReplayResult::unsupported; |
| 3838 | std::shared_ptr<const OcclusionSegmentPool> physical, statistics; | ||
| 3839 | if (pools && prepared.segment_count && | ||
| 3840 | !(physical = vk.create_segment_pool(VK_QUERY_TYPE_OCCLUSION, prepared.segment_count))) | ||
| 3841 | return ReplayResult::unsupported; | ||
| 3842 | if (pools && prepared.statistics_segment_count && | ||
| 3843 | !(statistics = vk.create_segment_pool(VK_QUERY_TYPE_PIPELINE_STATISTICS, prepared.statistics_segment_count))) | ||
| 3844 | return ReplayResult::unsupported; | ||
| 3769 | QueryReplay queries; | 3845 | QueryReplay queries; |
| 3770 | if (const auto result = queries.plan(prepared); result != ReplayResult::success) return result; | 3846 | if (const auto result = queries.plan(prepared, physical, 0, pools, statistics, 0); result != ReplayResult::success) |
| 3847 | return result; | ||
| 3771 | emit(prepared, command_buffer, vk, tracker); | 3848 | emit(prepared, command_buffer, vk, tracker); |
| 3772 | queries.commit(); // the caller owns submission of the legacy command buffer | 3849 | queries.commit(); // the caller owns submission of the legacy command buffer |
| 3850 | if (keep) keep->insert(keep->end(), queries.retained.begin(), queries.retained.end()); | ||
| 3773 | return ReplayResult::success; | 3851 | return ReplayResult::success; |
| 3774 | } | 3852 | } |
| 3775 | 3853 | ||