diff options
| author | Jan Trencansky <jan.trencansky@protonmail.com> | 2026-11-24 18:36:18 -0500 |
|---|---|---|
| committer | Jan Trencansky <jan.trencansky@protonmail.com> | 2026-11-24 18:36:18 -0500 |
| commit | d64f12b53d275c71604fc7f6fee7302ce0f2baa9 (patch) | |
| tree | a3953dc4fd8ee03d6a1c0906e9b2b06e561c7f0d /runtime/src | |
| parent | a213a232b8819cc0252b0cdcc85b351dc9a763a8 (diff) | |
| parent | 3a0af1f1503307570d998cfe609a70a16c5bbad2 (diff) | |
Merge main into TEST-1700, wave32 VS halves wording (#804)
Conflict in docs/design.md: this branch rewords the "Wave64 graphics: partition invariance
(SHADER-10)" row; main left that row as it was and added the SHADER-W64-WQM-UVOTE row after it.
Kept this branch's SHADER-10 row and main's new row below it. runtime/test/shaders/w64_graphics.py
merged without conflicts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'runtime/src')
| -rw-r--r-- | runtime/src/active_input.h | 17 | ||||
| -rw-r--r-- | runtime/src/arena_size.h | 5 | ||||
| -rw-r--r-- | runtime/src/command_list.h | 18 | ||||
| -rw-r--r-- | runtime/src/cpu_emulation.h | 97 | ||||
| -rw-r--r-- | runtime/src/crt_timed_wait.cpp | 29 | ||||
| -rw-r--r-- | runtime/src/frame_pacer.h | 100 | ||||
| -rw-r--r-- | runtime/src/gfx10_descriptors.h | 6 | ||||
| -rw-r--r-- | runtime/src/mods.h | 4 | ||||
| -rw-r--r-- | runtime/src/pe_loader.cpp | 7 | ||||
| -rw-r--r-- | runtime/src/retire_tickets.h | 16 | ||||
| -rw-r--r-- | runtime/src/shader_library.h | 23 | ||||
| -rw-r--r-- | runtime/src/uav_clear.h | 4 | ||||
| -rw-r--r-- | runtime/src/vulkan_backend.h | 45 | ||||
| -rw-r--r-- | runtime/src/vulkan_replay.h | 186 | ||||
| -rw-r--r-- | runtime/src/vulkan_scratch.h | 16 | ||||
| -rw-r--r-- | runtime/src/xdxr_build.h | 14 | ||||
| -rw-r--r-- | runtime/src/xdxr_descs.h | 7 |
17 files changed, 502 insertions, 92 deletions
diff --git a/runtime/src/active_input.h b/runtime/src/active_input.h index c0f7451b1..55b67d3bb 100644 --- a/runtime/src/active_input.h +++ b/runtime/src/active_input.h | |||
| @@ -95,7 +95,8 @@ public: | |||
| 95 | const InputEdge edge = edge_between(it->second, now); | 95 | const InputEdge edge = edge_between(it->second, now); |
| 96 | it->second = now; | 96 | it->second = now; |
| 97 | if (edge == InputEdge::None || family == tracked_) return InputEdge::None; | 97 | if (edge == InputEdge::None || family == tracked_) return InputEdge::None; |
| 98 | if (changed_once_ && time_us - changed_at_ < thresholds_.min_switch_us) return InputEdge::None; | 98 | if (changed_once_ && (time_us < changed_at_ || time_us - changed_at_ < thresholds_.min_switch_us)) |
| 99 | return InputEdge::None; | ||
| 99 | const InputFamily before = active(); | 100 | const InputFamily before = active(); |
| 100 | tracked_ = family; | 101 | tracked_ = family; |
| 101 | changed_at_ = time_us; | 102 | changed_at_ = time_us; |
| @@ -125,11 +126,17 @@ private: | |||
| 125 | InputEdge edge_between(const InputSample& was, const InputSample& now) const { | 126 | InputEdge edge_between(const InputSample& was, const InputSample& now) const { |
| 126 | if (now.buttons & ~was.buttons) return InputEdge::Button; | 127 | if (now.buttons & ~was.buttons) return InputEdge::Button; |
| 127 | const float t = thresholds_.trigger; | 128 | const float t = thresholds_.trigger; |
| 128 | if ((was.left_trigger <= t && now.left_trigger > t) || (was.right_trigger <= t && now.right_trigger > t)) | 129 | const auto trigger_rose = [t](float prev, float cur) { |
| 130 | return std::isfinite(prev) && std::isfinite(cur) && prev <= t && cur > t; | ||
| 131 | }; | ||
| 132 | if (trigger_rose(was.left_trigger, now.left_trigger) || trigger_rose(was.right_trigger, now.right_trigger)) | ||
| 129 | return InputEdge::Trigger; | 133 | return InputEdge::Trigger; |
| 130 | const auto out = [this](float x, float y) { return std::hypot(x, y) > thresholds_.stick; }; | 134 | const auto stick_left = [this](float px, float py, float cx, float cy) { |
| 131 | if ((!out(was.left_x, was.left_y) && out(now.left_x, now.left_y)) || | 135 | if (!std::isfinite(px) || !std::isfinite(py) || !std::isfinite(cx) || !std::isfinite(cy)) return false; |
| 132 | (!out(was.right_x, was.right_y) && out(now.right_x, now.right_y))) | 136 | return std::hypot(px, py) <= thresholds_.stick && std::hypot(cx, cy) > thresholds_.stick; |
| 137 | }; | ||
| 138 | if (stick_left(was.left_x, was.left_y, now.left_x, now.left_y) || | ||
| 139 | stick_left(was.right_x, was.right_y, now.right_x, now.right_y)) | ||
| 133 | return InputEdge::Stick; | 140 | return InputEdge::Stick; |
| 134 | return InputEdge::None; | 141 | return InputEdge::None; |
| 135 | } | 142 | } |
diff --git a/runtime/src/arena_size.h b/runtime/src/arena_size.h index 8f4ca4caf..196b03e3e 100644 --- a/runtime/src/arena_size.h +++ b/runtime/src/arena_size.h | |||
| @@ -60,7 +60,10 @@ struct ArenaSize { | |||
| 60 | // invalid Vulkan, while one under 16 MiB is only small (and no conformant device reports under 1 GiB). | 60 | // invalid Vulkan, while one under 16 MiB is only small (and no conformant device reports under 1 GiB). |
| 61 | inline ArenaSize decide_arena_size(const char* env, const ArenaLimits& limits, VkDeviceSize allocation_overhead = 0) { | 61 | inline ArenaSize decide_arena_size(const char* env, const ArenaLimits& limits, VkDeviceSize allocation_overhead = 0) { |
| 62 | VkDeviceSize megabytes = kArenaDefaultMiB; | 62 | VkDeviceSize megabytes = kArenaDefaultMiB; |
| 63 | if (env && *env) megabytes = std::clamp<VkDeviceSize>(std::strtoull(env, nullptr, 10), kArenaMinMiB, kArenaMaxMiB); | 63 | // Signed, so "-5" clamps to the floor (strtoull wraps it to a huge value, which clamps to the maximum). |
| 64 | if (env && *env) | ||
| 65 | megabytes = VkDeviceSize(std::clamp<long long>(std::strtoll(env, nullptr, 10), (long long)kArenaMinMiB, | ||
| 66 | (long long)kArenaMaxMiB)); | ||
| 64 | ArenaSize size; | 67 | ArenaSize size; |
| 65 | size.requested = size.bytes = megabytes * kArenaMiB; | 68 | size.requested = size.bytes = megabytes * kArenaMiB; |
| 66 | VkDeviceSize by_buffer = size.requested, by_allocation = size.requested; | 69 | VkDeviceSize by_buffer = size.requested, by_allocation = size.requested; |
diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h index 7c5c09e0a..c28904efe 100644 --- a/runtime/src/command_list.h +++ b/runtime/src/command_list.h | |||
| @@ -414,6 +414,15 @@ struct DrawViews { | |||
| 414 | std::uint32_t render_target_count = 8; | 414 | std::uint32_t render_target_count = 8; |
| 415 | }; | 415 | }; |
| 416 | 416 | ||
| 417 | // Shared across draws that keep the same multi-viewport / multi-scissor state (null for the common 1-viewport case). | ||
| 418 | struct DrawViewports { | ||
| 419 | static constexpr std::uint32_t max_count = 16; | ||
| 420 | std::array<Viewport, max_count> viewports{}; | ||
| 421 | std::uint32_t viewport_count = 0; | ||
| 422 | std::array<Rect, max_count> scissors{}; | ||
| 423 | std::uint32_t scissor_count = 0; | ||
| 424 | }; | ||
| 425 | |||
| 417 | // DrawInstanced / DrawIndexedInstanced / DispatchMesh, with everything they use captured when they are recorded: | 426 | // DrawInstanced / DrawIndexedInstanced / DispatchMesh, with everything they use captured when they are recorded: |
| 418 | // D3D12 reads render-target and depth descriptors at OMSetRenderTargets, and every other piece of state is the | 427 | // D3D12 reads render-target and depth descriptors at OMSetRenderTargets, and every other piece of state is the |
| 419 | // list's state at the draw. resource 0 marks an unbound render-target slot or no depth buffer. A mesh draw | 428 | // list's state at the draw. resource 0 marks an unbound render-target slot or no depth buffer. A mesh draw |
| @@ -440,6 +449,7 @@ struct Draw { | |||
| 440 | std::int32_t base_vertex = 0; | 449 | std::int32_t base_vertex = 0; |
| 441 | std::uint32_t first_instance = 0; | 450 | std::uint32_t first_instance = 0; |
| 442 | bool mesh = false; | 451 | bool mesh = false; |
| 452 | std::shared_ptr<const DrawViewports> viewports; // non-null when >1 viewport or >1 scissor was bound | ||
| 443 | }; | 453 | }; |
| 444 | 454 | ||
| 445 | // D3D12_TEXTURE_DATA_PITCH_ALIGNMENT and D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT. | 455 | // D3D12_TEXTURE_DATA_PITCH_ALIGNMENT and D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT. |
| @@ -587,6 +597,9 @@ enum class IndirectKind : std::uint8_t { | |||
| 587 | draw = 0, | 597 | draw = 0, |
| 588 | draw_indexed = 1, | 598 | draw_indexed = 1, |
| 589 | dispatch = 2, | 599 | dispatch = 2, |
| 600 | // D3D12_DISPATCH_MESH_ARGUMENTS. Created on a device with mesh shaders; ExecuteIndirect with it records nothing | ||
| 601 | // yet (the replay is #3777's), so a title that only creates such a signature at startup goes on. | ||
| 602 | dispatch_mesh = 3, | ||
| 590 | }; | 603 | }; |
| 591 | 604 | ||
| 592 | struct ExecuteIndirect { | 605 | struct ExecuteIndirect { |
| @@ -688,10 +701,11 @@ public: | |||
| 688 | return append(barrier); | 701 | return append(barrier); |
| 689 | } | 702 | } |
| 690 | 703 | ||
| 704 | // LayoutAfter UNDEFINED is legal: the subresources' contents are no longer needed, as before their memory is | ||
| 705 | // aliased (the retail title ends a depth buffer's use this way, #984; WARP closes such a list, | ||
| 706 | // d3d12_close_parity_test). Replay keeps the image's Vulkan layout and orders the accesses only. | ||
| 691 | bool barrier(const TextureBarrier& barrier) { | 707 | bool barrier(const TextureBarrier& barrier) { |
| 692 | if (!barrier.resource || !valid_sync(barrier.sync_before, barrier.sync_after)) return false; | 708 | if (!barrier.resource || !valid_sync(barrier.sync_before, barrier.sync_after)) return false; |
| 693 | if (barrier.layout_after == d3d12_layout::undefined && barrier.layout_before != d3d12_layout::undefined) | ||
| 694 | return false; | ||
| 695 | if (barrier.flags & ~texture_barrier_discard) return false; | 709 | if (barrier.flags & ~texture_barrier_discard) return false; |
| 696 | if (barrier.range.mip_count && (!barrier.range.layer_count || !barrier.range.plane_count)) return false; | 710 | if (barrier.range.mip_count && (!barrier.range.layer_count || !barrier.range.plane_count)) return false; |
| 697 | if (barrier.sync_after == d3d12_sync::split) return !closed_; | 711 | if (barrier.sync_after == d3d12_sync::split) return !closed_; |
diff --git a/runtime/src/cpu_emulation.h b/runtime/src/cpu_emulation.h index fac13eeee..8df3b55d0 100644 --- a/runtime/src/cpu_emulation.h +++ b/runtime/src/cpu_emulation.h | |||
| @@ -272,6 +272,84 @@ inline bool apply(const Decoded& d, CONTEXT* c, EXCEPTION_RECORD* fault = nullpt | |||
| 272 | return true; | 272 | return true; |
| 273 | } | 273 | } |
| 274 | 274 | ||
| 275 | inline uint64_t gpr_read(const CONTEXT* c, int r) { | ||
| 276 | switch (r) { | ||
| 277 | case 0: return c->Rax; case 1: return c->Rcx; case 2: return c->Rdx; case 3: return c->Rbx; | ||
| 278 | case 4: return c->Rsp; case 5: return c->Rbp; case 6: return c->Rsi; case 7: return c->Rdi; | ||
| 279 | case 8: return c->R8; case 9: return c->R9; case 10: return c->R10; case 11: return c->R11; | ||
| 280 | case 12: return c->R12; case 13: return c->R13; case 14: return c->R14; case 15: return c->R15; | ||
| 281 | default: return 0; | ||
| 282 | } | ||
| 283 | } | ||
| 284 | |||
| 285 | enum class ClzeroLoopResult { no_match, ok, faulted }; | ||
| 286 | |||
| 287 | inline void apply_cmp_flags(CONTEXT* c, uint64_t lhs, uint64_t rhs) { | ||
| 288 | const uint64_t diff = lhs - rhs; | ||
| 289 | uint32_t flags = c->EFlags & ~DWORD(0x8D5u); // clear CF(0), PF(2), AF(4), ZF(6), SF(7), OF(11) | ||
| 290 | if (lhs < rhs) flags |= 0x1u; // CF | ||
| 291 | uint8_t lo8 = static_cast<uint8_t>(diff); | ||
| 292 | lo8 ^= lo8 >> 4; | ||
| 293 | lo8 ^= lo8 >> 2; | ||
| 294 | lo8 ^= lo8 >> 1; | ||
| 295 | if ((lo8 & 1u) == 0) flags |= 0x4u; // PF | ||
| 296 | if ((lhs ^ rhs ^ diff) & 0x10u) flags |= 0x10u; // AF | ||
| 297 | if (diff == 0) flags |= 0x40u; // ZF | ||
| 298 | if (diff >> 63) flags |= 0x80u; // SF | ||
| 299 | if (((lhs ^ rhs) & (lhs ^ diff)) >> 63) flags |= 0x800u; // OF | ||
| 300 | c->EFlags = flags; | ||
| 301 | } | ||
| 302 | |||
| 303 | // Fast-path for the Zen 2 zeroing loop: `clzero; add rax, 0x40; cmp rax, reg64; jb -12` (12 bytes). | ||
| 304 | // Zeroes the entire writable span in one memset instead of raising #UD + VirtualQuery per 64-byte line. | ||
| 305 | inline ClzeroLoopResult try_clzero_loop(const uint8_t* code, std::size_t avail, CONTEXT* c, EXCEPTION_RECORD* fault) { | ||
| 306 | if (avail < 12) return ClzeroLoopResult::no_match; | ||
| 307 | if (code[0] != 0x0F || code[1] != 0x01 || code[2] != 0xFC) return ClzeroLoopResult::no_match; | ||
| 308 | if (code[3] != 0x48 || code[4] != 0x83 || code[5] != 0xC0 || code[6] != 0x40) return ClzeroLoopResult::no_match; | ||
| 309 | if ((code[7] != 0x48 && code[7] != 0x4C) || code[8] != 0x39 || (code[9] & 0xC7) != 0xC0) | ||
| 310 | return ClzeroLoopResult::no_match; | ||
| 311 | if (code[10] != 0x72 || code[11] != 0xF4) return ClzeroLoopResult::no_match; | ||
| 312 | |||
| 313 | const int limit_reg = ((code[9] >> 3) & 7) | ((code[7] & 4) << 1); | ||
| 314 | if (limit_reg == 0 || limit_reg == 4) return ClzeroLoopResult::no_match; | ||
| 315 | |||
| 316 | const uint64_t start = c->Rax; | ||
| 317 | const uint64_t limit = gpr_read(c, limit_reg); | ||
| 318 | if ((start & 63) != 0 || limit <= start + 64) return ClzeroLoopResult::no_match; | ||
| 319 | |||
| 320 | uint64_t total = (limit - start + 63) & ~uint64_t(63); | ||
| 321 | constexpr uint64_t kMaxBatch = uint64_t(64) << 20; | ||
| 322 | if (total > kMaxBatch) total = kMaxBatch; | ||
| 323 | const uint64_t end = start + total; | ||
| 324 | |||
| 325 | for (uint64_t cur = start; cur < end;) { | ||
| 326 | const DWORD err = writable(cur); | ||
| 327 | if (err) { | ||
| 328 | if (cur > start) { | ||
| 329 | std::memset(reinterpret_cast<void*>(start), 0, std::size_t(cur - start)); | ||
| 330 | c->Rax = cur; | ||
| 331 | apply_cmp_flags(c, cur, limit); | ||
| 332 | } | ||
| 333 | if (fault) { | ||
| 334 | std::memset(fault, 0, sizeof *fault); | ||
| 335 | fault->ExceptionCode = err; | ||
| 336 | fault->NumberParameters = 2; | ||
| 337 | fault->ExceptionInformation[0] = 1; | ||
| 338 | fault->ExceptionInformation[1] = ULONG_PTR(cur); | ||
| 339 | } | ||
| 340 | return ClzeroLoopResult::faulted; | ||
| 341 | } | ||
| 342 | const uint64_t next_page = (cur & ~uint64_t(0xFFF)) + 0x1000; | ||
| 343 | cur = next_page < end ? next_page : end; | ||
| 344 | } | ||
| 345 | |||
| 346 | std::memset(reinterpret_cast<void*>(start), 0, std::size_t(total)); | ||
| 347 | c->Rax = end; | ||
| 348 | apply_cmp_flags(c, end, limit); | ||
| 349 | if (end >= limit) c->Rip += 12; | ||
| 350 | return ClzeroLoopResult::ok; | ||
| 351 | } | ||
| 352 | |||
| 275 | inline LONG CALLBACK handler(EXCEPTION_POINTERS* info) { | 353 | inline LONG CALLBACK handler(EXCEPTION_POINTERS* info) { |
| 276 | if (info->ExceptionRecord->ExceptionCode != STATUS_ILLEGAL_INSTRUCTION) return EXCEPTION_CONTINUE_SEARCH; | 354 | if (info->ExceptionRecord->ExceptionCode != STATUS_ILLEGAL_INSTRUCTION) return EXCEPTION_CONTINUE_SEARCH; |
| 277 | CONTEXT* c = info->ContextRecord; | 355 | CONTEXT* c = info->ContextRecord; |
| @@ -281,6 +359,25 @@ inline LONG CALLBACK handler(EXCEPTION_POINTERS* info) { | |||
| 281 | const Decoded d = decode(code, avail); | 359 | const Decoded d = decode(code, avail); |
| 282 | if (d.op == Op::none) return EXCEPTION_CONTINUE_SEARCH; | 360 | if (d.op == Op::none) return EXCEPTION_CONTINUE_SEARCH; |
| 283 | EXCEPTION_RECORD fault; | 361 | EXCEPTION_RECORD fault; |
| 362 | if (d.op == Op::clzero && !d.addr32 && d.length == 3) { | ||
| 363 | const uint64_t fault_rip = c->Rip; | ||
| 364 | const ClzeroLoopResult lr = try_clzero_loop(code, avail, c, &fault); | ||
| 365 | if (lr == ClzeroLoopResult::ok) { | ||
| 366 | if (count(d.op).fetch_add(1, std::memory_order_relaxed) == 0) | ||
| 367 | std::fprintf(stderr, "[rt] cpu: this CPU has no %s; emulating it (first at %p)\n", name(d.op), | ||
| 368 | reinterpret_cast<void*>(fault_rip)); | ||
| 369 | return EXCEPTION_CONTINUE_EXECUTION; | ||
| 370 | } | ||
| 371 | if (lr == ClzeroLoopResult::faulted) { | ||
| 372 | EXCEPTION_RECORD* r = info->ExceptionRecord; | ||
| 373 | r->ExceptionCode = fault.ExceptionCode; | ||
| 374 | r->ExceptionFlags = 0; | ||
| 375 | r->NumberParameters = fault.NumberParameters; | ||
| 376 | r->ExceptionInformation[0] = fault.ExceptionInformation[0]; | ||
| 377 | r->ExceptionInformation[1] = fault.ExceptionInformation[1]; | ||
| 378 | return EXCEPTION_CONTINUE_SEARCH; | ||
| 379 | } | ||
| 380 | } | ||
| 284 | if (!apply(d, c, &fault)) { | 381 | if (!apply(d, c, &fault)) { |
| 285 | // CLZERO on a line it cannot write: the CPU would raise that fault at this instruction, so the next handlers | 382 | // CLZERO on a line it cannot write: the CPU would raise that fault at this instruction, so the next handlers |
| 286 | // see it instead of the #UD (RIP still points at the instruction). | 383 | // see it instead of the #UD (RIP still points at the instruction). |
diff --git a/runtime/src/crt_timed_wait.cpp b/runtime/src/crt_timed_wait.cpp index 6441f2868..cd26e7d3a 100644 --- a/runtime/src/crt_timed_wait.cpp +++ b/runtime/src/crt_timed_wait.cpp | |||
| @@ -25,7 +25,9 @@ extern "C" { | |||
| 25 | // absolute, in TIME_UTC seconds and nanoseconds, and the result uses _Thrd_result's values (0, or 2 on timeout). | 25 | // absolute, in TIME_UTC seconds and nanoseconds, and the result uses _Thrd_result's values (0, or 2 on timeout). |
| 26 | __declspec(dllimport) int __cdecl _Cnd_timedwait(_Cnd_t, _Mtx_t, const _timespec64*) noexcept; | 26 | __declspec(dllimport) int __cdecl _Cnd_timedwait(_Cnd_t, _Mtx_t, const _timespec64*) noexcept; |
| 27 | 27 | ||
| 28 | _Thrd_result __stdcall _Cnd_timedwait_for_unchecked(_Cnd_t cond, _Mtx_t mtx, unsigned int ms) noexcept { | 28 | namespace { |
| 29 | |||
| 30 | _Thrd_result timedwait_for_impl(_Cnd_t cond, _Mtx_t mtx, unsigned int ms, bool unchecked) noexcept { | ||
| 29 | _timespec64 deadline{}; | 31 | _timespec64 deadline{}; |
| 30 | if (_timespec64_get(&deadline, TIME_UTC) != TIME_UTC) deadline = {}; | 32 | if (_timespec64_get(&deadline, TIME_UTC) != TIME_UTC) deadline = {}; |
| 31 | deadline.tv_sec += ms / 1000; | 33 | deadline.tv_sec += ms / 1000; |
| @@ -34,13 +36,32 @@ _Thrd_result __stdcall _Cnd_timedwait_for_unchecked(_Cnd_t cond, _Mtx_t mtx, uns | |||
| 34 | deadline.tv_sec += 1; | 36 | deadline.tv_sec += 1; |
| 35 | deadline.tv_nsec -= 1000000000L; | 37 | deadline.tv_nsec -= 1000000000L; |
| 36 | } | 38 | } |
| 37 | // A spurious or early return is allowed ("unchecked"): the STL's callers check the clock themselves. | 39 | // Preserve the caller's LastError across the wait while detecting OS timer timeouts cleanly. |
| 38 | return static_cast<_Thrd_result>(_Cnd_timedwait(cond, mtx, &deadline)); | 40 | const DWORD saved_error = GetLastError(); |
| 41 | SetLastError(ERROR_SUCCESS); | ||
| 42 | const auto res = static_cast<_Thrd_result>(_Cnd_timedwait(cond, mtx, &deadline)); | ||
| 43 | const DWORD wait_error = GetLastError(); | ||
| 44 | SetLastError(saved_error); | ||
| 45 | // msvcp140's _Cnd_timedwait checks _Xtime_diff_to_millis2(target, &now) == 0 after SleepConditionVariableSRW | ||
| 46 | // returns FALSE/ERROR_TIMEOUT, so an OS timer wake even <1 ms before `deadline` turns into _Thrd_result::_Success. | ||
| 47 | // STL wait_for/wait_until callers treat _Success from _Cnd_timedwait_for_unchecked as a notification/spurious | ||
| 48 | // wake (cv_status::no_timeout) instead of looping until steady_clock reaches the target; report _Timedout here | ||
| 49 | // so the caller checks steady_clock and waits for the remaining time. | ||
| 50 | if (unchecked && res == _Thrd_result::_Success && wait_error == ERROR_TIMEOUT) { | ||
| 51 | return _Thrd_result::_Timedout; | ||
| 52 | } | ||
| 53 | return res; | ||
| 54 | } | ||
| 55 | |||
| 56 | } // namespace | ||
| 57 | |||
| 58 | _Thrd_result __stdcall _Cnd_timedwait_for_unchecked(_Cnd_t cond, _Mtx_t mtx, unsigned int ms) noexcept { | ||
| 59 | return timedwait_for_impl(cond, mtx, ms, true); | ||
| 39 | } | 60 | } |
| 40 | 61 | ||
| 41 | // Not declared by the 14.4x headers, but defined by the same member: keep a caller of the older name off it too. | 62 | // Not declared by the 14.4x headers, but defined by the same member: keep a caller of the older name off it too. |
| 42 | _Thrd_result __stdcall _Cnd_timedwait_for(_Cnd_t cond, _Mtx_t mtx, unsigned int ms) noexcept { | 63 | _Thrd_result __stdcall _Cnd_timedwait_for(_Cnd_t cond, _Mtx_t mtx, unsigned int ms) noexcept { |
| 43 | return _Cnd_timedwait_for_unchecked(cond, mtx, ms); | 64 | return timedwait_for_impl(cond, mtx, ms, false); |
| 44 | } | 65 | } |
| 45 | 66 | ||
| 46 | void __cdecl _Smtx_lock_exclusive(_Smtx_t* lock) noexcept { | 67 | void __cdecl _Smtx_lock_exclusive(_Smtx_t* lock) noexcept { |
diff --git a/runtime/src/frame_pacer.h b/runtime/src/frame_pacer.h index 38f7860c1..afeaf191e 100644 --- a/runtime/src/frame_pacer.h +++ b/runtime/src/frame_pacer.h | |||
| @@ -30,14 +30,17 @@ | |||
| 30 | // suspended) is unchanged. | 30 | // suspended) is unchanged. |
| 31 | 31 | ||
| 32 | #include <algorithm> | 32 | #include <algorithm> |
| 33 | #include <array> | ||
| 33 | #include <atomic> | 34 | #include <atomic> |
| 34 | #include <chrono> | 35 | #include <chrono> |
| 35 | #include <condition_variable> | 36 | #include <condition_variable> |
| 37 | #include <cstddef> | ||
| 36 | #include <cstdint> | 38 | #include <cstdint> |
| 37 | #include <deque> | 39 | #include <deque> |
| 38 | #include <functional> | 40 | #include <functional> |
| 39 | #include <limits> | 41 | #include <limits> |
| 40 | #include <mutex> | 42 | #include <mutex> |
| 43 | #include <vector> | ||
| 41 | 44 | ||
| 42 | namespace leonida { | 45 | namespace leonida { |
| 43 | 46 | ||
| @@ -149,6 +152,25 @@ struct FrameStatistic { | |||
| 149 | float percent_scanned = 0.0f; // display entries: where the scan was when the frame came up (0 at a vblank) | 152 | float percent_scanned = 0.0f; // display entries: where the scan was when the frame came up (0 at a vblank) |
| 150 | }; | 153 | }; |
| 151 | 154 | ||
| 155 | // Fixed-capacity ring buffer size for recent frame-time and origin-to-present latency samples (BL-6). | ||
| 156 | inline constexpr std::size_t frame_pacing_window = 1024; | ||
| 157 | |||
| 158 | // Summary over the most recent `frame_pacing_window` presented frames (p50/p95/p99 and mean drift against target). | ||
| 159 | struct FramePacingSummary { | ||
| 160 | std::uint64_t frames = 0; // total presented frames recorded | ||
| 161 | std::uint64_t samples = 0; // present-to-present intervals in the ring buffer (<= frame_pacing_window) | ||
| 162 | std::uint32_t target_interval_us = 0; // active target interval in us (0 when unpaced or uncapped) | ||
| 163 | double mean_us = 0.0; // mean present-to-present interval over `samples` | ||
| 164 | double drift_us = 0.0; // mean_us - target_interval_us (0 when unpaced/uncapped or samples == 0) | ||
| 165 | std::uint64_t p50_us = 0; // nearest-rank 50th percentile frame interval in us | ||
| 166 | std::uint64_t p95_us = 0; // nearest-rank 95th percentile frame interval in us | ||
| 167 | std::uint64_t p99_us = 0; // nearest-rank 99th percentile frame interval in us | ||
| 168 | std::uint64_t latency_samples = 0; // origin-to-present latency samples in the ring buffer | ||
| 169 | std::uint64_t latency_p50_us = 0; // nearest-rank 50th percentile origin-to-present latency in us | ||
| 170 | std::uint64_t latency_p95_us = 0; // nearest-rank 95th percentile origin-to-present latency in us | ||
| 171 | std::uint64_t latency_p99_us = 0; // nearest-rank 99th percentile origin-to-present latency in us | ||
| 172 | }; | ||
| 173 | |||
| 152 | class FramePacer { | 174 | class FramePacer { |
| 153 | public: | 175 | public: |
| 154 | explicit FramePacer(FrameClock& clock) : clock_(clock) { | 176 | explicit FramePacer(FrameClock& clock) : clock_(clock) { |
| @@ -311,6 +333,7 @@ public: | |||
| 311 | std::lock_guard guard(mutex_); | 333 | std::lock_guard guard(mutex_); |
| 312 | const std::uint64_t now = clock_.now_us(); | 334 | const std::uint64_t now = clock_.now_us(); |
| 313 | retire_locked(now); | 335 | retire_locked(now); |
| 336 | record_present_timing_locked(now, token); | ||
| 314 | last_presented_ = std::max(last_presented_, token); | 337 | last_presented_ = std::max(last_presented_, token); |
| 315 | if (!interval_set_ || !any_armed_locked() || uncapped_) { // not paced or uncapped: shows at once | 338 | if (!interval_set_ || !any_armed_locked() || uncapped_) { // not paced or uncapped: shows at once |
| 316 | for (Record& r : records_) | 339 | for (Record& r : records_) |
| @@ -340,8 +363,9 @@ public: | |||
| 340 | // the origin event not armed or the cap off it is not paced: it shows at once and is not counted. | 363 | // the origin event not armed or the cap off it is not paced: it shows at once and is not counted. |
| 341 | void note_untokened_present() { | 364 | void note_untokened_present() { |
| 342 | std::lock_guard guard(mutex_); | 365 | std::lock_guard guard(mutex_); |
| 343 | if (!interval_set_ || !any_armed_locked() || uncapped_) return; | ||
| 344 | const std::uint64_t now = clock_.now_us(); | 366 | const std::uint64_t now = clock_.now_us(); |
| 367 | record_present_timing_locked(now, 0); | ||
| 368 | if (!interval_set_ || !any_armed_locked() || uncapped_) return; | ||
| 345 | retire_locked(now); | 369 | retire_locked(now); |
| 346 | const std::uint64_t since = now > epoch_us_ ? now - epoch_us_ : 0; | 370 | const std::uint64_t since = now > epoch_us_ ? now - epoch_us_ : 0; |
| 347 | std::uint64_t flip = epoch_us_ + (since / period_us_ + 1) * period_us_; | 371 | std::uint64_t flip = epoch_us_ + (since / period_us_ + 1) * period_us_; |
| @@ -355,6 +379,7 @@ public: | |||
| 355 | std::lock_guard guard(mutex_); | 379 | std::lock_guard guard(mutex_); |
| 356 | suspended_ = true; | 380 | suspended_ = true; |
| 357 | interval_set_ = false; | 381 | interval_set_ = false; |
| 382 | has_last_present_ = false; // do not count the suspended pause as a frame interval after resume | ||
| 358 | for (bool& a : event_armed_) a = false; | 383 | for (bool& a : event_armed_) a = false; |
| 359 | pending_.clear(); | 384 | pending_.clear(); |
| 360 | cv_.notify_all(); | 385 | cv_.notify_all(); |
| @@ -385,6 +410,47 @@ public: | |||
| 385 | void set_uncapped(bool on) { std::lock_guard guard(mutex_); uncapped_ = on; } | 410 | void set_uncapped(bool on) { std::lock_guard guard(mutex_); uncapped_ = on; } |
| 386 | bool uncapped() const { std::lock_guard guard(mutex_); return uncapped_; } | 411 | bool uncapped() const { std::lock_guard guard(mutex_); return uncapped_; } |
| 387 | 412 | ||
| 413 | // Frame-time percentiles, mean drift against the active target interval, and origin-to-present latency over | ||
| 414 | // the last `frame_pacing_window` presented frames (BL-6). | ||
| 415 | FramePacingSummary pacing_summary() const { | ||
| 416 | FramePacingSummary out; | ||
| 417 | std::vector<std::uint64_t> intervals; | ||
| 418 | std::vector<std::uint64_t> latencies; | ||
| 419 | { | ||
| 420 | std::lock_guard guard(mutex_); | ||
| 421 | out.frames = presents_recorded_; | ||
| 422 | out.target_interval_us = (interval_set_ && !uncapped_) ? period_us_ : 0u; | ||
| 423 | intervals.reserve(interval_count_); | ||
| 424 | for (std::size_t i = 0; i < interval_count_; ++i) intervals.push_back(interval_ring_[i]); | ||
| 425 | latencies.reserve(latency_count_); | ||
| 426 | for (std::size_t i = 0; i < latency_count_; ++i) latencies.push_back(latency_ring_[i]); | ||
| 427 | } | ||
| 428 | auto percentile = [](const std::vector<std::uint64_t>& sorted, std::size_t pct) -> std::uint64_t { | ||
| 429 | if (sorted.empty()) return 0; | ||
| 430 | const std::size_t idx = (pct * sorted.size() + 99) / 100 - 1; | ||
| 431 | return sorted[std::min(idx, sorted.size() - 1)]; | ||
| 432 | }; | ||
| 433 | if (!intervals.empty()) { | ||
| 434 | out.samples = intervals.size(); | ||
| 435 | double sum = 0.0; | ||
| 436 | for (std::uint64_t v : intervals) sum += double(v); | ||
| 437 | out.mean_us = sum / double(intervals.size()); | ||
| 438 | if (out.target_interval_us != 0) out.drift_us = out.mean_us - double(out.target_interval_us); | ||
| 439 | std::sort(intervals.begin(), intervals.end()); | ||
| 440 | out.p50_us = percentile(intervals, 50); | ||
| 441 | out.p95_us = percentile(intervals, 95); | ||
| 442 | out.p99_us = percentile(intervals, 99); | ||
| 443 | } | ||
| 444 | if (!latencies.empty()) { | ||
| 445 | out.latency_samples = latencies.size(); | ||
| 446 | std::sort(latencies.begin(), latencies.end()); | ||
| 447 | out.latency_p50_us = percentile(latencies, 50); | ||
| 448 | out.latency_p95_us = percentile(latencies, 95); | ||
| 449 | out.latency_p99_us = percentile(latencies, 99); | ||
| 450 | } | ||
| 451 | return out; | ||
| 452 | } | ||
| 453 | |||
| 388 | private: | 454 | private: |
| 389 | struct Pending { | 455 | struct Pending { |
| 390 | std::uint64_t token; | 456 | std::uint64_t token; |
| @@ -398,6 +464,29 @@ private: | |||
| 398 | bool presented = false, displayed = false; | 464 | bool presented = false, displayed = false; |
| 399 | }; | 465 | }; |
| 400 | 466 | ||
| 467 | void record_present_timing_locked(std::uint64_t now, std::uint64_t token) { | ||
| 468 | ++presents_recorded_; | ||
| 469 | if (has_last_present_ && now >= last_present_us_) { | ||
| 470 | interval_ring_[interval_head_] = now - last_present_us_; | ||
| 471 | interval_head_ = (interval_head_ + 1) % frame_pacing_window; | ||
| 472 | if (interval_count_ < frame_pacing_window) ++interval_count_; | ||
| 473 | } | ||
| 474 | has_last_present_ = true; | ||
| 475 | last_present_us_ = now; | ||
| 476 | if (token != 0) { | ||
| 477 | for (const Record& r : records_) { | ||
| 478 | if (r.token == token) { | ||
| 479 | if (now >= r.origin_us) { | ||
| 480 | latency_ring_[latency_head_] = now - r.origin_us; | ||
| 481 | latency_head_ = (latency_head_ + 1) % frame_pacing_window; | ||
| 482 | if (latency_count_ < frame_pacing_window) ++latency_count_; | ||
| 483 | } | ||
| 484 | break; | ||
| 485 | } | ||
| 486 | } | ||
| 487 | } | ||
| 488 | } | ||
| 489 | |||
| 401 | // Frames whose vblank has come are shown. | 490 | // Frames whose vblank has come are shown. |
| 402 | void retire_locked(std::uint64_t now) { | 491 | void retire_locked(std::uint64_t now) { |
| 403 | while (!pending_.empty() && pending_.front().flip_us <= now) { | 492 | while (!pending_.empty() && pending_.front().flip_us <= now) { |
| @@ -494,6 +583,15 @@ private: | |||
| 494 | std::uint64_t issued_ = 0; | 583 | std::uint64_t issued_ = 0; |
| 495 | std::uint64_t last_presented_ = 0; | 584 | std::uint64_t last_presented_ = 0; |
| 496 | std::uint64_t immediate_presents_ = 0; | 585 | std::uint64_t immediate_presents_ = 0; |
| 586 | std::uint64_t presents_recorded_ = 0; | ||
| 587 | bool has_last_present_ = false; | ||
| 588 | std::uint64_t last_present_us_ = 0; | ||
| 589 | std::array<std::uint64_t, frame_pacing_window> interval_ring_{}; | ||
| 590 | std::size_t interval_head_ = 0; | ||
| 591 | std::size_t interval_count_ = 0; | ||
| 592 | std::array<std::uint64_t, frame_pacing_window> latency_ring_{}; | ||
| 593 | std::size_t latency_head_ = 0; | ||
| 594 | std::size_t latency_count_ = 0; | ||
| 497 | std::deque<Pending> pending_; | 595 | std::deque<Pending> pending_; |
| 498 | std::deque<Record> records_; | 596 | std::deque<Record> records_; |
| 499 | }; | 597 | }; |
diff --git a/runtime/src/gfx10_descriptors.h b/runtime/src/gfx10_descriptors.h index b225cddef..a4a9b4448 100644 --- a/runtime/src/gfx10_descriptors.h +++ b/runtime/src/gfx10_descriptors.h | |||
| @@ -631,8 +631,9 @@ inline VkSamplerCreateInfo vulkan_sampler(const Sampler& sampler, float max_lod_ | |||
| 631 | if (sampler.unnormalized) { | 631 | if (sampler.unnormalized) { |
| 632 | info.unnormalizedCoordinates = VK_TRUE; | 632 | info.unnormalizedCoordinates = VK_TRUE; |
| 633 | // VUID-VkSamplerCreateInfo-unnormalizedCoordinates-01075: U and V clamp to the edge or the border (a | 633 | // VUID-VkSamplerCreateInfo-unnormalizedCoordinates-01075: U and V clamp to the edge or the border (a |
| 634 | // repeating mode would wrap at a texel count the sampler cannot know); -01072: one filter for min and mag. | 634 | // repeating mode would wrap at a texel count the sampler cannot know); -01072: one filter for min and mag; |
| 635 | // The S# allows any address mode with FORCE_UNNORMALIZED, and WRAP is its default (word 0 = 0). | 635 | // -01074: mipLodBias must be zero. The S# allows any address mode or LOD bias with FORCE_UNNORMALIZED, and |
| 636 | // WRAP is its default (word 0 = 0). | ||
| 636 | const auto clamp_or_border = [](VkSamplerAddressMode m) { | 637 | const auto clamp_or_border = [](VkSamplerAddressMode m) { |
| 637 | return m == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ? m : VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; | 638 | return m == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ? m : VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; |
| 638 | }; | 639 | }; |
| @@ -640,6 +641,7 @@ inline VkSamplerCreateInfo vulkan_sampler(const Sampler& sampler, float max_lod_ | |||
| 640 | info.addressModeV = clamp_or_border(info.addressModeV); | 641 | info.addressModeV = clamp_or_border(info.addressModeV); |
| 641 | info.minFilter = info.magFilter; | 642 | info.minFilter = info.magFilter; |
| 642 | info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST; | 643 | info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST; |
| 644 | info.mipLodBias = 0.0f; | ||
| 643 | info.minLod = info.maxLod = 0.0f; | 645 | info.minLod = info.maxLod = 0.0f; |
| 644 | info.anisotropyEnable = VK_FALSE; | 646 | info.anisotropyEnable = VK_FALSE; |
| 645 | info.maxAnisotropy = 1.0f; | 647 | info.maxAnisotropy = 1.0f; |
diff --git a/runtime/src/mods.h b/runtime/src/mods.h index 10155bf19..bd635e9a0 100644 --- a/runtime/src/mods.h +++ b/runtime/src/mods.h | |||
| @@ -78,8 +78,8 @@ struct LoadResult { | |||
| 78 | // "0x..." -> that value; anything else -> joaat(name). Returns false for an empty name or a malformed hex value. | 78 | // "0x..." -> that value; anything else -> joaat(name). Returns false for an empty name or a malformed hex value. |
| 79 | inline bool parse_model_id(const std::string& text, uint32_t& out) { | 79 | inline bool parse_model_id(const std::string& text, uint32_t& out) { |
| 80 | if (text.empty()) return false; | 80 | if (text.empty()) return false; |
| 81 | if (text.size() > 2 && text[0] == '0' && (text[1] == 'x' || text[1] == 'X')) { | 81 | if (text.size() >= 2 && text[0] == '0' && (text[1] == 'x' || text[1] == 'X')) { |
| 82 | if (text.size() > 10) return false; | 82 | if (text.size() == 2 || text.size() > 10) return false; |
| 83 | uint32_t v = 0; | 83 | uint32_t v = 0; |
| 84 | for (std::size_t i = 2; i < text.size(); ++i) { | 84 | for (std::size_t i = 2; i < text.size(); ++i) { |
| 85 | const char c = text[i]; | 85 | const char c = text[i]; |
diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index c29a288a9..cc4ae88aa 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp | |||
| @@ -1094,6 +1094,7 @@ Loader::~Loader() { | |||
| 1094 | entry(m.base, DLL_PROCESS_DETACH, nullptr); // explicit unload; the return value is ignored | 1094 | entry(m.base, DLL_PROCESS_DETACH, nullptr); // explicit unload; the return value is ignored |
| 1095 | } | 1095 | } |
| 1096 | } | 1096 | } |
| 1097 | shims::remove_xmem_allocation_hooks(this); | ||
| 1097 | shims::remove_bundled_loader(this); | 1098 | shims::remove_bundled_loader(this); |
| 1098 | shims::remove_module_lookup(this); | 1099 | shims::remove_module_lookup(this); |
| 1099 | for (auto* m : order_) { | 1100 | for (auto* m : order_) { |
| @@ -1498,6 +1499,12 @@ Module& Loader::map_image(const std::filesystem::path& path, const std::string& | |||
| 1498 | // installed here, before bind_imports can return control to the caller and before any image code can run. | 1499 | // installed here, before bind_imports can return control to the caller and before any image code can run. |
| 1499 | initialize_tls(*m); | 1500 | initialize_tls(*m); |
| 1500 | parse_exports(*m); | 1501 | parse_exports(*m); |
| 1502 | if (auto it = m->exports.find("__XMemAllocationHooks__"); it != m->exports.end()) { | ||
| 1503 | const auto offset = static_cast<uint64_t>(static_cast<uint8_t*>(it->second) - m->base); | ||
| 1504 | if (offset <= m->size && m->size - offset >= sizeof(shims::XMemAllocationHooks)) { | ||
| 1505 | shims::add_xmem_allocation_hooks(this, static_cast<const shims::XMemAllocationHooks*>(it->second)); | ||
| 1506 | } | ||
| 1507 | } | ||
| 1501 | return *m; | 1508 | return *m; |
| 1502 | } | 1509 | } |
| 1503 | 1510 | ||
diff --git a/runtime/src/retire_tickets.h b/runtime/src/retire_tickets.h index a48302859..675460cac 100644 --- a/runtime/src/retire_tickets.h +++ b/runtime/src/retire_tickets.h | |||
| @@ -24,7 +24,7 @@ public: | |||
| 24 | while (!pending_.empty()) { | 24 | while (!pending_.empty()) { |
| 25 | const Entry& front = pending_.front(); | 25 | const Entry& front = pending_.front(); |
| 26 | if (!front.idle && !query(front.semaphore, front.value)) break; | 26 | if (!front.idle && !query(front.semaphore, front.value)) break; |
| 27 | completed_ = front.ticket; | 27 | if (front.ticket > completed_) completed_ = front.ticket; |
| 28 | pending_.pop_front(); | 28 | pending_.pop_front(); |
| 29 | } | 29 | } |
| 30 | return completed_; | 30 | return completed_; |
| @@ -34,8 +34,18 @@ public: | |||
| 34 | // that must have them done (and may not hold the lock that guards this object while it waits) waits for. | 34 | // that must have them done (and may not hold the lock that guards this object while it waits) waits for. |
| 35 | std::vector<std::pair<Semaphore, std::uint64_t>> pending_through(std::uint64_t ticket) const { | 35 | std::vector<std::pair<Semaphore, std::uint64_t>> pending_through(std::uint64_t ticket) const { |
| 36 | std::vector<std::pair<Semaphore, std::uint64_t>> out; | 36 | std::vector<std::pair<Semaphore, std::uint64_t>> out; |
| 37 | for (const Entry& entry : pending_) | 37 | for (const Entry& entry : pending_) { |
| 38 | if (entry.ticket <= ticket && !entry.idle) out.emplace_back(entry.semaphore, entry.value); | 38 | if (entry.ticket > ticket || entry.idle) continue; |
| 39 | bool merged = false; | ||
| 40 | for (auto& [sem, val] : out) { | ||
| 41 | if (sem == entry.semaphore) { | ||
| 42 | if (entry.value > val) val = entry.value; | ||
| 43 | merged = true; | ||
| 44 | break; | ||
| 45 | } | ||
| 46 | } | ||
| 47 | if (!merged) out.emplace_back(entry.semaphore, entry.value); | ||
| 48 | } | ||
| 39 | return out; | 49 | return out; |
| 40 | } | 50 | } |
| 41 | 51 | ||
diff --git a/runtime/src/shader_library.h b/runtime/src/shader_library.h index 9f752317e..596ad0ae9 100644 --- a/runtime/src/shader_library.h +++ b/runtime/src/shader_library.h | |||
| @@ -246,7 +246,7 @@ inline ZlibError inflate_codes(BitReader& in, std::vector<std::uint8_t>& out, co | |||
| 246 | if (d < 0 || d >= 30) return ZlibError::data; | 246 | if (d < 0 || d >= 30) return ZlibError::data; |
| 247 | const std::size_t distance = std::size_t(distance_base[d]) + in.bits(distance_extra[d]); | 247 | const std::size_t distance = std::size_t(distance_base[d]) + in.bits(distance_extra[d]); |
| 248 | if (in.failed() || distance > out.size()) return ZlibError::data; | 248 | if (in.failed() || distance > out.size()) return ZlibError::data; |
| 249 | if (out.size() + length > limit) return ZlibError::limit; | 249 | if (out.size() > limit || length > limit - out.size()) return ZlibError::limit; |
| 250 | const std::size_t from = out.size() - distance; | 250 | const std::size_t from = out.size() - distance; |
| 251 | for (std::size_t i = 0; i < length; ++i) out.push_back(out[from + i]); | 251 | for (std::size_t i = 0; i < length; ++i) out.push_back(out[from + i]); |
| 252 | } | 252 | } |
| @@ -284,7 +284,7 @@ inline bool zlib_inflate(std::span<const std::uint8_t> in, std::vector<std::uint | |||
| 284 | if (!reader.byte(x)) return fail(ZlibError::data); | 284 | if (!reader.byte(x)) return fail(ZlibError::data); |
| 285 | const unsigned length = b[0] | (b[1] << 8), complement = b[2] | (b[3] << 8); | 285 | const unsigned length = b[0] | (b[1] << 8), complement = b[2] | (b[3] << 8); |
| 286 | if (length != (~complement & 0xffff)) return fail(ZlibError::data); | 286 | if (length != (~complement & 0xffff)) return fail(ZlibError::data); |
| 287 | if (out.size() + length > limit) return fail(ZlibError::limit); | 287 | if (out.size() > limit || length > limit - out.size()) return fail(ZlibError::limit); |
| 288 | for (unsigned i = 0; i < length; ++i) { | 288 | for (unsigned i = 0; i < length; ++i) { |
| 289 | std::uint8_t x; | 289 | std::uint8_t x; |
| 290 | if (!reader.byte(x)) return fail(ZlibError::data); | 290 | if (!reader.byte(x)) return fail(ZlibError::data); |
| @@ -349,7 +349,7 @@ inline bool zlib_inflate(std::span<const std::uint8_t> in, std::vector<std::uint | |||
| 349 | } | 349 | } |
| 350 | // Adler-32, big-endian, after the deflate data's last whole byte. | 350 | // Adler-32, big-endian, after the deflate data's last whole byte. |
| 351 | const std::size_t at = 2 + reader.position(); | 351 | const std::size_t at = 2 + reader.position(); |
| 352 | if (at + 4 > in.size()) return fail(ZlibError::data); | 352 | if (at > in.size() || in.size() - at < 4) return fail(ZlibError::data); |
| 353 | std::uint32_t a = 1, b = 0; | 353 | std::uint32_t a = 1, b = 0; |
| 354 | for (const std::uint8_t x : out) { | 354 | for (const std::uint8_t x : out) { |
| 355 | a = (a + x) % 65521; | 355 | a = (a + x) % 65521; |
| @@ -1045,9 +1045,20 @@ private: | |||
| 1045 | if (const Json* fh = meta.find("f16_halves"); fh && fh->kind == Json::Kind::object) { | 1045 | if (const Json* fh = meta.find("f16_halves"); fh && fh->kind == Json::Kind::object) { |
| 1046 | for (const auto& [key, val] : fh->object) { | 1046 | for (const auto& [key, val] : fh->object) { |
| 1047 | if (key.empty() || val.kind != Json::Kind::array || val.array.size() != 2) continue; | 1047 | if (key.empty() || val.kind != Json::Kind::array || val.array.size() != 2) continue; |
| 1048 | char* end = nullptr; | 1048 | std::uint64_t param = 0; |
| 1049 | const unsigned long param = std::strtoul(key.c_str(), &end, 10); | 1049 | bool ok = true; |
| 1050 | if (!end || *end != '\0') continue; | 1050 | for (const char c : key) { |
| 1051 | if (c < '0' || c > '9') { | ||
| 1052 | ok = false; | ||
| 1053 | break; | ||
| 1054 | } | ||
| 1055 | param = param * 10u + std::uint64_t(c - '0'); | ||
| 1056 | if (param > UINT32_MAX) { | ||
| 1057 | ok = false; | ||
| 1058 | break; | ||
| 1059 | } | ||
| 1060 | } | ||
| 1061 | if (!ok) continue; | ||
| 1051 | e.f16_halves[std::uint32_t(param)] = {u32(&val.array[0]), u32(&val.array[1])}; | 1062 | e.f16_halves[std::uint32_t(param)] = {u32(&val.array[0]), u32(&val.array[1])}; |
| 1052 | } | 1063 | } |
| 1053 | } | 1064 | } |
diff --git a/runtime/src/uav_clear.h b/runtime/src/uav_clear.h index b73ec50e1..385d55950 100644 --- a/runtime/src/uav_clear.h +++ b/runtime/src/uav_clear.h | |||
| @@ -91,6 +91,10 @@ inline constexpr Layout layouts[] = { | |||
| 91 | {VK_FORMAT_R16_UNORM, Kind::unorm, 2, {{{0, 16}, {}, {}, {}}}}, | 91 | {VK_FORMAT_R16_UNORM, Kind::unorm, 2, {{{0, 16}, {}, {}, {}}}}, |
| 92 | // A4B4G4R4_UNORM: typed UAVs are the driver's call (WARP has them, AMD's D3D12 driver doesn't). | 92 | // A4B4G4R4_UNORM: typed UAVs are the driver's call (WARP has them, AMD's D3D12 driver doesn't). |
| 93 | {VK_FORMAT_R4G4B4A4_UNORM_PACK16, Kind::unorm, 2, {{{12, 4}, {8, 4}, {4, 4}, {0, 4}}}}, | 93 | {VK_FORMAT_R4G4B4A4_UNORM_PACK16, Kind::unorm, 2, {{{12, 4}, {8, 4}, {4, 4}, {0, 4}}}}, |
| 94 | // B5G6R5, B5G5R5A1 and B4G4R4A4_UNORM, likewise (WARP has all three). | ||
| 95 | {VK_FORMAT_R5G6B5_UNORM_PACK16, Kind::unorm, 2, {{{11, 5}, {5, 6}, {0, 5}, {}}}}, | ||
| 96 | {VK_FORMAT_A1R5G5B5_UNORM_PACK16, Kind::unorm, 2, {{{10, 5}, {5, 5}, {0, 5}, {15, 1}}}}, | ||
| 97 | {VK_FORMAT_A4R4G4B4_UNORM_PACK16, Kind::unorm, 2, {{{8, 4}, {4, 4}, {0, 4}, {12, 4}}}}, | ||
| 94 | {VK_FORMAT_R16_SNORM, Kind::snorm, 2, {{{0, 16}, {}, {}, {}}}}, | 98 | {VK_FORMAT_R16_SNORM, Kind::snorm, 2, {{{0, 16}, {}, {}, {}}}}, |
| 95 | {VK_FORMAT_R16_UINT, Kind::uint, 2, {{{0, 16}, {}, {}, {}}}}, | 99 | {VK_FORMAT_R16_UINT, Kind::uint, 2, {{{0, 16}, {}, {}, {}}}}, |
| 96 | {VK_FORMAT_R16_SINT, Kind::sint, 2, {{{0, 16}, {}, {}, {}}}}, | 100 | {VK_FORMAT_R16_SINT, Kind::sint, 2, {{{0, 16}, {}, {}, {}}}}, |
diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index e323ab22c..ab6786a51 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h | |||
| @@ -101,6 +101,7 @@ struct VulkanDeviceFunctions { | |||
| 101 | X(vkCreateComputePipelines) X(vkDestroyPipeline) X(vkCmdBindPipeline) X(vkCmdBindDescriptorSets) \ | 101 | X(vkCreateComputePipelines) X(vkDestroyPipeline) X(vkCmdBindPipeline) X(vkCmdBindDescriptorSets) \ |
| 102 | X(vkCmdPushConstants) X(vkCmdDispatch) \ | 102 | X(vkCmdPushConstants) X(vkCmdDispatch) \ |
| 103 | X(vkCmdBindVertexBuffers2) X(vkCmdBindIndexBuffer) X(vkCmdSetViewport) X(vkCmdSetScissor) \ | 103 | X(vkCmdBindVertexBuffers2) X(vkCmdBindIndexBuffer) X(vkCmdSetViewport) X(vkCmdSetScissor) \ |
| 104 | X(vkCmdSetViewportWithCount) X(vkCmdSetScissorWithCount) \ | ||
| 104 | X(vkCmdSetPrimitiveTopology) X(vkCmdSetPrimitiveRestartEnable) X(vkCmdSetStencilReference) \ | 105 | X(vkCmdSetPrimitiveTopology) X(vkCmdSetPrimitiveRestartEnable) X(vkCmdSetStencilReference) \ |
| 105 | X(vkCmdSetBlendConstants) X(vkCmdDraw) \ | 106 | X(vkCmdSetBlendConstants) X(vkCmdDraw) \ |
| 106 | X(vkCmdDrawIndexed) X(vkCreateGraphicsPipelines) X(vkQueueBindSparse) X(vkGetImageSparseMemoryRequirements) \ | 107 | X(vkCmdDrawIndexed) X(vkCreateGraphicsPipelines) X(vkQueueBindSparse) X(vkGetImageSparseMemoryRequirements) \ |
| @@ -987,6 +988,8 @@ public: | |||
| 987 | replay_.bind_index_buffer = vk.vkCmdBindIndexBuffer; | 988 | replay_.bind_index_buffer = vk.vkCmdBindIndexBuffer; |
| 988 | replay_.set_viewport = vk.vkCmdSetViewport; | 989 | replay_.set_viewport = vk.vkCmdSetViewport; |
| 989 | replay_.set_scissor = vk.vkCmdSetScissor; | 990 | replay_.set_scissor = vk.vkCmdSetScissor; |
| 991 | replay_.set_viewport_with_count = vk.vkCmdSetViewportWithCount; | ||
| 992 | replay_.set_scissor_with_count = vk.vkCmdSetScissorWithCount; | ||
| 990 | replay_.set_primitive_topology = vk.vkCmdSetPrimitiveTopology; | 993 | replay_.set_primitive_topology = vk.vkCmdSetPrimitiveTopology; |
| 991 | replay_.set_primitive_restart_enable = vk.vkCmdSetPrimitiveRestartEnable; | 994 | replay_.set_primitive_restart_enable = vk.vkCmdSetPrimitiveRestartEnable; |
| 992 | replay_.set_stencil_reference = vk.vkCmdSetStencilReference; | 995 | replay_.set_stencil_reference = vk.vkCmdSetStencilReference; |
| @@ -1017,7 +1020,7 @@ public: | |||
| 1017 | // binding's host pointer is null on DEFAULT and READBACK heaps, whose mapped bytes the GPU can write. | 1020 | // binding's host pointer is null on DEFAULT and READBACK heaps, whose mapped bytes the GPU can write. |
| 1018 | replay_.host_at = [this](std::uint64_t va, std::uint64_t bytes, const std::uint8_t*& host) { | 1021 | replay_.host_at = [this](std::uint64_t va, std::uint64_t bytes, const std::uint8_t*& host) { |
| 1019 | BufferVaIndex<ResourceId>::Hit hit{}; | 1022 | BufferVaIndex<ResourceId>::Hit hit{}; |
| 1020 | if (!buffer_vas_.find(va, hit)) return HostReadStatus::absent; | 1023 | if (!buffer_vas_.find(va, hit, bytes)) return HostReadStatus::absent; |
| 1021 | const ResourceBinding* b = resolve(hit.id); | 1024 | const ResourceBinding* b = resolve(hit.id); |
| 1022 | if (!b) return HostReadStatus::absent; | 1025 | if (!b) return HostReadStatus::absent; |
| 1023 | if (!b->host) return HostReadStatus::not_cpu_written; | 1026 | if (!b->host) return HostReadStatus::not_cpu_written; |
| @@ -1285,6 +1288,11 @@ public: | |||
| 1285 | replay_.zero_size = size; | 1288 | replay_.zero_size = size; |
| 1286 | } | 1289 | } |
| 1287 | 1290 | ||
| 1291 | void set_depth_range_unrestricted(bool enabled) { | ||
| 1292 | std::unique_lock lock(resource_mutex_); | ||
| 1293 | replay_.depth_range_unrestricted = enabled; | ||
| 1294 | } | ||
| 1295 | |||
| 1288 | // Physical-device COLOR_ATTACHMENT format check for reinterpreted UAV clears. | 1296 | // Physical-device COLOR_ATTACHMENT format check for reinterpreted UAV clears. |
| 1289 | void set_color_attachment_format(std::function<bool(VkFormat)> check) { | 1297 | void set_color_attachment_format(std::function<bool(VkFormat)> check) { |
| 1290 | std::unique_lock lock(resource_mutex_); | 1298 | std::unique_lock lock(resource_mutex_); |
| @@ -1500,12 +1508,23 @@ public: | |||
| 1500 | void note_bindless_upload() { bindless_upload_pending_ = true; } | 1508 | void note_bindless_upload() { bindless_upload_pending_ = true; } |
| 1501 | 1509 | ||
| 1502 | std::uint64_t completed_retire_ticket() { | 1510 | std::uint64_t completed_retire_ticket() { |
| 1503 | std::lock_guard lock(submit_mutex_); | 1511 | bool lost = false; |
| 1504 | if (is_device_lost()) return 0; | 1512 | std::uint64_t ticket = 0; |
| 1505 | return retire_tickets_.completed([this](VkSemaphore semaphore, std::uint64_t value) { | 1513 | { |
| 1506 | std::uint64_t done = 0; | 1514 | std::lock_guard lock(submit_mutex_); |
| 1507 | return vk.vkGetSemaphoreCounterValue(device_, semaphore, &done) == VK_SUCCESS && done >= value; | 1515 | if (is_device_lost()) return 0; |
| 1508 | }); | 1516 | ticket = retire_tickets_.completed([this, &lost](VkSemaphore semaphore, std::uint64_t value) { |
| 1517 | std::uint64_t done = 0; | ||
| 1518 | const VkResult result = vk.vkGetSemaphoreCounterValue(device_, semaphore, &done); | ||
| 1519 | if (result == VK_ERROR_DEVICE_LOST) lost = true; | ||
| 1520 | return result == VK_SUCCESS && done >= value; | ||
| 1521 | }); | ||
| 1522 | } | ||
| 1523 | // Outside submit_mutex_, as in submit(): notifying the fence dispatcher can run callbacks that submit. | ||
| 1524 | // A DEVICE_LOST seen here is the first Vulkan operation to discover it; it must not be mistaken for | ||
| 1525 | // "this ticket has not completed". | ||
| 1526 | if (lost) mark_device_lost(); | ||
| 1527 | return lost ? 0 : ticket; | ||
| 1509 | } | 1528 | } |
| 1510 | 1529 | ||
| 1511 | void drain_deleted_resources(std::uint64_t current_ticket) { | 1530 | void drain_deleted_resources(std::uint64_t current_ticket) { |
| @@ -2542,6 +2561,18 @@ private: | |||
| 2542 | discard(); | 2561 | discard(); |
| 2543 | return ReplayResult::unsupported; | 2562 | return ReplayResult::unsupported; |
| 2544 | } | 2563 | } |
| 2564 | // D3D12 ends every ExecuteCommandLists with all its work done and its writes visible to the next one on the | ||
| 2565 | // queue (implicit state decay relies on it), and a list may then touch the same memory without a barrier: | ||
| 2566 | // two submissions copying into one buffer, say. Vulkan orders submissions on a queue only by what their | ||
| 2567 | // barriers say, so this one starts with a full memory barrier against everything submitted before it | ||
| 2568 | // (synchronization validation: WRITE_AFTER_WRITE between vk_queue_test's back-to-back copies). | ||
| 2569 | if (context_.vk.vkCmdPipelineBarrier) { // a mocked context may leave it out | ||
| 2570 | VkMemoryBarrier full{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; | ||
| 2571 | full.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT; | ||
| 2572 | full.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT; | ||
| 2573 | context_.vk.vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, | ||
| 2574 | VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 1, &full, 0, nullptr, 0, nullptr); | ||
| 2575 | } | ||
| 2545 | if (!tracker_lock.owns_lock()) tracker_lock.lock(); | 2576 | if (!tracker_lock.owns_lock()) tracker_lock.lock(); |
| 2546 | if (!transfer_only && context_.bindless_prepare_ && !context_.bindless_prepare_(command_buffer)) { | 2577 | if (!transfer_only && context_.bindless_prepare_ && !context_.bindless_prepare_(command_buffer)) { |
| 2547 | const bool ended = context_.vk.vkEndCommandBuffer(command_buffer) == VK_SUCCESS; | 2578 | const bool ended = context_.vk.vkEndCommandBuffer(command_buffer) == VK_SUCCESS; |
diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index bda530a7a..7dcc7e2c0 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h | |||
| @@ -216,7 +216,10 @@ inline VkPipelineStageFlags2 vulkan_sync(std::uint32_t sync) { | |||
| 216 | VK_PIPELINE_STAGE_2_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_2_LATE_FRAGMENT_TESTS_BIT}, | 216 | VK_PIPELINE_STAGE_2_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_2_LATE_FRAGMENT_TESTS_BIT}, |
| 217 | {y::render_target, VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT}, | 217 | {y::render_target, VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT}, |
| 218 | {y::compute_shading, VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT}, | 218 | {y::compute_shading, VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT}, |
| 219 | {y::copy, VK_PIPELINE_STAGE_2_COPY_BIT}, | 219 | // CLEAR as well: two D3D12 copy-scope commands are recorded as Vulkan clear commands, WriteBufferImmediate |
| 220 | // as vkCmdUpdateBuffer and ResolveQueryData's never-written queries as vkCmdFillBuffer, and synchronization2 | ||
| 221 | // puts both in the CLEAR stage, not COPY. | ||
| 222 | {y::copy, VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_CLEAR_BIT}, | ||
| 220 | {y::resolve, VK_PIPELINE_STAGE_2_RESOLVE_BIT}, | 223 | {y::resolve, VK_PIPELINE_STAGE_2_RESOLVE_BIT}, |
| 221 | {y::execute_indirect, VK_PIPELINE_STAGE_2_DRAW_INDIRECT_BIT}, | 224 | {y::execute_indirect, VK_PIPELINE_STAGE_2_DRAW_INDIRECT_BIT}, |
| 222 | {y::all_shading, pre_raster | VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT}, | 225 | {y::all_shading, pre_raster | VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT}, |
| @@ -773,6 +776,7 @@ struct GraphicsPipeline { | |||
| 773 | std::uint32_t zero_step_slots = 0; // per-instance slots with InstanceDataStepRate 0: stride 0 at draw time | 776 | std::uint32_t zero_step_slots = 0; // per-instance slots with InstanceDataStepRate 0: stride 0 at draw time |
| 774 | std::uint32_t strip_cut = 0; // D3D12_INDEX_BUFFER_STRIP_CUT_VALUE (0: off, 1: 0xFFFF, 2: 0xFFFFFFFF) | 777 | std::uint32_t strip_cut = 0; // D3D12_INDEX_BUFFER_STRIP_CUT_VALUE (0: off, 1: 0xFFFF, 2: 0xFFFFFFFF) |
| 775 | bool mesh = false; // a mesh shader instead of a vertex shader: drawn by DispatchMesh only | 778 | bool mesh = false; // a mesh shader instead of a vertex shader: drawn by DispatchMesh only |
| 779 | bool viewport_with_count = false; // pipeline uses VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT / SCISSOR_WITH_COUNT | ||
| 776 | // The same pipeline with some attachment formats VK_FORMAT_UNDEFINED, for a draw that leaves those slots | 780 | // The same pipeline with some attachment formats VK_FORMAT_UNDEFINED, for a draw that leaves those slots |
| 777 | // unbound (D3D12 allows it; dynamic rendering needs the formats to agree). Bit i: colour slot i, bit 8: depth | 781 | // unbound (D3D12 allows it; dynamic rendering needs the formats to agree). Bit i: colour slot i, bit 8: depth |
| 778 | // and stencil. Null when it cannot be built. | 782 | // and stencil. Null when it cannot be built. |
| @@ -814,6 +818,7 @@ struct ReplayFunctions { | |||
| 814 | PFN_vkCmdPipelineBarrier pipeline_barrier = nullptr; | 818 | PFN_vkCmdPipelineBarrier pipeline_barrier = nullptr; |
| 815 | PFN_vkCmdClearColorImage clear_color_image = nullptr; | 819 | PFN_vkCmdClearColorImage clear_color_image = nullptr; |
| 816 | PFN_vkCmdClearDepthStencilImage clear_depth_stencil_image = nullptr; | 820 | PFN_vkCmdClearDepthStencilImage clear_depth_stencil_image = nullptr; |
| 821 | bool depth_range_unrestricted = false; // Allows out-of-range float depth clear values. | ||
| 817 | // Optional; a list that needs a missing one is rejected with ReplayResult::unsupported. | 822 | // Optional; a list that needs a missing one is rejected with ReplayResult::unsupported. |
| 818 | PFN_vkCmdPipelineBarrier2 pipeline_barrier2 = nullptr; // enhanced barriers | 823 | PFN_vkCmdPipelineBarrier2 pipeline_barrier2 = nullptr; // enhanced barriers |
| 819 | VkPipelineStageFlags2 queue_stages = 0; | 824 | VkPipelineStageFlags2 queue_stages = 0; |
| @@ -854,6 +859,8 @@ struct ReplayFunctions { | |||
| 854 | PFN_vkCmdBindIndexBuffer bind_index_buffer = nullptr; | 859 | PFN_vkCmdBindIndexBuffer bind_index_buffer = nullptr; |
| 855 | PFN_vkCmdSetViewport set_viewport = nullptr; | 860 | PFN_vkCmdSetViewport set_viewport = nullptr; |
| 856 | PFN_vkCmdSetScissor set_scissor = nullptr; | 861 | PFN_vkCmdSetScissor set_scissor = nullptr; |
| 862 | PFN_vkCmdSetViewportWithCount set_viewport_with_count = nullptr; | ||
| 863 | PFN_vkCmdSetScissorWithCount set_scissor_with_count = nullptr; | ||
| 857 | PFN_vkCmdSetPrimitiveTopology set_primitive_topology = nullptr; | 864 | PFN_vkCmdSetPrimitiveTopology set_primitive_topology = nullptr; |
| 858 | PFN_vkCmdSetPrimitiveRestartEnable set_primitive_restart_enable = nullptr; | 865 | PFN_vkCmdSetPrimitiveRestartEnable set_primitive_restart_enable = nullptr; |
| 859 | PFN_vkCmdSetStencilReference set_stencil_reference = nullptr; | 866 | PFN_vkCmdSetStencilReference set_stencil_reference = nullptr; |
| @@ -1607,6 +1614,7 @@ inline ReplayResult prepare_buffer_uav_clear(const ClearUnorderedAccess& clear, | |||
| 1607 | if (offset > UINT64_MAX - p.binding.buffer_offset || | 1614 | if (offset > UINT64_MAX - p.binding.buffer_offset || |
| 1608 | bytes > UINT64_MAX - (p.binding.buffer_offset + offset)) return ReplayResult::invalid_clear; | 1615 | bytes > UINT64_MAX - (p.binding.buffer_offset + offset)) return ReplayResult::invalid_clear; |
| 1609 | offset += p.binding.buffer_offset; // the view is relative to the resource, which starts at buffer_offset | 1616 | offset += p.binding.buffer_offset; // the view is relative to the resource, which starts at buffer_offset |
| 1617 | if (offset % std::min(e, 4u)) return ReplayResult::unsupported; | ||
| 1610 | if (e > 4 && bytes % 4) { | 1618 | if (e > 4 && bytes % 4) { |
| 1611 | return ReplayResult::unsupported; | 1619 | return ReplayResult::unsupported; |
| 1612 | } | 1620 | } |
| @@ -1878,27 +1886,48 @@ inline ReplayResult prepare_texture_copy(const CopyTexture& copy, Prepared& p) { | |||
| 1878 | return ReplayResult::success; | 1886 | return ReplayResult::success; |
| 1879 | } | 1887 | } |
| 1880 | 1888 | ||
| 1881 | // RGBA8 CopyTiles accepts arbitrary byte offsets into its linear buffer, while VkBufferImageCopy requires texel | 1889 | // CopyTiles accepts arbitrary byte offsets into its linear buffer, while VkBufferImageCopy requires texel/block |
| 1882 | // alignment. Stage only the occupied texels through aligned transfer scratch; leave partial-tile padding alone. | 1890 | // alignment (VUID-vkCmdCopyBufferToImage-dstImage-07975). Stage only the occupied texels/blocks through aligned |
| 1883 | inline bool stage_unaligned_tile(const ReplayFunctions& vk, Prepared& p, bool upload) { | 1891 | // transfer scratch; leave partial-tile padding alone. |
| 1892 | inline bool stage_unaligned_tile(const ReplayFunctions& vk, Prepared& p, const ResourceBinding& image, | ||
| 1893 | const BlockFormat& fmt, bool upload) { | ||
| 1884 | auto& region = p.buffer_image_copies.front(); | 1894 | auto& region = p.buffer_image_copies.front(); |
| 1885 | const VkDeviceSize row_bytes = VkDeviceSize(region.imageExtent.width) * 4; | 1895 | if (!fmt.bytes || !fmt.block || image.rgb96 || |
| 1886 | const VkDeviceSize pitch = VkDeviceSize(region.bufferRowLength) * 4; | 1896 | (image.depth24_as_float && region.imageSubresource.aspectMask == VK_IMAGE_ASPECT_DEPTH_BIT)) |
| 1887 | const auto rows = region.imageExtent.height; | 1897 | return false; |
| 1898 | const VkDeviceSize blocks_w = (VkDeviceSize(region.imageExtent.width) + fmt.block - 1) / fmt.block; | ||
| 1899 | const VkDeviceSize rows = (VkDeviceSize(region.imageExtent.height) + fmt.block - 1) / fmt.block; | ||
| 1900 | const VkDeviceSize depth = region.imageExtent.depth; | ||
| 1901 | const VkDeviceSize row_bytes = blocks_w * fmt.bytes; | ||
| 1902 | const VkDeviceSize pitch = | ||
| 1903 | region.bufferRowLength ? VkDeviceSize(region.bufferRowLength / fmt.block) * fmt.bytes : row_bytes; | ||
| 1904 | const VkDeviceSize slice_rows = | ||
| 1905 | region.bufferImageHeight ? VkDeviceSize(region.bufferImageHeight / fmt.block) : rows; | ||
| 1906 | const VkDeviceSize slice_pitch = slice_rows * pitch; | ||
| 1907 | const VkDeviceSize slice_bytes = row_bytes * rows; | ||
| 1908 | const VkDeviceSize total_bytes = slice_bytes * depth; | ||
| 1888 | VkDeviceSize scratch_offset = 0; | 1909 | VkDeviceSize scratch_offset = 0; |
| 1889 | if (!vk.copy_scratch || !vk.copy_scratch(row_bytes * rows, p.tile_scratch, scratch_offset)) return false; | 1910 | if (!total_bytes || !vk.copy_scratch || !vk.copy_scratch(total_bytes, p.tile_scratch, scratch_offset)) return false; |
| 1890 | const auto app_offset = region.bufferOffset; | 1911 | const auto app_offset = region.bufferOffset; |
| 1891 | const auto add_copy = [&](VkDeviceSize linear, VkDeviceSize scratch, VkDeviceSize bytes) { | 1912 | const auto add_copy = [&](VkDeviceSize linear, VkDeviceSize scratch, VkDeviceSize bytes) { |
| 1892 | p.tile_rows.push_back(upload ? VkBufferCopy{linear, scratch, bytes} : VkBufferCopy{scratch, linear, bytes}); | 1913 | p.tile_rows.push_back(upload ? VkBufferCopy{linear, scratch, bytes} : VkBufferCopy{scratch, linear, bytes}); |
| 1893 | }; | 1914 | }; |
| 1894 | if (row_bytes == pitch) { | 1915 | if (row_bytes == pitch && (depth == 1 || slice_rows == rows)) { |
| 1895 | add_copy(app_offset, scratch_offset, row_bytes * rows); | 1916 | add_copy(app_offset, scratch_offset, total_bytes); |
| 1917 | } else if (row_bytes == pitch) { | ||
| 1918 | for (VkDeviceSize z = 0; z < depth; ++z) | ||
| 1919 | add_copy(app_offset + z * slice_pitch, scratch_offset + z * slice_bytes, slice_bytes); | ||
| 1896 | } else { | 1920 | } else { |
| 1897 | for (std::uint32_t row = 0; row < rows; ++row) | 1921 | for (VkDeviceSize z = 0; z < depth; ++z) { |
| 1898 | add_copy(app_offset + row * pitch, scratch_offset + row * row_bytes, row_bytes); | 1922 | const VkDeviceSize linear_slice = app_offset + z * slice_pitch; |
| 1923 | const VkDeviceSize scratch_slice = scratch_offset + z * slice_bytes; | ||
| 1924 | for (VkDeviceSize row = 0; row < rows; ++row) | ||
| 1925 | add_copy(linear_slice + row * pitch, scratch_slice + row * row_bytes, row_bytes); | ||
| 1926 | } | ||
| 1899 | } | 1927 | } |
| 1900 | region.bufferOffset = scratch_offset; | 1928 | region.bufferOffset = scratch_offset; |
| 1901 | region.bufferRowLength = 0; | 1929 | region.bufferRowLength = 0; |
| 1930 | region.bufferImageHeight = 0; | ||
| 1902 | return true; | 1931 | return true; |
| 1903 | } | 1932 | } |
| 1904 | 1933 | ||
| @@ -2112,6 +2141,8 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct | |||
| 2112 | if (!pipeline || !pipeline->pipeline) return ReplayResult::unresolved_resource; | 2141 | if (!pipeline || !pipeline->pipeline) return ReplayResult::unresolved_resource; |
| 2113 | if (pipeline->mesh != draw.mesh) return ReplayResult::invalid_draw; | 2142 | if (pipeline->mesh != draw.mesh) return ReplayResult::invalid_draw; |
| 2114 | if (draw.mesh && !vk.draw_mesh_tasks) return ReplayResult::unsupported; | 2143 | if (draw.mesh && !vk.draw_mesh_tasks) return ReplayResult::unsupported; |
| 2144 | if (pipeline->viewport_with_count && (!vk.set_viewport_with_count || !vk.set_scissor_with_count)) | ||
| 2145 | return ReplayResult::unsupported; | ||
| 2115 | if (pipeline->bindless_set && !vk.bind_descriptor_sets) return ReplayResult::unsupported; | 2146 | if (pipeline->bindless_set && !vk.bind_descriptor_sets) return ReplayResult::unsupported; |
| 2116 | if (pipeline->color_formats.size() > max_render_targets) return ReplayResult::unsupported; | 2147 | if (pipeline->color_formats.size() > max_render_targets) return ReplayResult::unsupported; |
| 2117 | p.graphics = pipeline; | 2148 | p.graphics = pipeline; |
| @@ -2160,9 +2191,17 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct | |||
| 2160 | if (!a.view) return ReplayResult::unsupported; | 2191 | if (!a.view) return ReplayResult::unsupported; |
| 2161 | shrink(a.binding, draw.depth, a.range); | 2192 | shrink(a.binding, draw.depth, a.range); |
| 2162 | } | 2193 | } |
| 2163 | if (p.area.width == UINT32_MAX) { // no attachment: the viewport bounds the rendering | 2194 | if (p.area.width == UINT32_MAX) { // no attachment: the viewports bound the rendering |
| 2164 | p.area = {std::uint32_t(std::max(0.0f, draw.viewport.x + draw.viewport.width)), | 2195 | std::uint32_t max_w = std::uint32_t(std::max(0.0f, draw.viewport.x + draw.viewport.width)); |
| 2165 | std::uint32_t(std::max(0.0f, draw.viewport.y + draw.viewport.height))}; | 2196 | std::uint32_t max_h = std::uint32_t(std::max(0.0f, draw.viewport.y + draw.viewport.height)); |
| 2197 | if (draw.viewports) { | ||
| 2198 | for (std::uint32_t i = 0; i < draw.viewports->viewport_count; ++i) { | ||
| 2199 | const Viewport& v = draw.viewports->viewports[i]; | ||
| 2200 | max_w = std::max(max_w, std::uint32_t(std::max(0.0f, v.x + v.width))); | ||
| 2201 | max_h = std::max(max_h, std::uint32_t(std::max(0.0f, v.y + v.height))); | ||
| 2202 | } | ||
| 2203 | } | ||
| 2204 | p.area = {max_w, max_h}; | ||
| 2166 | } | 2205 | } |
| 2167 | p.layers = layers == UINT32_MAX ? 1 : std::max(1u, layers); | 2206 | p.layers = layers == UINT32_MAX ? 1 : std::max(1u, layers); |
| 2168 | 2207 | ||
| @@ -2812,9 +2851,15 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 2812 | // A depth plane footprint of a D24 texture stored as D32: words of 24-bit UNORM, floats in the image. | 2851 | // A depth plane footprint of a D24 texture stored as D32: words of 24-bit UNORM, floats in the image. |
| 2813 | const bool upload = texture_copy->src.footprint; | 2852 | const bool upload = texture_copy->src.footprint; |
| 2814 | const ResourceBinding& image = upload ? p.binding : p.source; | 2853 | const ResourceBinding& image = upload ? p.binding : p.source; |
| 2815 | if (result == ReplayResult::success && texture_copy->tile_footprint && !p.buffer_image_copies.empty() && | 2854 | if (result == ReplayResult::success && texture_copy->tile_footprint && !p.buffer_image_copies.empty()) { |
| 2816 | p.buffer_image_copies.front().bufferOffset % 4 && !detail::stage_unaligned_tile(vk, p, upload)) | 2855 | const auto& region = p.buffer_image_copies.front(); |
| 2817 | return ReplayResult::unsupported; | 2856 | const BlockFormat fmt = copy_block_format(image, region.imageSubresource.aspectMask); |
| 2857 | const std::uint32_t alignment = | ||
| 2858 | (region.imageSubresource.aspectMask & depth_stencil_aspects) || image.rgb96 ? 4 : fmt.bytes; | ||
| 2859 | if (alignment > 1 && region.bufferOffset % alignment && | ||
| 2860 | !detail::stage_unaligned_tile(vk, p, image, fmt, upload)) | ||
| 2861 | return ReplayResult::unsupported; | ||
| 2862 | } | ||
| 2818 | const bool depth24_footprint = result == ReplayResult::success && image.depth24_as_float && | 2863 | const bool depth24_footprint = result == ReplayResult::success && image.depth24_as_float && |
| 2819 | !p.buffer_image_copies.empty() && | 2864 | !p.buffer_image_copies.empty() && |
| 2820 | p.buffer_image_copies[0].imageSubresource.aspectMask == VK_IMAGE_ASPECT_DEPTH_BIT; | 2865 | p.buffer_image_copies[0].imageSubresource.aspectMask == VK_IMAGE_ASPECT_DEPTH_BIT; |
| @@ -3043,13 +3088,13 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 3043 | const VkDeviceSize record_size = detail::indirect_record_size(ind->kind); | 3088 | const VkDeviceSize record_size = detail::indirect_record_size(ind->kind); |
| 3044 | if (!record_size || ind->stride < record_size || ind->stride % sizeof(std::uint32_t)) | 3089 | if (!record_size || ind->stride < record_size || ind->stride % sizeof(std::uint32_t)) |
| 3045 | return ReplayResult::invalid_indirect_arguments; | 3090 | return ReplayResult::invalid_indirect_arguments; |
| 3046 | // The span is max_count * stride, the bytes the signature can walk, as D3D12 measures it: a record that | 3091 | // The range is the bytes the commands read, (max_count - 1) * stride + record_size: the rule recording |
| 3047 | // fits at the end of the buffer while its stride runs past it is refused (`240` with stride `20` in a | 3092 | // applies (d3d12_com.cpp, ExecuteIndirect) and the one vkCmdDraw*Indirect states. A zero max_count is a |
| 3048 | // `256`-byte buffer). A zero max_count still has to name an offset inside the buffer. | 3093 | // no-op that recording never passes on; if one arrives it reads nothing and needs no range. |
| 3049 | if (ind->argument_offset > p.binding.size || | 3094 | if (ind->max_count |
| 3050 | ind->max_count > (p.binding.size - ind->argument_offset) / ind->stride || | 3095 | ? !detail::indirect_range(p.binding, ind->argument_offset, |
| 3051 | !detail::indirect_range(p.binding, ind->argument_offset, | 3096 | VkDeviceSize(ind->max_count - 1) * ind->stride + record_size) |
| 3052 | VkDeviceSize(ind->max_count) * ind->stride)) | 3097 | : (p.binding.buffer_offset | ind->argument_offset) % sizeof(std::uint32_t) != 0) |
| 3053 | return ReplayResult::invalid_indirect_arguments; | 3098 | return ReplayResult::invalid_indirect_arguments; |
| 3054 | if (ind->count_buffer) { | 3099 | if (ind->count_buffer) { |
| 3055 | const ResourceBinding* cnt = resolve(ind->count_buffer); | 3100 | const ResourceBinding* cnt = resolve(ind->count_buffer); |
| @@ -3130,6 +3175,11 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 3130 | VkDeviceSize offset = 0; | 3175 | VkDeviceSize offset = 0; |
| 3131 | if (!vk.buffer_at(info->dest_va, room, buffer, offset)) return ReplayResult::unresolved_resource; | 3176 | if (!vk.buffer_at(info->dest_va, room, buffer, offset)) return ReplayResult::unresolved_resource; |
| 3132 | if (room < 8 * info->sources.size()) return ReplayResult::invalid_copy; | 3177 | if (room < 8 * info->sources.size()) return ReplayResult::invalid_copy; |
| 3178 | if (!info->sources.empty()) { | ||
| 3179 | // dest_va is resolved by VA and may target a host-readable buffer; XDXR postbuild writes from compute. | ||
| 3180 | out.wrote_readback = true; | ||
| 3181 | out.readback_src_stages |= VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT; | ||
| 3182 | } | ||
| 3133 | } else if (info->type == 0 && vk.write_acceleration_structures_properties && | 3183 | } else if (info->type == 0 && vk.write_acceleration_structures_properties && |
| 3134 | vk.resolve_acceleration_structure && vk.reset_query_pool && vk.copy_query_pool_results && | 3184 | vk.resolve_acceleration_structure && vk.reset_query_pool && vk.copy_query_pool_results && |
| 3135 | vk.pipeline_barrier && vk.buffer_at && vk.prepare_khr_postbuild) { | 3185 | vk.pipeline_barrier && vk.buffer_at && vk.prepare_khr_postbuild) { |
| @@ -3574,16 +3624,23 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c | |||
| 3574 | const auto range = detail::planes_for_layout(p.binding, p.range, separate); | 3624 | const auto range = detail::planes_for_layout(p.binding, p.range, separate); |
| 3575 | const bool discard = (texture->flags & texture_barrier_discard) || | 3625 | const bool discard = (texture->flags & texture_barrier_discard) || |
| 3576 | texture->layout_before == d3d12_layout::undefined; | 3626 | texture->layout_before == d3d12_layout::undefined; |
| 3627 | // LayoutAfter UNDEFINED from a defined layout: the contents are no longer needed (the memory is about to | ||
| 3628 | // be aliased, say). Vulkan has no transition into UNDEFINED (VUID-VkImageMemoryBarrier2-newLayout-01198), | ||
| 3629 | // so each piece keeps the layout it is in and the barrier only orders the accesses; the tracker keeps | ||
| 3630 | // that layout too. D3D12 has the next barrier on these subresources start from UNDEFINED, which discards | ||
| 3631 | // from whatever layout they are in. | ||
| 3632 | const bool release = texture->layout_after == d3d12_layout::undefined && | ||
| 3633 | texture->layout_before != d3d12_layout::undefined; | ||
| 3577 | const VkImageLayout new_layout = | 3634 | const VkImageLayout new_layout = |
| 3578 | image_layout(p.binding, vulkan_layout(texture->layout_after, p.binding.presentable)); | 3635 | image_layout(p.binding, vulkan_layout(texture->layout_after, p.binding.presentable)); |
| 3579 | LayoutPieces pieces; | 3636 | LayoutPieces pieces; |
| 3580 | if (discard) | 3637 | if (discard && !release) |
| 3581 | pieces.push_back({range, VK_IMAGE_LAYOUT_UNDEFINED}); | 3638 | pieces.push_back({range, VK_IMAGE_LAYOUT_UNDEFINED}); |
| 3582 | else { | 3639 | else { |
| 3583 | const VkImageLayout before = | 3640 | const VkImageLayout before = |
| 3584 | image_layout(p.binding, vulkan_layout(texture->layout_before, p.binding.presentable)); | 3641 | image_layout(p.binding, vulkan_layout(texture->layout_before, p.binding.presentable)); |
| 3585 | pieces = detail::current(tracker, id, range, before); | 3642 | pieces = detail::current(tracker, id, range, before); |
| 3586 | detail::initialize(vk, command_buffer, p.binding, id, pieces, before, tracker); | 3643 | if (!release) detail::initialize(vk, command_buffer, p.binding, id, pieces, before, tracker); |
| 3587 | } | 3644 | } |
| 3588 | const BarrierScope src = vulkan_barrier_scope(texture->sync_before, texture->access_before, predicates); | 3645 | const BarrierScope src = vulkan_barrier_scope(texture->sync_before, texture->access_before, predicates); |
| 3589 | const BarrierScope dst = vulkan_barrier_scope(texture->sync_after, texture->access_after, predicates); | 3646 | const BarrierScope dst = vulkan_barrier_scope(texture->sync_after, texture->access_after, predicates); |
| @@ -3594,6 +3651,8 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c | |||
| 3594 | VkImageMemoryBarrier2* const barriers = many.empty() ? few.data() : many.data(); | 3651 | VkImageMemoryBarrier2* const barriers = many.empty() ? few.data() : many.data(); |
| 3595 | std::uint32_t barrier_count = 0; | 3652 | std::uint32_t barrier_count = 0; |
| 3596 | for (const auto& piece : pieces) { | 3653 | for (const auto& piece : pieces) { |
| 3654 | // Released before it was ever used (the tracker still has it in UNDEFINED): nothing to order. | ||
| 3655 | if (release && piece.layout == VK_IMAGE_LAYOUT_UNDEFINED) continue; | ||
| 3597 | VkImageMemoryBarrier2& b = barriers[barrier_count++]; | 3656 | VkImageMemoryBarrier2& b = barriers[barrier_count++]; |
| 3598 | b = {VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2}; | 3657 | b = {VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2}; |
| 3599 | b.srcStageMask = src.stages; | 3658 | b.srcStageMask = src.stages; |
| @@ -3601,7 +3660,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c | |||
| 3601 | b.srcAccessMask = src.access; | 3660 | b.srcAccessMask = src.access; |
| 3602 | b.dstAccessMask = dst.access; | 3661 | b.dstAccessMask = dst.access; |
| 3603 | b.oldLayout = piece.layout; | 3662 | b.oldLayout = piece.layout; |
| 3604 | b.newLayout = new_layout; | 3663 | b.newLayout = release ? piece.layout : new_layout; |
| 3605 | b.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; | 3664 | b.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; |
| 3606 | b.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; | 3665 | b.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; |
| 3607 | b.image = p.binding.image; | 3666 | b.image = p.binding.image; |
| @@ -3609,11 +3668,13 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c | |||
| 3609 | if (b.srcStageMask) detail::restrict_to_queue(vk, b.srcStageMask, b.srcAccessMask); | 3668 | if (b.srcStageMask) detail::restrict_to_queue(vk, b.srcStageMask, b.srcAccessMask); |
| 3610 | if (b.dstStageMask) detail::restrict_to_queue(vk, b.dstStageMask, b.dstAccessMask); | 3669 | if (b.dstStageMask) detail::restrict_to_queue(vk, b.dstStageMask, b.dstAccessMask); |
| 3611 | } | 3670 | } |
| 3612 | VkDependencyInfo dependency{VK_STRUCTURE_TYPE_DEPENDENCY_INFO}; | 3671 | if (barrier_count) { |
| 3613 | dependency.imageMemoryBarrierCount = barrier_count; | 3672 | VkDependencyInfo dependency{VK_STRUCTURE_TYPE_DEPENDENCY_INFO}; |
| 3614 | dependency.pImageMemoryBarriers = barriers; | 3673 | dependency.imageMemoryBarrierCount = barrier_count; |
| 3615 | vk.pipeline_barrier2(command_buffer, &dependency); | 3674 | dependency.pImageMemoryBarriers = barriers; |
| 3616 | if (tracker) tracker->set(id, range, new_layout); | 3675 | vk.pipeline_barrier2(command_buffer, &dependency); |
| 3676 | } | ||
| 3677 | if (tracker && !release) tracker->set(id, range, new_layout); | ||
| 3617 | } else if (const auto* color_clear = std::get_if<ClearRenderTarget>(&command)) { | 3678 | } else if (const auto* color_clear = std::get_if<ClearRenderTarget>(&command)) { |
| 3618 | if (p.skip) continue; | 3679 | if (p.skip) continue; |
| 3619 | const VulkanAccess state = vulkan_access(d3d12_state::render_target, false); | 3680 | const VulkanAccess state = vulkan_access(d3d12_state::render_target, false); |
| @@ -3654,10 +3715,13 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c | |||
| 3654 | const VulkanAccess state = vulkan_access(d3d12_state::depth_write, false); | 3715 | const VulkanAccess state = vulkan_access(d3d12_state::depth_write, false); |
| 3655 | auto pieces = detail::current(tracker, id, range, image_layout(p.binding, state.layout)); | 3716 | auto pieces = detail::current(tracker, id, range, image_layout(p.binding, state.layout)); |
| 3656 | detail::initialize(vk, command_buffer, p.binding, id, pieces, image_layout(p.binding, state.layout), tracker); | 3717 | detail::initialize(vk, command_buffer, p.binding, id, pieces, image_layout(p.binding, state.layout), tracker); |
| 3657 | const float depth = p.binding.depth24 ? depth24_clear_value(depth_clear->depth) // see depth24.h | 3718 | float depth = p.binding.depth24 ? depth24_clear_value(depth_clear->depth) // see depth24.h |
| 3658 | : p.binding.format == VK_FORMAT_D16_UNORM | 3719 | : p.binding.format == VK_FORMAT_D16_UNORM |
| 3659 | ? detail::quantize_unorm(depth_clear->depth, 65535.0) // see quantize_unorm | 3720 | ? detail::quantize_unorm(depth_clear->depth, 65535.0) // see quantize_unorm |
| 3660 | : depth_clear->depth; | 3721 | : depth_clear->depth; |
| 3722 | // Without the extension both clear commands require a depth in [0, 1], including for float images. | ||
| 3723 | if (!vk.depth_range_unrestricted) | ||
| 3724 | depth = std::isnan(depth) ? 0.0f : std::clamp(depth, 0.0f, 1.0f); | ||
| 3661 | const VkClearDepthStencilValue value{depth, depth_clear->stencil}; | 3725 | const VkClearDepthStencilValue value{depth, depth_clear->stencil}; |
| 3662 | if (p.rects.empty()) { | 3726 | if (p.rects.empty()) { |
| 3663 | detail::round_trip(vk, command_buffer, p.binding, pieces, image_layout(p.binding, transfer_dst.layout), | 3727 | detail::round_trip(vk, command_buffer, p.binding, pieces, image_layout(p.binding, transfer_dst.layout), |
| @@ -4218,14 +4282,46 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c | |||
| 4218 | vk.push_constants(command_buffer, graphics.layout, graphics.push_stages, 0, sizeof(data), &data); | 4282 | vk.push_constants(command_buffer, graphics.layout, graphics.push_stages, 0, sizeof(data), &data); |
| 4219 | // Translated vertex shaders write D3D clip coordinates (y up); a negative-height viewport keeps the | 4283 | // Translated vertex shaders write D3D clip coordinates (y up); a negative-height viewport keeps the |
| 4220 | // image upright, and winding as D3D12 sees it. | 4284 | // image upright, and winding as D3D12 sees it. |
| 4221 | const Viewport& v = draw->viewport; | 4285 | if (graphics.viewport_with_count) { |
| 4222 | const VkViewport viewport{v.x, v.y + v.height, v.width, -v.height, v.min_depth, v.max_depth}; | 4286 | std::array<VkViewport, DrawViewports::max_count> vps{}; |
| 4223 | vk.set_viewport(command_buffer, 0, 1, &viewport); | 4287 | std::array<VkRect2D, DrawViewports::max_count> scs{}; |
| 4224 | const Rect& s = draw->scissor; | 4288 | const std::uint32_t vp_n = draw->viewports ? draw->viewports->viewport_count : 1u; |
| 4225 | const VkRect2D scissor{{std::max(0, s.left), std::max(0, s.top)}, | 4289 | const std::uint32_t sc_n = draw->viewports ? draw->viewports->scissor_count : 1u; |
| 4226 | {std::uint32_t(std::max(0, s.right - std::max(0, s.left))), | 4290 | const std::uint32_t count = std::clamp(std::max(vp_n, sc_n), 1u, DrawViewports::max_count); |
| 4227 | std::uint32_t(std::max(0, s.bottom - std::max(0, s.top)))}}; | 4291 | for (std::uint32_t k = 0; k < count; ++k) { |
| 4228 | vk.set_scissor(command_buffer, 0, 1, &scissor); | 4292 | const Viewport v = (draw->viewports && k < vp_n) ? draw->viewports->viewports[k] |
| 4293 | : (k == 0 ? draw->viewport : Viewport{}); | ||
| 4294 | const bool valid_vp = (k < vp_n) && (v.width > 0.0f) && (v.height > 0.0f); | ||
| 4295 | if (valid_vp) { | ||
| 4296 | vps[k] = {v.x, v.y + v.height, v.width, -v.height, v.min_depth, v.max_depth}; | ||
| 4297 | } else { | ||
| 4298 | // Vulkan forbids width/height == 0; pair a 1x1 dummy viewport with an empty scissor so nothing | ||
| 4299 | // rasterizes into an unbound/empty D3D12 viewport slot. | ||
| 4300 | vps[k] = {0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f}; | ||
| 4301 | } | ||
| 4302 | if (valid_vp && k < sc_n) { | ||
| 4303 | const Rect s = draw->viewports ? draw->viewports->scissors[k] : draw->scissor; | ||
| 4304 | const std::int32_t left = std::max(0, s.left); | ||
| 4305 | const std::int32_t top = std::max(0, s.top); | ||
| 4306 | scs[k] = {{left, top}, | ||
| 4307 | {std::uint32_t(std::max(0, s.right - left)), | ||
| 4308 | std::uint32_t(std::max(0, s.bottom - top))}}; | ||
| 4309 | } else { | ||
| 4310 | scs[k] = {{0, 0}, {0, 0}}; | ||
| 4311 | } | ||
| 4312 | } | ||
| 4313 | vk.set_viewport_with_count(command_buffer, count, vps.data()); | ||
| 4314 | vk.set_scissor_with_count(command_buffer, count, scs.data()); | ||
| 4315 | } else { | ||
| 4316 | const Viewport& v = draw->viewport; | ||
| 4317 | const VkViewport viewport{v.x, v.y + v.height, v.width, -v.height, v.min_depth, v.max_depth}; | ||
| 4318 | vk.set_viewport(command_buffer, 0, 1, &viewport); | ||
| 4319 | const Rect& s = draw->scissor; | ||
| 4320 | const VkRect2D scissor{{std::max(0, s.left), std::max(0, s.top)}, | ||
| 4321 | {std::uint32_t(std::max(0, s.right - std::max(0, s.left))), | ||
| 4322 | std::uint32_t(std::max(0, s.bottom - std::max(0, s.top)))}}; | ||
| 4323 | vk.set_scissor(command_buffer, 0, 1, &scissor); | ||
| 4324 | } | ||
| 4229 | // A mesh pipeline has no input assembly: its topology comes from the shader, and neither the topology | 4325 | // A mesh pipeline has no input assembly: its topology comes from the shader, and neither the topology |
| 4230 | // nor primitive restart is dynamic state there (VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-07065). | 4326 | // nor primitive restart is dynamic state there (VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-07065). |
| 4231 | if (!draw->mesh) { | 4327 | if (!draw->mesh) { |
diff --git a/runtime/src/vulkan_scratch.h b/runtime/src/vulkan_scratch.h index 4a8a59ddd..33d84bf72 100644 --- a/runtime/src/vulkan_scratch.h +++ b/runtime/src/vulkan_scratch.h | |||
| @@ -46,12 +46,16 @@ public: | |||
| 46 | constexpr VkDeviceSize alignment = 256, minimum = 4u << 20; | 46 | constexpr VkDeviceSize alignment = 256, minimum = 4u << 20; |
| 47 | if (!loaded_ || !bytes) return false; | 47 | if (!loaded_ || !bytes) return false; |
| 48 | for (auto& chunk : current_.chunks) { | 48 | for (auto& chunk : current_.chunks) { |
| 49 | const VkDeviceSize start = (chunk.used + alignment - 1) / alignment * alignment; | 49 | const VkDeviceSize rem = chunk.used % alignment; |
| 50 | if (start <= chunk.size && bytes <= chunk.size - start) { | 50 | const VkDeviceSize pad = rem ? alignment - rem : 0; |
| 51 | chunk.used = start + bytes; | 51 | if (pad <= chunk.size - chunk.used) { |
| 52 | buffer = chunk.buffer; | 52 | const VkDeviceSize start = chunk.used + pad; |
| 53 | offset = start; | 53 | if (bytes <= chunk.size - start) { |
| 54 | return true; | 54 | chunk.used = start + bytes; |
| 55 | buffer = chunk.buffer; | ||
| 56 | offset = start; | ||
| 57 | return true; | ||
| 58 | } | ||
| 55 | } | 59 | } |
| 56 | } | 60 | } |
| 57 | Chunk chunk; | 61 | Chunk chunk; |
diff --git a/runtime/src/xdxr_build.h b/runtime/src/xdxr_build.h index e0851098f..e1c1a233e 100644 --- a/runtime/src/xdxr_build.h +++ b/runtime/src/xdxr_build.h | |||
| @@ -133,7 +133,13 @@ public: | |||
| 133 | // update ignores `pair`. | 133 | // update ignores `pair`. |
| 134 | bool record_blas(VkCommandBuffer cb, const XdxrLayout& layout, const std::vector<XdxrTriangles>& geometries, | 134 | bool record_blas(VkCommandBuffer cb, const XdxrLayout& layout, const std::vector<XdxrTriangles>& geometries, |
| 135 | std::uint64_t dst, std::uint64_t scratch, std::uint64_t update_from = 0, bool pair = false) { | 135 | std::uint64_t dst, std::uint64_t scratch, std::uint64_t update_from = 0, bool pair = false) { |
| 136 | if (!loaded_ || layout.tlas) return false; | 136 | if (!loaded_ || layout.tlas || !layout.size || !dst || !scratch) return false; |
| 137 | std::uint64_t total = 0; | ||
| 138 | for (const auto& geo : geometries) { | ||
| 139 | total += geo.triangle_count; | ||
| 140 | if (total > layout.elements) return false; | ||
| 141 | } | ||
| 142 | if (total != layout.elements) return false; | ||
| 137 | Push p = base(layout, dst, scratch); | 143 | Push p = base(layout, dst, scratch); |
| 138 | if (pair && !update_from) p.flags |= flag_pair; | 144 | if (pair && !update_from) p.flags |= flag_pair; |
| 139 | if (update_from) refit_begin(cb, layout, p, update_from); else begin(cb, layout, p); | 145 | if (update_from) refit_begin(cb, layout, p, update_from); else begin(cb, layout, p); |
| @@ -155,7 +161,6 @@ public: | |||
| 155 | dispatch(cb, t, t.count); | 161 | dispatch(cb, t, t.count); |
| 156 | first += geo.triangle_count; | 162 | first += geo.triangle_count; |
| 157 | } | 163 | } |
| 158 | if (first != layout.elements) return false; | ||
| 159 | if (update_from) refit_finish(cb, layout, p); else finish(cb, layout, p); | 164 | if (update_from) refit_finish(cb, layout, p); else finish(cb, layout, p); |
| 160 | return true; | 165 | return true; |
| 161 | } | 166 | } |
| @@ -164,7 +169,8 @@ public: | |||
| 164 | // `update_from`: as for record_blas; the instances may move, and name other BLASes. | 169 | // `update_from`: as for record_blas; the instances may move, and name other BLASes. |
| 165 | bool record_tlas(VkCommandBuffer cb, const XdxrLayout& layout, std::uint64_t instances, std::uint64_t dst, | 170 | bool record_tlas(VkCommandBuffer cb, const XdxrLayout& layout, std::uint64_t instances, std::uint64_t dst, |
| 166 | std::uint64_t scratch, std::uint64_t bias = 0, std::uint64_t update_from = 0) { | 171 | std::uint64_t scratch, std::uint64_t bias = 0, std::uint64_t update_from = 0) { |
| 167 | if (!loaded_ || !layout.tlas) return false; | 172 | if (!loaded_ || !layout.tlas || !layout.size || !dst || !scratch || (layout.elements && !instances)) |
| 173 | return false; | ||
| 168 | Push p = base(layout, dst, scratch); | 174 | Push p = base(layout, dst, scratch); |
| 169 | p.bias = split(bias); | 175 | p.bias = split(bias); |
| 170 | if (update_from) refit_begin(cb, layout, p, update_from); else begin(cb, layout, p); | 176 | if (update_from) refit_begin(cb, layout, p, update_from); else begin(cb, layout, p); |
| @@ -341,7 +347,7 @@ private: | |||
| 341 | // dependency on its results to the caller's barrier (the application's UAV or AS barrier). | 347 | // dependency on its results to the caller's barrier (the application's UAV or AS barrier). |
| 342 | void dispatch(VkCommandBuffer cb, const Push& p, std::uint32_t threads, bool barrier = true) { | 348 | void dispatch(VkCommandBuffer cb, const Push& p, std::uint32_t threads, bool barrier = true) { |
| 343 | vk_.vkCmdPushConstants(cb, layout_, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(Push), &p); | 349 | vk_.vkCmdPushConstants(cb, layout_, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(Push), &p); |
| 344 | vk_.vkCmdDispatch(cb, (threads + 63) / 64, 1, 1); | 350 | vk_.vkCmdDispatch(cb, std::uint32_t((std::uint64_t(threads) + 63u) / 64u), 1, 1); |
| 345 | if (!barrier) return; | 351 | if (!barrier) return; |
| 346 | VkMemoryBarrier b{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; | 352 | VkMemoryBarrier b{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; |
| 347 | b.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; | 353 | b.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; |
diff --git a/runtime/src/xdxr_descs.h b/runtime/src/xdxr_descs.h index b44ce0372..3798b0fe7 100644 --- a/runtime/src/xdxr_descs.h +++ b/runtime/src/xdxr_descs.h | |||
| @@ -99,12 +99,11 @@ constexpr uint32_t kPostbuildInfoOfflineStatistics = 0x10; | |||
| 99 | // The record a setting is read from, the way the DLL finds it: the first record of `type` from the start, stepping | 99 | // The record a setting is read from, the way the DLL finds it: the first record of `type` from the start, stepping |
| 100 | // over types 0, 1 and 2, and stopping at any other type. Null when there is none. | 100 | // over types 0, 1 and 2, and stopping at any other type. Null when there is none. |
| 101 | inline const StreamRecord* find_stream_record(const StreamDesc& desc, uint32_t type) { | 101 | inline const StreamRecord* find_stream_record(const StreamDesc& desc, uint32_t type) { |
| 102 | if (desc.size_in_bytes == 0 || desc.stream == nullptr) | 102 | if (desc.size_in_bytes < sizeof(StreamRecord) || desc.stream == nullptr) |
| 103 | return nullptr; | 103 | return nullptr; |
| 104 | const auto* record = static_cast<const StreamRecord*>(desc.stream); | 104 | const auto* record = static_cast<const StreamRecord*>(desc.stream); |
| 105 | const auto* end = reinterpret_cast<const StreamRecord*>(static_cast<const uint8_t*>(desc.stream) + | 105 | const uint64_t count = desc.size_in_bytes / sizeof(StreamRecord); |
| 106 | desc.size_in_bytes); | 106 | for (uint64_t i = 0; i < count; ++i, ++record) { |
| 107 | for (; record < end; ++record) { | ||
| 108 | if (record->type == type) | 107 | if (record->type == type) |
| 109 | return record; | 108 | return record; |
| 110 | if (record->type > 2) | 109 | if (record->type > 2) |