upleb.uk

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

summaryrefslogtreecommitdiff
path: root/runtime/src
diff options
context:
space:
mode:
authorlumenpearson <139921639+lumenpearson@users.noreply.github.com>2026-11-22 23:25:25 +0300
committerlumenpearson <139921639+lumenpearson@users.noreply.github.com>2026-11-22 23:25:25 +0300
commitf324bfbc71f0eabf9515bcd7c8b7c9e4b89448bf (patch)
tree2db4ae6fd5412abbbc3e1894f8bc7ed88c8ae514 /runtime/src
parent18380c6d2baf1422109b369860a6e8be5e185b05 (diff)
parentf847748cc76bd3777f9c070c4034eb2fc1c04e64 (diff)
Merge upstream main into SHADER-537
Diffstat (limited to 'runtime/src')
-rw-r--r--runtime/src/command_list.h44
-rw-r--r--runtime/src/descriptor_table.h17
-rw-r--r--runtime/src/gfx10_tiling.h158
-rw-r--r--runtime/src/main.cpp2
-rw-r--r--runtime/src/pe_loader.cpp6
-rw-r--r--runtime/src/present_compose.comp130
-rw-r--r--runtime/src/present_compose.inc742
-rw-r--r--runtime/src/present_compose_spv.h11
-rw-r--r--runtime/src/queue_families.h48
-rw-r--r--runtime/src/resource_tiling.h15
-rw-r--r--runtime/src/root_signature.cpp4
-rw-r--r--runtime/src/shader_library.h27
-rw-r--r--runtime/src/spirv_f16_halves.h617
-rw-r--r--runtime/src/spirv_words.h26
-rw-r--r--runtime/src/vulkan_backend.h117
-rw-r--r--runtime/src/vulkan_present.h294
-rw-r--r--runtime/src/vulkan_present_compose.h257
-rw-r--r--runtime/src/vulkan_replay.h221
18 files changed, 2661 insertions, 75 deletions
diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h
index 2b6c03358..fcdc1ca33 100644
--- a/runtime/src/command_list.h
+++ b/runtime/src/command_list.h
@@ -395,25 +395,28 @@ struct IndexBufferView {
395// DrawInstanced / DrawIndexedInstanced, with everything they use captured when they are recorded: D3D12 reads 395// 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 396// 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. 397// the draw. resource 0 marks an unbound render-target slot or no depth buffer.
398// Render targets and vertex buffer views are inlined (8 simultaneous targets, 32 input slots), eliminating heap allocations
399// during command list recording (D3D-289).
398struct Draw { 400struct Draw {
399 std::uintptr_t pipeline; 401 std::uintptr_t pipeline = 0;
400 std::array<std::uint32_t, 32> user_data; 402 std::array<std::uint32_t, 32> user_data{};
401 std::vector<TargetView> render_targets; 403 std::array<TargetView, 8> render_targets{};
402 TargetView depth; 404 TargetView depth{};
403 std::vector<VertexBufferView> vertex_buffers; // by input slot 405 std::array<VertexBufferView, 32> vertex_buffers{}; // by input slot
404 IndexBufferView index; 406 IndexBufferView index{};
405 std::uint32_t topology; // D3D_PRIMITIVE_TOPOLOGY 407 std::uint32_t topology = 0; // D3D_PRIMITIVE_TOPOLOGY
406 Viewport viewport; // the first; more viewports are not modelled yet 408 Viewport viewport{}; // the first; more viewports are not modelled yet
407 Rect scissor; // the first; D3D12 always scissors 409 Rect scissor{}; // the first; D3D12 always scissors
408 std::array<float, 4> blend_factor; 410 std::array<float, 4> blend_factor{1, 1, 1, 1};
409 std::uint32_t stencil_front; 411 std::uint32_t stencil_front = 0;
410 std::uint32_t stencil_back; 412 std::uint32_t stencil_back = 0;
411 bool indexed; 413 bool indexed = false;
412 std::uint32_t count; // vertices or indices per instance 414 std::uint32_t count = 0; // vertices or indices per instance
413 std::uint32_t instances; 415 std::uint32_t instances = 0;
414 std::uint32_t first; // first vertex or first index 416 std::uint32_t first = 0; // first vertex or first index
415 std::int32_t base_vertex; 417 std::int32_t base_vertex = 0;
416 std::uint32_t first_instance; 418 std::uint32_t first_instance = 0;
419 std::uint32_t render_target_count = 8;
417}; 420};
418 421
419// D3D12_TEXTURE_DATA_PITCH_ALIGNMENT and D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT. 422// D3D12_TEXTURE_DATA_PITCH_ALIGNMENT and D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT.
@@ -715,6 +718,11 @@ public:
715 if (!draw.count || !draw.instances) return !closed_; 718 if (!draw.count || !draw.instances) return !closed_;
716 return append(draw); 719 return append(draw);
717 } 720 }
721 bool draw(Draw&& draw) {
722 if (!draw.pipeline) return false;
723 if (!draw.count || !draw.instances) return !closed_;
724 return append(std::move(draw));
725 }
718 726
719 // ClearRenderTargetView; the resource must be in render_target state at execution. No rects: the whole view. 727 // ClearRenderTargetView; the resource must be in render_target state at execution. No rects: the whole view.
720 bool clear_render_target(const TargetView& target, const ClearColor& color, std::span<const Rect> rects = {}) { 728 bool clear_render_target(const TargetView& target, const ClearColor& color, std::span<const Rect> rects = {}) {
diff --git a/runtime/src/descriptor_table.h b/runtime/src/descriptor_table.h
index 2b5b111f7..2b44d32df 100644
--- a/runtime/src/descriptor_table.h
+++ b/runtime/src/descriptor_table.h
@@ -10,6 +10,7 @@
10#include <cstring> 10#include <cstring>
11#include <mutex> 11#include <mutex>
12#include <span> 12#include <span>
13#include <stdexcept>
13#include <vector> 14#include <vector>
14 15
15namespace leonida { 16namespace leonida {
@@ -69,6 +70,8 @@ public:
69 enum class InsertResult { added, unchanged, replaced, added_with_relocation }; 70 enum class InsertResult { added, unchanged, replaced, added_with_relocation };
70 71
71 explicit DescriptorTable(std::uint32_t initial_capacity = 16) { 72 explicit DescriptorTable(std::uint32_t initial_capacity = 16) {
73 // Slots use nonnegative int indices internally. Larger powers also wrap the capacity counter.
74 if (initial_capacity > max_capacity) throw std::length_error("Descriptor table capacity exceeds slot range");
72 std::uint32_t cap = 16; 75 std::uint32_t cap = 16;
73 while (cap < initial_capacity) cap <<= 1; 76 while (cap < initial_capacity) cap <<= 1;
74 mask_ = cap - 1; 77 mask_ = cap - 1;
@@ -291,6 +294,17 @@ private:
291 continue; 294 continue;
292 } 295 }
293 296
297 // Nine distinct keys with the same full hash can never fit the shader's eight probes,
298 // regardless of capacity. Refuse before allocating ever larger tables.
299 if (empty_slot < 0) {
300 std::uint32_t same_hash = 0;
301 for (std::uint32_t k = 0; k < kDescriptorProbes; ++k) {
302 const auto& entry = entries_[(h + k) & mask_];
303 if (hash_descriptor_key(entry.key) == h) ++same_hash;
304 }
305 if (same_hash == kDescriptorProbes)
306 throw std::length_error("Descriptor hash collision exceeds shader probe limit");
307 }
294 const bool relocate = empty_slot < 0; 308 const bool relocate = empty_slot < 0;
295 std::uint32_t moved_to = 0; 309 std::uint32_t moved_to = 0;
296 if (relocate) empty_slot = make_probe_slot(entries_, h, &moved_to); 310 if (relocate) empty_slot = make_probe_slot(entries_, h, &moved_to);
@@ -332,6 +346,7 @@ private:
332 } 346 }
333 347
334 void grow_locked() { 348 void grow_locked() {
349 if (entries_.size() >= max_capacity) throw std::length_error("Descriptor table capacity exhausted");
335 std::uint32_t new_cap = static_cast<std::uint32_t>(entries_.size() * 2); 350 std::uint32_t new_cap = static_cast<std::uint32_t>(entries_.size() * 2);
336 while (true) { 351 while (true) {
337 std::vector<DescriptorEntry> new_entries(new_cap); 352 std::vector<DescriptorEntry> new_entries(new_cap);
@@ -364,10 +379,12 @@ private:
364 changed_slots_.clear(); 379 changed_slots_.clear();
365 break; 380 break;
366 } 381 }
382 if (new_cap >= max_capacity) throw std::length_error("Descriptor probe range exhausted");
367 new_cap *= 2; 383 new_cap *= 2;
368 } 384 }
369 } 385 }
370 386
387 static constexpr std::uint32_t max_capacity = std::uint32_t{1} << 31;
371 mutable std::mutex mutex_; 388 mutable std::mutex mutex_;
372 std::uint32_t mask_ = 15; 389 std::uint32_t mask_ = 15;
373 std::vector<DescriptorEntry> entries_; 390 std::vector<DescriptorEntry> entries_;
diff --git a/runtime/src/gfx10_tiling.h b/runtime/src/gfx10_tiling.h
new file mode 100644
index 000000000..d869d1102
--- /dev/null
+++ b/runtime/src/gfx10_tiling.h
@@ -0,0 +1,158 @@
1#pragma once
2
3#include <bit>
4#include <cstddef>
5#include <cstdint>
6#include <cstring>
7#include <limits>
8#include <span>
9
10namespace leonida::gfx10 {
11
12enum class TileMode { sw_4kb_s, sw_64kb_d };
13
14namespace tiling_detail {
15
16// Mesa addrlib GFX10_SW_4K_S_RBPLUS_PATINFO / GFX10_SW_64K_D_RBPLUS_PATINFO;
17// tools/ttpf_mips.py patterns, corpus validation in docs/textures.md. Zero bits address bytes within an element.
18inline constexpr int patterns_4k[5][12] = {
19 {1, 2, 3, 4, -1, -2, -3, -4, -5, 5, -6, 6},
20 {0, 1, 2, 3, -1, -2, -3, 4, -4, 5, -5, 6},
21 {0, 0, 1, 2, -1, -2, -3, 3, -4, 4, -5, 5},
22 {0, 0, 0, 1, -1, -2, 2, 3, -3, 4, -4, 5},
23 {0, 0, 0, 0, -1, -2, 1, 2, -3, 3, -4, 4}};
24inline constexpr int patterns_64k[5][16] = {
25 {1, 2, 3, -2, -1, -3, 4, -4, -5, 5, -6, 6, -7, 7, -8, 8},
26 {0, 1, 2, 3, -1, -2, -3, 4, -4, 5, -5, 6, -6, 7, -7, 8},
27 {0, 0, 1, 2, -1, -2, 3, -3, -4, 4, -5, 5, -6, 6, -7, 7},
28 {0, 0, 0, 1, -1, 2, 3, -2, -3, 4, -4, 5, -5, 6, -6, 7},
29 {0, 0, 0, 0, 1, -1, 2, -2, -3, 3, -4, 4, -5, 5, -6, 6}};
30
31inline bool overlap(std::span<const std::byte> source, std::span<std::byte> destination) {
32 const auto a = reinterpret_cast<std::uintptr_t>(source.data());
33 const auto b = reinterpret_cast<std::uintptr_t>(destination.data());
34 return a <= b ? b - a < source.size() : a - b < destination.size();
35}
36
37} // namespace tiling_detail
38
39// One standalone 2D level, no mip tail or tile XOR. BC formats use a compressed block as one element.
40class TiledSurface2D {
41public:
42 static bool make(TileMode mode, std::size_t element_bytes, std::size_t width, std::size_t height,
43 TiledSurface2D& out) {
44 if (!width || !height) return false;
45 unsigned index = 0;
46 switch (element_bytes) {
47 case 1: break;
48 case 2: index = 1; break;
49 case 4: index = 2; break;
50 case 8: index = 3; break;
51 case 16: index = 4; break;
52 default: return false;
53 }
54 TiledSurface2D next;
55 switch (mode) {
56 case TileMode::sw_4kb_s:
57 next.pattern_ = tiling_detail::patterns_4k[index];
58 next.bits_ = 12;
59 break;
60 case TileMode::sw_64kb_d:
61 next.pattern_ = tiling_detail::patterns_64k[index];
62 next.bits_ = 16;
63 break;
64 default: return false;
65 }
66 unsigned x_bits = 0, y_bits = 0;
67 for (unsigned bit = 0; bit < next.bits_; ++bit) {
68 x_bits += next.pattern_[bit] > 0;
69 y_bits += next.pattern_[bit] < 0;
70 }
71 next.tile_width_ = std::size_t{1} << x_bits;
72 next.tile_height_ = std::size_t{1} << y_bits;
73 next.tiles_x_ = (width - 1) / next.tile_width_ + 1;
74 const std::size_t tiles_y = (height - 1) / next.tile_height_ + 1;
75 const std::size_t tile_bytes = std::size_t{1} << next.bits_;
76 constexpr auto max = std::numeric_limits<std::size_t>::max();
77 if (next.tiles_x_ > max / tiles_y || next.tiles_x_ * tiles_y > max / tile_bytes) return false;
78 next.size_ = next.tiles_x_ * tiles_y * tile_bytes;
79 next.width_ = width;
80 next.height_ = height;
81 next.element_bytes_ = element_bytes;
82 out = next;
83 return true;
84 }
85
86 std::size_t tiled_size() const { return size_; }
87 std::size_t tile_width() const { return tile_width_; }
88 std::size_t tile_height() const { return tile_height_; }
89
90 bool element_offset(std::size_t x, std::size_t y, std::size_t& offset) const {
91 if (!size_ || x >= width_ || y >= height_) return false;
92 offset = address(x, y);
93 return true;
94 }
95
96 // Buffers must not overlap. Padding in either destination is left untouched; failure writes nothing.
97 bool detile(std::span<const std::byte> tiled, std::span<std::byte> linear, std::size_t row_pitch) const {
98 return copy(tiled, linear, row_pitch, false);
99 }
100
101 bool tile(std::span<const std::byte> linear, std::span<std::byte> tiled, std::size_t row_pitch) const {
102 return copy(linear, tiled, row_pitch, true);
103 }
104
105private:
106 std::size_t address(std::size_t x, std::size_t y) const {
107 std::size_t offset = ((y / tile_height_) * tiles_x_ + x / tile_width_) << bits_;
108 for (unsigned bit = 0; bit < bits_; ++bit) {
109 const int source = pattern_[bit];
110 if (source > 0) offset |= ((x >> (source - 1)) & 1) << bit;
111 else if (source < 0) offset |= ((y >> (-source - 1)) & 1) << bit;
112 }
113 return offset;
114 }
115
116 bool copy(std::span<const std::byte> source, std::span<std::byte> destination, std::size_t pitch,
117 bool to_tiled) const {
118 if (!size_) return false;
119 const std::size_t row_bytes = width_ * element_bytes_;
120 if (pitch < row_bytes || (height_ - 1 &&
121 pitch > (std::numeric_limits<std::size_t>::max() - row_bytes) / (height_ - 1))) return false;
122 const std::size_t linear_size = (height_ - 1) * pitch + row_bytes;
123 if (source.size() < (to_tiled ? linear_size : size_) ||
124 destination.size() < (to_tiled ? size_ : linear_size) ||
125 tiling_detail::overlap(source, destination)) return false;
126 const auto tile_x_bits = std::countr_zero(tile_width_);
127 std::size_t x_offsets[256]{};
128 for (std::size_t x = 0; x < tile_width_; ++x) {
129 for (unsigned bit = 0; bit < bits_; ++bit) {
130 const int source_bit = pattern_[bit];
131 if (source_bit > 0) x_offsets[x] |= ((x >> (source_bit - 1)) & 1) << bit;
132 }
133 }
134 for (std::size_t y = 0; y < height_; ++y) {
135 std::size_t y_offset = 0;
136 for (unsigned bit = 0; bit < bits_; ++bit) {
137 const int source_bit = pattern_[bit];
138 if (source_bit < 0) y_offset |= ((y >> (-source_bit - 1)) & 1) << bit;
139 }
140 const std::size_t tile_row = (y / tile_height_) * tiles_x_;
141 for (std::size_t x = 0; x < width_; ++x) {
142 const std::size_t linear = y * pitch + x * element_bytes_;
143 const std::size_t tiled = ((tile_row + (x >> tile_x_bits)) << bits_) +
144 y_offset + x_offsets[x & (tile_width_ - 1)];
145 std::memcpy(destination.data() + (to_tiled ? tiled : linear),
146 source.data() + (to_tiled ? linear : tiled), element_bytes_);
147 }
148 }
149 return true;
150 }
151
152 const int* pattern_ = nullptr;
153 unsigned bits_ = 0;
154 std::size_t width_ = 0, height_ = 0, element_bytes_ = 0;
155 std::size_t tile_width_ = 0, tile_height_ = 0, tiles_x_ = 0, size_ = 0;
156};
157
158} // namespace leonida::gfx10
diff --git a/runtime/src/main.cpp b/runtime/src/main.cpp
index 06baae387..7bc2d78ab 100644
--- a/runtime/src/main.cpp
+++ b/runtime/src/main.cpp
@@ -94,6 +94,7 @@ int wmain(int argc, wchar_t** argv) {
94 try { 94 try {
95 rt::Loader loader(game_dir); 95 rt::Loader loader(game_dir);
96 rt::Module& main_module = loader.load(image); // maps, binds and installs TLS; runs no image code 96 rt::Module& main_module = loader.load(image); // maps, binds and installs TLS; runs no image code
97 if (run) rt::process::set_command_line(image.filename().wstring(), game_args);
97 if (init || run) { 98 if (init || run) {
98 loader.initialise(); // TLS callbacks, then DllMain(DLL_PROCESS_ATTACH) for DLLs 99 loader.initialise(); // TLS callbacks, then DllMain(DLL_PROCESS_ATTACH) for DLLs
99 std::printf("%zu module(s) initialised\n", loader.modules().size()); 100 std::printf("%zu module(s) initialised\n", loader.modules().size());
@@ -128,7 +129,6 @@ int wmain(int argc, wchar_t** argv) {
128 std::fprintf(stderr, "error: %s has no entry point\n", main_module.name.c_str()); 129 std::fprintf(stderr, "error: %s has no entry point\n", main_module.name.c_str());
129 return 1; 130 return 1;
130 } 131 }
131 rt::process::set_command_line(image.filename().wstring(), game_args);
132 std::printf("console paths: GAME: -> %ls, writes -> %ls\n", game_dir.c_str(), overlay_dir.c_str()); 132 std::printf("console paths: GAME: -> %ls, writes -> %ls\n", game_dir.c_str(), overlay_dir.c_str());
133 std::printf("running %s\n", main_module.name.c_str()); 133 std::printf("running %s\n", main_module.name.c_str());
134 std::fflush(stdout); 134 std::fflush(stdout);
diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp
index a59f9d0b1..f2c62ec91 100644
--- a/runtime/src/pe_loader.cpp
+++ b/runtime/src/pe_loader.cpp
@@ -65,7 +65,8 @@ uint64_t rva_in(const Module& m, uint64_t va, const char* what) {
65 65
66IMAGE_TLS_DIRECTORY64* tls_directory(Module& m) { 66IMAGE_TLS_DIRECTORY64* tls_directory(Module& m) {
67 auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew); 67 auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew);
68 const auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_TLS]; 68 // Through directory(), as every other directory: an entry past NumberOfRvaAndSizes is not a TLS directory.
69 const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_TLS);
69 if (!dir.Size || !dir.VirtualAddress) return nullptr; 70 if (!dir.Size || !dir.VirtualAddress) return nullptr;
70 require_range(m.name, dir.VirtualAddress, sizeof(IMAGE_TLS_DIRECTORY64), m.size, "the TLS directory"); 71 require_range(m.name, dir.VirtualAddress, sizeof(IMAGE_TLS_DIRECTORY64), m.size, "the TLS directory");
71 return at<IMAGE_TLS_DIRECTORY64>(m.base, dir.VirtualAddress); 72 return at<IMAGE_TLS_DIRECTORY64>(m.base, dir.VirtualAddress);
@@ -696,7 +697,6 @@ void Loader::initialise(Module& m) {
696 // Only a DLL gets DllMain. An EXE's entry point has a different signature and is the caller's to run. 697 // Only a DLL gets DllMain. An EXE's entry point has a different signature and is the caller's to run.
697 auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew); 698 auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew);
698 if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && m.entry_rva) { 699 if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && m.entry_rva) {
699 if (m.entry_rva >= m.size) throw std::runtime_error(m.name + ": the entry point is outside the image");
700 auto entry = reinterpret_cast<BOOL(NTAPI*)(void*, DWORD, void*)>(m.base + m.entry_rva); 700 auto entry = reinterpret_cast<BOOL(NTAPI*)(void*, DWORD, void*)>(m.base + m.entry_rva);
701 const BOOL ok = entry(m.base, DLL_PROCESS_ATTACH, nullptr); 701 const BOOL ok = entry(m.base, DLL_PROCESS_ATTACH, nullptr);
702 if (startup_trace::enabled()) 702 if (startup_trace::enabled())
@@ -741,6 +741,8 @@ Module& Loader::map_image(const std::filesystem::path& path) {
741 if (!oh.SizeOfImage || oh.SizeOfHeaders < headers_end || oh.SizeOfHeaders > oh.SizeOfImage || 741 if (!oh.SizeOfImage || oh.SizeOfHeaders < headers_end || oh.SizeOfHeaders > oh.SizeOfImage ||
742 oh.SizeOfHeaders > file.size()) 742 oh.SizeOfHeaders > file.size())
743 throw std::runtime_error(name + ": SizeOfHeaders and SizeOfImage don't fit the headers and file"); 743 throw std::runtime_error(name + ": SizeOfHeaders and SizeOfImage don't fit the headers and file");
744 if (oh.AddressOfEntryPoint && oh.AddressOfEntryPoint >= oh.SizeOfImage)
745 throw std::runtime_error(name + ": the entry point is outside the image");
744 746
745 auto* m = new Module; 747 auto* m = new Module;
746 m->name = name; 748 m->name = name;
diff --git a/runtime/src/present_compose.comp b/runtime/src/present_compose.comp
new file mode 100644
index 000000000..b557a6444
--- /dev/null
+++ b/runtime/src/present_compose.comp
@@ -0,0 +1,130 @@
1// PresentX plane composition (docs/d3d12_vulkan.md section 4.5): one or two planes, each scaled from a source rectangle to
2// a destination rectangle of the output, plane 1 blended over plane 0, written to an RGBA16F image the presenter then
3// copies to the swapchain. present_compose_spv.h is this file compiled with
4// `glslc --target-env=vulkan1.1 -O -mfmt=c` (see the header for the command); keep them together.
5//
6// Every plane is read with texelFetch (no sampler: the filtering is done here, so it works on any sampled format and
7// only reads texels inside the source rectangle). Values are the encoded ones of the plane's colour space: SDR planes
8// hold G2.2 values, HDR10 planes hold ST.2084 (PQ) Rec.2020 values. An sRGB-format source is decoded by the texture unit,
9// so `flag_srgb_source` encodes it again with the sRGB curve and the bytes come out as they went in.
10//
11// Conversions (all provisional, docs section 4.5): SDR -> HDR10: pow 2.2, Rec.709 -> Rec.2020, times the SDR white level
12// in nits, PQ. HDR10 -> SDR: PQ, Rec.2020 -> Rec.709, divided by the white level, clipped to 0..1, pow 1/2.2 (no
13// tone mapping). Same space: untouched. Plane 1 is blended after conversion, in the output's encoded space.
14#version 450
15#extension GL_EXT_samplerless_texture_functions : require
16
17layout(local_size_x = 8, local_size_y = 8, local_size_z = 1) in;
18
19layout(set = 0, binding = 0) uniform texture2D plane0;
20layout(set = 0, binding = 1) uniform texture2D plane1;
21layout(set = 0, binding = 2, rgba16f) uniform writeonly image2D out_image;
22
23const uint flag_point = 1u;
24const uint flag_srgb_source = 2u;
25const uint flag_hdr10 = 4u;
26const uint flag_straight_alpha = 8u;
27
28layout(push_constant) uniform Push {
29 vec4 dest0; // destination rectangle in output pixels: left, top, right, bottom
30 vec4 dest1;
31 vec4 src0; // source rectangle in texels
32 vec4 src1;
33 uint flags0;
34 uint flags1;
35 uint plane_count;
36 uint out_hdr; // 1: the output holds PQ Rec.2020 values
37 float sdr_white; // nits of SDR white, for the conversions
38 uint width, height;
39 uint pad;
40} pc;
41
42vec3 srgb_encode(vec3 c) {
43 c = clamp(c, 0.0, 1.0);
44 return mix(c * 12.92, 1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055, greaterThan(c, vec3(0.0031308)));
45}
46
47// `pre`: straight-alpha data is filtered premultiplied (colour * alpha), else a transparent texel would drag the colour of its neighbours down.
48vec4 fetch_texel(texture2D t, ivec2 i, bool pre) {
49 vec4 c = texelFetch(t, i, 0);
50 return pre ? vec4(c.rgb * c.a, c.a) : c;
51}
52
53// The plane's value at output pixel `pixel` (its centre), in the plane's own encoding.
54vec4 fetch_plane(texture2D t, vec4 dest, vec4 src, uint flags, ivec2 pixel) {
55 vec2 p = (vec2(pixel) + 0.5 - dest.xy) / (dest.zw - dest.xy); // 0..1 across the destination rectangle
56 vec2 s = src.xy + p * (src.zw - src.xy); // continuous texel coordinates
57 vec2 lo = src.xy, hi = src.zw - 1.0;
58 bool pre = (flags & flag_straight_alpha) != 0u;
59 vec4 c;
60 if ((flags & flag_point) != 0u) {
61 c = fetch_texel(t, ivec2(clamp(floor(s), lo, hi)), false);
62 } else {
63 vec2 f = clamp(s - 0.5, lo, hi); // the texel whose centre is at or before the sample, clamped inside the rectangle
64 vec2 base = floor(f), w = f - base;
65 ivec2 i0 = ivec2(base), i1 = ivec2(min(base + 1.0, hi));
66 c = mix(mix(fetch_texel(t, ivec2(i0.x, i0.y), pre), fetch_texel(t, ivec2(i1.x, i0.y), pre), w.x),
67 mix(fetch_texel(t, ivec2(i0.x, i1.y), pre), fetch_texel(t, ivec2(i1.x, i1.y), pre), w.x), w.y);
68 if (pre) c.rgb = c.a > 0.0 ? c.rgb / c.a : vec3(0.0); // back to unassociated colour
69 }
70 if ((flags & flag_srgb_source) != 0u) c.rgb = srgb_encode(c.rgb);
71 return c;
72}
73
74const float m1 = 0.1593017578125, m2 = 78.84375, c1 = 0.8359375, c2 = 18.8515625, c3 = 18.6875;
75
76vec3 pq_to_nits(vec3 e) {
77 vec3 ep = pow(clamp(e, 0.0, 1.0), vec3(1.0 / m2));
78 return 10000.0 * pow(max(ep - c1, 0.0) / (c2 - c3 * ep), vec3(1.0 / m1));
79}
80
81vec3 nits_to_pq(vec3 nits) {
82 vec3 y = pow(clamp(nits / 10000.0, 0.0, 1.0), vec3(m1));
83 return pow((c1 + c2 * y) / (1.0 + c3 * y), vec3(m2));
84}
85
86vec3 bt709_to_bt2020(vec3 v) {
87 return vec3(dot(vec3(0.627404, 0.329283, 0.043313), v), dot(vec3(0.069097, 0.919540, 0.011362), v),
88 dot(vec3(0.016391, 0.088013, 0.895595), v));
89}
90
91vec3 bt2020_to_bt709(vec3 v) {
92 return vec3(dot(vec3(1.660491, -0.587641, -0.072850), v), dot(vec3(-0.124550, 1.132900, -0.008349), v),
93 dot(vec3(-0.018151, -0.100579, 1.118730), v));
94}
95
96// `c` in the encoding of the plane (hdr: PQ Rec.2020, else G2.2 Rec.709) to the output's.
97vec3 to_output(vec3 c, bool plane_hdr) {
98 bool out_hdr = pc.out_hdr != 0u;
99 if (plane_hdr == out_hdr) return c;
100 if (!plane_hdr) return nits_to_pq(bt709_to_bt2020(pow(clamp(c, 0.0, 1.0), vec3(2.2))) * pc.sdr_white);
101 return pow(clamp(bt2020_to_bt709(pq_to_nits(c)) / pc.sdr_white, 0.0, 1.0), vec3(1.0 / 2.2));
102}
103
104void main() {
105 ivec2 pixel = ivec2(gl_GlobalInvocationID.xy);
106 if (pixel.x >= int(pc.width) || pixel.y >= int(pc.height)) return;
107 vec2 centre = vec2(pixel) + 0.5;
108
109 vec3 base = vec3(0.0); // outside plane 0's rectangle: black
110 if (all(greaterThanEqual(centre, pc.dest0.xy)) && all(lessThan(centre, pc.dest0.zw))) {
111 vec4 c = fetch_plane(plane0, pc.dest0, pc.src0, pc.flags0 & ~flag_straight_alpha, pixel);
112 base = to_output(c.rgb, (pc.flags0 & flag_hdr10) != 0u);
113 }
114 if (pc.plane_count > 1u && all(greaterThanEqual(centre, pc.dest1.xy)) && all(lessThan(centre, pc.dest1.zw))) {
115 vec4 c = fetch_plane(plane1, pc.dest1, pc.src1, pc.flags1, pixel);
116 bool hdr = (pc.flags1 & flag_hdr10) != 0u;
117 float a = clamp(c.a, 0.0, 1.0);
118 bool straight = (pc.flags1 & flag_straight_alpha) != 0u;
119 vec3 over;
120 if (hdr == (pc.out_hdr != 0u)) {
121 over = c.rgb; // already in the output's space: no conversion, so no un-premultiplying either
122 } else {
123 vec3 colour = straight || a <= 0.0 ? c.rgb : c.rgb / a; // convert unassociated colour
124 over = to_output(colour, hdr);
125 if (!straight) over *= a;
126 }
127 base = straight ? mix(base, over, a) : over + (1.0 - a) * base;
128 }
129 imageStore(out_image, pixel, vec4(base, 1.0));
130}
diff --git a/runtime/src/present_compose.inc b/runtime/src/present_compose.inc
new file mode 100644
index 000000000..35cfc3e80
--- /dev/null
+++ b/runtime/src/present_compose.inc
@@ -0,0 +1,742 @@
1{0x07230203,0x00010300,0x000d000b,0x00000632,
20x00000000,0x00020011,0x00000001,0x0006000b,
30x00000001,0x4c534c47,0x6474732e,0x3035342e,
40x00000000,0x0003000e,0x00000000,0x00000001,
50x0006000f,0x00000005,0x00000004,0x6e69616d,
60x00000000,0x000001b3,0x00060010,0x00000004,
70x00000011,0x00000008,0x00000008,0x00000001,
80x00030047,0x0000017b,0x00000002,0x00050048,
90x0000017b,0x00000000,0x00000023,0x00000000,
100x00050048,0x0000017b,0x00000001,0x00000023,
110x00000010,0x00050048,0x0000017b,0x00000002,
120x00000023,0x00000020,0x00050048,0x0000017b,
130x00000003,0x00000023,0x00000030,0x00050048,
140x0000017b,0x00000004,0x00000023,0x00000040,
150x00050048,0x0000017b,0x00000005,0x00000023,
160x00000044,0x00050048,0x0000017b,0x00000006,
170x00000023,0x00000048,0x00050048,0x0000017b,
180x00000007,0x00000023,0x0000004c,0x00050048,
190x0000017b,0x00000008,0x00000023,0x00000050,
200x00050048,0x0000017b,0x00000009,0x00000023,
210x00000054,0x00050048,0x0000017b,0x0000000a,
220x00000023,0x00000058,0x00050048,0x0000017b,
230x0000000b,0x00000023,0x0000005c,0x00040047,
240x000001b3,0x0000000b,0x0000001c,0x00040047,
250x000001e7,0x00000021,0x00000000,0x00040047,
260x000001e7,0x00000022,0x00000000,0x00040047,
270x0000021c,0x00000021,0x00000001,0x00040047,
280x0000021c,0x00000022,0x00000000,0x00030047,
290x00000274,0x00000019,0x00040047,0x00000274,
300x00000021,0x00000002,0x00040047,0x00000274,
310x00000022,0x00000000,0x00040047,0x0000027c,
320x0000000b,0x00000019,0x00020013,0x00000002,
330x00030021,0x00000003,0x00000002,0x00030016,
340x00000006,0x00000020,0x00040017,0x00000007,
350x00000006,0x00000003,0x00090019,0x0000000d,
360x00000006,0x00000001,0x00000000,0x00000000,
370x00000000,0x00000001,0x00000000,0x00040020,
380x0000000e,0x00000000,0x0000000d,0x00040015,
390x0000000f,0x00000020,0x00000001,0x00040017,
400x00000010,0x0000000f,0x00000002,0x00020014,
410x00000012,0x00040017,0x00000014,0x00000006,
420x00000004,0x00040015,0x0000001c,0x00000020,
430x00000000,0x0004002b,0x00000006,0x00000038,
440x00000000,0x0004002b,0x00000006,0x00000039,
450x3f800000,0x0004002b,0x00000006,0x0000003e,
460x414eb852,0x0004002b,0x00000006,0x00000040,
470x3f870a3d,0x0004002b,0x00000006,0x00000042,
480x3ed55555,0x0006002c,0x00000007,0x00000043,
490x00000042,0x00000042,0x00000042,0x0004002b,
500x00000006,0x00000046,0x3d6147ae,0x0004002b,
510x00000006,0x0000004a,0x3b4d2e1c,0x0006002c,
520x00000007,0x0000004b,0x0000004a,0x0000004a,
530x0000004a,0x00040017,0x0000004c,0x00000012,
540x00000003,0x0004002b,0x0000000f,0x00000054,
550x00000000,0x00040017,0x0000006c,0x00000006,
560x00000002,0x0004002b,0x00000006,0x00000071,
570x3f000000,0x0004002b,0x0000001c,0x00000092,
580x00000008,0x0004002b,0x0000001c,0x00000094,
590x00000000,0x0004002b,0x0000001c,0x00000097,
600x00000001,0x0006002c,0x00000007,0x00000101,
610x00000038,0x00000038,0x00000038,0x0004002b,
620x0000001c,0x00000107,0x00000002,0x0004002b,
630x00000006,0x00000121,0x3c4fcdac,0x0006002c,
640x00000007,0x00000122,0x00000121,0x00000121,
650x00000121,0x0004002b,0x00000006,0x00000124,
660x461c4000,0x0004002b,0x00000006,0x00000126,
670x3f560000,0x0004002b,0x00000006,0x0000012b,
680x4196d000,0x0004002b,0x00000006,0x0000012c,
690x41958000,0x0004002b,0x00000006,0x00000132,
700x40c8e06b,0x0006002c,0x00000007,0x00000133,
710x00000132,0x00000132,0x00000132,0x0004002b,
720x00000006,0x0000013f,0x3e232000,0x0006002c,
730x00000007,0x00000140,0x0000013f,0x0000013f,
740x0000013f,0x0004002b,0x00000006,0x0000014b,
750x429db000,0x0006002c,0x00000007,0x0000014c,
760x0000014b,0x0000014b,0x0000014b,0x0004002b,
770x00000006,0x00000150,0x3f209d8c,0x0004002b,
780x00000006,0x00000151,0x3ea897c8,0x0004002b,
790x00000006,0x00000152,0x3d3168f9,0x0006002c,
800x00000007,0x00000153,0x00000150,0x00000151,
810x00000152,0x0004002b,0x00000006,0x00000156,
820x3d8d82ba,0x0004002b,0x00000006,0x00000157,
830x3f6b66f9,0x0004002b,0x00000006,0x00000158,
840x3c3a27af,0x0006002c,0x00000007,0x00000159,
850x00000156,0x00000157,0x00000158,0x0004002b,
860x00000006,0x0000015c,0x3c86466b,0x0004002b,
870x00000006,0x0000015d,0x3db44029,0x0004002b,
880x00000006,0x0000015e,0x3f6545b7,0x0006002c,
890x00000007,0x0000015f,0x0000015c,0x0000015d,
900x0000015e,0x0004002b,0x00000006,0x00000165,
910x3fd48af8,0x0004002b,0x00000006,0x00000166,
920xbf166fa4,0x0004002b,0x00000006,0x00000167,
930xbd953261,0x0006002c,0x00000007,0x00000168,
940x00000165,0x00000166,0x00000167,0x0004002b,
950x00000006,0x0000016b,0xbdff1412,0x0004002b,
960x00000006,0x0000016c,0x3f9102de,0x0004002b,
970x00000006,0x0000016d,0xbc08ca3e,0x0006002c,
980x00000007,0x0000016e,0x0000016b,0x0000016c,
990x0000016d,0x0004002b,0x00000006,0x00000171,
1000xbc94b168,0x0004002b,0x00000006,0x00000172,
1010xbdcdfc5d,0x0004002b,0x00000006,0x00000173,
1020x3f8f328b,0x0006002c,0x00000007,0x00000174,
1030x00000171,0x00000172,0x00000173,0x000e001e,
1040x0000017b,0x00000014,0x00000014,0x00000014,
1050x00000014,0x0000001c,0x0000001c,0x0000001c,
1060x0000001c,0x00000006,0x0000001c,0x0000001c,
1070x0000001c,0x00040020,0x0000017c,0x00000009,
1080x0000017b,0x0004003b,0x0000017c,0x0000017d,
1090x00000009,0x0004002b,0x0000000f,0x0000017e,
1100x00000007,0x00040020,0x0000017f,0x00000009,
1110x0000001c,0x0004002b,0x00000006,0x00000192,
1120x400ccccd,0x0006002c,0x00000007,0x00000193,
1130x00000192,0x00000192,0x00000192,0x0004002b,
1140x0000000f,0x00000197,0x00000008,0x00040020,
1150x00000198,0x00000009,0x00000006,0x0004002b,
1160x00000006,0x000001ab,0x3ee8ba2f,0x0006002c,
1170x00000007,0x000001ac,0x000001ab,0x000001ab,
1180x000001ab,0x00040017,0x000001b1,0x0000001c,
1190x00000003,0x00040020,0x000001b2,0x00000001,
1200x000001b1,0x0004003b,0x000001b2,0x000001b3,
1210x00000001,0x00040017,0x000001b4,0x0000001c,
1220x00000002,0x0004002b,0x0000000f,0x000001ba,
1230x00000009,0x0004002b,0x0000000f,0x000001c4,
1240x0000000a,0x00040020,0x000001d4,0x00000009,
1250x00000014,0x00040017,0x000001d8,0x00000012,
1260x00000002,0x0004003b,0x0000000e,0x000001e7,
1270x00000000,0x0004002b,0x0000000f,0x000001e8,
1280x00000002,0x0004002b,0x0000000f,0x000001e9,
1290x00000004,0x0004002b,0x0000001c,0x000001fa,
1300x00000004,0x0004002b,0x0000000f,0x00000202,
1310x00000006,0x0004002b,0x0000000f,0x00000209,
1320x00000001,0x0004003b,0x0000000e,0x0000021c,
1330x00000000,0x0004002b,0x0000000f,0x0000021d,
1340x00000003,0x0004002b,0x0000000f,0x0000021e,
1350x00000005,0x00090019,0x00000272,0x00000006,
1360x00000001,0x00000000,0x00000000,0x00000000,
1370x00000002,0x00000002,0x00040020,0x00000273,
1380x00000000,0x00000272,0x0004003b,0x00000273,
1390x00000274,0x00000000,0x0006002c,0x000001b1,
1400x0000027c,0x00000092,0x00000092,0x00000097,
1410x0005002c,0x0000006c,0x00000627,0x00000071,
1420x00000071,0x0005002c,0x0000006c,0x00000628,
1430x00000039,0x00000039,0x0006002c,0x00000007,
1440x0000062a,0x00000039,0x00000039,0x00000039,
1450x0006002c,0x00000007,0x0000062b,0x00000046,
1460x00000046,0x00000046,0x0006002c,0x00000007,
1470x0000062d,0x00000126,0x00000126,0x00000126,
1480x0006002c,0x00000007,0x0000062e,0x0000012b,
1490x0000012b,0x0000012b,0x0004002b,0x00000006,
1500x0000062f,0x38d1b717,0x0006002c,0x00000007,
1510x00000630,0x0000062f,0x0000062f,0x0000062f,
1520x00030001,0x00000014,0x00000631,0x00050036,
1530x00000002,0x00000004,0x00000000,0x00000003,
1540x000200f8,0x00000005,0x000300f7,0x0000027d,
1550x00000000,0x000300fb,0x00000094,0x0000027e,
1560x000200f8,0x0000027e,0x0004003d,0x000001b1,
1570x000001b5,0x000001b3,0x0007004f,0x000001b4,
1580x000001b6,0x000001b5,0x000001b5,0x00000000,
1590x00000001,0x0004007c,0x00000010,0x000001b7,
1600x000001b6,0x00050051,0x0000000f,0x000001b9,
1610x000001b7,0x00000000,0x00050041,0x0000017f,
1620x000001bb,0x0000017d,0x000001ba,0x0004003d,
1630x0000001c,0x000001bc,0x000001bb,0x0004007c,
1640x0000000f,0x000001bd,0x000001bc,0x000500af,
1650x00000012,0x000001be,0x000001b9,0x000001bd,
1660x000400a8,0x00000012,0x000001bf,0x000001be,
1670x000300f7,0x000001c1,0x00000000,0x000400fa,
1680x000001bf,0x000001c0,0x000001c1,0x000200f8,
1690x000001c0,0x00050051,0x0000000f,0x000001c3,
1700x000001b7,0x00000001,0x00050041,0x0000017f,
1710x000001c5,0x0000017d,0x000001c4,0x0004003d,
1720x0000001c,0x000001c6,0x000001c5,0x0004007c,
1730x0000000f,0x000001c7,0x000001c6,0x000500af,
1740x00000012,0x000001c8,0x000001c3,0x000001c7,
1750x000200f9,0x000001c1,0x000200f8,0x000001c1,
1760x000700f5,0x00000012,0x000001c9,0x000001be,
1770x0000027e,0x000001c8,0x000001c0,0x000300f7,
1780x000001cb,0x00000000,0x000400fa,0x000001c9,
1790x000001ca,0x000001cb,0x000200f8,0x000001ca,
1800x000200f9,0x0000027d,0x000200f8,0x000001cb,
1810x0004006f,0x0000006c,0x000001cf,0x000001b7,
1820x00050081,0x0000006c,0x000001d1,0x000001cf,
1830x00000627,0x00050041,0x000001d4,0x000001d5,
1840x0000017d,0x00000054,0x0004003d,0x00000014,
1850x000001d6,0x000001d5,0x0007004f,0x0000006c,
1860x000001d7,0x000001d6,0x000001d6,0x00000000,
1870x00000001,0x000500be,0x000001d8,0x000001d9,
1880x000001d1,0x000001d7,0x0004009b,0x00000012,
1890x000001da,0x000001d9,0x000300f7,0x000001dc,
1900x00000000,0x000400fa,0x000001da,0x000001db,
1910x000001dc,0x000200f8,0x000001db,0x0007004f,
1920x0000006c,0x000001e0,0x000001d6,0x000001d6,
1930x00000002,0x00000003,0x000500b8,0x000001d8,
1940x000001e1,0x000001d1,0x000001e0,0x0004009b,
1950x00000012,0x000001e2,0x000001e1,0x000200f9,
1960x000001dc,0x000200f8,0x000001dc,0x000700f5,
1970x00000012,0x000001e3,0x000001da,0x000001cb,
1980x000001e2,0x000001db,0x000300f7,0x000001e5,
1990x00000000,0x000400fa,0x000001e3,0x000001e4,
2000x000001e5,0x000200f8,0x000001e4,0x00050041,
2010x0000017f,0x000001ea,0x0000017d,0x000001e9,
2020x0004003d,0x0000001c,0x000001eb,0x000001ea,
2030x00050041,0x000001d4,0x000001f2,0x0000017d,
2040x000001e8,0x0004003d,0x00000014,0x000001f3,
2050x000001f2,0x00050083,0x0000006c,0x000002a5,
2060x000001d1,0x000001d7,0x0007004f,0x0000006c,
2070x000002a7,0x000001d6,0x000001d6,0x00000002,
2080x00000003,0x00050083,0x0000006c,0x000002aa,
2090x000002a7,0x000001d7,0x00050088,0x0000006c,
2100x000002ab,0x000002a5,0x000002aa,0x0007004f,
2110x0000006c,0x000002ad,0x000001f3,0x000001f3,
2120x00000000,0x00000001,0x0007004f,0x0000006c,
2130x000002b0,0x000001f3,0x000001f3,0x00000002,
2140x00000003,0x00050083,0x0000006c,0x000002b3,
2150x000002b0,0x000002ad,0x00050085,0x0000006c,
2160x000002b4,0x000002ab,0x000002b3,0x00050081,
2170x0000006c,0x000002b5,0x000002ad,0x000002b4,
2180x00050083,0x0000006c,0x000002bb,0x000002b0,
2190x00000628,0x000500c7,0x0000001c,0x000002c0,
2200x000001eb,0x00000097,0x000500ab,0x00000012,
2210x000002c1,0x000002c0,0x00000094,0x000300f7,
2220x0000031c,0x00000000,0x000400fa,0x000002c1,
2230x000002c2,0x000002ca,0x000200f8,0x000002ca,
2240x00050083,0x0000006c,0x000002cd,0x000002b5,
2250x00000627,0x0008000c,0x0000006c,0x000002d0,
2260x00000001,0x0000002b,0x000002cd,0x000002ad,
2270x000002bb,0x0006000c,0x0000006c,0x000002d2,
2280x00000001,0x00000008,0x000002d0,0x00050083,
2290x0000006c,0x000002d5,0x000002d0,0x000002d2,
2300x0004006e,0x00000010,0x000002d7,0x000002d2,
2310x00050081,0x0000006c,0x000002da,0x000002d2,
2320x00000628,0x0007000c,0x0000006c,0x000002dc,
2330x00000001,0x00000025,0x000002da,0x000002bb,
2340x0004006e,0x00000010,0x000002dd,0x000002dc,
2350x00050051,0x0000000f,0x000002df,0x000002d7,
2360x00000000,0x00050051,0x0000000f,0x000002e1,
2370x000002d7,0x00000001,0x0004003d,0x0000000d,
2380x00000348,0x000001e7,0x0007005f,0x00000014,
2390x0000034a,0x00000348,0x000002d7,0x00000002,
2400x00000054,0x00050051,0x0000000f,0x000002e6,
2410x000002dd,0x00000000,0x00050050,0x00000010,
2420x000002e9,0x000002e6,0x000002e1,0x0004003d,
2430x0000000d,0x00000360,0x000001e7,0x0007005f,
2440x00000014,0x00000362,0x00000360,0x000002e9,
2450x00000002,0x00000054,0x00050051,0x00000006,
2460x000002ed,0x000002d5,0x00000000,0x00070050,
2470x00000014,0x000002ee,0x000002ed,0x000002ed,
2480x000002ed,0x000002ed,0x0008000c,0x00000014,
2490x000002ef,0x00000001,0x0000002e,0x0000034a,
2500x00000362,0x000002ee,0x00050051,0x0000000f,
2510x000002f3,0x000002dd,0x00000001,0x00050050,
2520x00000010,0x000002f4,0x000002df,0x000002f3,
2530x0004003d,0x0000000d,0x00000378,0x000001e7,
2540x0007005f,0x00000014,0x0000037a,0x00000378,
2550x000002f4,0x00000002,0x00000054,0x0004003d,
2560x0000000d,0x00000390,0x000001e7,0x0007005f,
2570x00000014,0x00000392,0x00000390,0x000002dd,
2580x00000002,0x00000054,0x0008000c,0x00000014,
2590x00000301,0x00000001,0x0000002e,0x0000037a,
2600x00000392,0x000002ee,0x00050051,0x00000006,
2610x00000303,0x000002d5,0x00000001,0x00070050,
2620x00000014,0x00000304,0x00000303,0x00000303,
2630x00000303,0x00000303,0x0008000c,0x00000014,
2640x00000305,0x00000001,0x0000002e,0x000002ef,
2650x00000301,0x00000304,0x000200f9,0x0000031c,
2660x000200f8,0x000002c2,0x0006000c,0x0000006c,
2670x000002c4,0x00000001,0x00000008,0x000002b5,
2680x0008000c,0x0000006c,0x000002c7,0x00000001,
2690x0000002b,0x000002c4,0x000002ad,0x000002bb,
2700x0004006e,0x00000010,0x000002c8,0x000002c7,
2710x0004003d,0x0000000d,0x00000330,0x000001e7,
2720x0007005f,0x00000014,0x00000332,0x00000330,
2730x000002c8,0x00000002,0x00000054,0x000200f9,
2740x0000031c,0x000200f8,0x0000031c,0x000700f5,
2750x00000014,0x00000602,0x00000332,0x000002c2,
2760x00000305,0x000002ca,0x000500c7,0x0000001c,
2770x0000031e,0x000001eb,0x00000107,0x000500ab,
2780x00000012,0x0000031f,0x0000031e,0x00000094,
2790x000300f7,0x0000032a,0x00000000,0x000400fa,
2800x0000031f,0x00000320,0x0000032a,0x000200f8,
2810x00000320,0x0008004f,0x00000007,0x00000322,
2820x00000602,0x00000602,0x00000000,0x00000001,
2830x00000002,0x0008000c,0x00000007,0x000003a9,
2840x00000001,0x0000002b,0x00000322,0x00000101,
2850x0000062a,0x0005008e,0x00000007,0x000003ab,
2860x000003a9,0x0000003e,0x0007000c,0x00000007,
2870x000003ad,0x00000001,0x0000001a,0x000003a9,
2880x00000043,0x0005008e,0x00000007,0x000003ae,
2890x000003ad,0x00000040,0x00050083,0x00000007,
2900x000003b0,0x000003ae,0x0000062b,0x000500ba,
2910x0000004c,0x000003b2,0x000003a9,0x0000004b,
2920x000600a9,0x00000007,0x000003b3,0x000003b2,
2930x000003b0,0x000003ab,0x00050051,0x00000006,
2940x00000325,0x000003b3,0x00000000,0x00060052,
2950x00000014,0x000005d2,0x00000325,0x00000631,
2960x00000000,0x00050051,0x00000006,0x00000327,
2970x000003b3,0x00000001,0x00060052,0x00000014,
2980x000005d4,0x00000327,0x000005d2,0x00000001,
2990x00050051,0x00000006,0x00000329,0x000003b3,
3000x00000002,0x00060052,0x00000014,0x000005d6,
3010x00000329,0x000005d4,0x00000002,0x000200f9,
3020x0000032a,0x000200f8,0x0000032a,0x000700f5,
3030x00000014,0x00000604,0x00000602,0x0000031c,
3040x000005d6,0x00000320,0x000500c7,0x0000001c,
3050x000001fb,0x000001eb,0x000001fa,0x000500ab,
3060x00000012,0x000001fc,0x000001fb,0x00000094,
3070x0008004f,0x00000007,0x000001ff,0x00000604,
3080x00000604,0x00000000,0x00000001,0x00000002,
3090x000300f7,0x000003e0,0x00000000,0x000300fb,
3100x00000094,0x000003bd,0x000200f8,0x000003bd,
3110x00050041,0x0000017f,0x000003be,0x0000017d,
3120x0000017e,0x0004003d,0x0000001c,0x000003bf,
3130x000003be,0x000500ab,0x00000012,0x000003c0,
3140x000003bf,0x00000094,0x000500a4,0x00000012,
3150x000003c3,0x000001fc,0x000003c0,0x000300f7,
3160x000003c6,0x00000000,0x000400fa,0x000003c3,
3170x000003c4,0x000003c6,0x000200f8,0x000003c4,
3180x000200f9,0x000003e0,0x000200f8,0x000003c6,
3190x000400a8,0x00000012,0x000003c8,0x000001fc,
3200x000300f7,0x000003d4,0x00000000,0x000400fa,
3210x000003c8,0x000003c9,0x000003d4,0x000200f8,
3220x000003c9,0x0008000c,0x00000007,0x000003cd,
3230x00000001,0x0000002b,0x000001ff,0x00000101,
3240x0000062a,0x0007000c,0x00000007,0x000003ce,
3250x00000001,0x0000001a,0x000003cd,0x00000193,
3260x00050094,0x00000006,0x000003e5,0x00000153,
3270x000003ce,0x00050094,0x00000006,0x000003e7,
3280x00000159,0x000003ce,0x00050094,0x00000006,
3290x000003e9,0x0000015f,0x000003ce,0x00060050,
3300x00000007,0x000003ea,0x000003e5,0x000003e7,
3310x000003e9,0x00050041,0x00000198,0x000003d0,
3320x0000017d,0x00000197,0x0004003d,0x00000006,
3330x000003d1,0x000003d0,0x0005008e,0x00000007,
3340x000003d2,0x000003ea,0x000003d1,0x00050085,
3350x00000007,0x000003f0,0x000003d2,0x00000630,
3360x0008000c,0x00000007,0x000003f3,0x00000001,
3370x0000002b,0x000003f0,0x00000101,0x0000062a,
3380x0007000c,0x00000007,0x000003f4,0x00000001,
3390x0000001a,0x000003f3,0x00000140,0x0005008e,
3400x00000007,0x000003f6,0x000003f4,0x0000012b,
3410x00050081,0x00000007,0x000003f8,0x0000062d,
3420x000003f6,0x0005008e,0x00000007,0x000003fa,
3430x000003f4,0x0000012c,0x00050081,0x00000007,
3440x000003fc,0x0000062a,0x000003fa,0x00050088,
3450x00000007,0x000003fd,0x000003f8,0x000003fc,
3460x0007000c,0x00000007,0x000003fe,0x00000001,
3470x0000001a,0x000003fd,0x0000014c,0x000200f9,
3480x000003e0,0x000200f8,0x000003d4,0x0008000c,
3490x00000007,0x00000405,0x00000001,0x0000002b,
3500x000001ff,0x00000101,0x0000062a,0x0007000c,
3510x00000007,0x00000406,0x00000001,0x0000001a,
3520x00000405,0x00000122,0x00050083,0x00000007,
3530x00000409,0x00000406,0x0000062d,0x0007000c,
3540x00000007,0x0000040b,0x00000001,0x00000028,
3550x00000409,0x00000101,0x0005008e,0x00000007,
3560x0000040d,0x00000406,0x0000012c,0x00050083,
3570x00000007,0x0000040f,0x0000062e,0x0000040d,
3580x00050088,0x00000007,0x00000410,0x0000040b,
3590x0000040f,0x0007000c,0x00000007,0x00000411,
3600x00000001,0x0000001a,0x00000410,0x00000133,
3610x0005008e,0x00000007,0x00000412,0x00000411,
3620x00000124,0x00050094,0x00000006,0x00000416,
3630x00000168,0x00000412,0x00050094,0x00000006,
3640x00000418,0x0000016e,0x00000412,0x00050094,
3650x00000006,0x0000041a,0x00000174,0x00000412,
3660x00060050,0x00000007,0x0000041b,0x00000416,
3670x00000418,0x0000041a,0x00050041,0x00000198,
3680x000003d8,0x0000017d,0x00000197,0x0004003d,
3690x00000006,0x000003d9,0x000003d8,0x00060050,
3700x00000007,0x000003da,0x000003d9,0x000003d9,
3710x000003d9,0x00050088,0x00000007,0x000003db,
3720x0000041b,0x000003da,0x0008000c,0x00000007,
3730x000003de,0x00000001,0x0000002b,0x000003db,
3740x00000101,0x0000062a,0x0007000c,0x00000007,
3750x000003df,0x00000001,0x0000001a,0x000003de,
3760x000001ac,0x000200f9,0x000003e0,0x000200f8,
3770x000003e0,0x000900f5,0x00000007,0x00000605,
3780x000001ff,0x000003c4,0x000003fe,0x000003c9,
3790x000003df,0x000003d4,0x000200f9,0x000001e5,
3800x000200f8,0x000001e5,0x000700f5,0x00000007,
3810x0000061a,0x00000101,0x000001dc,0x00000605,
3820x000003e0,0x00050041,0x0000017f,0x00000203,
3830x0000017d,0x00000202,0x0004003d,0x0000001c,
3840x00000204,0x00000203,0x000500ac,0x00000012,
3850x00000205,0x00000204,0x00000097,0x000300f7,
3860x00000207,0x00000000,0x000400fa,0x00000205,
3870x00000206,0x00000207,0x000200f8,0x00000206,
3880x00050041,0x000001d4,0x0000020a,0x0000017d,
3890x00000209,0x0004003d,0x00000014,0x0000020b,
3900x0000020a,0x0007004f,0x0000006c,0x0000020c,
3910x0000020b,0x0000020b,0x00000000,0x00000001,
3920x000500be,0x000001d8,0x0000020d,0x000001d1,
3930x0000020c,0x0004009b,0x00000012,0x0000020e,
3940x0000020d,0x000200f9,0x00000207,0x000200f8,
3950x00000207,0x000700f5,0x00000012,0x0000020f,
3960x00000205,0x000001e5,0x0000020e,0x00000206,
3970x000300f7,0x00000211,0x00000000,0x000400fa,
3980x0000020f,0x00000210,0x00000211,0x000200f8,
3990x00000210,0x00050041,0x000001d4,0x00000213,
4000x0000017d,0x00000209,0x0004003d,0x00000014,
4010x00000214,0x00000213,0x0007004f,0x0000006c,
4020x00000215,0x00000214,0x00000214,0x00000002,
4030x00000003,0x000500b8,0x000001d8,0x00000216,
4040x000001d1,0x00000215,0x0004009b,0x00000012,
4050x00000217,0x00000216,0x000200f9,0x00000211,
4060x000200f8,0x00000211,0x000700f5,0x00000012,
4070x00000218,0x0000020f,0x00000207,0x00000217,
4080x00000210,0x000300f7,0x0000021a,0x00000000,
4090x000400fa,0x00000218,0x00000219,0x0000021a,
4100x000200f8,0x00000219,0x00050041,0x000001d4,
4110x00000220,0x0000017d,0x00000209,0x0004003d,
4120x00000014,0x00000221,0x00000220,0x00050041,
4130x000001d4,0x00000223,0x0000017d,0x0000021d,
4140x0004003d,0x00000014,0x00000224,0x00000223,
4150x00050041,0x0000017f,0x00000226,0x0000017d,
4160x0000021e,0x0004003d,0x0000001c,0x00000227,
4170x00000226,0x0007004f,0x0000006c,0x0000043a,
4180x00000221,0x00000221,0x00000000,0x00000001,
4190x00050083,0x0000006c,0x0000043b,0x000001d1,
4200x0000043a,0x0007004f,0x0000006c,0x0000043d,
4210x00000221,0x00000221,0x00000002,0x00000003,
4220x00050083,0x0000006c,0x00000440,0x0000043d,
4230x0000043a,0x00050088,0x0000006c,0x00000441,
4240x0000043b,0x00000440,0x0007004f,0x0000006c,
4250x00000443,0x00000224,0x00000224,0x00000000,
4260x00000001,0x0007004f,0x0000006c,0x00000446,
4270x00000224,0x00000224,0x00000002,0x00000003,
4280x00050083,0x0000006c,0x00000449,0x00000446,
4290x00000443,0x00050085,0x0000006c,0x0000044a,
4300x00000441,0x00000449,0x00050081,0x0000006c,
4310x0000044b,0x00000443,0x0000044a,0x00050083,
4320x0000006c,0x00000451,0x00000446,0x00000628,
4330x000500c7,0x0000001c,0x00000453,0x00000227,
4340x00000092,0x000500ab,0x00000012,0x00000454,
4350x00000453,0x00000094,0x000500c7,0x0000001c,
4360x00000456,0x00000227,0x00000097,0x000500ab,
4370x00000012,0x00000457,0x00000456,0x00000094,
4380x000300f7,0x000004b2,0x00000000,0x000400fa,
4390x00000457,0x00000458,0x00000460,0x000200f8,
4400x00000460,0x00050083,0x0000006c,0x00000463,
4410x0000044b,0x00000627,0x0008000c,0x0000006c,
4420x00000466,0x00000001,0x0000002b,0x00000463,
4430x00000443,0x00000451,0x0006000c,0x0000006c,
4440x00000468,0x00000001,0x00000008,0x00000466,
4450x00050083,0x0000006c,0x0000046b,0x00000466,
4460x00000468,0x0004006e,0x00000010,0x0000046d,
4470x00000468,0x00050081,0x0000006c,0x00000470,
4480x00000468,0x00000628,0x0007000c,0x0000006c,
4490x00000472,0x00000001,0x00000025,0x00000470,
4500x00000451,0x0004006e,0x00000010,0x00000473,
4510x00000472,0x00050051,0x0000000f,0x00000475,
4520x0000046d,0x00000000,0x00050051,0x0000000f,
4530x00000477,0x0000046d,0x00000001,0x0004003d,
4540x0000000d,0x000004de,0x0000021c,0x0007005f,
4550x00000014,0x000004e0,0x000004de,0x0000046d,
4560x00000002,0x00000054,0x000300f7,0x000004f0,
4570x00000000,0x000400fa,0x00000454,0x000004e2,
4580x000004ee,0x000200f8,0x000004ee,0x000200f9,
4590x000004f0,0x000200f8,0x000004e2,0x0008004f,
4600x00000007,0x000004e4,0x000004e0,0x000004e0,
4610x00000000,0x00000001,0x00000002,0x00050051,
4620x00000006,0x000004e6,0x000004e0,0x00000003,
4630x0005008e,0x00000007,0x000004e7,0x000004e4,
4640x000004e6,0x00050051,0x00000006,0x000004ea,
4650x000004e7,0x00000000,0x00050051,0x00000006,
4660x000004eb,0x000004e7,0x00000001,0x00050051,
4670x00000006,0x000004ec,0x000004e7,0x00000002,
4680x00070050,0x00000014,0x000004ed,0x000004ea,
4690x000004eb,0x000004ec,0x000004e6,0x000200f9,
4700x000004f0,0x000200f8,0x000004f0,0x000700f5,
4710x00000014,0x00000606,0x000004ed,0x000004e2,
4720x000004e0,0x000004ee,0x00050051,0x0000000f,
4730x0000047c,0x00000473,0x00000000,0x00050050,
4740x00000010,0x0000047f,0x0000047c,0x00000477,
4750x0004003d,0x0000000d,0x000004f6,0x0000021c,
4760x0007005f,0x00000014,0x000004f8,0x000004f6,
4770x0000047f,0x00000002,0x00000054,0x000300f7,
4780x00000508,0x00000000,0x000400fa,0x00000454,
4790x000004fa,0x00000506,0x000200f8,0x00000506,
4800x000200f9,0x00000508,0x000200f8,0x000004fa,
4810x0008004f,0x00000007,0x000004fc,0x000004f8,
4820x000004f8,0x00000000,0x00000001,0x00000002,
4830x00050051,0x00000006,0x000004fe,0x000004f8,
4840x00000003,0x0005008e,0x00000007,0x000004ff,
4850x000004fc,0x000004fe,0x00050051,0x00000006,
4860x00000502,0x000004ff,0x00000000,0x00050051,
4870x00000006,0x00000503,0x000004ff,0x00000001,
4880x00050051,0x00000006,0x00000504,0x000004ff,
4890x00000002,0x00070050,0x00000014,0x00000505,
4900x00000502,0x00000503,0x00000504,0x000004fe,
4910x000200f9,0x00000508,0x000200f8,0x00000508,
4920x000700f5,0x00000014,0x00000607,0x00000505,
4930x000004fa,0x000004f8,0x00000506,0x00050051,
4940x00000006,0x00000483,0x0000046b,0x00000000,
4950x00070050,0x00000014,0x00000484,0x00000483,
4960x00000483,0x00000483,0x00000483,0x0008000c,
4970x00000014,0x00000485,0x00000001,0x0000002e,
4980x00000606,0x00000607,0x00000484,0x00050051,
4990x0000000f,0x00000489,0x00000473,0x00000001,
5000x00050050,0x00000010,0x0000048a,0x00000475,
5010x00000489,0x0004003d,0x0000000d,0x0000050e,
5020x0000021c,0x0007005f,0x00000014,0x00000510,
5030x0000050e,0x0000048a,0x00000002,0x00000054,
5040x000300f7,0x00000520,0x00000000,0x000400fa,
5050x00000454,0x00000512,0x0000051e,0x000200f8,
5060x0000051e,0x000200f9,0x00000520,0x000200f8,
5070x00000512,0x0008004f,0x00000007,0x00000514,
5080x00000510,0x00000510,0x00000000,0x00000001,
5090x00000002,0x00050051,0x00000006,0x00000516,
5100x00000510,0x00000003,0x0005008e,0x00000007,
5110x00000517,0x00000514,0x00000516,0x00050051,
5120x00000006,0x0000051a,0x00000517,0x00000000,
5130x00050051,0x00000006,0x0000051b,0x00000517,
5140x00000001,0x00050051,0x00000006,0x0000051c,
5150x00000517,0x00000002,0x00070050,0x00000014,
5160x0000051d,0x0000051a,0x0000051b,0x0000051c,
5170x00000516,0x000200f9,0x00000520,0x000200f8,
5180x00000520,0x000700f5,0x00000014,0x00000608,
5190x0000051d,0x00000512,0x00000510,0x0000051e,
5200x0004003d,0x0000000d,0x00000526,0x0000021c,
5210x0007005f,0x00000014,0x00000528,0x00000526,
5220x00000473,0x00000002,0x00000054,0x000300f7,
5230x00000538,0x00000000,0x000400fa,0x00000454,
5240x0000052a,0x00000536,0x000200f8,0x00000536,
5250x000200f9,0x00000538,0x000200f8,0x0000052a,
5260x0008004f,0x00000007,0x0000052c,0x00000528,
5270x00000528,0x00000000,0x00000001,0x00000002,
5280x00050051,0x00000006,0x0000052e,0x00000528,
5290x00000003,0x0005008e,0x00000007,0x0000052f,
5300x0000052c,0x0000052e,0x00050051,0x00000006,
5310x00000532,0x0000052f,0x00000000,0x00050051,
5320x00000006,0x00000533,0x0000052f,0x00000001,
5330x00050051,0x00000006,0x00000534,0x0000052f,
5340x00000002,0x00070050,0x00000014,0x00000535,
5350x00000532,0x00000533,0x00000534,0x0000052e,
5360x000200f9,0x00000538,0x000200f8,0x00000538,
5370x000700f5,0x00000014,0x00000609,0x00000535,
5380x0000052a,0x00000528,0x00000536,0x0008000c,
5390x00000014,0x00000497,0x00000001,0x0000002e,
5400x00000608,0x00000609,0x00000484,0x00050051,
5410x00000006,0x00000499,0x0000046b,0x00000001,
5420x00070050,0x00000014,0x0000049a,0x00000499,
5430x00000499,0x00000499,0x00000499,0x0008000c,
5440x00000014,0x0000049b,0x00000001,0x0000002e,
5450x00000485,0x00000497,0x0000049a,0x000300f7,
5460x000004b1,0x00000000,0x000400fa,0x00000454,
5470x0000049d,0x000004b1,0x000200f8,0x0000049d,
5480x00050051,0x00000006,0x0000049f,0x0000049b,
5490x00000003,0x000500ba,0x00000012,0x000004a0,
5500x0000049f,0x00000038,0x000300f7,0x000004a9,
5510x00000000,0x000400fa,0x000004a0,0x000004a1,
5520x000004a8,0x000200f8,0x000004a8,0x000200f9,
5530x000004a9,0x000200f8,0x000004a1,0x0008004f,
5540x00000007,0x000004a3,0x0000049b,0x0000049b,
5550x00000000,0x00000001,0x00000002,0x00060050,
5560x00000007,0x000004a6,0x0000049f,0x0000049f,
5570x0000049f,0x00050088,0x00000007,0x000004a7,
5580x000004a3,0x000004a6,0x000200f9,0x000004a9,
5590x000200f8,0x000004a9,0x000700f5,0x00000007,
5600x0000060a,0x000004a7,0x000004a1,0x00000101,
5610x000004a8,0x00050051,0x00000006,0x000004ac,
5620x0000060a,0x00000000,0x00060052,0x00000014,
5630x000005ef,0x000004ac,0x0000049b,0x00000000,
5640x00050051,0x00000006,0x000004ae,0x0000060a,
5650x00000001,0x00060052,0x00000014,0x000005f1,
5660x000004ae,0x000005ef,0x00000001,0x00050051,
5670x00000006,0x000004b0,0x0000060a,0x00000002,
5680x00060052,0x00000014,0x000005f3,0x000004b0,
5690x000005f1,0x00000002,0x000200f9,0x000004b1,
5700x000200f8,0x000004b1,0x000700f5,0x00000014,
5710x0000060e,0x0000049b,0x00000538,0x000005f3,
5720x000004a9,0x000200f9,0x000004b2,0x000200f8,
5730x00000458,0x0006000c,0x0000006c,0x0000045a,
5740x00000001,0x00000008,0x0000044b,0x0008000c,
5750x0000006c,0x0000045d,0x00000001,0x0000002b,
5760x0000045a,0x00000443,0x00000451,0x0004006e,
5770x00000010,0x0000045e,0x0000045d,0x0004003d,
5780x0000000d,0x000004c6,0x0000021c,0x0007005f,
5790x00000014,0x000004c8,0x000004c6,0x0000045e,
5800x00000002,0x00000054,0x000200f9,0x000004b2,
5810x000200f8,0x000004b2,0x000700f5,0x00000014,
5820x0000060d,0x000004c8,0x00000458,0x0000060e,
5830x000004b1,0x000500c7,0x0000001c,0x000004b4,
5840x00000227,0x00000107,0x000500ab,0x00000012,
5850x000004b5,0x000004b4,0x00000094,0x000300f7,
5860x000004c0,0x00000000,0x000400fa,0x000004b5,
5870x000004b6,0x000004c0,0x000200f8,0x000004b6,
5880x0008004f,0x00000007,0x000004b8,0x0000060d,
5890x0000060d,0x00000000,0x00000001,0x00000002,
5900x0008000c,0x00000007,0x0000053f,0x00000001,
5910x0000002b,0x000004b8,0x00000101,0x0000062a,
5920x0005008e,0x00000007,0x00000541,0x0000053f,
5930x0000003e,0x0007000c,0x00000007,0x00000543,
5940x00000001,0x0000001a,0x0000053f,0x00000043,
5950x0005008e,0x00000007,0x00000544,0x00000543,
5960x00000040,0x00050083,0x00000007,0x00000546,
5970x00000544,0x0000062b,0x000500ba,0x0000004c,
5980x00000548,0x0000053f,0x0000004b,0x000600a9,
5990x00000007,0x00000549,0x00000548,0x00000546,
6000x00000541,0x00050051,0x00000006,0x000004bb,
6010x00000549,0x00000000,0x00060052,0x00000014,
6020x000005f5,0x000004bb,0x0000060d,0x00000000,
6030x00050051,0x00000006,0x000004bd,0x00000549,
6040x00000001,0x00060052,0x00000014,0x000005f7,
6050x000004bd,0x000005f5,0x00000001,0x00050051,
6060x00000006,0x000004bf,0x00000549,0x00000002,
6070x00060052,0x00000014,0x000005f9,0x000004bf,
6080x000005f7,0x00000002,0x000200f9,0x000004c0,
6090x000200f8,0x000004c0,0x000700f5,0x00000014,
6100x0000060f,0x0000060d,0x000004b2,0x000005f9,
6110x000004b6,0x000500c7,0x0000001c,0x0000022e,
6120x00000227,0x000001fa,0x000500ab,0x00000012,
6130x0000022f,0x0000022e,0x00000094,0x00050051,
6140x00000006,0x00000232,0x0000060f,0x00000003,
6150x0008000c,0x00000006,0x00000233,0x00000001,
6160x0000002b,0x00000232,0x00000038,0x00000039,
6170x00050041,0x0000017f,0x0000023a,0x0000017d,
6180x0000017e,0x0004003d,0x0000001c,0x0000023b,
6190x0000023a,0x000500ab,0x00000012,0x0000023c,
6200x0000023b,0x00000094,0x000500a4,0x00000012,
6210x0000023d,0x0000022f,0x0000023c,0x000300f7,
6220x0000023f,0x00000000,0x000400fa,0x0000023d,
6230x0000023e,0x00000243,0x000200f8,0x00000243,
6240x000500bc,0x00000012,0x00000247,0x00000233,
6250x00000038,0x000500a6,0x00000012,0x00000248,
6260x00000454,0x00000247,0x000300f7,0x0000024b,
6270x00000000,0x000400fa,0x00000248,0x0000024a,
6280x0000024e,0x000200f8,0x0000024e,0x0008004f,
6290x00000007,0x00000250,0x0000060f,0x0000060f,
6300x00000000,0x00000001,0x00000002,0x00060050,
6310x00000007,0x00000252,0x00000233,0x00000233,
6320x00000233,0x00050088,0x00000007,0x00000253,
6330x00000250,0x00000252,0x000200f9,0x0000024b,
6340x000200f8,0x0000024a,0x0008004f,0x00000007,
6350x0000024d,0x0000060f,0x0000060f,0x00000000,
6360x00000001,0x00000002,0x000200f9,0x0000024b,
6370x000200f8,0x0000024b,0x000700f5,0x00000007,
6380x00000610,0x0000024d,0x0000024a,0x00000253,
6390x0000024e,0x000300f7,0x00000576,0x00000000,
6400x000300fb,0x00000094,0x00000553,0x000200f8,
6410x00000553,0x000300f7,0x0000055c,0x00000000,
6420x000400fa,0x0000023d,0x0000055a,0x0000055c,
6430x000200f8,0x0000055a,0x000200f9,0x00000576,
6440x000200f8,0x0000055c,0x000400a8,0x00000012,
6450x0000055e,0x0000022f,0x000300f7,0x0000056a,
6460x00000000,0x000400fa,0x0000055e,0x0000055f,
6470x0000056a,0x000200f8,0x0000055f,0x0008000c,
6480x00000007,0x00000563,0x00000001,0x0000002b,
6490x00000610,0x00000101,0x0000062a,0x0007000c,
6500x00000007,0x00000564,0x00000001,0x0000001a,
6510x00000563,0x00000193,0x00050094,0x00000006,
6520x0000057b,0x00000153,0x00000564,0x00050094,
6530x00000006,0x0000057d,0x00000159,0x00000564,
6540x00050094,0x00000006,0x0000057f,0x0000015f,
6550x00000564,0x00060050,0x00000007,0x00000580,
6560x0000057b,0x0000057d,0x0000057f,0x00050041,
6570x00000198,0x00000566,0x0000017d,0x00000197,
6580x0004003d,0x00000006,0x00000567,0x00000566,
6590x0005008e,0x00000007,0x00000568,0x00000580,
6600x00000567,0x00050085,0x00000007,0x00000586,
6610x00000568,0x00000630,0x0008000c,0x00000007,
6620x00000589,0x00000001,0x0000002b,0x00000586,
6630x00000101,0x0000062a,0x0007000c,0x00000007,
6640x0000058a,0x00000001,0x0000001a,0x00000589,
6650x00000140,0x0005008e,0x00000007,0x0000058c,
6660x0000058a,0x0000012b,0x00050081,0x00000007,
6670x0000058e,0x0000062d,0x0000058c,0x0005008e,
6680x00000007,0x00000590,0x0000058a,0x0000012c,
6690x00050081,0x00000007,0x00000592,0x0000062a,
6700x00000590,0x00050088,0x00000007,0x00000593,
6710x0000058e,0x00000592,0x0007000c,0x00000007,
6720x00000594,0x00000001,0x0000001a,0x00000593,
6730x0000014c,0x000200f9,0x00000576,0x000200f8,
6740x0000056a,0x0008000c,0x00000007,0x0000059b,
6750x00000001,0x0000002b,0x00000610,0x00000101,
6760x0000062a,0x0007000c,0x00000007,0x0000059c,
6770x00000001,0x0000001a,0x0000059b,0x00000122,
6780x00050083,0x00000007,0x0000059f,0x0000059c,
6790x0000062d,0x0007000c,0x00000007,0x000005a1,
6800x00000001,0x00000028,0x0000059f,0x00000101,
6810x0005008e,0x00000007,0x000005a3,0x0000059c,
6820x0000012c,0x00050083,0x00000007,0x000005a5,
6830x0000062e,0x000005a3,0x00050088,0x00000007,
6840x000005a6,0x000005a1,0x000005a5,0x0007000c,
6850x00000007,0x000005a7,0x00000001,0x0000001a,
6860x000005a6,0x00000133,0x0005008e,0x00000007,
6870x000005a8,0x000005a7,0x00000124,0x00050094,
6880x00000006,0x000005ac,0x00000168,0x000005a8,
6890x00050094,0x00000006,0x000005ae,0x0000016e,
6900x000005a8,0x00050094,0x00000006,0x000005b0,
6910x00000174,0x000005a8,0x00060050,0x00000007,
6920x000005b1,0x000005ac,0x000005ae,0x000005b0,
6930x00050041,0x00000198,0x0000056e,0x0000017d,
6940x00000197,0x0004003d,0x00000006,0x0000056f,
6950x0000056e,0x00060050,0x00000007,0x00000570,
6960x0000056f,0x0000056f,0x0000056f,0x00050088,
6970x00000007,0x00000571,0x000005b1,0x00000570,
6980x0008000c,0x00000007,0x00000574,0x00000001,
6990x0000002b,0x00000571,0x00000101,0x0000062a,
7000x0007000c,0x00000007,0x00000575,0x00000001,
7010x0000001a,0x00000574,0x000001ac,0x000200f9,
7020x00000576,0x000200f8,0x00000576,0x000900f5,
7030x00000007,0x00000611,0x00000610,0x0000055a,
7040x00000594,0x0000055f,0x00000575,0x0000056a,
7050x000400a8,0x00000012,0x0000025b,0x00000454,
7060x000300f7,0x0000025d,0x00000000,0x000400fa,
7070x0000025b,0x0000025c,0x0000025d,0x000200f8,
7080x0000025c,0x0005008e,0x00000007,0x00000260,
7090x00000611,0x00000233,0x000200f9,0x0000025d,
7100x000200f8,0x0000025d,0x000700f5,0x00000007,
7110x00000613,0x00000611,0x00000576,0x00000260,
7120x0000025c,0x000200f9,0x0000023f,0x000200f8,
7130x0000023e,0x0008004f,0x00000007,0x00000242,
7140x0000060f,0x0000060f,0x00000000,0x00000001,
7150x00000002,0x000200f9,0x0000023f,0x000200f8,
7160x0000023f,0x000700f5,0x00000007,0x00000612,
7170x00000242,0x0000023e,0x00000613,0x0000025d,
7180x000300f7,0x00000264,0x00000000,0x000400fa,
7190x00000454,0x00000263,0x0000026a,0x000200f8,
7200x0000026a,0x00050083,0x00000006,0x0000026d,
7210x00000039,0x00000233,0x0005008e,0x00000007,
7220x0000026f,0x0000061a,0x0000026d,0x00050081,
7230x00000007,0x00000270,0x00000612,0x0000026f,
7240x000200f9,0x00000264,0x000200f8,0x00000263,
7250x00060050,0x00000007,0x00000268,0x00000233,
7260x00000233,0x00000233,0x0008000c,0x00000007,
7270x00000269,0x00000001,0x0000002e,0x0000061a,
7280x00000612,0x00000268,0x000200f9,0x00000264,
7290x000200f8,0x00000264,0x000700f5,0x00000007,
7300x00000625,0x00000269,0x00000263,0x00000270,
7310x0000026a,0x000200f9,0x0000021a,0x000200f8,
7320x0000021a,0x000700f5,0x00000007,0x00000626,
7330x0000061a,0x00000211,0x00000625,0x00000264,
7340x0004003d,0x00000272,0x00000275,0x00000274,
7350x00050051,0x00000006,0x00000278,0x00000626,
7360x00000000,0x00050051,0x00000006,0x00000279,
7370x00000626,0x00000001,0x00050051,0x00000006,
7380x0000027a,0x00000626,0x00000002,0x00070050,
7390x00000014,0x0000027b,0x00000278,0x00000279,
7400x0000027a,0x00000039,0x00040063,0x00000275,
7410x000001b7,0x0000027b,0x000200f9,0x0000027d,
7420x000200f8,0x0000027d,0x000100fd,0x00010038}
diff --git a/runtime/src/present_compose_spv.h b/runtime/src/present_compose_spv.h
new file mode 100644
index 000000000..966f31976
--- /dev/null
+++ b/runtime/src/present_compose_spv.h
@@ -0,0 +1,11 @@
1#pragma once
2#include <cstdint>
3
4namespace leonida {
5
6// present_compose.comp compiled with: glslc --target-env=vulkan1.1 -O -mfmt=c present_compose.comp -o present_compose.inc
7inline constexpr std::uint32_t present_compose_spirv[] =
8#include "present_compose.inc"
9;
10
11} // namespace leonida
diff --git a/runtime/src/queue_families.h b/runtime/src/queue_families.h
new file mode 100644
index 000000000..32ef1eb1d
--- /dev/null
+++ b/runtime/src/queue_families.h
@@ -0,0 +1,48 @@
1#pragma once
2
3// Picking Vulkan queue families for D3D12's direct, compute and copy queues. Header-only and free of the rest of
4// the backend, so test harnesses can use it too.
5
6#include <vulkan/vulkan.h>
7
8#include <cstdint>
9#include <span>
10
11namespace leonida {
12
13// Queue families for D3D12's three queue types. Direct needs graphics. Compute prefers a family with compute and no
14// graphics (async compute), copy one with transfer and neither (a DMA engine); each falls back to a more capable
15// family, ending at the graphics one. A dedicated copy family is only used when its image transfer granularity is
16// 1x1x1, because D3D12 copies any box.
17struct QueueFamilies {
18 std::uint32_t direct = 0;
19 std::uint32_t compute = 0;
20 std::uint32_t copy = 0;
21};
22
23inline QueueFamilies pick_queue_families(std::span<const VkQueueFamilyProperties> families, std::uint32_t graphics) {
24 QueueFamilies out{graphics, graphics, graphics};
25 constexpr VkQueueFlags g = VK_QUEUE_GRAPHICS_BIT, c = VK_QUEUE_COMPUTE_BIT, t = VK_QUEUE_TRANSFER_BIT;
26 const auto fine_grained = [](const VkQueueFamilyProperties& f) {
27 return f.minImageTransferGranularity.width == 1 && f.minImageTransferGranularity.height == 1 &&
28 f.minImageTransferGranularity.depth == 1;
29 };
30 bool have_compute = false, have_copy = false;
31 for (std::uint32_t i = 0; i < families.size(); ++i) {
32 const auto& f = families[i];
33 if (!f.queueCount) continue;
34 if (!have_compute && (f.queueFlags & c) && !(f.queueFlags & g)) {
35 out.compute = i;
36 have_compute = true;
37 }
38 if (!have_copy && (f.queueFlags & t) && !(f.queueFlags & (g | c)) && fine_grained(f)) {
39 out.copy = i;
40 have_copy = true;
41 }
42 }
43 // No DMA family: copies go to the async-compute family, which can transfer too (compute implies transfer).
44 if (!have_copy && have_compute && fine_grained(families[out.compute])) out.copy = out.compute;
45 return out;
46}
47
48} // namespace leonida
diff --git a/runtime/src/resource_tiling.h b/runtime/src/resource_tiling.h
index e63f7ff45..84f77f747 100644
--- a/runtime/src/resource_tiling.h
+++ b/runtime/src/resource_tiling.h
@@ -13,9 +13,11 @@
13// AMD's PC runtime does on RDNA2 and RDNA4 (D3D-65; the console is AMD): 47 measured layouts, see 13// AMD's PC runtime does on RDNA2 and RDNA4 (D3D-65; the console is AMD): 47 measured layouts, see
14// resource_tiling_test. A standard mip may be smaller than a tile and then takes one tile on that axis. An NVIDIA 14// resource_tiling_test. A standard mip may be smaller than a tile and then takes one tile on that axis. An NVIDIA
15// GPU packs from the first mip smaller than a tile on any axis and WARP packs nothing; the test accepts all of 15// GPU packs from the first mip smaller than a tile on any axis and WARP packs nothing; the test accepts all of
16// them. The packed size is their tight 16// them. The packed tail takes one tile per tile-depth slice it spans: ceil(depth of the first packed mip / tile
17// linear size rounded up to whole tiles (at least one); NVIDIA sometimes reports one more. Applications read the 17// depth), so 1 for 2D, as AMD's PC runtime reports on RDNA2 and RDNA4 (83 measured layouts, see
18// numbers rather than assume them, and this layer backs reserved textures fully, so any split is consistent. 18// resource_tiling_test), and never fewer than the tail's tight linear size in whole tiles. NVIDIA sometimes reports
19// one more. Applications read the numbers rather than assume them, and this layer backs reserved textures fully, so
20// any split is consistent.
19 21
20#include <algorithm> 22#include <algorithm>
21#include <cstdint> 23#include <cstdint>
@@ -137,6 +139,7 @@ inline bool resource_tiling(const TilingDesc& desc, ResourceTiling& out) {
137 // One array slice: standard mips while wider than half a tile or taller than a tile, then the packed tail. 139 // One array slice: standard mips while wider than half a tile or taller than a tile, then the packed tail.
138 std::vector<SubresourceTiling> slice(desc.mips); 140 std::vector<SubresourceTiling> slice(desc.mips);
139 std::uint64_t standard_tiles = 0, packed_bytes = 0; 141 std::uint64_t standard_tiles = 0, packed_bytes = 0;
142 std::uint32_t tail_depth = 0; // depth of the first packed mip
140 for (std::uint32_t mip = 0; mip < desc.mips; ++mip) { 143 for (std::uint32_t mip = 0; mip < desc.mips; ++mip) {
141 const std::uint64_t w = mip >= 64 ? 1 : std::max<std::uint64_t>(1, desc.width >> mip); 144 const std::uint64_t w = mip >= 64 ? 1 : std::max<std::uint64_t>(1, desc.width >> mip);
142 const std::uint32_t h = mip >= 32 ? 1u : std::max(1u, desc.height >> mip); 145 const std::uint32_t h = mip >= 32 ? 1u : std::max(1u, desc.height >> mip);
@@ -160,11 +163,15 @@ inline bool resource_tiling(const TilingDesc& desc, ResourceTiling& out) {
160 up(w, desc.block) * up(h, desc.block) * desc.element_bytes * desc.samples; 163 up(w, desc.block) * up(h, desc.block) * desc.element_bytes * desc.samples;
161 if (d > (max_packed_bytes - packed_bytes) / row_slice_bytes) return false; 164 if (d > (max_packed_bytes - packed_bytes) / row_slice_bytes) return false;
162 packed_bytes += row_slice_bytes * d; 165 packed_bytes += row_slice_bytes * d;
166 if (result.packed_mips == 0) tail_depth = d;
163 ++result.packed_mips; 167 ++result.packed_mips;
164 } 168 }
165 } 169 }
170 // One tile per tile-depth slice of the tail (AMD), at least its tight size; 1 for 2D.
166 const std::uint64_t packed_tiles = 171 const std::uint64_t packed_tiles =
167 result.packed_mips ? std::max<std::uint64_t>(1, up(packed_bytes, tile_size_in_bytes)) : 0; 172 result.packed_mips ? std::max<std::uint64_t>({1, up(packed_bytes, tile_size_in_bytes),
173 up(tail_depth, result.shape.depth)})
174 : 0;
168 if (packed_tiles > max_tiles - standard_tiles) return false; 175 if (packed_tiles > max_tiles - standard_tiles) return false;
169 const std::uint64_t per_slice = standard_tiles + packed_tiles; 176 const std::uint64_t per_slice = standard_tiles + packed_tiles;
170 if (per_slice > max_tiles / layers) return false; 177 if (per_slice > max_tiles / layers) return false;
diff --git a/runtime/src/root_signature.cpp b/runtime/src/root_signature.cpp
index 762dd704e..844f1b580 100644
--- a/runtime/src/root_signature.cpp
+++ b/runtime/src/root_signature.cpp
@@ -13,6 +13,10 @@ PackResult pack(const RootSignature& sig) {
13 } 13 }
14 uint64_t cost = 0; // 64-bit: a parameter of 0xFFFFFFFF constants must not wrap past the limits 14 uint64_t cost = 0; // 64-bit: a parameter of 0xFFFFFFFF constants must not wrap past the limits
15 for (const RootParameter& p : sig.params) { 15 for (const RootParameter& p : sig.params) {
16 if (p.type != ParamType::Constants && p.type != ParamType::Descriptor && p.type != ParamType::Table) {
17 out.error = "unknown root parameter type";
18 return out;
19 }
16 if (p.type == ParamType::Constants && p.num_values == 0) { 20 if (p.type == ParamType::Constants && p.num_values == 0) {
17 out.error = "root constant parameter needs at least 1 dword"; 21 out.error = "root constant parameter needs at least 1 dword";
18 return out; 22 return out;
diff --git a/runtime/src/shader_library.h b/runtime/src/shader_library.h
index c8c994451..5a02ed437 100644
--- a/runtime/src/shader_library.h
+++ b/runtime/src/shader_library.h
@@ -8,6 +8,8 @@
8// writes into `spirv/index.json`, next to `<name>.spv`. This header needs no Windows, Vulkan or third-party code: 8// writes into `spirv/index.json`, next to `<name>.spv`. This header needs no Windows, Vulkan or third-party code:
9// it carries its own inflate (RFC 1950/1951), SHA-256 (FIPS 180-4) and a minimal JSON reader. 9// it carries its own inflate (RFC 1950/1951), SHA-256 (FIPS 180-4) and a minimal JSON reader.
10 10
11#include "spirv_words.h"
12
11#include <algorithm> 13#include <algorithm>
12#include <array> 14#include <array>
13#include <cerrno> 15#include <cerrno>
@@ -636,7 +638,10 @@ struct ShaderEntry {
636 std::string wave64_exchange; 638 std::string wave64_exchange;
637 bool emulated() const { return !wave64_exchange.empty(); } 639 bool emulated() const { return !wave64_exchange.empty(); }
638 std::vector<SignatureElement> input_signature; // vertex shaders: what the input layout must feed 640 std::vector<SignatureElement> input_signature; // vertex shaders: what the input layout must feed
639 std::vector<std::uint32_t> outputs; // pixel shaders: the render-target locations written 641 std::vector<std::uint32_t> inputs; // pixel shaders: input locations declared
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).
644 std::map<std::uint32_t, std::array<std::uint32_t, 2>> f16_halves;
640}; 645};
641 646
642class ShaderLibrary { 647class ShaderLibrary {
@@ -717,13 +722,8 @@ public:
717 722
718 // The module's words, or empty when <dir>/<name>.spv is missing or not SPIR-V. 723 // The module's words, or empty when <dir>/<name>.spv is missing or not SPIR-V.
719 std::vector<std::uint32_t> spirv(const ShaderEntry& entry) const { 724 std::vector<std::uint32_t> spirv(const ShaderEntry& entry) const {
720 std::ifstream file(dir_ + "/" + entry.name + ".spv", std::ios::binary); 725 std::ifstream file(dir_ + "/" + entry.name + ".spv", std::ios::binary | std::ios::ate);
721 if (!file) return {}; 726 return read_spirv_words(file, file.tellg());
722 const std::string bytes((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
723 if (bytes.size() < 20 || bytes.size() % 4) return {};
724 std::vector<std::uint32_t> words(bytes.size() / 4);
725 std::memcpy(words.data(), bytes.data(), bytes.size());
726 return words[0] == 0x07230203 ? words : std::vector<std::uint32_t>{};
727 } 727 }
728 728
729private: 729private:
@@ -796,8 +796,19 @@ private:
796 e.input_signature.push_back(std::move(element)); 796 e.input_signature.push_back(std::move(element));
797 } 797 }
798 } 798 }
799 if (const Json* in = meta.find("inputs"); in && in->kind == Json::Kind::array)
800 for (const Json& item : in->array) e.inputs.push_back(u32(&item));
799 if (const Json* o = meta.find("outputs"); o && o->kind == Json::Kind::array) 801 if (const Json* o = meta.find("outputs"); o && o->kind == Json::Kind::array)
800 for (const Json& item : o->array) e.outputs.push_back(u32(&item)); 802 for (const Json& item : o->array) e.outputs.push_back(u32(&item));
803 if (const Json* fh = meta.find("f16_halves"); fh && fh->kind == Json::Kind::object) {
804 for (const auto& [key, val] : fh->object) {
805 if (key.empty() || val.kind != Json::Kind::array || val.array.size() != 2) continue;
806 char* end = nullptr;
807 const unsigned long param = std::strtoul(key.c_str(), &end, 10);
808 if (!end || *end != '\0') continue;
809 e.f16_halves[std::uint32_t(param)] = {u32(&val.array[0]), u32(&val.array[1])};
810 }
811 }
801 if (by_fspx) fspx_entries_[{e.stage, e.fspx_code_sha256}].push_back(e); 812 if (by_fspx) fspx_entries_[{e.stage, e.fspx_code_sha256}].push_back(e);
802 if (by_fssm) entries_[{e.stage, e.fssm_sha256}].push_back(std::move(e)); 813 if (by_fssm) entries_[{e.stage, e.fssm_sha256}].push_back(std::move(e));
803 ++count_; 814 ++count_;
diff --git a/runtime/src/spirv_f16_halves.h b/runtime/src/spirv_f16_halves.h
new file mode 100644
index 000000000..5dffb64ed
--- /dev/null
+++ b/runtime/src/spirv_f16_halves.h
@@ -0,0 +1,617 @@
1#pragma once
2
3// Per-pipeline `--f16-interp-fallback` half placement and SPIR-V specialization (SHADER-378).
4//
5// Under `--f16-interp-fallback` (MoltenVK / devices without PerVertexKHR), a pixel shader reads decoded f16 halves
6// as ordinary smooth vec4 inputs recorded in `index.json` under `f16_halves: {param: [lo_loc, hi_loc]}`. When a
7// producer (VS) exports many params (up to 16) or a PS reads high attributes alongside f16 attributes, no fixed
8// static location map fits all pairs within MoltenVK's 30 locations (0..29, 124 output components counting
9// gl_Position). At graphics PSO creation, once both VS and PS are known, `link_f16_halves`:
10// 1. Fast-paths unchanged when every PS `f16_halves` entry is already exported at the exact same locations by VS.
11// 2. Chooses mutually non-colliding `[lo_loc, hi_loc]` slots in `0..top_location` (keeping PS locations unchanged
12// whenever they do not collide with any raw VS output; otherwise relocating PS `OpDecorate Location` in place).
13// 3. Specializes the VS SPIR-V binary for the pair: reuses matching static `f16_halves` outputs (updating their
14// `Location` decorations), demotes unneeded static `f16_halves` outputs to `Private` (freeing their locations),
15// and synthesizes `UnpackHalf2x16` half exports right before every `OpReturn` in the Vertex entry function for
16// any param the VS did not emit statically.
17//
18// Pure C++20 stdlib, no Vulkan or Windows headers required.
19
20#include "shader_library.h"
21
22#include <algorithm>
23#include <array>
24#include <cstdint>
25#include <map>
26#include <set>
27#include <span>
28#include <string>
29#include <vector>
30
31namespace leonida {
32
33namespace spirv_detail {
34
35constexpr std::uint32_t kSpirvMagic = 0x07230203u;
36constexpr std::uint32_t kSpirvVersion14 = 0x00010400u;
37
38constexpr std::uint16_t kOpSourceContinued = 2;
39constexpr std::uint16_t kOpSource = 3;
40constexpr std::uint16_t kOpSourceExtension = 4;
41constexpr std::uint16_t kOpName = 5;
42constexpr std::uint16_t kOpMemberName = 6;
43constexpr std::uint16_t kOpString = 7;
44constexpr std::uint16_t kOpExtension = 10;
45constexpr std::uint16_t kOpExtInstImport = 11;
46constexpr std::uint16_t kOpExtInst = 12;
47constexpr std::uint16_t kOpMemoryModel = 14;
48constexpr std::uint16_t kOpEntryPoint = 15;
49constexpr std::uint16_t kOpExecutionMode = 16;
50constexpr std::uint16_t kOpCapability = 17;
51constexpr std::uint16_t kOpTypeInt = 21;
52constexpr std::uint16_t kOpTypeFloat = 22;
53constexpr std::uint16_t kOpTypeVector = 23;
54constexpr std::uint16_t kOpTypePointer = 32;
55constexpr std::uint16_t kOpConstantNull = 46;
56constexpr std::uint16_t kOpFunction = 54;
57constexpr std::uint16_t kOpFunctionEnd = 56;
58constexpr std::uint16_t kOpVariable = 59;
59constexpr std::uint16_t kOpLoad = 61;
60constexpr std::uint16_t kOpStore = 62;
61constexpr std::uint16_t kOpAccessChain = 65;
62constexpr std::uint16_t kOpInBoundsAccessChain = 66;
63constexpr std::uint16_t kOpDecorate = 71;
64constexpr std::uint16_t kOpMemberDecorate = 72;
65constexpr std::uint16_t kOpDecorationGroup = 73;
66constexpr std::uint16_t kOpGroupDecorate = 74;
67constexpr std::uint16_t kOpGroupMemberDecorate = 75;
68constexpr std::uint16_t kOpCompositeConstruct = 80;
69constexpr std::uint16_t kOpCompositeExtract = 81;
70constexpr std::uint16_t kOpBitcast = 124;
71constexpr std::uint16_t kOpReturn = 253;
72constexpr std::uint16_t kOpModuleProcessed = 330;
73constexpr std::uint16_t kOpExecutionModeId = 331;
74constexpr std::uint16_t kOpDecorateId = 332;
75constexpr std::uint16_t kOpDecorateString = 5632;
76constexpr std::uint16_t kOpMemberDecorateString = 5633;
77
78constexpr std::uint32_t kExecModelVertex = 0;
79constexpr std::uint32_t kExecModelFragment = 4;
80
81constexpr std::uint32_t kStorageInput = 1;
82constexpr std::uint32_t kStorageOutput = 3;
83constexpr std::uint32_t kStoragePrivate = 6;
84
85constexpr std::uint32_t kDecorationLocation = 30;
86constexpr std::uint32_t kGlslUnpackHalf2x16 = 62;
87
88struct Inst {
89 std::uint16_t opcode = 0;
90 std::vector<std::uint32_t> words;
91};
92
93inline Inst make_inst(std::uint16_t opcode, std::initializer_list<std::uint32_t> operands) {
94 Inst inst;
95 inst.opcode = opcode;
96 inst.words.reserve(1 + operands.size());
97 inst.words.push_back((std::uint32_t(1 + operands.size()) << 16) | opcode);
98 for (std::uint32_t w : operands) inst.words.push_back(w);
99 return inst;
100}
101
102inline Inst make_inst_vec(std::uint16_t opcode, const std::vector<std::uint32_t>& operands) {
103 Inst inst;
104 inst.opcode = opcode;
105 inst.words.reserve(1 + operands.size());
106 inst.words.push_back((std::uint32_t(1 + operands.size()) << 16) | opcode);
107 inst.words.insert(inst.words.end(), operands.begin(), operands.end());
108 return inst;
109}
110
111struct Module {
112 std::array<std::uint32_t, 5> header{};
113 std::vector<Inst> insts;
114
115 bool parse(std::span<const std::uint32_t> words) {
116 if (words.size() < 5 || words[0] != kSpirvMagic || words[3] == 0) return false;
117 for (std::size_t i = 0; i < 5; ++i) header[i] = words[i];
118 insts.clear();
119 std::size_t pos = 5;
120 while (pos < words.size()) {
121 const std::uint32_t head = words[pos];
122 const std::uint32_t wc = head >> 16;
123 const std::uint16_t op = std::uint16_t(head & 0xffffu);
124 if (wc == 0 || pos + wc > words.size()) return false;
125 Inst inst;
126 inst.opcode = op;
127 inst.words.assign(words.begin() + std::ptrdiff_t(pos), words.begin() + std::ptrdiff_t(pos + wc));
128 insts.push_back(std::move(inst));
129 pos += wc;
130 }
131 return true;
132 }
133
134 std::vector<std::uint32_t> serialize() const {
135 std::size_t total = 5;
136 for (const Inst& inst : insts) total += inst.words.size();
137 std::vector<std::uint32_t> out;
138 out.reserve(total);
139 out.insert(out.end(), header.begin(), header.end());
140 for (const Inst& inst : insts) out.insert(out.end(), inst.words.begin(), inst.words.end());
141 return out;
142 }
143
144 std::uint32_t alloc_id() { return header[3]++; }
145};
146
147inline bool is_pre_type_opcode(std::uint16_t op) {
148 switch (op) {
149 case kOpCapability:
150 case kOpExtension:
151 case kOpExtInstImport:
152 case kOpMemoryModel:
153 case kOpEntryPoint:
154 case kOpExecutionMode:
155 case kOpExecutionModeId:
156 case kOpString:
157 case kOpSourceContinued:
158 case kOpSource:
159 case kOpSourceExtension:
160 case kOpName:
161 case kOpMemberName:
162 case kOpModuleProcessed:
163 case kOpDecorate:
164 case kOpMemberDecorate:
165 case kOpDecorationGroup:
166 case kOpGroupDecorate:
167 case kOpGroupMemberDecorate:
168 case kOpDecorateId:
169 case kOpDecorateString:
170 case kOpMemberDecorateString:
171 return true;
172 default:
173 return false;
174 }
175}
176
177inline std::string decode_literal_string(std::span<const std::uint32_t> words) {
178 std::string s;
179 for (std::uint32_t w : words) {
180 for (int b = 0; b < 4; ++b) {
181 const char c = char((w >> (8 * b)) & 0xffu);
182 if (c == '\0') return s;
183 s.push_back(c);
184 }
185 }
186 return s;
187}
188
189inline std::size_t entry_point_interface_start(const Inst& ep) {
190 // OpEntryPoint <ExecModel> <EntryPointId> <Name...> <InterfaceIds...>
191 for (std::size_t i = 3; i < ep.words.size(); ++i) {
192 const std::uint32_t w = ep.words[i];
193 if ((w & 0x000000ffu) == 0 || (w & 0x0000ff00u) == 0 || (w & 0x00ff0000u) == 0 || (w & 0xff000000u) == 0)
194 return i + 1;
195 }
196 return ep.words.size();
197}
198
199// Collects global OpVariables of `storage_class` that carry `OpDecorate <id> Location <loc>`.
200// Returns map: location -> variable_id (first variable found at that location).
201inline std::map<std::uint32_t, std::uint32_t> collect_located_vars(const Module& mod, std::uint32_t storage_class) {
202 std::map<std::uint32_t, std::uint32_t> var_storage;
203 for (const Inst& inst : mod.insts) {
204 if (inst.opcode == kOpFunction) break;
205 if (inst.opcode == kOpVariable && inst.words.size() >= 4) var_storage[inst.words[2]] = inst.words[3];
206 }
207 std::map<std::uint32_t, std::uint32_t> by_loc;
208 for (const Inst& inst : mod.insts) {
209 if (inst.opcode == kOpDecorate && inst.words.size() >= 4 && inst.words[2] == kDecorationLocation) {
210 const std::uint32_t target = inst.words[1];
211 const auto it = var_storage.find(target);
212 if (it != var_storage.end() && it->second == storage_class) by_loc.emplace(inst.words[3], target);
213 }
214 }
215 return by_loc;
216}
217
218} // namespace spirv_detail
219
220// Specializes/patches `vs_words` and (if needed) `ps_words` so that every entry in `ps_entry.f16_halves` is
221// exported by the VS at the exact smooth location the PS reads, within `0..top_location` (default 29, MoltenVK's
222// 124-component vertex output limit counting gl_Position).
223//
224// Returns true on success (including the no-op fast path when no patching is needed). On failure returns false and
225// writes a concise reason to `*error` if non-null; the caller's word vectors are only replaced on success.
226inline bool link_f16_halves(std::vector<std::uint32_t>& vs_words, const ShaderEntry& vs_entry,
227 std::vector<std::uint32_t>& ps_words, const ShaderEntry& ps_entry,
228 std::string* error = nullptr, std::uint32_t top_location = 29) {
229 const auto fail = [&](const std::string& msg) {
230 if (error) *error = msg;
231 return false;
232 };
233 if (ps_entry.f16_halves.empty()) return true;
234
235 // Fast path: every PS half pair is already exported at the exact same locations by VS.
236 bool already_linked = true;
237 for (const auto& [param, ps_pair] : ps_entry.f16_halves) {
238 const auto it = vs_entry.f16_halves.find(param);
239 if (it == vs_entry.f16_halves.end() || it->second != ps_pair) {
240 already_linked = false;
241 break;
242 }
243 }
244 if (already_linked) return true;
245
246 using namespace spirv_detail;
247 Module vs_mod, ps_mod;
248 if (!vs_mod.parse(vs_words)) return fail("f16_halves: malformed VS SPIR-V");
249 if (!ps_mod.parse(ps_words)) return fail("f16_halves: malformed PS SPIR-V");
250
251 const auto vs_outputs = collect_located_vars(vs_mod, kStorageOutput);
252 const auto ps_inputs = collect_located_vars(ps_mod, kStorageInput);
253
254 std::set<std::uint32_t> vs_static_half_locs;
255 for (const auto& [param, pair] : vs_entry.f16_halves) {
256 vs_static_half_locs.insert(pair[0]);
257 vs_static_half_locs.insert(pair[1]);
258 }
259 std::set<std::uint32_t> ps_static_half_locs;
260 for (const auto& [param, pair] : ps_entry.f16_halves) {
261 ps_static_half_locs.insert(pair[0]);
262 ps_static_half_locs.insert(pair[1]);
263 }
264
265 // Raw outputs of VS (all located Output variables excluding VS's own static f16_halves).
266 std::map<std::uint32_t, std::uint32_t> vs_raw_outputs;
267 std::set<std::uint32_t> vs_raw_locs;
268 for (const auto& [loc, var_id] : vs_outputs) {
269 if (!vs_static_half_locs.count(loc)) {
270 vs_raw_outputs[loc] = var_id;
271 vs_raw_locs.insert(loc);
272 }
273 }
274 std::set<std::uint32_t> ps_raw_locs;
275 for (const auto& [loc, var_id] : ps_inputs) {
276 if (!ps_static_half_locs.count(loc)) ps_raw_locs.insert(loc);
277 }
278
279 // Choose paired [lo, hi] locations for every param in ps_entry.f16_halves.
280 // Keep PS's existing locations unchanged whenever none collides with VS raw outputs or exceeds top_location.
281 bool keep_ps_locs = true;
282 std::set<std::uint32_t> seen_ps_halves;
283 for (const auto& [param, pair] : ps_entry.f16_halves) {
284 for (std::uint32_t loc : pair) {
285 if (loc > top_location || vs_raw_locs.count(loc) || !seen_ps_halves.insert(loc).second) {
286 keep_ps_locs = false;
287 break;
288 }
289 }
290 if (!keep_ps_locs) break;
291 }
292
293 std::map<std::uint32_t, std::array<std::uint32_t, 2>> pair_halves;
294 if (keep_ps_locs) {
295 pair_halves = ps_entry.f16_halves;
296 } else {
297 std::set<std::uint32_t> reserved = vs_raw_locs;
298 reserved.insert(ps_raw_locs.begin(), ps_raw_locs.end());
299 std::vector<std::uint32_t> free_locs;
300 for (std::int64_t loc = top_location; loc >= 0; --loc)
301 if (!reserved.count(std::uint32_t(loc))) free_locs.push_back(std::uint32_t(loc));
302 const std::size_t need = 2 * ps_entry.f16_halves.size();
303 if (free_locs.size() < need)
304 return fail("f16_halves: need " + std::to_string(need) + " free locations in 0.." +
305 std::to_string(top_location) + ", only " + std::to_string(free_locs.size()) + " available");
306 std::size_t k = 0;
307 for (const auto& [param, old_pair] : ps_entry.f16_halves) {
308 const std::uint32_t hi = free_locs[2 * k];
309 const std::uint32_t lo = free_locs[2 * k + 1];
310 pair_halves[param] = {lo, hi};
311 ++k;
312 }
313 }
314
315 // Patch PS OpDecorate Location in place if we relocated any PS half input.
316 bool ps_changed = false;
317 if (!keep_ps_locs) {
318 std::map<std::uint32_t, std::uint32_t> ps_var_new_loc;
319 for (const auto& [param, old_pair] : ps_entry.f16_halves) {
320 const auto& new_pair = pair_halves[param];
321 for (std::size_t h = 0; h < 2; ++h) {
322 const auto it = ps_inputs.find(old_pair[h]);
323 if (it != ps_inputs.end()) ps_var_new_loc[it->second] = new_pair[h];
324 }
325 }
326 for (Inst& inst : ps_mod.insts) {
327 if (inst.opcode == kOpDecorate && inst.words.size() >= 4 && inst.words[2] == kDecorationLocation) {
328 const auto it = ps_var_new_loc.find(inst.words[1]);
329 if (it != ps_var_new_loc.end() && inst.words[3] != it->second) {
330 inst.words[3] = it->second;
331 ps_changed = true;
332 }
333 }
334 }
335 }
336
337 // Inspect VS types, globals, entry point, and uses of existing static f16_halves variables.
338 std::uint32_t float_ty = 0, uint_ty = 0, v2float_ty = 0, v4float_ty = 0;
339 std::uint32_t ptr_out_v4_ty = 0, ptr_priv_v4_ty = 0, null_v4_id = 0, glsl_id = 0;
340 std::map<std::uint32_t, std::uint32_t> ptr_pointee; // ptr_type_id -> pointee_type_id
341 std::map<std::uint32_t, std::uint32_t> var_ptr_type; // var_id -> ptr_type_id
342 std::uint32_t vs_entry_fn = 0;
343 std::size_t vs_ep_idx = vs_mod.insts.size();
344
345 for (std::size_t idx = 0; idx < vs_mod.insts.size(); ++idx) {
346 const Inst& inst = vs_mod.insts[idx];
347 if (inst.opcode == kOpExtInstImport && inst.words.size() >= 3) {
348 if (decode_literal_string(std::span<const std::uint32_t>(inst.words).subspan(2)) == "GLSL.std.450")
349 glsl_id = inst.words[1];
350 } else if (inst.opcode == kOpEntryPoint && inst.words.size() >= 4 && inst.words[1] == kExecModelVertex) {
351 if (vs_ep_idx == vs_mod.insts.size()) {
352 vs_ep_idx = idx;
353 vs_entry_fn = inst.words[2];
354 }
355 } else if (inst.opcode == kOpTypeFloat && inst.words.size() == 3 && inst.words[2] == 32) {
356 float_ty = inst.words[1];
357 } else if (inst.opcode == kOpTypeInt && inst.words.size() == 4 && inst.words[2] == 32 && inst.words[3] == 0) {
358 uint_ty = inst.words[1];
359 } else if (inst.opcode == kOpTypeVector && inst.words.size() == 4) {
360 if (float_ty && inst.words[2] == float_ty && inst.words[3] == 2) v2float_ty = inst.words[1];
361 if (float_ty && inst.words[2] == float_ty && inst.words[3] == 4) v4float_ty = inst.words[1];
362 } else if (inst.opcode == kOpTypePointer && inst.words.size() == 4) {
363 ptr_pointee[inst.words[1]] = inst.words[3];
364 if (v4float_ty && inst.words[3] == v4float_ty) {
365 if (inst.words[2] == kStorageOutput) ptr_out_v4_ty = inst.words[1];
366 if (inst.words[2] == kStoragePrivate) ptr_priv_v4_ty = inst.words[1];
367 }
368 } else if (inst.opcode == kOpConstantNull && inst.words.size() == 3 && v4float_ty && inst.words[1] == v4float_ty) {
369 null_v4_id = inst.words[2];
370 } else if (inst.opcode == kOpVariable && inst.words.size() >= 4) {
371 var_ptr_type[inst.words[2]] = inst.words[1];
372 } else if (inst.opcode == kOpFunction) {
373 break;
374 }
375 }
376 if (vs_ep_idx == vs_mod.insts.size() || !vs_entry_fn) return fail("f16_halves: VS has no Vertex entry point");
377
378 // Check which existing VS variables are addressed by OpAccessChain (those cannot be trivially demoted to Private).
379 std::set<std::uint32_t> access_chained_vars;
380 for (const Inst& inst : vs_mod.insts) {
381 if ((inst.opcode == kOpAccessChain || inst.opcode == kOpInBoundsAccessChain) && inst.words.size() >= 4)
382 access_chained_vars.insert(inst.words[3]);
383 }
384
385 // Decide per VS static f16_halves entry: reuse (update Location) or demote (Output -> Private, drop Location).
386 std::map<std::uint32_t, std::uint32_t> vs_var_new_loc;
387 std::set<std::uint32_t> demote_vars;
388 std::set<std::uint32_t> satisfied_params;
389 for (const auto& [param, old_pair] : vs_entry.f16_halves) {
390 const auto lo_it = vs_outputs.find(old_pair[0]);
391 const auto hi_it = vs_outputs.find(old_pair[1]);
392 const auto want_it = pair_halves.find(param);
393 if (want_it != pair_halves.end() && lo_it != vs_outputs.end() && hi_it != vs_outputs.end()) {
394 vs_var_new_loc[lo_it->second] = want_it->second[0];
395 vs_var_new_loc[hi_it->second] = want_it->second[1];
396 satisfied_params.insert(param);
397 } else {
398 for (const auto& it : {lo_it, hi_it}) {
399 if (it == vs_outputs.end()) continue;
400 const std::uint32_t vid = it->second;
401 const auto pty = var_ptr_type.find(vid);
402 const bool is_v4 = pty != var_ptr_type.end() && v4float_ty && ptr_pointee[pty->second] == v4float_ty;
403 if (!is_v4 || access_chained_vars.count(vid))
404 return fail("f16_halves: cannot demote non-vec4 or access-chained VS static half output");
405 demote_vars.insert(vid);
406 }
407 }
408 }
409
410 // Params that must be synthesized in the VS epilogue.
411 struct SynthParam {
412 std::uint32_t param = 0;
413 std::uint32_t src_var = 0; // 0 if VS does not export this param (emit null vec4)
414 std::uint32_t lo_loc = 0;
415 std::uint32_t hi_loc = 0;
416 std::uint32_t lo_var = 0;
417 std::uint32_t hi_var = 0;
418 };
419 std::vector<SynthParam> synth;
420 bool need_null_v4 = false;
421 for (const auto& [param, target_pair] : pair_halves) {
422 if (satisfied_params.count(param)) continue;
423 SynthParam sp;
424 sp.param = param;
425 sp.lo_loc = target_pair[0];
426 sp.hi_loc = target_pair[1];
427 const auto raw_it = vs_raw_outputs.find(param);
428 if (raw_it != vs_raw_outputs.end()) {
429 const auto pty = var_ptr_type.find(raw_it->second);
430 if (pty == var_ptr_type.end() || !v4float_ty || ptr_pointee[pty->second] != v4float_ty)
431 return fail("f16_halves: VS param " + std::to_string(param) + " output is not vec4 float");
432 sp.src_var = raw_it->second;
433 } else {
434 need_null_v4 = true;
435 }
436 synth.push_back(sp);
437 }
438
439 // Create any missing types / GLSL.std.450 import needed for demotion or synthesis.
440 std::vector<Inst> new_types;
441 const bool need_glsl = std::any_of(synth.begin(), synth.end(), [](const SynthParam& s) { return s.src_var != 0; });
442 bool insert_glsl = false;
443 if (need_glsl && !glsl_id) {
444 glsl_id = vs_mod.alloc_id();
445 insert_glsl = true;
446 }
447 if ((!synth.empty() || !demote_vars.empty()) && !float_ty) {
448 float_ty = vs_mod.alloc_id();
449 new_types.push_back(make_inst(kOpTypeFloat, {float_ty, 32}));
450 }
451 if (need_glsl && !uint_ty) {
452 uint_ty = vs_mod.alloc_id();
453 new_types.push_back(make_inst(kOpTypeInt, {uint_ty, 32, 0}));
454 }
455 if (need_glsl && !v2float_ty) {
456 v2float_ty = vs_mod.alloc_id();
457 new_types.push_back(make_inst(kOpTypeVector, {v2float_ty, float_ty, 2}));
458 }
459 if ((!synth.empty() || !demote_vars.empty()) && !v4float_ty) {
460 v4float_ty = vs_mod.alloc_id();
461 new_types.push_back(make_inst(kOpTypeVector, {v4float_ty, float_ty, 4}));
462 }
463 if (!synth.empty() && !ptr_out_v4_ty) {
464 ptr_out_v4_ty = vs_mod.alloc_id();
465 new_types.push_back(make_inst(kOpTypePointer, {ptr_out_v4_ty, kStorageOutput, v4float_ty}));
466 }
467 if (!demote_vars.empty() && !ptr_priv_v4_ty) {
468 ptr_priv_v4_ty = vs_mod.alloc_id();
469 new_types.push_back(make_inst(kOpTypePointer, {ptr_priv_v4_ty, kStoragePrivate, v4float_ty}));
470 }
471 if (need_null_v4 && !null_v4_id) {
472 null_v4_id = vs_mod.alloc_id();
473 new_types.push_back(make_inst(kOpConstantNull, {v4float_ty, null_v4_id}));
474 }
475
476 // Allocate Output OpVariables for synthesized params.
477 std::vector<Inst> new_decorates;
478 std::vector<Inst> new_vars;
479 for (SynthParam& sp : synth) {
480 sp.lo_var = vs_mod.alloc_id();
481 sp.hi_var = vs_mod.alloc_id();
482 new_decorates.push_back(make_inst(kOpDecorate, {sp.lo_var, kDecorationLocation, sp.lo_loc}));
483 new_decorates.push_back(make_inst(kOpDecorate, {sp.hi_var, kDecorationLocation, sp.hi_loc}));
484 new_vars.push_back(make_inst(kOpVariable, {ptr_out_v4_ty, sp.lo_var, kStorageOutput}));
485 new_vars.push_back(make_inst(kOpVariable, {ptr_out_v4_ty, sp.hi_var, kStorageOutput}));
486 }
487
488 // Rebuild VS instruction stream in exact SPIR-V logical layout order.
489 // Demoted OpVariables are emitted right after new_types (before the first OpFunction) so ptr_priv_v4_ty is
490 // always defined before every OpVariable that uses it.
491 const bool drop_private_from_ep = vs_mod.header[1] < kSpirvVersion14;
492 std::vector<Inst> demoted_var_insts;
493 std::vector<Inst> out_insts;
494 out_insts.reserve(vs_mod.insts.size() + new_types.size() + new_decorates.size() + new_vars.size() +
495 synth.size() * 32);
496
497 bool glsl_inserted = !insert_glsl;
498 bool decorates_inserted = new_decorates.empty();
499 bool globals_inserted = new_types.empty() && new_vars.empty() && demote_vars.empty();
500 bool in_entry_fn = false;
501 bool found_entry_return = false;
502
503 for (std::size_t idx = 0; idx < vs_mod.insts.size(); ++idx) {
504 Inst inst = vs_mod.insts[idx];
505
506 // Insert OpExtInstImport "GLSL.std.450" right before OpMemoryModel if the module didn't already have it.
507 if (!glsl_inserted && inst.opcode == kOpMemoryModel) {
508 // "GLSL.std.450\0" -> 4 little-endian words: 0x4c534c47, 0x6474732e, 0x3035342e, 0x00000000
509 out_insts.push_back(
510 make_inst(kOpExtInstImport, {glsl_id, 0x4c534c47u, 0x6474732eu, 0x3035342eu, 0x00000000u}));
511 glsl_inserted = true;
512 }
513
514 // Insert new OpDecorate instructions at the end of the Annotations section (before the first type/global).
515 if (!decorates_inserted && !is_pre_type_opcode(inst.opcode)) {
516 out_insts.insert(out_insts.end(), new_decorates.begin(), new_decorates.end());
517 decorates_inserted = true;
518 }
519
520 // Insert new Types / Constants, demoted Private OpVariables, and new Output OpVariables before OpFunction.
521 if (!globals_inserted && inst.opcode == kOpFunction) {
522 out_insts.insert(out_insts.end(), new_types.begin(), new_types.end());
523 out_insts.insert(out_insts.end(), demoted_var_insts.begin(), demoted_var_insts.end());
524 out_insts.insert(out_insts.end(), new_vars.begin(), new_vars.end());
525 globals_inserted = true;
526 }
527
528 // Update Vertex OpEntryPoint interface list.
529 if (idx == vs_ep_idx) {
530 const std::size_t if_start = entry_point_interface_start(inst);
531 std::vector<std::uint32_t> operands(inst.words.begin() + 1, inst.words.begin() + std::ptrdiff_t(if_start));
532 for (std::size_t i = if_start; i < inst.words.size(); ++i) {
533 const std::uint32_t id = inst.words[i];
534 if (drop_private_from_ep && demote_vars.count(id)) continue;
535 operands.push_back(id);
536 }
537 for (const SynthParam& sp : synth) {
538 operands.push_back(sp.lo_var);
539 operands.push_back(sp.hi_var);
540 }
541 out_insts.push_back(make_inst_vec(kOpEntryPoint, operands));
542 continue;
543 }
544
545 // Update or remove OpDecorate Location on static VS f16_halves outputs.
546 if (inst.opcode == kOpDecorate && inst.words.size() >= 4 && inst.words[2] == kDecorationLocation) {
547 const std::uint32_t target = inst.words[1];
548 if (demote_vars.count(target)) continue; // drop Location decoration from demoted Private variable
549 const auto it = vs_var_new_loc.find(target);
550 if (it != vs_var_new_loc.end()) inst.words[3] = it->second;
551 out_insts.push_back(std::move(inst));
552 continue;
553 }
554
555 // Demote unneeded static VS f16_halves OpVariable from Output to Private (emitted after new_types).
556 if (!globals_inserted && inst.opcode == kOpVariable && inst.words.size() >= 4 &&
557 demote_vars.count(inst.words[2])) {
558 inst.words[1] = ptr_priv_v4_ty;
559 inst.words[3] = kStoragePrivate;
560 demoted_var_insts.push_back(std::move(inst));
561 continue;
562 }
563
564 // Track Vertex entry function and inject UnpackHalf2x16 epilogue before every OpReturn inside it.
565 if (inst.opcode == kOpFunction && inst.words.size() >= 3 && inst.words[2] == vs_entry_fn) {
566 in_entry_fn = true;
567 } else if (inst.opcode == kOpFunctionEnd && in_entry_fn) {
568 in_entry_fn = false;
569 } else if (in_entry_fn && inst.opcode == kOpReturn && !synth.empty()) {
570 found_entry_return = true;
571 for (const SynthParam& sp : synth) {
572 if (sp.src_var == 0) {
573 out_insts.push_back(make_inst(kOpStore, {sp.lo_var, null_v4_id}));
574 out_insts.push_back(make_inst(kOpStore, {sp.hi_var, null_v4_id}));
575 continue;
576 }
577 const std::uint32_t raw_id = vs_mod.alloc_id();
578 out_insts.push_back(make_inst(kOpLoad, {v4float_ty, raw_id, sp.src_var}));
579 std::array<std::uint32_t, 4> lo_c{}, hi_c{};
580 for (std::uint32_t c = 0; c < 4; ++c) {
581 const std::uint32_t e_id = vs_mod.alloc_id();
582 const std::uint32_t u_id = vs_mod.alloc_id();
583 const std::uint32_t h2_id = vs_mod.alloc_id();
584 const std::uint32_t a_id = vs_mod.alloc_id();
585 const std::uint32_t b_id = vs_mod.alloc_id();
586 out_insts.push_back(make_inst(kOpCompositeExtract, {float_ty, e_id, raw_id, c}));
587 out_insts.push_back(make_inst(kOpBitcast, {uint_ty, u_id, e_id}));
588 out_insts.push_back(make_inst(kOpExtInst, {v2float_ty, h2_id, glsl_id, kGlslUnpackHalf2x16, u_id}));
589 out_insts.push_back(make_inst(kOpCompositeExtract, {float_ty, a_id, h2_id, 0}));
590 out_insts.push_back(make_inst(kOpCompositeExtract, {float_ty, b_id, h2_id, 1}));
591 lo_c[c] = a_id;
592 hi_c[c] = b_id;
593 }
594 const std::uint32_t lo_vec = vs_mod.alloc_id();
595 const std::uint32_t hi_vec = vs_mod.alloc_id();
596 out_insts.push_back(make_inst(kOpCompositeConstruct, {v4float_ty, lo_vec, lo_c[0], lo_c[1], lo_c[2], lo_c[3]}));
597 out_insts.push_back(make_inst(kOpCompositeConstruct, {v4float_ty, hi_vec, hi_c[0], hi_c[1], hi_c[2], hi_c[3]}));
598 out_insts.push_back(make_inst(kOpStore, {sp.lo_var, lo_vec}));
599 out_insts.push_back(make_inst(kOpStore, {sp.hi_var, hi_vec}));
600 }
601 }
602
603 out_insts.push_back(std::move(inst));
604 }
605
606 if (!synth.empty() && !found_entry_return)
607 return fail("f16_halves: Vertex entry point has no OpReturn to emit decoded halves");
608 if (!glsl_inserted || !decorates_inserted || !globals_inserted)
609 return fail("f16_halves: unexpected VS SPIR-V layout");
610
611 vs_mod.insts = std::move(out_insts);
612 vs_words = vs_mod.serialize();
613 if (ps_changed) ps_words = ps_mod.serialize();
614 return true;
615}
616
617} // namespace leonida
diff --git a/runtime/src/spirv_words.h b/runtime/src/spirv_words.h
new file mode 100644
index 000000000..e7e91fe5d
--- /dev/null
+++ b/runtime/src/spirv_words.h
@@ -0,0 +1,26 @@
1#pragma once
2
3#include <cstddef>
4#include <cstdint>
5#include <istream>
6#include <vector>
7
8namespace leonida {
9
10// Checks the binary framing used by the translator and returns words aligned for Vulkan.
11// The caller still relies on the driver or spirv-val for instruction and capability validation.
12inline std::vector<std::uint32_t> read_spirv_words(std::istream& input, std::streamoff byte_count) {
13 constexpr std::streamoff word_bytes = sizeof(std::uint32_t);
14 constexpr std::streamoff header_bytes = 5 * word_bytes;
15 if (byte_count < header_bytes || byte_count % word_bytes || !input.seekg(0)) return {};
16
17 std::uint32_t magic = 0;
18 if (!input.read(reinterpret_cast<char*>(&magic), word_bytes) || magic != 0x07230203) return {};
19
20 std::vector<std::uint32_t> words(static_cast<std::size_t>(byte_count / word_bytes));
21 words.front() = magic;
22 if (!input.read(reinterpret_cast<char*>(words.data() + 1), byte_count - word_bytes)) return {};
23 return words;
24}
25
26} // namespace leonida
diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h
index 140d7234b..1be77a0ca 100644
--- a/runtime/src/vulkan_backend.h
+++ b/runtime/src/vulkan_backend.h
@@ -17,6 +17,7 @@
17#include "vulkan_depth24.h" 17#include "vulkan_depth24.h"
18#include "vulkan_scratch.h" 18#include "vulkan_scratch.h"
19#include "vulkan_replay.h" 19#include "vulkan_replay.h"
20#include "queue_families.h"
20#include "resource_tiling.h" 21#include "resource_tiling.h"
21#include "xdxr_build.h" 22#include "xdxr_build.h"
22 23
@@ -80,7 +81,8 @@ struct VulkanDeviceFunctions {
80 X(vkCmdBindVertexBuffers2) X(vkCmdBindIndexBuffer) X(vkCmdSetViewport) X(vkCmdSetScissor) \ 81 X(vkCmdBindVertexBuffers2) X(vkCmdBindIndexBuffer) X(vkCmdSetViewport) X(vkCmdSetScissor) \
81 X(vkCmdSetPrimitiveTopology) X(vkCmdSetPrimitiveRestartEnable) X(vkCmdSetStencilReference) \ 82 X(vkCmdSetPrimitiveTopology) X(vkCmdSetPrimitiveRestartEnable) X(vkCmdSetStencilReference) \
82 X(vkCmdSetBlendConstants) X(vkCmdDraw) \ 83 X(vkCmdSetBlendConstants) X(vkCmdDraw) \
83 X(vkCmdDrawIndexed) X(vkCreateGraphicsPipelines) X(vkQueueBindSparse) 84 X(vkCmdDrawIndexed) X(vkCreateGraphicsPipelines) X(vkQueueBindSparse) \
85 X(vkCreateEvent) X(vkDestroyEvent) X(vkResetEvent) X(vkCmdSetEvent) X(vkCmdWaitEvents)
84#define LEONIDA_VK_MEMBER(name) PFN_##name name = nullptr; 86#define LEONIDA_VK_MEMBER(name) PFN_##name name = nullptr;
85 LEONIDA_VK_DEVICE_FUNCTIONS(LEONIDA_VK_MEMBER) 87 LEONIDA_VK_DEVICE_FUNCTIONS(LEONIDA_VK_MEMBER)
86#undef LEONIDA_VK_MEMBER 88#undef LEONIDA_VK_MEMBER
@@ -202,7 +204,11 @@ public:
202 return vk_.vkCreatePipelineLayout(device_, &layout, nullptr, &layout_) == VK_SUCCESS; 204 return vk_.vkCreatePipelineLayout(device_, &layout, nullptr, &layout_) == VK_SUCCESS;
203 } 205 }
204 206
205 bool prepare(bool needs_sum, bool needs_binary, bool needs_statistics_sum = false) { 207 bool prepare(bool needs_sum, bool needs_binary, bool needs_statistics_sum = false,
208 bool needs_sum_binary = false) {
209 // The composite (sum then normalize, D3D-252) uses both pipelines.
210 needs_sum = needs_sum || needs_sum_binary;
211 needs_binary = needs_binary || needs_sum_binary;
206 return (!needs_sum || sum_pipeline_ || create_pipeline(occlusion_sum_spirv, sum_pipeline_)) && 212 return (!needs_sum || sum_pipeline_ || create_pipeline(occlusion_sum_spirv, sum_pipeline_)) &&
207 (!needs_binary || binary_pipeline_ || create_pipeline(binary_occlusion_spirv, binary_pipeline_)) && 213 (!needs_binary || binary_pipeline_ || create_pipeline(binary_occlusion_spirv, binary_pipeline_)) &&
208 (!needs_statistics_sum || statistics_pipeline_ || 214 (!needs_statistics_sum || statistics_pipeline_ ||
@@ -250,6 +256,31 @@ public:
250 copy_result(cb, dst, offset, word_size); 256 copy_result(cb, dst, offset, word_size);
251 } 257 }
252 258
259 // Sums `count` binary-occlusion segments into one value and normalizes that total in place to 0 or 1: the
260 // result of a binary query whose interval spans more than one physical segment (overlapping queries, D3D-252).
261 void sum_binary(VkCommandBuffer cb, VkQueryPool queries, std::uint32_t first, std::uint32_t count,
262 VkBuffer dst, VkDeviceSize offset) const {
263 begin_scratch_write(cb);
264 vk_.vkCmdFillBuffer(cb, scratch_, 0, word_size, 0);
265 bind(cb, sum_pipeline_);
266 auto tail = first, left = count;
267 while (left) {
268 const auto chunk = std::min(left, sum_capacity);
269 vk_.vkCmdCopyQueryPoolResults(cb, queries, tail, chunk, scratch_, word_size, word_size,
270 VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT);
271 barrier(cb, transfer | compute, compute, VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_SHADER_WRITE_BIT,
272 shader_access);
273 dispatch(cb, chunk, 1);
274 tail += chunk;
275 left -= chunk;
276 if (left) barrier(cb, compute, transfer, shader_access, VK_ACCESS_TRANSFER_WRITE_BIT);
277 }
278 barrier(cb, compute, compute, VK_ACCESS_SHADER_WRITE_BIT, shader_access);
279 bind(cb, binary_pipeline_);
280 dispatch(cb, 1, 1);
281 copy_result(cb, dst, offset, word_size);
282 }
283
253 void normalize(VkCommandBuffer cb, VkQueryPool queries, std::uint32_t first, std::uint32_t count, 284 void normalize(VkCommandBuffer cb, VkQueryPool queries, std::uint32_t first, std::uint32_t count,
254 VkBuffer dst, VkDeviceSize offset) const { 285 VkBuffer dst, VkDeviceSize offset) const {
255 bind(cb, binary_pipeline_); 286 bind(cb, binary_pipeline_);
@@ -1002,6 +1033,10 @@ public:
1002 // (timestampValidBits 0). Set by the device before any queue uses it. 1033 // (timestampValidBits 0). Set by the device before any queue uses it.
1003 double timestamp_period() const { return timestamp_period_; } 1034 double timestamp_period() const { return timestamp_period_; }
1004 void set_timestamp_period(double period) { timestamp_period_ = period; } 1035 void set_timestamp_period(double period) { timestamp_period_ = period; }
1036 // True where a timestamp resolve must be ordered explicitly after the timestamps it copies (MoltenVK on Apple
1037 // GPUs, docs/d3d12_vulkan.md section 4.6). Set by the device before any queue uses it.
1038 bool order_timestamp_copies() const { return order_timestamp_copies_; }
1039 void set_order_timestamp_copies(bool order) { order_timestamp_copies_ = order; }
1005 1040
1006 // The device address of the GPU address arena: console VAs are offsets from it (docs section 3.3). 1041 // The device address of the GPU address arena: console VAs are offsets from it (docs section 3.3).
1007 // execute() copies replay_ under a shared resource_mutex_, so writers hold it uniquely. 1042 // execute() copies replay_ under a shared resource_mutex_, so writers hold it uniquely.
@@ -1115,6 +1150,8 @@ public:
1115 // `prepare` is called at the start of the command buffer of every ExecuteCommandLists, before the lists are 1150 // `prepare` is called at the start of the command buffer of every ExecuteCommandLists, before the lists are
1116 // written: the device brings the bindless set 0 of the translated shaders up to date there (vulkan_bindless.h) 1151 // written: the device brings the bindless set 0 of the translated shaders up to date there (vulkan_bindless.h)
1117 // and records what the set needs first. When it fails, nothing of that call is executed. 1152 // and records what the set needs first. When it fails, nothing of that call is executed.
1153 void set_transfer_only_family(std::uint32_t family) { transfer_only_family_ = family; }
1154
1118 void set_bindless_prepare(std::function<bool(VkCommandBuffer)> prepare) { 1155 void set_bindless_prepare(std::function<bool(VkCommandBuffer)> prepare) {
1119 std::unique_lock lock(resource_mutex_); 1156 std::unique_lock lock(resource_mutex_);
1120 bindless_prepare_ = std::move(prepare); 1157 bindless_prepare_ = std::move(prepare);
@@ -1289,11 +1326,13 @@ private:
1289 std::function<void(bool)> bindless_commit_; 1326 std::function<void(bool)> bindless_commit_;
1290 std::unordered_map<QueryHeapId, QueryPool> query_pools_; // element pointers stay valid across inserts 1327 std::unordered_map<QueryHeapId, QueryPool> query_pools_; // element pointers stay valid across inserts
1291 double timestamp_period_ = 0; 1328 double timestamp_period_ = 0;
1329 bool order_timestamp_copies_ = false;
1292 VkPhysicalDeviceMemoryProperties occlusion_resolve_memory_{}; 1330 VkPhysicalDeviceMemoryProperties occlusion_resolve_memory_{};
1293 ReplayFunctions replay_; 1331 ReplayFunctions replay_;
1294 std::unique_ptr<PredicateReducer> predicate_reducer_; 1332 std::unique_ptr<PredicateReducer> predicate_reducer_;
1295 std::unique_ptr<PredicatedBufferCopier> predicated_copier_; 1333 std::unique_ptr<PredicatedBufferCopier> predicated_copier_;
1296 std::uint32_t predicate_family_ = UINT32_MAX; 1334 std::uint32_t predicate_family_ = UINT32_MAX;
1335 std::uint32_t transfer_only_family_ = UINT32_MAX;
1297 DebugLabelFunctions labels_; 1336 DebugLabelFunctions labels_;
1298}; 1337};
1299#ifdef _MSC_VER 1338#ifdef _MSC_VER
@@ -1401,6 +1440,8 @@ public:
1401 } 1440 }
1402 if (pool_) vk.vkDestroyCommandPool(context_.device(), pool_, nullptr); 1441 if (pool_) vk.vkDestroyCommandPool(context_.device(), pool_, nullptr);
1403 if (progress_) vk.vkDestroySemaphore(context_.device(), progress_, nullptr); 1442 if (progress_) vk.vkDestroySemaphore(context_.device(), progress_, nullptr);
1443 for (auto& slot : buffers_) free_events_.insert(free_events_.end(), slot.events.begin(), slot.events.end());
1444 for (VkEvent event : free_events_) vk.vkDestroyEvent(context_.device(), event, nullptr);
1404 } 1445 }
1405 1446
1406 VulkanQueue(const VulkanQueue&) = delete; 1447 VulkanQueue(const VulkanQueue&) = delete;
@@ -1474,6 +1515,12 @@ public:
1474 // the layout tracker as it was. Pending Wait()s are attached to this submission. 1515 // the layout tracker as it was. Pending Wait()s are attached to this submission.
1475 ReplayResult execute(std::span<const CommandList* const> lists) { 1516 ReplayResult execute(std::span<const CommandList* const> lists) {
1476 if (context_.is_device_lost()) return ReplayResult::unsupported; 1517 if (context_.is_device_lost()) return ReplayResult::unsupported;
1518 if (kind_ != QueueKind::direct)
1519 for (const auto* list : lists)
1520 for (const auto& command : list->commands())
1521 if (std::holds_alternative<ClearRenderTarget>(command) ||
1522 std::holds_alternative<ClearDepthStencil>(command))
1523 return ReplayResult::unsupported;
1477 VkCommandBuffer command_buffer = VK_NULL_HANDLE; 1524 VkCommandBuffer command_buffer = VK_NULL_HANDLE;
1478 std::function<void(bool)> bindless_commit; 1525 std::function<void(bool)> bindless_commit;
1479 // Lock hierarchy: resource_mutex_ -> tracker_mutex_ -> submit_mutex_. 1526 // Lock hierarchy: resource_mutex_ -> tracker_mutex_ -> submit_mutex_.
@@ -1500,12 +1547,16 @@ public:
1500 if (active && scratch) scratch->retire(progress, 0); 1547 if (active && scratch) scratch->retire(progress, 0);
1501 } 1548 }
1502 } scratch_guard{context_.scratch_.get(), progress_, false}; 1549 } scratch_guard{context_.scratch_.get(), progress_, false};
1503 bindless_commit = context_.bindless_commit_; 1550 const bool transfer_only = family_ == context_.transfer_only_family_;
1551 if (!transfer_only) bindless_commit = context_.bindless_commit_;
1504 // Kept between executions: prepare refills each list's entries in the storage the last execution left, where 1552 // Kept between executions: prepare refills each list's entries in the storage the last execution left, where
1505 // making them fresh for every command was about half the layer's CPU cost per command (replay_cpu_bench). 1553 // making them fresh for every command was about half the layer's CPU cost per command (replay_cpu_bench).
1506 auto& prepared = prepared_; 1554 auto& prepared = prepared_;
1507 prepared.resize(lists.size()); 1555 prepared.resize(lists.size());
1508 ReplayFunctions replay = context_.replay_; 1556 ReplayFunctions replay = context_.replay_;
1557 replay.queue_stages = kind_ == QueueKind::copy ? detail::queue_stages_copy
1558 : kind_ == QueueKind::compute ? detail::queue_stages_compute
1559 : 0;
1509 std::uint64_t captures = 0; 1560 std::uint64_t captures = 0;
1510 for (const auto* list : lists) 1561 for (const auto* list : lists)
1511 for (const auto& command : list->commands()) 1562 for (const auto& command : list->commands())
@@ -1549,7 +1600,7 @@ public:
1549 return context_.scratch_->get(bytes, buffer, offset); 1600 return context_.scratch_->get(bytes, buffer, offset);
1550 }; 1601 };
1551 } 1602 }
1552 if (context_.depth24_) { 1603 if (context_.depth24_ && !transfer_only) {
1553 replay.depth24_prepare = [this, &tracker_lock, &depth24_guard](Depth24Job& job, 1604 replay.depth24_prepare = [this, &tracker_lock, &depth24_guard](Depth24Job& job,
1554 std::vector<Depth24Job>& parts) { 1605 std::vector<Depth24Job>& parts) {
1555 if (!tracker_lock.owns_lock()) tracker_lock.lock(); 1606 if (!tracker_lock.owns_lock()) tracker_lock.lock();
@@ -1575,6 +1626,10 @@ public:
1575 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { 1626 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) {
1576 occlusion_resolve_->sum_statistics(cb, pool, first, count, dst, offset); 1627 occlusion_resolve_->sum_statistics(cb, pool, first, count, dst, offset);
1577 }; 1628 };
1629 replay.sum_binary_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first,
1630 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) {
1631 occlusion_resolve_->sum_binary(cb, pool, first, count, dst, offset);
1632 };
1578 } 1633 }
1579 const auto resolve = [this](ResourceId id) { return context_.resolve(id); }; 1634 const auto resolve = [this](ResourceId id) { return context_.resolve(id); };
1580 std::uint32_t segments = 0, statistics_segments = 0; 1635 std::uint32_t segments = 0, statistics_segments = 0;
@@ -1621,19 +1676,38 @@ public:
1621 base += list.segment_count; 1676 base += list.segment_count;
1622 statistics_base += list.statistics_segment_count; 1677 statistics_base += list.statistics_segment_count;
1623 } 1678 }
1624 if (queries.needs_sum || queries.needs_binary || queries.needs_statistics_sum) { 1679 if (queries.needs_sum || queries.needs_binary || queries.needs_statistics_sum || queries.needs_sum_binary) {
1625 if (!occlusion_resolve_) { 1680 if (!occlusion_resolve_) {
1626 auto helper = std::make_unique<OcclusionResolve>(context_.vk, context_.device()); 1681 auto helper = std::make_unique<OcclusionResolve>(context_.vk, context_.device());
1627 if (!helper->initialize(occlusion_memory)) return ReplayResult::unsupported; 1682 if (!helper->initialize(occlusion_memory)) return ReplayResult::unsupported;
1628 occlusion_resolve_ = std::move(helper); 1683 occlusion_resolve_ = std::move(helper);
1629 } 1684 }
1630 if (!occlusion_resolve_->prepare(queries.needs_sum, queries.needs_binary, queries.needs_statistics_sum)) 1685 if (!occlusion_resolve_->prepare(queries.needs_sum, queries.needs_binary, queries.needs_statistics_sum,
1686 queries.needs_sum_binary))
1631 return ReplayResult::unsupported; 1687 return ReplayResult::unsupported;
1632 } 1688 }
1633 1689
1634 CommandSlot* slot = acquire(); 1690 CommandSlot* slot = acquire();
1635 if (!slot) return ReplayResult::unsupported; 1691 if (!slot) return ReplayResult::unsupported;
1636 command_buffer = slot->buffer; 1692 command_buffer = slot->buffer;
1693 // MoltenVK writes a timestamp at the end of a Metal encoder and resolves it with a blit that nothing orders
1694 // after that write, so a copy in the same or the next command buffer reads the old value (docs section 4.6).
1695 // An event set and waited for in this command buffer orders it after this submission's timestamps; a wait for
1696 // this queue's previous submission orders it after earlier ones still running.
1697 bool ordered_timestamps = false;
1698 const auto& events = context_.vk;
1699 if (context_.order_timestamp_copies() && events.vkCreateEvent && events.vkDestroyEvent && events.vkResetEvent &&
1700 events.vkCmdSetEvent && events.vkCmdWaitEvents)
1701 replay.order_timestamp_copy = [this, slot, &ordered_timestamps](VkCommandBuffer cb) {
1702 const VkEvent event = take_event();
1703 if (!event) return;
1704 slot->events.push_back(event);
1705 const auto& vk = context_.vk;
1706 vk.vkCmdSetEvent(cb, event, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
1707 vk.vkCmdWaitEvents(cb, 1, &event, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
1708 VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, nullptr, 0, nullptr, 0, nullptr);
1709 ordered_timestamps = true;
1710 };
1637 const auto discard = [&] { 1711 const auto discard = [&] {
1638 if (context_.vk.vkResetCommandBuffer(command_buffer, 0) == VK_SUCCESS) slot->ticket = 0; 1712 if (context_.vk.vkResetCommandBuffer(command_buffer, 0) == VK_SUCCESS) slot->ticket = 0;
1639 }; 1713 };
@@ -1644,7 +1718,7 @@ public:
1644 return ReplayResult::unsupported; 1718 return ReplayResult::unsupported;
1645 } 1719 }
1646 if (!tracker_lock.owns_lock()) tracker_lock.lock(); 1720 if (!tracker_lock.owns_lock()) tracker_lock.lock();
1647 if (context_.bindless_prepare_ && !context_.bindless_prepare_(command_buffer)) { 1721 if (!transfer_only && context_.bindless_prepare_ && !context_.bindless_prepare_(command_buffer)) {
1648 const bool ended = context_.vk.vkEndCommandBuffer(command_buffer) == VK_SUCCESS; 1722 const bool ended = context_.vk.vkEndCommandBuffer(command_buffer) == VK_SUCCESS;
1649 resource_lock.unlock(); 1723 resource_lock.unlock();
1650 const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0); 1724 const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0);
@@ -1730,6 +1804,11 @@ public:
1730 } 1804 }
1731 const bool ended = context_.vk.vkEndCommandBuffer(command_buffer) == VK_SUCCESS; 1805 const bool ended = context_.vk.vkEndCommandBuffer(command_buffer) == VK_SUCCESS;
1732 resource_lock.unlock(); // release resource_mutex_ before vkQueueSubmit while keeping tracker_lock held 1806 resource_lock.unlock(); // release resource_mutex_ before vkQueueSubmit while keeping tracker_lock held
1807 const bool wait_previous = ordered_timestamps && submitted_;
1808 if (wait_previous) {
1809 waits_.push_back(progress_);
1810 wait_values_.push_back(submitted_);
1811 }
1733 const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0); 1812 const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0);
1734 if (!submitted && !storage_images.empty()) { // not initialized after all: try again with the next submission 1813 if (!submitted && !storage_images.empty()) { // not initialized after all: try again with the next submission
1735 std::lock_guard lock(context_.storage_mutex_); 1814 std::lock_guard lock(context_.storage_mutex_);
@@ -1742,6 +1821,10 @@ public:
1742 ++context_.storage_init_version_; 1821 ++context_.storage_init_version_;
1743 storage_init_seen_ = context_.storage_init_version_; 1822 storage_init_seen_ = context_.storage_init_version_;
1744 } 1823 }
1824 if (wait_previous && !submitted && !waits_.empty()) { // a failed submit keeps the waits for the next one
1825 waits_.pop_back();
1826 wait_values_.pop_back();
1827 }
1745 if (submitted) { 1828 if (submitted) {
1746 context_.tracker_ = std::move(next_tracker); 1829 context_.tracker_ = std::move(next_tracker);
1747 slot->predicate = std::move(batch); 1830 slot->predicate = std::move(batch);
@@ -1804,6 +1887,7 @@ private:
1804 VkCommandBuffer buffer; 1887 VkCommandBuffer buffer;
1805 std::uint64_t ticket; 1888 std::uint64_t ticket;
1806 std::vector<std::shared_ptr<const OcclusionSegmentPool>> segments; 1889 std::vector<std::shared_ptr<const OcclusionSegmentPool>> segments;
1890 std::vector<VkEvent> events; // order_timestamp_copy's, reset and reused once the slot completes
1807 std::unique_ptr<PredicatedBufferCopier::Batch> predicated_copy; 1891 std::unique_ptr<PredicatedBufferCopier::Batch> predicated_copy;
1808 std::unique_ptr<PredicateReducer::Batch> predicate; // retained until this slot completes 1892 std::unique_ptr<PredicateReducer::Batch> predicate; // retained until this slot completes
1809 }; 1893 };
@@ -1913,6 +1997,10 @@ private:
1913 for (auto& slot : buffers_) { 1997 for (auto& slot : buffers_) {
1914 if (slot.ticket > done) continue; 1998 if (slot.ticket > done) continue;
1915 slot.segments.clear(); 1999 slot.segments.clear();
2000 for (VkEvent event : slot.events)
2001 if (context_.vk.vkResetEvent(context_.device(), event) == VK_SUCCESS) free_events_.push_back(event);
2002 else context_.vk.vkDestroyEvent(context_.device(), event, nullptr);
2003 slot.events.clear();
1916 if (!reuse) reuse = &slot; 2004 if (!reuse) reuse = &slot;
1917 } 2005 }
1918 if (reuse) { 2006 if (reuse) {
@@ -1933,6 +2021,20 @@ private:
1933 return &buffers_.back(); 2021 return &buffers_.back();
1934 } 2022 }
1935 2023
2024 // An unsignaled event for order_timestamp_copy, or null. MoltenVK decides when the command buffer is submitted
2025 // whether a set or wait does anything, from the event's state then, so each use gets an event of its own.
2026 VkEvent take_event() {
2027 if (!free_events_.empty()) {
2028 const VkEvent event = free_events_.back();
2029 free_events_.pop_back();
2030 return event;
2031 }
2032 VkEventCreateInfo info{VK_STRUCTURE_TYPE_EVENT_CREATE_INFO};
2033 VkEvent event = VK_NULL_HANDLE;
2034 if (context_.vk.vkCreateEvent(context_.device(), &info, nullptr, &event) != VK_SUCCESS) return VK_NULL_HANDLE;
2035 return event;
2036 }
2037
1936 bool submit(VkCommandBuffer command_buffer, VkSemaphore fence, std::uint64_t value) { 2038 bool submit(VkCommandBuffer command_buffer, VkSemaphore fence, std::uint64_t value) {
1937 if (context_.is_device_lost()) return false; 2039 if (context_.is_device_lost()) return false;
1938 const std::uint64_t ticket = submitted_ + 1; 2040 const std::uint64_t ticket = submitted_ + 1;
@@ -2002,6 +2104,7 @@ private:
2002 VkSemaphore progress_ = VK_NULL_HANDLE; // our own timeline: which command buffers are done 2104 VkSemaphore progress_ = VK_NULL_HANDLE; // our own timeline: which command buffers are done
2003 std::uint64_t submitted_ = 0; 2105 std::uint64_t submitted_ = 0;
2004 std::vector<CommandSlot> buffers_; 2106 std::vector<CommandSlot> buffers_;
2107 std::vector<VkEvent> free_events_; // unsignaled, for order_timestamp_copy
2005 std::unique_ptr<OcclusionResolve> occlusion_resolve_; 2108 std::unique_ptr<OcclusionResolve> occlusion_resolve_;
2006 std::uint64_t storage_init_seen_ = 0; // the storage_init_version_ this queue has waited for 2109 std::uint64_t storage_init_seen_ = 0; // the storage_init_version_ this queue has waited for
2007 std::uint64_t last_sparse_ = 0; 2110 std::uint64_t last_sparse_ = 0;
diff --git a/runtime/src/vulkan_present.h b/runtime/src/vulkan_present.h
index 9a73d2f82..a2874b4b3 100644
--- a/runtime/src/vulkan_present.h
+++ b/runtime/src/vulkan_present.h
@@ -15,12 +15,18 @@
15// that follows the source (an sRGB source gets an sRGB swapchain, so the blit's decode and encode cancel; every 15// that follows the source (an sRGB source gets an sRGB swapchain, so the blit's decode and encode cancel; every
16// other source gets a UNORM one), and an optional capture that copies each presented frame to host memory. 16// other source gets a UNORM one), and an optional capture that copies each presented frame to host memory.
17// 17//
18// Plane composition (PresentX with placement, a filter, HDR10 or a second plane): present_planes() runs a compute pass
19// (present_compose.comp, vulkan_present_compose.h) over up to two textures into an RGBA16F image and copies that to the
20// swapchain; with an HDR10 plane and a surface that lists an ST.2084 format the swapchain is created in it. The plain
21// blit above is unchanged.
22//
18// Tearing on request (PresentX's ImmediateThresholdPercent): with VK_KHR_swapchain_maintenance1 (or the EXT original) 23// Tearing on request (PresentX's ImmediateThresholdPercent): with VK_KHR_swapchain_maintenance1 (or the EXT original)
19// the vsync swapchain is created with FIFO plus IMMEDIATE (FIFO_RELAXED when the surface cannot switch to IMMEDIATE), 24// the vsync swapchain is created with FIFO plus IMMEDIATE (FIFO_RELAXED when the surface cannot switch to IMMEDIATE),
20// and a present that asks for it is queued in that mode alone. Without the extension, or without either mode, a 25// and a present that asks for it is queued in that mode alone. Without the extension, or without either mode, a
21// request is ignored and the frame waits for the vblank. 26// request is ignored and the frame waits for the vblank.
22 27
23#include "vulkan_backend.h" 28#include "vulkan_backend.h"
29#include "vulkan_present_compose.h"
24 30
25// Use the original EXT spellings. They are aliases of the promoted KHR types and are available in older headers. 31// Use the original EXT spellings. They are aliases of the promoted KHR types and are available in older headers.
26#if defined(VK_EXT_SWAPCHAIN_MAINTENANCE_1_EXTENSION_NAME) && defined(VK_EXT_SURFACE_MAINTENANCE_1_EXTENSION_NAME) 32#if defined(VK_EXT_SWAPCHAIN_MAINTENANCE_1_EXTENSION_NAME) && defined(VK_EXT_SURFACE_MAINTENANCE_1_EXTENSION_NAME)
@@ -29,11 +35,13 @@
29 35
30#include <algorithm> 36#include <algorithm>
31#include <array> 37#include <array>
38#include <cmath>
32#include <cstdint> 39#include <cstdint>
33#include <cstdio> 40#include <cstdio>
34#include <cstring> 41#include <cstring>
35#include <functional> 42#include <functional>
36#include <map> 43#include <map>
44#include <memory>
37#include <vector> 45#include <vector>
38 46
39namespace leonida { 47namespace leonida {
@@ -43,6 +51,22 @@ struct PresentRect {
43 std::int32_t left, top, right, bottom; 51 std::int32_t left, top, right, bottom;
44}; 52};
45 53
54// One plane of present_planes(): a colour texture, the part of it shown, and where in the output it goes.
55struct PresentPlane {
56 ResourceId source{};
57 PresentRect source_rect{}; // texels; used when has_source_rect
58 bool has_source_rect = false;
59 float dest[4] = {0, 0, 1, 1}; // left, top, right, bottom as fractions of the output (0..1)
60 bool point_filter = false; // nearest texel; otherwise bilinear inside the source rectangle
61 bool hdr10 = false; // the texture holds ST.2084 (PQ) Rec.2020 values; otherwise G2.2 Rec.709 ones
62 bool straight_alpha = false; // plane 1 only: alpha is not premultiplied into the colour
63};
64struct PresentPlanes {
65 PresentPlane plane[2];
66 std::uint32_t count = 1;
67 float sdr_white_nits = 203.0f; // what SDR white maps to in an HDR10 output, and what HDR10 is divided by for SDR
68};
69
46namespace detail { 70namespace detail {
47inline bool is_srgb_format(VkFormat format) { 71inline bool is_srgb_format(VkFormat format) {
48 switch (format) { 72 switch (format) {
@@ -140,7 +164,9 @@ public:
140 release(swapchain_); 164 release(swapchain_);
141 swapchain_ = VK_NULL_HANDLE; 165 swapchain_ = VK_NULL_HANDLE;
142 release_capture(); 166 release_capture();
167 composer_.reset();
143 for (Frame& frame : frames_) { 168 for (Frame& frame : frames_) {
169 drop_views(frame);
144 if (frame.done) vkDestroyFence_(device, frame.done, nullptr); 170 if (frame.done) vkDestroyFence_(device, frame.done, nullptr);
145 if (frame.acquired) vk.vkDestroySemaphore(device, frame.acquired, nullptr); 171 if (frame.acquired) vk.vkDestroySemaphore(device, frame.acquired, nullptr);
146 } 172 }
@@ -200,6 +226,47 @@ public:
200 return submit(&binding, source, vsync, source_rect, detail::is_srgb_format(binding.format), tear); 226 return submit(&binding, source, vsync, source_rect, detail::is_srgb_format(binding.format), tear);
201 } 227 }
202 228
229 // PresentX with planes (docs section 4.5): one or two textures, each scaled from its source rectangle to its
230 // destination rectangle of the window, plane 1 blended over plane 0, composed by a compute pass into an RGBA16F image
231 // that is then copied to the swapchain image. Colour spaces are converted to the swapchain's: when a plane is HDR10 and
232 // the surface lists an HDR10 (ST.2084) format the swapchain uses it (hdr_active()), else the HDR10 planes are
233 // converted to SDR by clipping (no tone mapping). The swapchain is always UNORM here; sRGB-format sources are
234 // encoded again by the pass. Sources must be single-sample, sampled (no DENY_SHADER_RESOURCE) float/UNORM/sRGB
235 // colour textures; others are refused (VK_ERROR_FORMAT_NOT_SUPPORTED). Rectangles outside their range give
236 // VK_ERROR_UNKNOWN. vsync and `tear` as for present().
237 VkResult present_planes(const PresentPlanes& planes, bool vsync, bool tear = false) {
238 if (planes.count < 1 || planes.count > 2) return VK_ERROR_UNKNOWN;
239 if (!(planes.sdr_white_nits > 0.0f) || !std::isfinite(planes.sdr_white_nits)) return VK_ERROR_UNKNOWN;
240 for (std::uint32_t i = 0; i < planes.count; ++i) {
241 const PresentPlane& plane = planes.plane[i];
242 ResourceBinding binding;
243 {
244 std::shared_lock lock(context_.resource_mutex_);
245 const ResourceBinding* found = context_.resolve(plane.source);
246 if (!found || !found->image) return VK_ERROR_UNKNOWN;
247 binding = *found;
248 }
249 if (binding.aspects != VK_IMAGE_ASPECT_COLOR_BIT || binding.samples > 1 || !binding.sampled || detail::blit_unsupported_format(binding.format) ||
250 !(format_features(binding.format) & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT))
251 return VK_ERROR_FORMAT_NOT_SUPPORTED;
252 const PresentRect& r = plane.source_rect;
253 if (plane.has_source_rect && (r.left < 0 || r.top < 0 || r.left >= r.right || r.top >= r.bottom ||
254 std::uint32_t(r.right) > binding.width || std::uint32_t(r.bottom) > binding.height))
255 return VK_ERROR_UNKNOWN;
256 const float* d = plane.dest;
257 if (!(d[0] >= 0.0f && d[0] < d[2] && d[2] <= 1.0f && d[1] >= 0.0f && d[1] < d[3] && d[3] <= 1.0f))
258 return VK_ERROR_UNKNOWN; // (also false for NaN)
259 }
260 return submit(nullptr, ResourceId{}, vsync, nullptr, false, tear, &planes);
261 }
262 // The swapchain holds HDR10 (ST.2084) values: a plane asked for it and the surface has the format.
263 bool hdr_active() const { return hdr_active_; }
264 // Presents that went through the compose pass (present_planes); plain blits and blank frames are not counted.
265 std::uint64_t composed_presents() const { return composed_; }
266 // Tests, on surfaces without HDR10: compose as if the output were HDR10 but write the PQ values into the (8-bit,
267 // UNORM) swapchain, so the encoder can be checked on any GPU. Takes effect with the next present_planes().
268 void force_hdr_encoding(bool on) { force_hdr_encoding_ = on; }
269
203 // Polled while a present waits for a swapchain image (every 50 ms): when it returns true the present gives up with 270 // Polled while a present waits for a swapchain image (every 50 ms): when it returns true the present gives up with
204 // VK_NOT_READY, so a caller that is being suspended is never held by a window that stopped taking frames. 271 // VK_NOT_READY, so a caller that is being suspended is never held by a window that stopped taking frames.
205 void set_abort(std::function<bool()> abort) { abort_ = std::move(abort); } 272 void set_abort(std::function<bool()> abort) { abort_ = std::move(abort); }
@@ -216,7 +283,7 @@ public:
216 if (!ok_) return false; 283 if (!ok_) return false;
217 capture_ = true; 284 capture_ = true;
218 stale_ = true; 285 stale_ = true;
219 if (!recreate(vsync_, swapchain_srgb_) || (swapchain_ && !capture_buffer_)) { 286 if (!recreate(vsync_, swapchain_srgb_, swapchain_hdr_req_) || (swapchain_ && !capture_buffer_)) {
220 capture_ = false; 287 capture_ = false;
221 return false; 288 return false;
222 } 289 }
@@ -236,22 +303,32 @@ public:
236 return true; 303 return true;
237 } 304 }
238 305
239 // Shared by present() and present_blank(). `binding` null: clear instead of blit. 306 // Shared by present(), present_blank() and present_planes(). `binding` null and `planes` null: clear instead of blit;
307 // `planes`: compose them (`binding`, `source`, `source_rect` unused).
240 VkResult submit(const ResourceBinding* binding, ResourceId source, bool vsync, const PresentRect* source_rect, 308 VkResult submit(const ResourceBinding* binding, ResourceId source, bool vsync, const PresentRect* source_rect,
241 bool srgb, bool tear = false) { 309 bool srgb, bool tear = false, const PresentPlanes* planes = nullptr) {
242 last_tore_ = false; 310 last_tore_ = false;
243 if (!ok_) return VK_ERROR_INITIALIZATION_FAILED; 311 if (!ok_) return VK_ERROR_INITIALIZATION_FAILED;
244 if (vsync != vsync_ || stale_ || srgb != swapchain_srgb_) { 312 // The swapchain's HDR10 format is only for composed planes that ask for it; a blit of an SDR source or a blank
313 // frame keeps whatever the swapchain has (black is black), except that a blit needs the SDR one.
314 bool want_hdr = swapchain_hdr_req_;
315 if (planes)
316 want_hdr = (planes->plane[0].hdr10) || (planes->count > 1 && planes->plane[1].hdr10);
317 else if (binding)
318 want_hdr = false;
319 if (vsync != vsync_ || stale_ || srgb != swapchain_srgb_ || want_hdr != swapchain_hdr_req_) {
245 // The swapchain's colour encoding is only recorded once the new swapchain exists, so a failed 320 // The swapchain's colour encoding is only recorded once the new swapchain exists, so a failed
246 // recreate is tried again at the next present. 321 // recreate is tried again at the next present.
247 if (!recreate(vsync, srgb)) return VK_ERROR_OUT_OF_DATE_KHR; 322 if (!recreate(vsync, srgb, want_hdr)) return VK_ERROR_OUT_OF_DATE_KHR;
248 } 323 }
249 if (!swapchain_) { // minimised: try again next frame 324 if (!swapchain_) { // minimised: try again next frame
250 stale_ = true; 325 stale_ = true;
251 return VK_SUCCESS; 326 return VK_SUCCESS;
252 } 327 }
253 if (binding && !presentable(source)) return VK_ERROR_UNKNOWN; // checked before an image is acquired for it 328 if (binding && !presentable(source)) return VK_ERROR_UNKNOWN; // checked before an image is acquired for it
254 if (binding && !(format_features(format_) & VK_FORMAT_FEATURE_BLIT_DST_BIT)) return VK_ERROR_FORMAT_NOT_SUPPORTED; 329 if ((binding || planes) && !(format_features(format_) & VK_FORMAT_FEATURE_BLIT_DST_BIT))
330 return VK_ERROR_FORMAT_NOT_SUPPORTED;
331 if (planes && !prepare_compose()) return VK_ERROR_FORMAT_NOT_SUPPORTED;
255 auto& vk = context_.vk; 332 auto& vk = context_.vk;
256 const VkDevice device = context_.device(); 333 const VkDevice device = context_.device();
257 Frame& frame = frames_[frame_index_ % frames_.size()]; 334 Frame& frame = frames_[frame_index_ % frames_.size()];
@@ -261,18 +338,43 @@ public:
261 std::uint32_t image = 0; 338 std::uint32_t image = 0;
262 VkResult acquired = acquire(frame.acquired, &image); 339 VkResult acquired = acquire(frame.acquired, &image);
263 if (acquired == VK_ERROR_OUT_OF_DATE_KHR) { 340 if (acquired == VK_ERROR_OUT_OF_DATE_KHR) {
264 if (!recreate(vsync, swapchain_srgb_)) return acquired; 341 if (!recreate(vsync, swapchain_srgb_, swapchain_hdr_req_)) return acquired;
265 if (!swapchain_) return VK_SUCCESS; 342 if (!swapchain_) return VK_SUCCESS;
266 acquired = acquire(frame.acquired, &image); 343 acquired = acquire(frame.acquired, &image);
267 } 344 }
268 if (acquired != VK_SUCCESS && acquired != VK_SUBOPTIMAL_KHR) return acquired; // nothing was acquired 345 if (acquired != VK_SUCCESS && acquired != VK_SUBOPTIMAL_KHR) return acquired; // nothing was acquired
269 if (acquired == VK_SUBOPTIMAL_KHR) stale_ = true; 346 if (acquired == VK_SUBOPTIMAL_KHR) stale_ = true;
347 // An out-of-date retry above may have given the swapchain another extent: the compose target follows it.
348 if (planes && !prepare_compose()) return give_back(frame, VK_ERROR_FORMAT_NOT_SUPPORTED);
270 349
271 bool recorded = false; 350 bool recorded = false;
272 std::unique_lock tracker_lock(context_.tracker_mutex_, std::defer_lock); 351 std::unique_lock tracker_lock(context_.tracker_mutex_, std::defer_lock);
273 bool rollback_source = false; 352 bool rollback_source = false;
274 VkImageLayout prev_layout = VK_IMAGE_LAYOUT_UNDEFINED; 353 VkImageLayout prev_layout = VK_IMAGE_LAYOUT_UNDEFINED;
275 if (binding) { 354 std::array<RollbackPlane, 2> plane_rollbacks{}; // present_planes(): the same, per plane
355 if (planes) {
356 std::array<ResourceBinding, 2> current{};
357 bool found_all = true;
358 {
359 std::shared_lock resource_lock(context_.resource_mutex_);
360 for (std::uint32_t i = 0; i < planes->count; ++i) {
361 const ResourceBinding* found = context_.resolve(planes->plane[i].source);
362 if (found && found->image && found->aspects == VK_IMAGE_ASPECT_COLOR_BIT && found->sampled)
363 current[i] = *found;
364 else
365 found_all = false;
366 }
367 if (found_all) {
368 tracker_lock.lock();
369 for (std::uint32_t i = 0; i < planes->count; ++i) {
370 plane_rollbacks[i].id = planes->plane[i].source;
371 plane_rollbacks[i].tracked = context_.tracker_.tracked(plane_rollbacks[i].id);
372 if (plane_rollbacks[i].tracked) plane_rollbacks[i].layout = context_.tracker_.layout(plane_rollbacks[i].id, 0);
373 }
374 recorded = record_planes(frame, std::uint32_t(frame_index_ % frames_.size()), current, *planes, image);
375 }
376 }
377 } else if (binding) {
276 // Lock hierarchy: resource_mutex_ -> tracker_mutex_ -> submit_mutex_ (vulkan_backend.h). 378 // Lock hierarchy: resource_mutex_ -> tracker_mutex_ -> submit_mutex_ (vulkan_backend.h).
277 // record() only touches subresource 0 (mip 0, layer 0, color) of `source`, so saving that one layout 379 // record() only touches subresource 0 (mip 0, layer 0, color) of `source`, so saving that one layout
278 // rolls back a failed submit in O(1) without copying the entire LayoutTracker map. 380 // rolls back a failed submit in O(1) without copying the entire LayoutTracker map.
@@ -292,6 +394,11 @@ public:
292 const auto rollback = [&] { 394 const auto rollback = [&] {
293 if (rollback_source) 395 if (rollback_source)
294 context_.tracker_.set(source, {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}, prev_layout); 396 context_.tracker_.set(source, {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}, prev_layout);
397 if (planes)
398 for (std::uint32_t i = 0; i < planes->count; ++i)
399 if (plane_rollbacks[i].tracked)
400 context_.tracker_.set(plane_rollbacks[i].id, {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1},
401 plane_rollbacks[i].layout);
295 }; 402 };
296 if (!recorded) return give_back(frame, VK_ERROR_UNKNOWN); // released by another thread since presentable() 403 if (!recorded) return give_back(frame, VK_ERROR_UNKNOWN); // released by another thread since presentable()
297 if (const VkResult reset = vkResetFences_(device, 1, &frame.done); reset != VK_SUCCESS) { 404 if (const VkResult reset = vkResetFences_(device, 1, &frame.done); reset != VK_SUCCESS) {
@@ -342,6 +449,7 @@ public:
342 // is recreated next time, and the caller sees VK_SUCCESS, since its work was submitted. 449 // is recreated next time, and the caller sees VK_SUCCESS, since its work was submitted.
343 if (result == VK_SUCCESS || result == VK_SUBOPTIMAL_KHR) { 450 if (result == VK_SUCCESS || result == VK_SUBOPTIMAL_KHR) {
344 ++presented_; 451 ++presented_;
452 if (planes) ++composed_;
345 if (tearing) { 453 if (tearing) {
346 last_tore_ = true; 454 last_tore_ = true;
347 ++tear_presents_; 455 ++tear_presents_;
@@ -364,6 +472,7 @@ private:
364 VkCommandBuffer commands = VK_NULL_HANDLE; 472 VkCommandBuffer commands = VK_NULL_HANDLE;
365 VkFence done = VK_NULL_HANDLE; 473 VkFence done = VK_NULL_HANDLE;
366 VkSemaphore acquired = VK_NULL_HANDLE; 474 VkSemaphore acquired = VK_NULL_HANDLE;
475 std::array<VkImageView, 2> views{}; // the plane views of the last composed present, until the frame is reused
367 }; 476 };
368 477
369 // Whether `source` is a colour texture the device knows, so present() can refuse it before acquiring an image. 478 // Whether `source` is a colour texture the device knows, so present() can refuse it before acquiring an image.
@@ -462,6 +571,139 @@ private:
462 vk.vkEndCommandBuffer(commands); 571 vk.vkEndCommandBuffer(commands);
463 } 572 }
464 573
574 struct RollbackPlane {
575 ResourceId id{};
576 bool tracked = false;
577 VkImageLayout layout = VK_IMAGE_LAYOUT_UNDEFINED;
578 };
579
580 void drop_views(Frame& frame) {
581 for (VkImageView& view : frame.views)
582 if (view) context_.vk.vkDestroyImageView(context_.device(), view, nullptr);
583 frame.views = {};
584 }
585
586 // The compose pass and its target image, for the swapchain's current size.
587 bool prepare_compose() {
588 if (!composer_) {
589 VkPhysicalDeviceMemoryProperties memory{};
590 if (!vkGetPhysicalDeviceMemoryProperties_) return false;
591 vkGetPhysicalDeviceMemoryProperties_(physical_, &memory);
592 composer_ = std::make_unique<PresentComposer>(context_, memory);
593 }
594 if (!composer_->ready()) return false;
595 if (composer_->target() && composer_->extent().width == extent_.width &&
596 composer_->extent().height == extent_.height)
597 return true;
598 {
599 std::lock_guard lock(context_.submit_mutex());
600 context_.vk.vkQueueWaitIdle(queue_); // the old target may still be in use
601 }
602 bool changed = false;
603 return composer_->ensure_target(extent_, changed);
604 }
605
606 // Records the composition of `planes` and its copy to swapchain image `image`. False, with nothing recorded and the
607 // tracker untouched, when a view cannot be made. The caller holds the resource and tracker locks.
608 bool record_planes(Frame& frame, std::uint32_t slot, const std::array<ResourceBinding, 2>& current,
609 const PresentPlanes& planes, std::uint32_t image) {
610 auto& vk = context_.vk;
611 const ReplayFunctions& fn = context_.replay_;
612 if (composer_->target() == VK_NULL_HANDLE || composer_->extent().width != extent_.width ||
613 composer_->extent().height != extent_.height)
614 return false; // the target does not match the swapchain: nothing recorded
615 drop_views(frame);
616 for (std::uint32_t i = 0; i < planes.count; ++i) {
617 VkImageViewCreateInfo view_info{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO};
618 view_info.image = current[i].image;
619 view_info.viewType = VK_IMAGE_VIEW_TYPE_2D;
620 view_info.format = current[i].format;
621 view_info.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
622 if (vk.vkCreateImageView(context_.device(), &view_info, nullptr, &frame.views[i]) != VK_SUCCESS) {
623 drop_views(frame);
624 return false;
625 }
626 }
627 if (planes.count == 1) frame.views[1] = VK_NULL_HANDLE; // the shader never reads it; plane 0's view is bound twice
628
629 VkCommandBuffer commands = frame.commands;
630 vk.vkResetCommandBuffer(commands, 0);
631 VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO};
632 begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
633 vk.vkBeginCommandBuffer(commands, &begin);
634
635 constexpr VkAccessFlags any = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
636 const VkImageSubresourceRange range{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
637 const bool same = planes.count > 1 && planes.plane[1].source == planes.plane[0].source;
638 std::array<LayoutPieces, 2> pieces;
639 std::array<VkImageLayout, 2> read_layout{};
640 // Each distinct source: its PRESENT (common) layout, then readable by the compute pass. A never-written back buffer
641 // is zero-filled first, as any committed resource is.
642 for (std::uint32_t i = 0; i < planes.count; ++i) {
643 read_layout[i] = image_layout(current[i], VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
644 if (i == 1 && same) continue;
645 const VkImageLayout common = image_layout(current[i], VK_IMAGE_LAYOUT_GENERAL);
646 pieces[i] = detail::current(&context_.tracker_, planes.plane[i].source, range, common);
647 detail::initialize(fn, commands, current[i], planes.plane[i].source, pieces[i], common, &context_.tracker_);
648 for (const auto& piece : pieces[i])
649 detail::image_barrier(fn, commands, current[i], piece.range, piece.layout, read_layout[i],
650 VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
651 VK_ACCESS_SHADER_READ_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
652 }
653
654 // The pass: destinations in output pixels, sources in texels.
655 PresentComposePush push{};
656 const float out_w = float(extent_.width), out_h = float(extent_.height);
657 std::uint32_t* flags[2] = {&push.flags0, &push.flags1};
658 float* dest[2] = {push.dest0, push.dest1};
659 float* src[2] = {push.src0, push.src1};
660 for (std::uint32_t i = 0; i < planes.count; ++i) {
661 const PresentPlane& plane = planes.plane[i];
662 dest[i][0] = plane.dest[0] * out_w;
663 dest[i][1] = plane.dest[1] * out_h;
664 dest[i][2] = plane.dest[2] * out_w;
665 dest[i][3] = plane.dest[3] * out_h;
666 const PresentRect whole{0, 0, std::int32_t(current[i].width), std::int32_t(current[i].height)};
667 const PresentRect& r = plane.has_source_rect ? plane.source_rect : whole;
668 src[i][0] = float(r.left);
669 src[i][1] = float(r.top);
670 src[i][2] = float(r.right);
671 src[i][3] = float(r.bottom);
672 *flags[i] = (plane.point_filter ? compose_flag::point : 0u) |
673 (detail::is_srgb_format(current[i].format) ? compose_flag::srgb_source : 0u) |
674 (plane.hdr10 ? compose_flag::hdr10 : 0u) | (plane.straight_alpha ? compose_flag::straight_alpha : 0u);
675 }
676 push.plane_count = planes.count;
677 push.out_hdr = (hdr_active_ || force_hdr_encoding_) ? 1u : 0u;
678 push.sdr_white = planes.sdr_white_nits;
679 push.width = extent_.width;
680 push.height = extent_.height;
681 composer_->record(commands, slot, frame.views[0], read_layout[0], frame.views[1] ? frame.views[1] : frame.views[0],
682 read_layout[1] ? read_layout[1] : read_layout[0], push);
683
684 // The swapchain image, written by a copy of the composed image (same size: no scaling).
685 ResourceBinding target = target_of(image);
686 detail::image_barrier(fn, commands, target, range, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 0,
687 VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT);
688 VkImageBlit blit{};
689 blit.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1};
690 blit.srcOffsets[1] = {std::int32_t(extent_.width), std::int32_t(extent_.height), 1};
691 blit.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1};
692 blit.dstOffsets[1] = {std::int32_t(extent_.width), std::int32_t(extent_.height), 1};
693 vkCmdBlitImage_(commands, composer_->target(), VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, images_[image],
694 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit, VK_FILTER_NEAREST);
695 finish_image(commands, image);
696 for (std::uint32_t i = 0; i < planes.count; ++i) {
697 if (i == 1 && same) continue;
698 for (const auto& piece : pieces[i])
699 detail::image_barrier(fn, commands, current[i], piece.range, read_layout[i], piece.layout,
700 VK_ACCESS_SHADER_READ_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, any,
701 VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
702 }
703 vk.vkEndCommandBuffer(commands);
704 return true;
705 }
706
465 // vkGetPhysicalDeviceFormatProperties, optimal tiling, cached per format. 707 // vkGetPhysicalDeviceFormatProperties, optimal tiling, cached per format.
466 VkFormatFeatureFlags format_features(VkFormat format) { 708 VkFormatFeatureFlags format_features(VkFormat format) {
467 const auto it = features_.find(format); 709 const auto it = features_.find(format);
@@ -595,7 +837,7 @@ private:
595 // (Re)creates the swapchain for the surface's current size. A zero-sized surface (minimised) leaves no 837 // (Re)creates the swapchain for the surface's current size. A zero-sized surface (minimised) leaves no
596 // swapchain and is retried on the next present. Keep the old swapchain until the surface queries succeed and 838 // swapchain and is retried on the next present. Keep the old swapchain until the surface queries succeed and
597 // the replacement can be attempted. An incomplete replacement stays stale so the next present tries again. 839 // the replacement can be attempted. An incomplete replacement stays stale so the next present tries again.
598 bool recreate(bool vsync, bool srgb) { 840 bool recreate(bool vsync, bool srgb, bool hdr = false) {
599 auto& vk = context_.vk; 841 auto& vk = context_.vk;
600 const VkDevice device = context_.device(); 842 const VkDevice device = context_.device();
601 { 843 {
@@ -625,6 +867,8 @@ private:
625 swapchain_ = VK_NULL_HANDLE; 867 swapchain_ = VK_NULL_HANDLE;
626 vsync_ = vsync; 868 vsync_ = vsync;
627 swapchain_srgb_ = srgb; 869 swapchain_srgb_ = srgb;
870 swapchain_hdr_req_ = hdr;
871 hdr_active_ = false;
628 stale_ = false; 872 stale_ = false;
629 return true; 873 return true;
630 } 874 }
@@ -643,8 +887,28 @@ private:
643 // wants UNORM (the bytes go through as they are). BGRA before RGBA, as the surface lists them. 887 // wants UNORM (the bytes go through as they are). BGRA before RGBA, as the surface lists them.
644 VkSurfaceFormatKHR chosen = formats[0]; 888 VkSurfaceFormatKHR chosen = formats[0];
645 bool found = false; 889 bool found = false;
890 bool chose_hdr = false;
891 if (hdr) {
892 // A plane in HDR10 (PQ, Rec.2020): the surface's ST.2084 format, which needs VK_EXT_swapchain_colorspace on
893 // the instance. Without it the composition converts to SDR.
894 for (const VkFormat wanted : {VK_FORMAT_A2B10G10R10_UNORM_PACK32, VK_FORMAT_A2R10G10B10_UNORM_PACK32}) {
895 for (const auto& f : formats)
896 if (f.format == wanted && f.colorSpace == VK_COLOR_SPACE_HDR10_ST2084_EXT) {
897 chosen = f;
898 found = chose_hdr = true;
899 break;
900 }
901 if (found) break;
902 }
903 if (!found && !warned_hdr_) {
904 warned_hdr_ = true;
905 std::fprintf(stderr, "[rt] present: the surface has no HDR10 (ST.2084) format; HDR10 planes are converted to "
906 "SDR by clipping\n");
907 }
908 }
646 for (const VkFormat wanted : srgb ? std::array<VkFormat, 2>{VK_FORMAT_B8G8R8A8_SRGB, VK_FORMAT_R8G8B8A8_SRGB} 909 for (const VkFormat wanted : srgb ? std::array<VkFormat, 2>{VK_FORMAT_B8G8R8A8_SRGB, VK_FORMAT_R8G8B8A8_SRGB}
647 : std::array<VkFormat, 2>{VK_FORMAT_B8G8R8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM}) { 910 : std::array<VkFormat, 2>{VK_FORMAT_B8G8R8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM}) {
911 if (chose_hdr) break;
648 for (const auto& f : formats) 912 for (const auto& f : formats)
649 if (f.format == wanted && f.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) { 913 if (f.format == wanted && f.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) {
650 chosen = f; 914 chosen = f;
@@ -739,14 +1003,18 @@ private:
739 ready_ = std::move(ready); 1003 ready_ = std::move(ready);
740 format_ = chosen.format; 1004 format_ = chosen.format;
741 extent_ = extent; 1005 extent_ = extent;
1006 hdr_active_ = chose_hdr;
742 if (capture_) { 1007 if (capture_) {
743 // A capture that cannot be made fails the recreation with the swapchain in place and stale_ still set. 1008 // A capture that cannot be made fails the recreation with the swapchain in place and stale_ still set.
744 const bool four_bytes = format_ == VK_FORMAT_B8G8R8A8_UNORM || format_ == VK_FORMAT_R8G8B8A8_UNORM || 1009 const bool four_bytes = format_ == VK_FORMAT_B8G8R8A8_UNORM || format_ == VK_FORMAT_R8G8B8A8_UNORM ||
745 format_ == VK_FORMAT_B8G8R8A8_SRGB || format_ == VK_FORMAT_R8G8B8A8_SRGB; 1010 format_ == VK_FORMAT_B8G8R8A8_SRGB || format_ == VK_FORMAT_R8G8B8A8_SRGB ||
1011 format_ == VK_FORMAT_A2B10G10R10_UNORM_PACK32 ||
1012 format_ == VK_FORMAT_A2R10G10B10_UNORM_PACK32;
746 if (!four_bytes || !make_capture_buffer()) return false; 1013 if (!four_bytes || !make_capture_buffer()) return false;
747 } 1014 }
748 vsync_ = vsync; 1015 vsync_ = vsync;
749 swapchain_srgb_ = srgb; 1016 swapchain_srgb_ = srgb;
1017 swapchain_hdr_req_ = hdr;
750 stale_ = false; 1018 stale_ = false;
751 return true; 1019 return true;
752 } 1020 }
@@ -836,6 +1104,12 @@ private:
836 bool stale_ = false; 1104 bool stale_ = false;
837 bool ok_ = false; 1105 bool ok_ = false;
838 bool swapchain_srgb_ = false; // the swapchain format follows the source being presented (set once it exists) 1106 bool swapchain_srgb_ = false; // the swapchain format follows the source being presented (set once it exists)
1107 bool swapchain_hdr_req_ = false; // the swapchain was built for an HDR10 request (it has the format only if hdr_active_)
1108 bool hdr_active_ = false;
1109 std::uint64_t composed_ = 0;
1110 bool force_hdr_encoding_ = false;
1111 bool warned_hdr_ = false;
1112 std::unique_ptr<PresentComposer> composer_;
839 std::function<bool()> abort_; 1113 std::function<bool()> abort_;
840 std::function<VkExtent2D()> extent_fn_; 1114 std::function<VkExtent2D()> extent_fn_;
841 std::map<VkFormat, VkFormatFeatureFlags> features_; 1115 std::map<VkFormat, VkFormatFeatureFlags> features_;
diff --git a/runtime/src/vulkan_present_compose.h b/runtime/src/vulkan_present_compose.h
new file mode 100644
index 000000000..3fe834c1c
--- /dev/null
+++ b/runtime/src/vulkan_present_compose.h
@@ -0,0 +1,257 @@
1#pragma once
2
3// The compute pass behind PresentX's plane composition (docs/d3d12_vulkan.md section 4.5), used by VulkanPresenter::
4// present_planes(): up to two sampled planes in, each scaled from a source rectangle to a destination rectangle,
5// plane 1 blended over plane 0, colour spaces converted, the result in an RGBA16F image of the swapchain's size that the
6// presenter copies to the swapchain image. The shader is present_compose.comp (SPIR-V embedded, present_compose_spv.h).
7// Not thread safe: the presenter calls it with its own state locked, one present at a time.
8
9#include "vulkan_backend.h"
10#include "present_compose_spv.h"
11
12#include <array>
13#include <cstdint>
14#include <cstring>
15
16namespace leonida {
17
18// Mirrors the shader's push constants (96 bytes).
19struct PresentComposePush {
20 float dest0[4], dest1[4]; // destination rectangles in output pixels: left, top, right, bottom
21 float src0[4], src1[4]; // source rectangles in texels
22 std::uint32_t flags0, flags1, plane_count, out_hdr;
23 float sdr_white;
24 std::uint32_t width, height, pad;
25};
26static_assert(sizeof(PresentComposePush) == 96);
27
28namespace compose_flag {
29inline constexpr std::uint32_t point = 1, srgb_source = 2, hdr10 = 4, straight_alpha = 8;
30}
31
32class PresentComposer {
33public:
34 static constexpr std::uint32_t frame_slots = 2;
35
36 PresentComposer(VulkanContext& context, const VkPhysicalDeviceMemoryProperties& memory)
37 : context_(context), memory_(memory) {}
38
39 ~PresentComposer() {
40 const VkDevice device = context_.device();
41 auto& vk = context_.vk;
42 release_target();
43 if (pipeline_) vk.vkDestroyPipeline(device, pipeline_, nullptr);
44 if (pipeline_layout_) vk.vkDestroyPipelineLayout(device, pipeline_layout_, nullptr);
45 if (pool_) vk.vkDestroyDescriptorPool(device, pool_, nullptr); // frees its sets
46 if (set_layout_) vk.vkDestroyDescriptorSetLayout(device, set_layout_, nullptr);
47 }
48 PresentComposer(const PresentComposer&) = delete;
49 PresentComposer& operator=(const PresentComposer&) = delete;
50
51 // Builds the pipeline once; false when the device cannot (a function is missing, or creation fails).
52 bool ready() {
53 if (state_ != State::untried) return state_ == State::ready;
54 state_ = State::failed;
55 auto& vk = context_.vk;
56 const VkDevice device = context_.device();
57 if (!vk.vkCreateDescriptorSetLayout || !vk.vkCreateDescriptorPool || !vk.vkAllocateDescriptorSets ||
58 !vk.vkUpdateDescriptorSets || !vk.vkCreatePipelineLayout || !vk.vkCreateShaderModule ||
59 !vk.vkCreateComputePipelines || !vk.vkCmdBindPipeline || !vk.vkCmdBindDescriptorSets ||
60 !vk.vkCmdPushConstants || !vk.vkCmdDispatch || !vk.vkCreateImage || !vk.vkCreateImageView ||
61 !vk.vkAllocateMemory)
62 return false;
63 std::array<VkDescriptorSetLayoutBinding, 3> bindings{};
64 for (std::uint32_t i = 0; i < 3; ++i) {
65 bindings[i].binding = i;
66 bindings[i].descriptorType = i < 2 ? VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE : VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
67 bindings[i].descriptorCount = 1;
68 bindings[i].stageFlags = VK_SHADER_STAGE_COMPUTE_BIT;
69 }
70 VkDescriptorSetLayoutCreateInfo set_info{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO};
71 set_info.bindingCount = std::uint32_t(bindings.size());
72 set_info.pBindings = bindings.data();
73 if (vk.vkCreateDescriptorSetLayout(device, &set_info, nullptr, &set_layout_) != VK_SUCCESS) return false;
74 const std::array<VkDescriptorPoolSize, 2> sizes{{{VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 2 * frame_slots},
75 {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, frame_slots}}};
76 VkDescriptorPoolCreateInfo pool_info{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO};
77 pool_info.maxSets = frame_slots;
78 pool_info.poolSizeCount = std::uint32_t(sizes.size());
79 pool_info.pPoolSizes = sizes.data();
80 if (vk.vkCreateDescriptorPool(device, &pool_info, nullptr, &pool_) != VK_SUCCESS) return false;
81 std::array<VkDescriptorSetLayout, frame_slots> layouts;
82 layouts.fill(set_layout_);
83 VkDescriptorSetAllocateInfo allocate{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO};
84 allocate.descriptorPool = pool_;
85 allocate.descriptorSetCount = frame_slots;
86 allocate.pSetLayouts = layouts.data();
87 if (vk.vkAllocateDescriptorSets(device, &allocate, sets_.data()) != VK_SUCCESS) return false;
88 const VkPushConstantRange push{VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(PresentComposePush)};
89 VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO};
90 layout_info.setLayoutCount = 1;
91 layout_info.pSetLayouts = &set_layout_;
92 layout_info.pushConstantRangeCount = 1;
93 layout_info.pPushConstantRanges = &push;
94 if (vk.vkCreatePipelineLayout(device, &layout_info, nullptr, &pipeline_layout_) != VK_SUCCESS) return false;
95 VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO};
96 module_info.codeSize = sizeof(present_compose_spirv);
97 module_info.pCode = present_compose_spirv;
98 VkShaderModule module = VK_NULL_HANDLE;
99 if (vk.vkCreateShaderModule(device, &module_info, nullptr, &module) != VK_SUCCESS) return false;
100 VkComputePipelineCreateInfo pipeline_info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO};
101 pipeline_info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, nullptr, 0,
102 VK_SHADER_STAGE_COMPUTE_BIT, module, "main", nullptr};
103 pipeline_info.layout = pipeline_layout_;
104 const VkResult created =
105 vk.vkCreateComputePipelines(device, VK_NULL_HANDLE, 1, &pipeline_info, nullptr, &pipeline_);
106 vk.vkDestroyShaderModule(device, module, nullptr);
107 if (created != VK_SUCCESS) return false;
108 state_ = State::ready;
109 return true;
110 }
111
112 // The RGBA16F image of `extent` the pass writes (storage + transfer source), made again when the extent changes.
113 // The caller has made the queue idle first when this returns after a change (changed() says so): the old image
114 // may still be in use.
115 bool ensure_target(VkExtent2D extent, bool& changed) {
116 changed = false;
117 if (image_ && extent_.width == extent.width && extent_.height == extent.height) return true;
118 changed = true;
119 release_target();
120 auto& vk = context_.vk;
121 const VkDevice device = context_.device();
122 VkImageCreateInfo info{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO};
123 info.imageType = VK_IMAGE_TYPE_2D;
124 info.format = target_format;
125 info.extent = {extent.width, extent.height, 1};
126 info.mipLevels = 1;
127 info.arrayLayers = 1;
128 info.samples = VK_SAMPLE_COUNT_1_BIT;
129 info.tiling = VK_IMAGE_TILING_OPTIMAL;
130 info.usage = VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
131 info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
132 info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
133 if (vk.vkCreateImage(device, &info, nullptr, &image_) != VK_SUCCESS) return false;
134 VkMemoryRequirements requirements{};
135 vk.vkGetImageMemoryRequirements(device, image_, &requirements);
136 std::uint32_t type = UINT32_MAX;
137 for (std::uint32_t i = 0; i < memory_.memoryTypeCount; ++i)
138 if ((requirements.memoryTypeBits & (1u << i)) &&
139 (memory_.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)) {
140 type = i;
141 break;
142 }
143 VkMemoryAllocateInfo allocate{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};
144 allocate.allocationSize = requirements.size;
145 allocate.memoryTypeIndex = type;
146 if (type == UINT32_MAX || vk.vkAllocateMemory(device, &allocate, nullptr, &memory_object_) != VK_SUCCESS ||
147 vk.vkBindImageMemory(device, image_, memory_object_, 0) != VK_SUCCESS) {
148 release_target();
149 return false;
150 }
151 VkImageViewCreateInfo view_info{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO};
152 view_info.image = image_;
153 view_info.viewType = VK_IMAGE_VIEW_TYPE_2D;
154 view_info.format = target_format;
155 view_info.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
156 if (vk.vkCreateImageView(device, &view_info, nullptr, &view_) != VK_SUCCESS) {
157 release_target();
158 return false;
159 }
160 extent_ = extent;
161 return true;
162 }
163
164 VkImage target() const { return image_; }
165 VkExtent2D extent() const { return extent_; }
166 static constexpr VkFormat target_format = VK_FORMAT_R16G16B16A16_SFLOAT;
167
168 // The binding the image barrier helpers take for the target.
169 ResourceBinding target_binding() const {
170 ResourceBinding binding{};
171 binding.image = image_;
172 binding.format = target_format;
173 binding.aspects = VK_IMAGE_ASPECT_COLOR_BIT;
174 binding.width = extent_.width;
175 binding.height = extent_.height;
176 return binding;
177 }
178
179 // Records the dispatch into `commands`: the planes' views (`plane1` may repeat `plane0` for a single plane) are
180 // bound with the target, the target goes UNDEFINED -> GENERAL for the writes and ends in TRANSFER_SRC_OPTIMAL for
181 // the copy that follows. The planes themselves must be in SHADER_READ_ONLY_OPTIMAL (or GENERAL) already.
182 void record(VkCommandBuffer commands, std::uint32_t slot, VkImageView plane0, VkImageLayout layout0,
183 VkImageView plane1, VkImageLayout layout1,
184 const PresentComposePush& push) {
185 auto& vk = context_.vk;
186 const VkDevice device = context_.device();
187 const VkDescriptorSet set = sets_[slot % frame_slots];
188 std::array<VkDescriptorImageInfo, 3> images{};
189 images[0] = {VK_NULL_HANDLE, plane0, layout0};
190 images[1] = {VK_NULL_HANDLE, plane1, layout1};
191 images[2] = {VK_NULL_HANDLE, view_, VK_IMAGE_LAYOUT_GENERAL};
192 std::array<VkWriteDescriptorSet, 3> writes{};
193 for (std::uint32_t i = 0; i < 3; ++i) {
194 writes[i].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
195 writes[i].dstSet = set;
196 writes[i].dstBinding = i;
197 writes[i].descriptorCount = 1;
198 writes[i].descriptorType = i < 2 ? VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE : VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
199 writes[i].pImageInfo = &images[i];
200 }
201 vk.vkUpdateDescriptorSets(device, std::uint32_t(writes.size()), writes.data(), 0, nullptr);
202
203 VkImageMemoryBarrier to_write{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER};
204 to_write.srcAccessMask = 0; // the previous reader (a copy) only needs the execution dependency
205 to_write.dstAccessMask = VK_ACCESS_SHADER_WRITE_BIT;
206 to_write.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
207 to_write.newLayout = VK_IMAGE_LAYOUT_GENERAL;
208 to_write.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
209 to_write.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
210 to_write.image = image_;
211 to_write.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
212 vk.vkCmdPipelineBarrier(commands, VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
213 VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &to_write);
214 vk.vkCmdBindPipeline(commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_);
215 vk.vkCmdBindDescriptorSets(commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_layout_, 0, 1, &set, 0, nullptr);
216 vk.vkCmdPushConstants(commands, pipeline_layout_, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(push), &push);
217 vk.vkCmdDispatch(commands, (extent_.width + 7) / 8, (extent_.height + 7) / 8, 1);
218 VkImageMemoryBarrier to_read = to_write;
219 to_read.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT;
220 to_read.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
221 to_read.oldLayout = VK_IMAGE_LAYOUT_GENERAL;
222 to_read.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
223 vk.vkCmdPipelineBarrier(commands, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0,
224 nullptr, 0, nullptr, 1, &to_read);
225 }
226
227
228private:
229 enum class State { untried, ready, failed };
230
231 void release_target() {
232 auto& vk = context_.vk;
233 const VkDevice device = context_.device();
234 if (view_) vk.vkDestroyImageView(device, view_, nullptr);
235 if (image_) vk.vkDestroyImage(device, image_, nullptr);
236 if (memory_object_) vk.vkFreeMemory(device, memory_object_, nullptr);
237 view_ = VK_NULL_HANDLE;
238 image_ = VK_NULL_HANDLE;
239 memory_object_ = VK_NULL_HANDLE;
240 extent_ = {};
241 }
242
243 VulkanContext& context_;
244 VkPhysicalDeviceMemoryProperties memory_;
245 State state_ = State::untried;
246 VkDescriptorSetLayout set_layout_ = VK_NULL_HANDLE;
247 VkDescriptorPool pool_ = VK_NULL_HANDLE;
248 std::array<VkDescriptorSet, frame_slots> sets_{};
249 VkPipelineLayout pipeline_layout_ = VK_NULL_HANDLE;
250 VkPipeline pipeline_ = VK_NULL_HANDLE;
251 VkImage image_ = VK_NULL_HANDLE;
252 VkDeviceMemory memory_object_ = VK_NULL_HANDLE;
253 VkImageView view_ = VK_NULL_HANDLE;
254 VkExtent2D extent_{};
255};
256
257} // namespace leonida
diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h
index fd69ab91b..6bc59f326 100644
--- a/runtime/src/vulkan_replay.h
+++ b/runtime/src/vulkan_replay.h
@@ -87,6 +87,7 @@ struct ResourceBinding {
87 // bytes, and copies between it and a buffer are repacked by the depth24 pass (Depth24Job::rgb96). 87 // bytes, and copies between it and a buffer are repacked by the depth24 pass (Depth24Job::rgb96).
88 bool rgb96 = false; 88 bool rgb96 = false;
89 bool color_attachment = false; // has COLOR_ATTACHMENT usage: unordered-access rectangle clears need it 89 bool color_attachment = false; // has COLOR_ATTACHMENT usage: unordered-access rectangle clears need it
90 bool sampled = false; // has SAMPLED usage (no DENY_SHADER_RESOURCE): the present compose pass reads it
90 bool host_readable = false; // D3D12_HEAP_TYPE_READBACK (or CUSTOM write-back): needs host-read flush 91 bool host_readable = false; // D3D12_HEAP_TYPE_READBACK (or CUSTOM write-back): needs host-read flush
91 bool sparse_buffer = false; 92 bool sparse_buffer = false;
92}; 93};
@@ -773,6 +774,7 @@ struct ReplayFunctions {
773 PFN_vkCmdClearDepthStencilImage clear_depth_stencil_image = nullptr; 774 PFN_vkCmdClearDepthStencilImage clear_depth_stencil_image = nullptr;
774 // Optional; a list that needs a missing one is rejected with ReplayResult::unsupported. 775 // Optional; a list that needs a missing one is rejected with ReplayResult::unsupported.
775 PFN_vkCmdPipelineBarrier2 pipeline_barrier2 = nullptr; // enhanced barriers 776 PFN_vkCmdPipelineBarrier2 pipeline_barrier2 = nullptr; // enhanced barriers
777 VkPipelineStageFlags2 queue_stages = 0;
776 PFN_vkCmdBeginRendering begin_rendering = nullptr; // rectangle clears 778 PFN_vkCmdBeginRendering begin_rendering = nullptr; // rectangle clears
777 PFN_vkCmdEndRendering end_rendering = nullptr; 779 PFN_vkCmdEndRendering end_rendering = nullptr;
778 PFN_vkCmdClearAttachments clear_attachments = nullptr; 780 PFN_vkCmdClearAttachments clear_attachments = nullptr;
@@ -792,6 +794,9 @@ struct ReplayFunctions {
792 PFN_vkCmdEndQuery end_query = nullptr; 794 PFN_vkCmdEndQuery end_query = nullptr;
793 PFN_vkCmdWriteTimestamp write_timestamp = nullptr; 795 PFN_vkCmdWriteTimestamp write_timestamp = nullptr;
794 PFN_vkCmdCopyQueryPoolResults copy_query_pool_results = nullptr; 796 PFN_vkCmdCopyQueryPoolResults copy_query_pool_results = nullptr;
797 // Set only where a copy of timestamp results is not ordered after the timestamps written before it (MoltenVK on
798 // Apple GPUs, docs/d3d12_vulkan.md section 4.6): records what orders them, before each timestamp resolve.
799 std::function<void(VkCommandBuffer)> order_timestamp_copy;
795 std::function<void(VkCommandBuffer, VkQueryPool, std::uint32_t, std::uint32_t, VkBuffer, VkDeviceSize)> 800 std::function<void(VkCommandBuffer, VkQueryPool, std::uint32_t, std::uint32_t, VkBuffer, VkDeviceSize)>
796 sum_occlusion; 801 sum_occlusion;
797 PFN_vkCmdBindPipeline bind_pipeline = nullptr; // dispatches 802 PFN_vkCmdBindPipeline bind_pipeline = nullptr; // dispatches
@@ -826,6 +831,10 @@ struct ReplayFunctions {
826 // rendering: the segments of a statistics query split around resolves (D3D-162). 831 // rendering: the segments of a statistics query split around resolves (D3D-162).
827 std::function<void(VkCommandBuffer, VkQueryPool, std::uint32_t first, std::uint32_t count, 832 std::function<void(VkCommandBuffer, VkQueryPool, std::uint32_t first, std::uint32_t count,
828 VkBuffer dst, VkDeviceSize offset)> sum_statistics; 833 VkBuffer dst, VkDeviceSize offset)> sum_statistics;
834 // Sums `count` binary-occlusion segments and normalizes the total to a 64-bit 0 or 1, outside conditional
835 // rendering: a binary query split over physical segments because it overlaps other occlusion queries (D3D-252).
836 std::function<void(VkCommandBuffer, VkQueryPool, std::uint32_t first, std::uint32_t count,
837 VkBuffer dst, VkDeviceSize offset)> sum_binary_occlusion;
829 // VK_EXT_debug_utils, set only when the instance enabled it; debug markers are skipped without them. 838 // VK_EXT_debug_utils, set only when the instance enabled it; debug markers are skipped without them.
830 PFN_vkCmdInsertDebugUtilsLabelEXT insert_label = nullptr; 839 PFN_vkCmdInsertDebugUtilsLabelEXT insert_label = nullptr;
831 PFN_vkCmdBeginDebugUtilsLabelEXT begin_label = nullptr; 840 PFN_vkCmdBeginDebugUtilsLabelEXT begin_label = nullptr;
@@ -1101,6 +1110,36 @@ inline void clip(std::span<const Rect> rects, VkExtent2D extent, std::uint32_t l
1101 } 1110 }
1102} 1111}
1103 1112
1113inline constexpr VkPipelineStageFlags2 queue_stages_copy =
1114 VK_PIPELINE_STAGE_2_TOP_OF_PIPE_BIT | VK_PIPELINE_STAGE_2_BOTTOM_OF_PIPE_BIT | VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT |
1115 VK_PIPELINE_STAGE_2_HOST_BIT | VK_PIPELINE_STAGE_2_TRANSFER_BIT | VK_PIPELINE_STAGE_2_COPY_BIT;
1116inline constexpr VkPipelineStageFlags2 queue_stages_compute =
1117 queue_stages_copy | VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_2_DRAW_INDIRECT_BIT |
1118 VK_PIPELINE_STAGE_2_CLEAR_BIT;
1119
1120inline void restrict_to_queue(const ReplayFunctions& vk, VkPipelineStageFlags2& stages, VkAccessFlags2& access) {
1121 if (!vk.queue_stages) return;
1122 VkAccessFlags2 allowed = VK_ACCESS_2_TRANSFER_READ_BIT | VK_ACCESS_2_TRANSFER_WRITE_BIT |
1123 VK_ACCESS_2_MEMORY_READ_BIT | VK_ACCESS_2_MEMORY_WRITE_BIT | VK_ACCESS_2_HOST_READ_BIT |
1124 VK_ACCESS_2_HOST_WRITE_BIT;
1125 if (vk.queue_stages & VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT)
1126 allowed |= VK_ACCESS_2_SHADER_READ_BIT | VK_ACCESS_2_SHADER_WRITE_BIT | VK_ACCESS_2_UNIFORM_READ_BIT |
1127 VK_ACCESS_2_SHADER_SAMPLED_READ_BIT | VK_ACCESS_2_SHADER_STORAGE_READ_BIT |
1128 VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT | VK_ACCESS_2_INDIRECT_COMMAND_READ_BIT;
1129 stages &= vk.queue_stages;
1130 if (!stages) stages = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT;
1131 access &= allowed;
1132}
1133
1134inline void restrict_to_queue(const ReplayFunctions& vk, VkPipelineStageFlags& stages, VkAccessFlags& access) {
1135 if (!vk.queue_stages) return;
1136 VkPipelineStageFlags2 s2 = stages;
1137 VkAccessFlags2 a2 = access;
1138 restrict_to_queue(vk, s2, a2);
1139 stages = static_cast<VkPipelineStageFlags>(s2 & 0xFFFFFFFFull);
1140 access = static_cast<VkAccessFlags>(a2 & 0xFFFFFFFFull);
1141}
1142
1104// A D3D12 barrier on a volume mip covers every W slice, including on devices with maintenance9. 1143// A D3D12 barrier on a volume mip covers every W slice, including on devices with maintenance9.
1105inline VkImageSubresourceRange layout_range(const ResourceBinding& resource, VkImageSubresourceRange range) { 1144inline VkImageSubresourceRange layout_range(const ResourceBinding& resource, VkImageSubresourceRange range) {
1106 if (resource.volume) range.layerCount = VK_REMAINING_ARRAY_LAYERS; 1145 if (resource.volume) range.layerCount = VK_REMAINING_ARRAY_LAYERS;
@@ -1111,6 +1150,8 @@ inline void image_barrier(const ReplayFunctions& vk, VkCommandBuffer command_buf
1111 const VkImageSubresourceRange& range, VkImageLayout old_layout, VkImageLayout new_layout, 1150 const VkImageSubresourceRange& range, VkImageLayout old_layout, VkImageLayout new_layout,
1112 VkAccessFlags src_access, VkPipelineStageFlags src_stages, VkAccessFlags dst_access, 1151 VkAccessFlags src_access, VkPipelineStageFlags src_stages, VkAccessFlags dst_access,
1113 VkPipelineStageFlags dst_stages) { 1152 VkPipelineStageFlags dst_stages) {
1153 restrict_to_queue(vk, src_stages, src_access);
1154 restrict_to_queue(vk, dst_stages, dst_access);
1114 VkImageMemoryBarrier barrier{}; 1155 VkImageMemoryBarrier barrier{};
1115 barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; 1156 barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
1116 barrier.srcAccessMask = src_access; 1157 barrier.srcAccessMask = src_access;
@@ -1126,6 +1167,8 @@ inline void image_barrier(const ReplayFunctions& vk, VkCommandBuffer command_buf
1126 1167
1127inline void memory_barrier(const ReplayFunctions& vk, VkCommandBuffer command_buffer, VkAccessFlags src_access, 1168inline void memory_barrier(const ReplayFunctions& vk, VkCommandBuffer command_buffer, VkAccessFlags src_access,
1128 VkPipelineStageFlags src_stages, VkAccessFlags dst_access, VkPipelineStageFlags dst_stages) { 1169 VkPipelineStageFlags src_stages, VkAccessFlags dst_access, VkPipelineStageFlags dst_stages) {
1170 restrict_to_queue(vk, src_stages, src_access);
1171 restrict_to_queue(vk, dst_stages, dst_access);
1129 VkMemoryBarrier barrier{}; 1172 VkMemoryBarrier barrier{};
1130 barrier.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER; 1173 barrier.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER;
1131 barrier.srcAccessMask = src_access; 1174 barrier.srcAccessMask = src_access;
@@ -1152,7 +1195,7 @@ inline bool zero_compressed_image(const ReplayFunctions& vk, VkCommandBuffer com
1152 const ResourceBinding& resource, const VkImageSubresourceRange& range, 1195 const ResourceBinding& resource, const VkImageSubresourceRange& range,
1153 VkImageLayout dst_layout) { 1196 VkImageLayout dst_layout) {
1154 const BlockFormat fmt = block_format(resource.format, VK_IMAGE_ASPECT_COLOR_BIT); 1197 const BlockFormat fmt = block_format(resource.format, VK_IMAGE_ASPECT_COLOR_BIT);
1155 if (fmt.block <= 1 || !fmt.bytes || !vk.copy_buffer_to_image) return false; 1198 if (fmt.block < 1 || !fmt.bytes || !vk.copy_buffer_to_image) return false;
1156 const std::uint32_t mip_begin = range.baseMipLevel; 1199 const std::uint32_t mip_begin = range.baseMipLevel;
1157 const std::uint32_t mip_end = 1200 const std::uint32_t mip_end =
1158 range.levelCount == VK_REMAINING_MIP_LEVELS ? resource.mip_levels 1201 range.levelCount == VK_REMAINING_MIP_LEVELS ? resource.mip_levels
@@ -1296,8 +1339,10 @@ inline void initialize(const ReplayFunctions& vk, VkCommandBuffer command_buffer
1296 for (auto& piece : pieces) { 1339 for (auto& piece : pieces) {
1297 if (piece.layout != VK_IMAGE_LAYOUT_UNDEFINED) continue; 1340 if (piece.layout != VK_IMAGE_LAYOUT_UNDEFINED) continue;
1298 const BlockFormat fmt = block_format(resource.format, VK_IMAGE_ASPECT_COLOR_BIT); 1341 const BlockFormat fmt = block_format(resource.format, VK_IMAGE_ASPECT_COLOR_BIT);
1299 const bool compressed = fmt.block > 1; 1342 const bool color = piece.range.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT;
1300 if (resource.not_zeroed) { 1343 const bool can_clear = !vk.queue_stages || ((vk.queue_stages & VK_PIPELINE_STAGE_2_CLEAR_BIT) && color);
1344 const bool compressed = fmt.block > 1 || (!can_clear && color);
1345 if (resource.not_zeroed || (!can_clear && !color)) {
1301 image_barrier(vk, command_buffer, resource, piece.range, VK_IMAGE_LAYOUT_UNDEFINED, layout, 0, 1346 image_barrier(vk, command_buffer, resource, piece.range, VK_IMAGE_LAYOUT_UNDEFINED, layout, 0,
1302 VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, any_memory, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); 1347 VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, any_memory, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
1303 } else if (compressed) { 1348 } else if (compressed) {
@@ -1498,21 +1543,46 @@ inline ReplayResult prepare_texture_copy(const CopyTexture& copy, Prepared& p) {
1498 if (block > 1) { 1543 if (block > 1) {
1499 // D3D12 copies whole blocks: the box is rounded up to blocks and must fit the destination's padded mip. 1544 // D3D12 copies whole blocks: the box is rounded up to blocks and must fit the destination's padded mip.
1500 // Vulkan takes an extent that is a block multiple or reaches the edge of each image separately, so the 1545 // Vulkan takes an extent that is a block multiple or reaches the edge of each image separately, so the
1501 // extent is cut where it reaches an edge, and a copy that cannot satisfy both images is refused. 1546 // extent is cut where it reaches an edge, and a copy that cannot satisfy both images is staged (below).
1502 if ((box.left | box.top | copy.x | copy.y) % block || box.left >= from.width || box.top >= from.height || 1547 if ((box.left | box.top | copy.x | copy.y) % block || box.left >= from.width || box.top >= from.height ||
1503 copy.x >= padded(to.width) || copy.y >= padded(to.height)) 1548 copy.x >= padded(to.width) || copy.y >= padded(to.height))
1504 return ReplayResult::invalid_copy; 1549 return ReplayResult::invalid_copy;
1505 w = padded(w); 1550 w = padded(w);
1506 h = padded(h); 1551 h = padded(h);
1507 if (w > padded(to.width) - copy.x || h > padded(to.height) - copy.y) return ReplayResult::invalid_copy; 1552 if (w > padded(to.width) - copy.x || h > padded(to.height) - copy.y) return ReplayResult::invalid_copy;
1508 w = std::min({w, from.width - box.left, to.width - copy.x}); 1553 // Each image's own extent: the whole blocks, cut where they reach that image's edge.
1509 h = std::min({h, from.height - box.top, to.height - copy.y}); 1554 const std::uint32_t src_w = std::min(w, from.width - box.left), src_h = std::min(h, from.height - box.top);
1555 const std::uint32_t dst_w = std::min(w, to.width - copy.x), dst_h = std::min(h, to.height - copy.y);
1556 const std::uint32_t blocks_w = w, blocks_h = h;
1557 w = std::min(src_w, dst_w);
1558 h = std::min(src_h, dst_h);
1510 const auto fits = [block](std::uint32_t offset, std::uint32_t extent, std::uint32_t size) { 1559 const auto fits = [block](std::uint32_t offset, std::uint32_t extent, std::uint32_t size) {
1511 return extent % block == 0 || offset + extent == size; 1560 return extent % block == 0 || offset + extent == size;
1512 }; 1561 };
1513 if (!fits(box.left, w, from.width) || !fits(copy.x, w, to.width) || !fits(box.top, h, from.height) || 1562 if (!fits(box.left, w, from.width) || !fits(copy.x, w, to.width) || !fits(box.top, h, from.height) ||
1514 !fits(copy.y, h, to.height)) 1563 !fits(copy.y, h, to.height)) {
1515 return ReplayResult::invalid_copy; 1564 // No one extent does for both images: a mip edge inside a block on one side only (a 4x4 box into a
1565 // 3x3 mip, a 6x6 mip into a 12x12 one). The source's blocks go into transfer scratch with its own
1566 // cut extent and from there into the destination with the destination's (`staged_reads` and
1567 // `staged_writes`, offsets from the start of the scratch; prepare allocates it). The box fits the
1568 // source's padded mip, so the scratch holds every block the destination reads.
1569 if (!within(copy.z, d, to_depth)) return ReplayResult::invalid_copy;
1570 VkBufferImageCopy read{};
1571 read.bufferRowLength = blocks_w;
1572 read.bufferImageHeight = blocks_h;
1573 read.imageSubresource = {src.aspectMask, src.baseMipLevel, src.baseArrayLayer, 1};
1574 read.imageOffset = {std::int32_t(box.left), std::int32_t(box.top), std::int32_t(box.front)};
1575 read.imageExtent = {src_w, src_h, d};
1576 VkBufferImageCopy write = read;
1577 write.imageSubresource = {dst.aspectMask, dst.baseMipLevel, dst.baseArrayLayer, 1};
1578 write.imageOffset = {std::int32_t(copy.x), std::int32_t(copy.y), std::int32_t(copy.z)};
1579 write.imageExtent = {dst_w, dst_h, d};
1580 p.staged_reads.push_back(read);
1581 p.staged_writes.push_back(write);
1582 p.range = dst;
1583 p.source_range = src;
1584 return ReplayResult::success;
1585 }
1516 } 1586 }
1517 if (!within(copy.x, w, to.width) || !within(copy.y, h, to.height) || !within(copy.z, d, to_depth)) 1587 if (!within(copy.x, w, to.width) || !within(copy.y, h, to.height) || !within(copy.z, d, to_depth))
1518 return ReplayResult::invalid_copy; 1588 return ReplayResult::invalid_copy;
@@ -1819,7 +1889,7 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct
1819 }; 1889 };
1820 1890
1821 p.colors.assign(pipeline->color_formats.size(), {}); 1891 p.colors.assign(pipeline->color_formats.size(), {});
1822 for (std::size_t slot = 0; slot < draw.render_targets.size() && slot < p.colors.size(); ++slot) { 1892 for (std::size_t slot = 0; slot < draw.render_target_count && slot < draw.render_targets.size() && slot < p.colors.size(); ++slot) {
1823 const TargetView& target = draw.render_targets[slot]; 1893 const TargetView& target = draw.render_targets[slot];
1824 if (!target.resource) continue; 1894 if (!target.resource) continue;
1825 const ResourceBinding* binding = resolve(target.resource); 1895 const ResourceBinding* binding = resolve(target.resource);
@@ -1991,6 +2061,9 @@ public:
1991 VkQueryPool statistics_pool = VK_NULL_HANDLE; 2061 VkQueryPool statistics_pool = VK_NULL_HANDLE;
1992 std::uint32_t statistics_base = 0; 2062 std::uint32_t statistics_base = 0;
1993 std::uint32_t statistics_segment_count = 0; 2063 std::uint32_t statistics_segment_count = 0;
2064 // The list's statistics queries overlap (D3D-252): without a statistics pool they cannot run whole, because
2065 // two Vulkan queries of one type may not be active at once; QueryReplay::plan refuses such a list.
2066 bool statistics_overlaps = false;
1994 // Copies, resolves and UAV clears that run as transfers, recorded while a predicate was set. D3D12 skips them 2067 // Copies, resolves and UAV clears that run as transfers, recorded while a predicate was set. D3D12 skips them
1995 // when the predicate says so, but Vulkan's conditional rendering does not cover transfer commands, so they run 2068 // when the predicate says so, but Vulkan's conditional rendering does not cover transfer commands, so they run
1996 // unconditionally (docs/d3d12_vulkan.md section 4.7). Counted so the caller can report it. 2069 // unconditionally (docs/d3d12_vulkan.md section 4.7). Counted so the caller can report it.
@@ -2009,7 +2082,9 @@ inline ReplayResult plan_occlusion_segments(PreparedList& out) {
2009 const Command& command = out.list->commands()[query.command]; 2082 const Command& command = out.list->commands()[query.command];
2010 if (std::holds_alternative<ResolveQueries>(command)) continue; 2083 if (std::holds_alternative<ResolveQueries>(command)) continue;
2011 const auto range = query_range(command); 2084 const auto range = query_range(command);
2012 if (range.type != d3d12_query::occlusion) continue; 2085 // Binary occlusion is virtualized alongside the ordinary kind (D3D-252): both are VK_QUERY_TYPE_OCCLUSION,
2086 // so one physical query is open at a time and a binary resolve normalizes the summed counts (0 or 1).
2087 if (range.type != d3d12_query::occlusion && range.type != d3d12_query::binary_occlusion) continue;
2013 const auto key = std::pair{range.heap, range.first}; 2088 const auto key = std::pair{range.heap, range.first};
2014 query.end_segment = current; 2089 query.end_segment = current;
2015 if (std::holds_alternative<BeginQuery>(command)) { 2090 if (std::holds_alternative<BeginQuery>(command)) {
@@ -2071,6 +2146,60 @@ inline void plan_statistics_segments(PreparedList& out) {
2071 } 2146 }
2072} 2147}
2073 2148
2149// Overlapping pipeline-statistics queries (D3D-252): the same physical-segment layout the occlusion planner
2150// builds, in the statistics pool. Each Begin and End of a statistics query — and every non-timestamp resolve
2151// while one runs, because its helper dispatch would be counted — closes the one open physical query and opens
2152// a new one, so each logical query keeps a contiguous slot range and its result is the sum of that range
2153// (statistics_sum.comp). A Begin or End of another query kind leaves the segments alone.
2154inline ReplayResult plan_overlapping_statistics_segments(PreparedList& out) {
2155 std::map<std::pair<QueryHeapId, std::uint32_t>, std::uint32_t> active;
2156 std::uint32_t current = detail::PreparedQuery::no_segment;
2157 std::size_t next_query = 0;
2158 for (std::size_t i = 0; i < out.commands.size(); ++i) {
2159 auto& p = out.commands[i];
2160 detail::PreparedQuery* query = nullptr;
2161 if (next_query != out.queries.size() && out.queries[next_query].command == i)
2162 query = &out.queries[next_query++];
2163 if (!query) {
2164 // A helper dispatch while a query runs would be counted into it (D3D-162): close the shared physical
2165 // segment before it and open a new one after, the way resolves do.
2166 if (!active.empty() && (p.predicate.scratch || !p.predicated_copy.empty() || p.has_depth24)) {
2167 p.statistics_end = current;
2168 current = out.statistics_segment_count++;
2169 p.statistics_begin = current;
2170 }
2171 continue;
2172 }
2173 const Command& command = out.list->commands()[i];
2174 const auto range = query_range(command);
2175 if (!std::holds_alternative<ResolveQueries>(command)) {
2176 // A Begin or End of another query kind leaves the shared segment alone.
2177 if (range.type != d3d12_query::pipeline_statistics) continue;
2178 query->statistics_end = current;
2179 const auto key = std::pair{range.heap, range.first};
2180 if (std::holds_alternative<BeginQuery>(command)) {
2181 // A flattened bundle can reuse a slot already active in the parent list.
2182 if (!active.emplace(key, out.statistics_segment_count).second) return ReplayResult::invalid_query;
2183 } else {
2184 const auto start = active.find(key);
2185 if (start == active.end()) return ReplayResult::invalid_query;
2186 query->statistics_first = start->second;
2187 query->statistics_count = out.statistics_segment_count - start->second;
2188 active.erase(start);
2189 }
2190 } else {
2191 if (current == detail::PreparedQuery::no_segment || range.type == d3d12_query::timestamp) continue;
2192 query->statistics_end = current;
2193 current = out.statistics_segment_count++;
2194 query->statistics_begin = current;
2195 continue;
2196 }
2197 current = active.empty() ? detail::PreparedQuery::no_segment : out.statistics_segment_count++;
2198 query->statistics_begin = current;
2199 }
2200 return active.empty() ? ReplayResult::success : ReplayResult::invalid_query;
2201}
2202
2074// detail::initialize zero-clears an image piece the tracker holds in UNDEFINED (D3D12 committed resources start 2203// detail::initialize zero-clears an image piece the tracker holds in UNDEFINED (D3D12 committed resources start
2075// zeroed) the first time a command touches it, with vkCmdClearColorImage or vkCmdClearDepthStencilImage. True when 2204// zeroed) the first time a command touches it, with vkCmdClearColorImage or vkCmdClearDepthStencilImage. True when
2076// a command of the list would need one of those and it is unset; replay() then refuses the list as unsupported, as 2205// a command of the list would need one of those and it is unset; replay() then refuses the list as unsupported, as
@@ -2150,9 +2279,12 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2150 out.unpredicated_copies = 0; 2279 out.unpredicated_copies = 0;
2151 const bool queries = vk.reset_query_pool && vk.begin_query && vk.end_query && vk.write_timestamp && 2280 const bool queries = vk.reset_query_pool && vk.begin_query && vk.end_query && vk.write_timestamp &&
2152 vk.copy_query_pool_results && vk.fill_buffer && vk.query_pool; 2281 vk.copy_query_pool_results && vk.fill_buffer && vk.query_pool;
2153 // Vulkan allows one active query per type. Only ordinary occlusion uses virtual segments. 2282 // Vulkan allows one active query per type. Overlapping ordinary and binary occlusion share one physical
2154 std::size_t ordinary_active = 0; 2283 // segment pool, and overlapping statistics split into the statistics pool (D3D-252); a physical query of a
2155 bool overlaps = false, binary_active = false, statistics_active = false; 2284 // type is still open at most once at any point, because each event closes the one open slot and opens a new
2285 // one. The occlusion kinds share their D3D12 heap, statistics have their own, so their states are separate.
2286 std::size_t ordinary_active = 0, binary_active = 0, statistics_active_count = 0;
2287 bool overlaps = false, statistics_overlaps = false, statistics_active = false;
2156 out.wrote_readback = false; 2288 out.wrote_readback = false;
2157 out.readback_src_stages = 0; 2289 out.readback_src_stages = 0;
2158 2290
@@ -2321,6 +2453,20 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2321 } else p.buffer_copies.push_back({src, dst, buffer_copy->size}); 2453 } else p.buffer_copies.push_back({src, dst, buffer_copy->size});
2322 } else if (const auto* texture_copy = std::get_if<CopyTexture>(&command)) { 2454 } else if (const auto* texture_copy = std::get_if<CopyTexture>(&command)) {
2323 result = detail::prepare_texture_copy(*texture_copy, p); 2455 result = detail::prepare_texture_copy(*texture_copy, p);
2456 if (result == ReplayResult::success && !p.staged_reads.empty()) {
2457 // A block-compressed copy staged through transfer scratch (prepare_texture_copy): whole blocks of
2458 // the read's row length and height, one region a copy.
2459 const VkBufferImageCopy& read = p.staged_reads[0];
2460 const BlockFormat f = block_format(p.source.format, read.imageSubresource.aspectMask);
2461 const VkDeviceSize bytes = VkDeviceSize(read.bufferRowLength / f.block) *
2462 (read.bufferImageHeight / f.block) * read.imageExtent.depth * f.bytes;
2463 VkDeviceSize base = 0;
2464 if (!f.bytes || !vk.copy_image_to_buffer || !vk.copy_buffer_to_image || !vk.copy_scratch ||
2465 !vk.copy_scratch(bytes, p.staged, base))
2466 return ReplayResult::invalid_copy; // refused as before this path existed
2467 p.staged_reads[0].bufferOffset += base;
2468 p.staged_writes[0].bufferOffset += base;
2469 }
2324 // A depth plane footprint of a D24 texture stored as D32: words of 24-bit UNORM, floats in the image. 2470 // A depth plane footprint of a D24 texture stored as D32: words of 24-bit UNORM, floats in the image.
2325 const bool upload = texture_copy->src.footprint; 2471 const bool upload = texture_copy->src.footprint;
2326 const ResourceBinding& image = upload ? p.binding : p.source; 2472 const ResourceBinding& image = upload ? p.binding : p.source;
@@ -2495,15 +2641,15 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2495 if (range.type != d3d12_query::timestamp && !std::holds_alternative<ResolveQueries>(command)) { 2641 if (range.type != d3d12_query::timestamp && !std::holds_alternative<ResolveQueries>(command)) {
2496 const bool begin = std::holds_alternative<BeginQuery>(command); 2642 const bool begin = std::holds_alternative<BeginQuery>(command);
2497 if (range.type == d3d12_query::occlusion) { 2643 if (range.type == d3d12_query::occlusion) {
2498 if (begin && binary_active) return ReplayResult::unsupported; 2644 overlaps |= begin && (ordinary_active || binary_active);
2499 if (begin) overlaps |= ordinary_active++ != 0; 2645 if (begin) ++ordinary_active; else --ordinary_active;
2500 else --ordinary_active;
2501 } else if (range.type == d3d12_query::binary_occlusion) { 2646 } else if (range.type == d3d12_query::binary_occlusion) {
2502 if (begin && (binary_active || ordinary_active)) return ReplayResult::unsupported; 2647 overlaps |= begin && (ordinary_active || binary_active);
2503 binary_active = begin; 2648 if (begin) ++binary_active; else --binary_active;
2504 } else { 2649 } else {
2505 if (begin && statistics_active) return ReplayResult::unsupported; 2650 statistics_overlaps |= begin && statistics_active_count;
2506 statistics_active = begin; 2651 if (begin) ++statistics_active_count; else --statistics_active_count;
2652 statistics_active = statistics_active_count != 0;
2507 } 2653 }
2508 } 2654 }
2509 if (const auto* resolve_queries = std::get_if<ResolveQueries>(&command)) { 2655 if (const auto* resolve_queries = std::get_if<ResolveQueries>(&command)) {
@@ -2603,8 +2749,14 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2603 if (const auto r = detail::prepare_draw(*draw, resolve, vk, p); r != ReplayResult::success) return r; 2749 if (const auto r = detail::prepare_draw(*draw, resolve, vk, p); r != ReplayResult::success) return r;
2604 } 2750 }
2605 } 2751 }
2606 if (ordinary_active) return ReplayResult::invalid_query; 2752 if (ordinary_active || binary_active) return ReplayResult::invalid_query;
2607 plan_statistics_segments(out); 2753 out.statistics_overlaps = statistics_overlaps;
2754 if (statistics_overlaps) {
2755 const auto result = plan_overlapping_statistics_segments(out);
2756 if (result != ReplayResult::success) return result;
2757 } else {
2758 plan_statistics_segments(out);
2759 }
2608 if (overlaps) { 2760 if (overlaps) {
2609 if (!vk.sum_occlusion || out.queries.size() >= detail::PreparedQuery::no_segment) 2761 if (!vk.sum_occlusion || out.queries.size() >= detail::PreparedQuery::no_segment)
2610 return ReplayResult::unsupported; 2762 return ReplayResult::unsupported;
@@ -2634,6 +2786,9 @@ public:
2634 retain(statistics_pool); 2786 retain(statistics_pool);
2635 list.statistics_pool = statistics_pool->pool; 2787 list.statistics_pool = statistics_pool->pool;
2636 list.statistics_base = statistics_base; 2788 list.statistics_base = statistics_base;
2789 } else if (list.statistics_overlaps) {
2790 // Whole queries on the heap pool would keep two pipeline-statistics queries active at once.
2791 return ReplayResult::unsupported;
2637 } else { 2792 } else {
2638 for (const auto& command : list.commands) 2793 for (const auto& command : list.commands)
2639 if (command.statistics_end != detail::PreparedQuery::no_segment) 2794 if (command.statistics_end != detail::PreparedQuery::no_segment)
@@ -2674,11 +2829,14 @@ public:
2674 detail::QueryResolveRun run{value.ended ? query.heap->pool : VK_NULL_HANDLE, 2829 detail::QueryResolveRun run{value.ended ? query.heap->pool : VK_NULL_HANDLE,
2675 index, 1, offset + VkDeviceSize(i) * size}; 2830 index, 1, offset + VkDeviceSize(i) * size};
2676 if (value.occlusion.segments) { 2831 if (value.occlusion.segments) {
2677 if (resolve.type != d3d12_query::occlusion && !statistics) return ReplayResult::invalid_query; 2832 if (resolve.type != d3d12_query::occlusion && !binary && !statistics)
2833 return ReplayResult::invalid_query;
2678 const auto& saved = value.occlusion; 2834 const auto& saved = value.occlusion;
2679 run = {saved.segments->pool, saved.first, saved.count, run.offset, saved.count > 1}; 2835 run = {saved.segments->pool, saved.first, saved.count, run.offset, saved.count > 1};
2680 if (!can_sum || (run.sum && !uncounted)) return ReplayResult::unsupported; 2836 if (!can_sum || (run.sum && !uncounted)) return ReplayResult::unsupported;
2681 (statistics ? needs_statistics_sum : needs_sum) |= run.sum; 2837 if (statistics) needs_statistics_sum |= run.sum;
2838 else if (binary) (run.sum ? needs_sum_binary : needs_binary) = true;
2839 else needs_sum |= run.sum;
2682 retain(saved.segments); 2840 retain(saved.segments);
2683 } 2841 }
2684 if (!query.resolves.empty() && !run.sum && run.count == 1) { 2842 if (!query.resolves.empty() && !run.sum && run.count == 1) {
@@ -2707,6 +2865,7 @@ public:
2707 bool needs_sum = false; 2865 bool needs_sum = false;
2708 bool needs_binary = false; 2866 bool needs_binary = false;
2709 bool needs_statistics_sum = false; 2867 bool needs_statistics_sum = false;
2868 bool needs_sum_binary = false; // a binary query whose segments must be summed before the 0/1 normalize
2710 std::vector<std::shared_ptr<const OcclusionSegmentPool>> retained; 2869 std::vector<std::shared_ptr<const OcclusionSegmentPool>> retained;
2711 2870
2712private: 2871private:
@@ -2782,11 +2941,16 @@ inline void emit_query(const PreparedList& list, const detail::PreparedQuery& qu
2782 const bool suspend = predicate.buffer && !query.resolves.empty(); 2941 const bool suspend = predicate.buffer && !query.resolves.empty();
2783 end_statistics(); 2942 end_statistics();
2784 if (suspend) vk.end_conditional_rendering(cb); 2943 if (suspend) vk.end_conditional_rendering(cb);
2944 if (resolve.type == d3d12_query::timestamp && vk.order_timestamp_copy &&
2945 std::any_of(query.resolves.begin(), query.resolves.end(), [](const auto& run) { return run.pool; }))
2946 vk.order_timestamp_copy(cb);
2785 for (const auto& run : query.resolves) { 2947 for (const auto& run : query.resolves) {
2786 if (!run.pool) { 2948 if (!run.pool) {
2787 vk.fill_buffer(cb, dst, run.offset, VkDeviceSize(run.count) * size, 0); 2949 vk.fill_buffer(cb, dst, run.offset, VkDeviceSize(run.count) * size, 0);
2788 } else if (run.sum && resolve.type == d3d12_query::pipeline_statistics) { 2950 } else if (run.sum && resolve.type == d3d12_query::pipeline_statistics) {
2789 vk.sum_statistics(cb, run.pool, run.first, run.count, dst, run.offset); 2951 vk.sum_statistics(cb, run.pool, run.first, run.count, dst, run.offset);
2952 } else if (run.sum && binary) {
2953 vk.sum_binary_occlusion(cb, run.pool, run.first, run.count, dst, run.offset);
2790 } else if (run.sum || binary) { 2954 } else if (run.sum || binary) {
2791 const auto& resolve_occlusion = run.sum ? vk.sum_occlusion : vk.resolve_binary_occlusion; 2955 const auto& resolve_occlusion = run.sum ? vk.sum_occlusion : vk.resolve_binary_occlusion;
2792 resolve_occlusion(cb, run.pool, run.first, run.count, dst, run.offset); 2956 resolve_occlusion(cb, run.pool, run.first, run.count, dst, run.offset);
@@ -2925,6 +3089,8 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
2925 barrier.dstStageMask = dst.stages; 3089 barrier.dstStageMask = dst.stages;
2926 barrier.srcAccessMask = src.access; 3090 barrier.srcAccessMask = src.access;
2927 barrier.dstAccessMask = dst.access; 3091 barrier.dstAccessMask = dst.access;
3092 if (barrier.srcStageMask) detail::restrict_to_queue(vk, barrier.srcStageMask, barrier.srcAccessMask);
3093 if (barrier.dstStageMask) detail::restrict_to_queue(vk, barrier.dstStageMask, barrier.dstAccessMask);
2928 VkDependencyInfo dependency{VK_STRUCTURE_TYPE_DEPENDENCY_INFO}; 3094 VkDependencyInfo dependency{VK_STRUCTURE_TYPE_DEPENDENCY_INFO};
2929 dependency.memoryBarrierCount = 1; 3095 dependency.memoryBarrierCount = 1;
2930 dependency.pMemoryBarriers = &barrier; 3096 dependency.pMemoryBarriers = &barrier;
@@ -2959,6 +3125,8 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
2959 b.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; 3125 b.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
2960 b.image = p.binding.image; 3126 b.image = p.binding.image;
2961 b.subresourceRange = detail::layout_range(p.binding, piece.range); 3127 b.subresourceRange = detail::layout_range(p.binding, piece.range);
3128 if (b.srcStageMask) detail::restrict_to_queue(vk, b.srcStageMask, b.srcAccessMask);
3129 if (b.dstStageMask) detail::restrict_to_queue(vk, b.dstStageMask, b.dstAccessMask);
2962 barriers.push_back(b); 3130 barriers.push_back(b);
2963 } 3131 }
2964 VkDependencyInfo dependency{VK_STRUCTURE_TYPE_DEPENDENCY_INFO}; 3132 VkDependencyInfo dependency{VK_STRUCTURE_TYPE_DEPENDENCY_INFO};
@@ -3099,7 +3267,10 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
3099 vk.copy_buffer(command_buffer, p.source.buffer, p.binding.buffer, std::uint32_t(p.buffer_copies.size()), 3267 vk.copy_buffer(command_buffer, p.source.buffer, p.binding.buffer, std::uint32_t(p.buffer_copies.size()),
3100 p.buffer_copies.data()); 3268 p.buffer_copies.data());
3101 } else if (p.staged) { 3269 } else if (p.staged) {
3102 // Depth <-> colour: the source into the scratch, then the scratch into the destination. 3270 // Depth <-> colour, or a block-compressed copy no one extent fits: the source into the scratch, then
3271 // the scratch into the destination. The destination's copy_layout comes after the scratch write, so
3272 // its barrier orders every earlier transfer write before the destination's (#860, Vonsek's
3273 // synchronization-validation run).
3103 const VkImageLayout src_layout = detail::copy_layout( 3274 const VkImageLayout src_layout = detail::copy_layout(
3104 vk, command_buffer, p.source, src_id, detail::planes_for_layout(p.source, p.source_range, separate), 3275 vk, command_buffer, p.source, src_id, detail::planes_for_layout(p.source, p.source_range, separate),
3105 VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_TRANSFER_READ_BIT, tracker); 3276 VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_TRANSFER_READ_BIT, tracker);