From fde992135d37359339cb79723b8c6280b5b00f8d Mon Sep 17 00:00:00 2001 From: Ryx <118130241+Ryx69@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:44:40 +0100 Subject: [PATCH 1/9] Runtime: present D3D12 back buffers to a window on Vulkan (milestone M0) - vulkan_present.h: VulkanPresenter blits a back buffer (an ordinary texture in D3D12's PRESENT state, layout tracked like any other) to an acquired swapchain image and presents it on the same VkQueue, after the application's work. Two frames in flight, a present semaphore per image, FIFO for vsync else MAILBOX/IMMEDIATE, swapchain recreated on resize or out-of-date/suboptimal, minimised windows skip presents. - rt::d3d12::create_window_presenter / WindowPresenter: Win32 surface for a Vulkan device created with presentation; holds the device. This is the back end a DXGI shim or PresentX would call; the game's own front end is still open (docs question 6), so neither is invented here. - Standalone device enables VK_KHR_surface/win32_surface and VK_KHR_swapchain when present; the test helper can too. Test: d3d12_present_test opens a window and presents 60 frames through the Xbox-ABI proxy (reset, PRESENT->RENDER_TARGET, clear, ->PRESENT, execute, present, fence), resizes the window (swapchain recreated, scaled blit), switches to unsynchronised presents, and reads the screen with GDI: 51,153,229 for a 51,153,230 clear. Clean under the Khronos validation layer, as are the other GPU tests; 6/6 ctest. --- README.md | 2 +- docs/d3d12_vulkan.md | 39 ++- runtime/CMakeLists.txt | 6 + runtime/README.md | 4 +- runtime/shims/d3d12_com.h | 30 +++ runtime/shims/d3d12_vulkan_device.cpp | 79 ++++++ runtime/src/vulkan_backend.h | 1 + runtime/src/vulkan_present.h | 346 ++++++++++++++++++++++++++ runtime/test/d3d12_present_test.cpp | 198 +++++++++++++++ runtime/test/vk_test_device.h | 18 +- 10 files changed, 711 insertions(+), 12 deletions(-) create mode 100644 runtime/src/vulkan_present.h create mode 100644 runtime/test/d3d12_present_test.cpp diff --git a/README.md b/README.md index e64e292a6..652eb5eec 100644 --- a/README.md +++ b/README.md @@ -52,7 +52,7 @@ work on booting can start as soon as one is available to a developer. | Audio banks (AWC: Opus, XMA2) | ✅ Exported whole. Opus repackaged **losslessly** as Ogg Opus; PCM (codec 0/2) as WAV; XMA2 decoded with ffmpeg. `--wav` adds 16-bit PCM WAV ([notes](docs/audio.md)) | | Music/radio config | ? Measured. **1,589** audio-config records with exact durations and AWC stream ids; station grouping and content-id lists; no per-track start offsets ([notes](docs/audio_config.md)) | | PE loader and import shims | ⚠️ Skeleton. Untested against the real executable | -| Xbox D3D12 → Vulkan | ⚠️ In progress. A Vulkan-backed device behind the Xbox-ABI proxy creates queues, command lists, fences, descriptor heaps, views and committed resources; barriers, clears, uploads and copies (BC included) run on Vulkan, checked on one GPU. No shader views, pipelines, draws or swapchain yet ([plan](docs/d3d12_vulkan.md)) | +| Xbox D3D12 → Vulkan | ⚠️ In progress. A Vulkan-backed device behind the Xbox-ABI proxy creates queues, command lists, fences, descriptor heaps, views and committed resources; barriers, clears, uploads and copies (BC included) run on Vulkan, and frames are presented to a window (milestone M0 passes in a synthetic test), checked on one GPU. No shader views, pipelines or draws yet, and the game's own present call is not hooked up ([plan](docs/d3d12_vulkan.md)) | | Booting, story mode, anything playable | ❌ No | ## How to build diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 0ef4012c9..503a512da 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -1,9 +1,11 @@ # Xbox D3D12 (`d3d12_xs`) to Vulkan **Status: in progress. A Vulkan-backed `ID3D12Device` (queues, allocators, command lists, fences, descriptor heaps, -render-target and depth views, committed buffers, 2D textures and 3D texture transfers) runs behind the Xbox-ABI device proxy -(section 3.2). `D3D12XboxCreateDevice` uses it when `LEONIDA_D3D12=vulkan` is set and the host PC device otherwise. -Shader views, root signatures, PSOs, draws and the swapchain are not implemented.** This is the plan for replacing the console's +render-target and depth views, committed buffers, 2D textures and 3D texture transfers, copies) runs behind the +Xbox-ABI device proxy, and a presenter puts back buffers in a window (section 3.2). The M0 milestone passes in a +synthetic test (section 6). `D3D12XboxCreateDevice` uses the Vulkan device when `LEONIDA_D3D12=vulkan` is set and +the host PC device otherwise. Shader views, root signatures, PSOs, draws, and the game's own present entry point +(DXGI or PresentX) are not implemented.** This is the plan for replacing the console's `d3d12_xs.dll` with an implementation that records D3D12 commands and replays them on Vulkan, while producing exactly the shader-visible contract that `tools/rdna2spirv.py` already emits against (see [design.md](design.md#translator-status-and-runtime-contract)). @@ -208,6 +210,19 @@ What is implemented (all of it testable without the game): depth-stencil rows are padded to 512 bytes, not 256. BC1–7 textures need `textureCompressionBC`, which the device enables when the GPU has it. +- **Presentation** (`runtime/src/vulkan_present.h`, `rt::d3d12::create_window_presenter`). This is the part every + present front end needs; DXGI or `PresentX` is still open (question 6). It takes a back buffer, an ordinary + texture in the D3D12 `PRESENT` state, and blits it to an acquired `VkSwapchainKHR` image, scaling when the window + size differs. The blit goes on the same `VkQueue` after the application's work, so the frame contains everything + submitted before the present. Details: + - two frames in flight, and a present semaphore per swapchain image; + - FIFO when vsync is asked for, otherwise MAILBOX or IMMEDIATE; + - the swapchain is recreated on resize or when the surface reports it out of date or suboptimal, and a minimised + window skips presents; + - a back buffer that was never written is zero-filled like any other texture. + + The device needs `VK_KHR_swapchain` (and the instance the surface extensions). The standalone device enables + them when present. New textures are not touched at creation. They are tracked as `UNDEFINED`, and the first command that uses a part of one zero-fills it (D3D12 committed resources start zeroed; `CREATE_NOT_ZEROED` skips this) and moves it @@ -239,9 +254,10 @@ Two pieces of milestone M2 that the device does not use yet, built and tested on a table that has grown gets a new buffer behind binding 2: `flush_needs_idle()` says when a flush would do either, so the owner can wait until no command buffer that uses the set is still running. -Known gaps: shader-resource, UAV and constant-buffer views, samplers, root signatures, PSOs, draws, volume attachment -views, placed and reserved resources, `GetGPUVirtualAddress` (the shared buffer arena), depth-stencil resolves and -`ResolveSubresourceRegion`, 1D textures and the swapchain; +Known gaps: the game's present entry point (DXGI factory/swapchain or `PresentX`; the presenter above is what +either calls), HDR and fullscreen; shader-resource, UAV and constant-buffer views, samplers, root signatures, PSOs, +draws, volume attachment views, placed and reserved resources, `GetGPUVirtualAddress` (the shared buffer arena), +depth-stencil resolves and `ResolveSubresourceRegion`, and 1D textures; default-heap buffers are not zero-filled yet; a fence cannot be signalled to a lower value (Vulkan timelines only increase; such a signal is reported and dropped); enhanced-barrier access bits are not filtered against the sync scope, so a combination D3D12 accepts but Vulkan does not would show up as a validation error; the GCL8 @@ -291,6 +307,10 @@ and any validation error fails them. repeats on a standalone device, the path `LEONIDA_D3D12=vulkan` takes. - `d3d12_descriptor_test`: descriptor copies through the proxy, checked on the slots' bytes: one run, range lists of different shapes on each side, null size arrays, and a destination longer than its source. +- `d3d12_present_test`: milestone M0. It opens a window and presents 60 frames, each one: reset the list, move + the back buffer `PRESENT` → `RENDER_TARGET`, clear, move it back, execute, present, signal a fence. It then + resizes the window, which recreates the swapchain and scales the blit, and switches to unsynchronised presents. + Last, it reads the colour on screen with GDI when the window is in front. **Open:** whether the game uses command-list flags, bundles, or `ExecuteCommandLists` with many lists at once. All are supported by the IR; the trace will show which are hot. @@ -714,6 +734,11 @@ That import must be shimmed. The shim provides: toggles borderless/fullscreen; `GetFrameStatistics` is a stub. - `DXGI_PRESENT_TEST`/`DO_NOT_WAIT` map to a no-op/`VK_NOT_READY` path. +**What exists.** The back end of this path is `leonida::VulkanPresenter` (section 3.2): surface, swapchain, +blit, present, resize. A DXGI shim's `Present` and a `PresentX` implementation would both end in its `present()`. +`GetBuffer(i)` therefore does not need to wrap swapchain images: the buffers can be ordinary committed textures, +blitted at present time, which also frees the game's buffer count and format from the surface's. + **PresentX.** Public Xbox documentation mentions `ID3D12CommandQueue::PresentX`, `D3D12XBOX_FRAME_PIPELINE_TOKEN` and `D3D12XBOX_PRESENT_PLANE_PARAMETERS` in the game-streaming APIs ([example](https://docs.xbox.com/reference/system/xgamestreaming/functions/xgamestreamingsetresolution)). PresentX @@ -904,7 +929,7 @@ M0–M2 do not need the executable. | # | Scope | What it proves | Done when | |---|---|---|---| -| **M0** | `D3D12XboxCreateDevice` and the measured device overrides (heap start handles in RAX), one direct queue, allocator/list, fence, fake DXGI factory/adapter/swapchain, clear + present | COM interception, the known Xbox device entry point and ABI overrides, swapchain, frame loop, clean shutdown | A window shows a stable clear colour for 60 frames, no Vulkan validation errors, every D3D12 call traced | +| **M0** | `D3D12XboxCreateDevice` and the measured device overrides (heap start handles in RAX), one direct queue, allocator/list, fence, fake DXGI factory/adapter/swapchain, clear + present | COM interception, the known Xbox device entry point and ABI overrides, swapchain, frame loop, clean shutdown | A window shows a stable clear colour for 60 frames, no Vulkan validation errors, every D3D12 call traced. **Synthetic part met** by `d3d12_present_test`: 60 frames through the proxy on Vulkan, validation clean, colour checked on screen. Still open: the game's present front end (DXGI or PresentX) and the per-call trace | | **M1** | Root signature with root constants (mask the measured `0x03000000` flag byte on a copy), one translated VS+PS, PSO, vertex buffer in the arena, draw, push constants `s0..s31` + heap base | PSO translation, shader hash lookup, vertex input, root-constant packing, heap base, present | The triangle matches a CPU/GPU reference; the existing texture-test style comparison passes with error 0 | | **M2** | Descriptor heap (heap slots 9/10 return in RAX), `CreateShaderResourceView`, sampler, root descriptor table, hash-table insert, bindless sampling | The full D3D12 descriptor path and the shader's T#/S# contract | A textured quad matches the synthetic 8×8 gradient or a known texture with error 0; the hash table has the expected entries | | **M3** | Depth/stencil, multiple render targets, resource barriers, render passes, occlusion queries, fences, 2–3 frames in flight; run the game's first frames | Real frame structure and the first game code | The game reaches its first rendered frame (loading screen/menu or whatever the executable does) or stops on a single unsupported call with a clean report | diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index f28c743ce..b96a27141 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -337,6 +337,12 @@ if(Vulkan_FOUND) target_compile_definitions(d3d12_descriptor_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) target_compile_options(d3d12_descriptor_test PRIVATE /W4 /permissive- /utf-8) + # Milestone M0: a window, 60 cleared frames presented through the proxy on Vulkan. + add_executable(d3d12_present_test test/d3d12_present_test.cpp) + target_link_libraries(d3d12_present_test PRIVATE gta6rt_d3d12_com user32 gdi32) + target_compile_definitions(d3d12_present_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_present_test PRIVATE /W4 /permissive- /utf-8) + # The loader can create this device instead of the host's (D3D12XboxCreateDevice, LEONIDA_D3D12=vulkan). if(TARGET gta6rt) target_link_libraries(gta6rt PRIVATE gta6rt_d3d12_com) diff --git a/runtime/README.md b/runtime/README.md index 934b0d48c..451b8d8c3 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -94,7 +94,9 @@ when the Vulkan SDK is found: - `vk_harness` — hand-written RDNA2 shader programs on a real Vulkan device. - `vk_texture_test`, `vk_compute_test`, `vk_store_test` — texture, LDS/compute, and buffer-store paths. - `vk_command_replay_test`, `d3d12_com_test`, `d3d12_vulkan_device_test` — the D3D12 command path on - Vulkan: replay, the COM command objects, and the Vulkan device behind the Xbox-ABI proxy. Set + Vulkan: replay, the COM command objects, and the Vulkan device behind the Xbox-ABI proxy. +- `d3d12_present_test` — milestone M0: opens a window and presents 60 cleared frames through the proxy on + Vulkan, resizes it, and checks the colour on screen. Set `LEONIDA_VK_VALIDATION=1` to run them under the Khronos validation layer. - `vk_pipeline_check [cache.bin] [--jobs N] [--start I] [--count N] [--max-bytes N]` - creates a shader module and, for compute shaders, a pipeline for every entry in the translator's diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index 472f5786f..b71652267 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -14,6 +14,12 @@ #include "../src/vulkan_backend.h" +#include + +namespace leonida { +class VulkanPresenter; +} + namespace rt::d3d12 { // `device` (optional) is what the object's GetDevice returns; the object holds a reference to it. @@ -38,6 +44,7 @@ struct VulkanDeviceInfo { bool separate_depth_stencil_layouts = true; std::uint32_t max_push_constants_size = 0; bool push_constants_need_fallback = false; + bool presentation = false; // VK_KHR_surface + VK_KHR_win32_surface on the instance, VK_KHR_swapchain on the device }; // A Vulkan-backed ID3D12Device (PC ABI, up to ID3D12Device11) on caller-owned Vulkan objects, which must outlive @@ -62,6 +69,29 @@ std::uint32_t device_max_push_constants_size(ID3D12Device* device); // the uniform-buffer fallback for the 16-byte tail (heap/code base). bool device_push_constants_need_fallback(ID3D12Device* device); +// Puts back buffers of a device from create_vulkan_device* into a window (leonida::VulkanPresenter), for the +// presentation front end the game uses (DXGI or PresentX, still open). Holds a reference to the device. +class WindowPresenter { +public: + WindowPresenter(IUnknown* device, std::unique_ptr presenter); + ~WindowPresenter(); + WindowPresenter(const WindowPresenter&) = delete; + WindowPresenter& operator=(const WindowPresenter&) = delete; + + // `back_buffer` is a colour texture in D3D12's PRESENT state. sync_interval 0 presents without vsync. + // S_OK also covers a skipped present while the window is minimised. + HRESULT present(ID3D12Resource* back_buffer, UINT sync_interval); + VkExtent2D extent() const; + std::uint64_t presented() const; + +private: + IUnknown* device_; + std::unique_ptr presenter_; +}; + +// Null when `device` is not a Vulkan device created with presentation, or the window cannot be presented to. +std::unique_ptr create_window_presenter(ID3D12Device* device, HWND window); + // ExecuteCommandLists returns void; this is what the last call on the queue did. leonida::ReplayResult last_execute_result(ID3D12CommandQueue* queue); diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index e3def8865..8db9da89f 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -7,6 +7,9 @@ #include "d3d12_stubs.h" // generated #include "d3d12_com_object.h" #include "d3d12_xs_device.h" +#include "../src/vulkan_present.h" + +#include #include #include @@ -371,6 +374,8 @@ class Device final bool ok() const { return state_.context && state_.context->loaded(); } const VulkanDeviceInfo& info() const { return state_.info; } + const DeviceState& state() const { return state_; } + IUnknown* holder() { return identity(); } void own(const OwnedRuntime& owned) { owned_ = owned; } void set_outer(IUnknown* outer) { outer_ = outer; } @@ -798,6 +803,53 @@ bool device_push_constants_need_fallback(ID3D12Device* device) { return false; } +WindowPresenter::WindowPresenter(IUnknown* device, std::unique_ptr presenter) + : device_(device), presenter_(std::move(presenter)) { + device_->AddRef(); +} + +WindowPresenter::~WindowPresenter() { + presenter_.reset(); // before the device it runs on + device_->Release(); +} + +HRESULT WindowPresenter::present(ID3D12Resource* back_buffer, UINT sync_interval) { + if (!back_buffer) return E_INVALIDARG; + const VkResult result = presenter_->present(resource_id(back_buffer), sync_interval > 0); + if (result == VK_SUCCESS) return S_OK; + std::fprintf(stderr, "[rt] d3d12: present failed (VkResult %d)\n", int(result)); + return result == VK_ERROR_DEVICE_LOST ? DXGI_ERROR_DEVICE_REMOVED : E_FAIL; +} + +VkExtent2D WindowPresenter::extent() const { return presenter_->extent(); } +std::uint64_t WindowPresenter::presented() const { return presenter_->presented(); } + +std::unique_ptr create_window_presenter(ID3D12Device* device, HWND window) { + Device* d = Device::from(device); + if (!d || !window) return nullptr; + const VulkanDeviceInfo& info = d->state().info; + if (!info.presentation) { + std::fprintf(stderr, "[rt] d3d12: the Vulkan device was created without presentation support\n"); + return nullptr; + } + const auto create_surface = reinterpret_cast( + info.get_instance_proc(info.instance, "vkCreateWin32SurfaceKHR")); + if (!create_surface) return nullptr; + VkWin32SurfaceCreateInfoKHR surface_info{VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR}; + surface_info.hinstance = GetModuleHandleW(nullptr); + surface_info.hwnd = window; + VkSurfaceKHR surface = VK_NULL_HANDLE; + if (create_surface(info.instance, &surface_info, nullptr, &surface) != VK_SUCCESS) return nullptr; + auto presenter = std::make_unique(*d->state().context, info.get_instance_proc, + info.instance, info.physical, info.queue, + info.queue_family, surface); // owns the surface + if (!presenter->ok()) { + std::fprintf(stderr, "[rt] d3d12: cannot present to this window from the device's queue family\n"); + return nullptr; + } + return std::make_unique(d->holder(), std::move(presenter)); +} + // Creates its own Vulkan 1.3 instance and device. LEONIDA_VK_VALIDATION=1 adds VK_LAYER_KHRONOS_validation. HRESULT create_vulkan_device_standalone(REFIID riid, void** out) { if (!out) return E_POINTER; @@ -811,11 +863,28 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out) { return E_FAIL; } const auto create_instance = reinterpret_cast(get(nullptr, "vkCreateInstance")); + const auto instance_extensions = reinterpret_cast( + get(nullptr, "vkEnumerateInstanceExtensionProperties")); + std::uint32_t extension_count = 0; + instance_extensions(nullptr, &extension_count, nullptr); + std::vector available(extension_count); + instance_extensions(nullptr, &extension_count, available.data()); + const auto has = [](const std::vector& list, const char* name) { + for (const auto& e : list) + if (std::strcmp(e.extensionName, name) == 0) return true; + return false; + }; + const char* surface_extensions[] = {VK_KHR_SURFACE_EXTENSION_NAME, VK_KHR_WIN32_SURFACE_EXTENSION_NAME}; + const bool surfaces = has(available, surface_extensions[0]) && has(available, surface_extensions[1]); VkApplicationInfo app{VK_STRUCTURE_TYPE_APPLICATION_INFO}; app.pApplicationName = "gta6rt"; app.apiVersion = VK_API_VERSION_1_3; VkInstanceCreateInfo instance_info{VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO}; instance_info.pApplicationInfo = &app; + if (surfaces) { + instance_info.enabledExtensionCount = 2; + instance_info.ppEnabledExtensionNames = surface_extensions; + } const char* layer = "VK_LAYER_KHRONOS_validation"; char validation[8] = {}; size_t length = 0; @@ -842,6 +911,7 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out) { LEONIDA_INSTANCE(vkGetPhysicalDeviceFeatures2); LEONIDA_INSTANCE(vkCreateDevice); LEONIDA_INSTANCE(vkGetDeviceProcAddr); + LEONIDA_INSTANCE(vkEnumerateDeviceExtensionProperties); #undef LEONIDA_INSTANCE std::uint32_t count = 0; vkEnumeratePhysicalDevices(owned.instance, &count, nullptr); @@ -902,6 +972,15 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out) { device_info.queueCreateInfoCount = 1; device_info.pQueueCreateInfos = &queue_info; device_info.pEnabledFeatures = &enable; + vkEnumerateDeviceExtensionProperties(info.physical, nullptr, &extension_count, nullptr); + std::vector device_extensions(extension_count); + vkEnumerateDeviceExtensionProperties(info.physical, nullptr, &extension_count, device_extensions.data()); + const char* swapchain = VK_KHR_SWAPCHAIN_EXTENSION_NAME; + info.presentation = surfaces && has(device_extensions, swapchain); + if (info.presentation) { + device_info.enabledExtensionCount = 1; + device_info.ppEnabledExtensionNames = &swapchain; + } if (vkCreateDevice(info.physical, &device_info, nullptr, &owned.device) != VK_SUCCESS) return fail("vkCreateDevice failed"); info.device = owned.device; diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index aea59705e..14203fa95 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -129,6 +129,7 @@ class VulkanContext { private: friend class VulkanQueue; + friend class VulkanPresenter; const ResourceBinding* resolve(ResourceId id) const { const auto it = resources_.find(id); diff --git a/runtime/src/vulkan_present.h b/runtime/src/vulkan_present.h new file mode 100644 index 000000000..818f85ac7 --- /dev/null +++ b/runtime/src/vulkan_present.h @@ -0,0 +1,346 @@ +#pragma once + +// Puts a D3D12 back buffer on screen through a Vulkan swapchain, for whichever front end the game turns out to use +// (DXGI or the console's PresentX; docs/d3d12_vulkan.md question 6). The back buffer is an ordinary texture in the +// D3D12 PRESENT (common) state; present() blits it to the acquired swapchain image, scaling if the window size +// differs, and queues the present. The application's own work reaches the same VkQueue first, so every draw it +// submitted before present() is in the frame. +// +// Needs VK_KHR_swapchain on the device and a surface from the caller (which this object then owns). The swapchain +// is recreated when the window changes size or the surface reports it out of date; a minimised window skips +// presents. Two frames are in flight; present() waits for the older one before reusing its command buffer. + +#include "vulkan_backend.h" + +#include +#include +#include +#include + +namespace leonida { + +class VulkanPresenter { +public: + VulkanPresenter(VulkanContext& context, PFN_vkGetInstanceProcAddr get_instance, VkInstance instance, + VkPhysicalDevice physical, VkQueue queue, std::uint32_t family, VkSurfaceKHR surface) + : context_(context), instance_(instance), physical_(physical), queue_(queue), surface_(surface) { +#define LEONIDA_INSTANCE_FN(name) name##_ = reinterpret_cast(get_instance(instance, #name)); + LEONIDA_INSTANCE_FN(vkGetPhysicalDeviceSurfaceSupportKHR) + LEONIDA_INSTANCE_FN(vkGetPhysicalDeviceSurfaceCapabilitiesKHR) + LEONIDA_INSTANCE_FN(vkGetPhysicalDeviceSurfaceFormatsKHR) + LEONIDA_INSTANCE_FN(vkGetPhysicalDeviceSurfacePresentModesKHR) + LEONIDA_INSTANCE_FN(vkDestroySurfaceKHR) + LEONIDA_INSTANCE_FN(vkGetDeviceProcAddr) +#undef LEONIDA_INSTANCE_FN + if (!vkGetDeviceProcAddr_ || !vkDestroySurfaceKHR_) return; + const VkDevice device = context.device(); +#define LEONIDA_DEVICE_FN(name) name##_ = reinterpret_cast(vkGetDeviceProcAddr_(device, #name)); + LEONIDA_DEVICE_FN(vkCreateSwapchainKHR) + LEONIDA_DEVICE_FN(vkDestroySwapchainKHR) + LEONIDA_DEVICE_FN(vkGetSwapchainImagesKHR) + LEONIDA_DEVICE_FN(vkAcquireNextImageKHR) + LEONIDA_DEVICE_FN(vkQueuePresentKHR) + LEONIDA_DEVICE_FN(vkCmdBlitImage) + LEONIDA_DEVICE_FN(vkCreateFence) + LEONIDA_DEVICE_FN(vkDestroyFence) + LEONIDA_DEVICE_FN(vkWaitForFences) + LEONIDA_DEVICE_FN(vkResetFences) +#undef LEONIDA_DEVICE_FN + if (!vkCreateSwapchainKHR_ || !vkQueuePresentKHR_ || !vkCmdBlitImage_ || !vkCreateFence_) return; + + VkBool32 supported = VK_FALSE; + vkGetPhysicalDeviceSurfaceSupportKHR_(physical, family, surface, &supported); + if (!supported) return; + + auto& vk = context.vk; + VkCommandPoolCreateInfo pool{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; + pool.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; + pool.queueFamilyIndex = family; + if (vk.vkCreateCommandPool(device, &pool, nullptr, &pool_) != VK_SUCCESS) return; + for (Frame& frame : frames_) { + VkCommandBufferAllocateInfo allocate{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; + allocate.commandPool = pool_; + allocate.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; + allocate.commandBufferCount = 1; + VkFenceCreateInfo fence{VK_STRUCTURE_TYPE_FENCE_CREATE_INFO}; + fence.flags = VK_FENCE_CREATE_SIGNALED_BIT; + VkSemaphoreCreateInfo semaphore{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO}; + if (vk.vkAllocateCommandBuffers(device, &allocate, &frame.commands) != VK_SUCCESS || + vkCreateFence_(device, &fence, nullptr, &frame.done) != VK_SUCCESS || + vk.vkCreateSemaphore(device, &semaphore, nullptr, &frame.acquired) != VK_SUCCESS) + return; + } + ok_ = recreate(true); + } + + ~VulkanPresenter() { + auto& vk = context_.vk; + const VkDevice device = context_.device(); + { + std::lock_guard lock(context_.submit_mutex()); + vk.vkQueueWaitIdle(queue_); + } + release(swapchain_); + swapchain_ = VK_NULL_HANDLE; + for (Frame& frame : frames_) { + if (frame.done) vkDestroyFence_(device, frame.done, nullptr); + if (frame.acquired) vk.vkDestroySemaphore(device, frame.acquired, nullptr); + } + if (pool_) vk.vkDestroyCommandPool(device, pool_, nullptr); + if (surface_ && vkDestroySurfaceKHR_) vkDestroySurfaceKHR_(instance_, surface_, nullptr); + } + + VulkanPresenter(const VulkanPresenter&) = delete; + VulkanPresenter& operator=(const VulkanPresenter&) = delete; + + bool ok() const { return ok_; } + VkExtent2D extent() const { return extent_; } + VkFormat format() const { return format_; } + std::uint64_t presented() const { return presented_; } + + // Blits the colour texture `source` (mip 0, layer 0, in D3D12's PRESENT state) to the window and presents it. + // vsync: FIFO; otherwise MAILBOX or IMMEDIATE when the surface has them. VK_SUCCESS also covers a skipped + // present (minimised window); VK_ERROR_OUT_OF_DATE_KHR only if recreating the swapchain failed. + VkResult present(ResourceId source, bool vsync) { + if (!ok_) return VK_ERROR_INITIALIZATION_FAILED; + if (vsync != vsync_ || stale_) { + if (!recreate(vsync)) return VK_ERROR_OUT_OF_DATE_KHR; + } + if (!swapchain_) { // minimised: try again next frame + stale_ = true; + return VK_SUCCESS; + } + auto& vk = context_.vk; + const VkDevice device = context_.device(); + Frame& frame = frames_[frame_index_ % frames_.size()]; + vkWaitForFences_(device, 1, &frame.done, VK_TRUE, UINT64_MAX); + + std::uint32_t image = 0; + VkResult acquired = vkAcquireNextImageKHR_(device, swapchain_, UINT64_MAX, frame.acquired, VK_NULL_HANDLE, &image); + if (acquired == VK_ERROR_OUT_OF_DATE_KHR) { + if (!recreate(vsync)) return acquired; + if (!swapchain_) return VK_SUCCESS; + acquired = vkAcquireNextImageKHR_(device, swapchain_, UINT64_MAX, frame.acquired, VK_NULL_HANDLE, &image); + } + if (acquired != VK_SUCCESS && acquired != VK_SUBOPTIMAL_KHR) return acquired; + if (acquired == VK_SUBOPTIMAL_KHR) stale_ = true; + + { + // The back buffer's layout is tracked like any other texture; this holds the context while it is read. + std::lock_guard lock(context_.mutex_); + const ResourceBinding* binding = context_.resolve(source); + if (!binding || !binding->image || binding->aspects != VK_IMAGE_ASPECT_COLOR_BIT) return VK_ERROR_UNKNOWN; + record(frame.commands, *binding, source, image); + } + vkResetFences_(device, 1, &frame.done); + const VkPipelineStageFlags wait_stage = VK_PIPELINE_STAGE_TRANSFER_BIT; + VkSubmitInfo submit{VK_STRUCTURE_TYPE_SUBMIT_INFO}; + submit.waitSemaphoreCount = 1; + submit.pWaitSemaphores = &frame.acquired; + submit.pWaitDstStageMask = &wait_stage; + submit.commandBufferCount = 1; + submit.pCommandBuffers = &frame.commands; + submit.signalSemaphoreCount = 1; + submit.pSignalSemaphores = &ready_[image]; // one per image: reused only once that image comes back + VkPresentInfoKHR present{VK_STRUCTURE_TYPE_PRESENT_INFO_KHR}; + present.waitSemaphoreCount = 1; + present.pWaitSemaphores = &ready_[image]; + present.swapchainCount = 1; + present.pSwapchains = &swapchain_; + present.pImageIndices = ℑ + VkResult result; + { + std::lock_guard lock(context_.submit_mutex()); + result = vk.vkQueueSubmit(queue_, 1, &submit, frame.done); + if (result != VK_SUCCESS) return result; + result = vkQueuePresentKHR_(queue_, &present); + } + ++frame_index_; + if (result == VK_ERROR_OUT_OF_DATE_KHR || result == VK_SUBOPTIMAL_KHR) { + stale_ = true; + result = VK_SUCCESS; + } + if (result == VK_SUCCESS) ++presented_; + return result; + } + +private: + struct Frame { + VkCommandBuffer commands = VK_NULL_HANDLE; + VkFence done = VK_NULL_HANDLE; + VkSemaphore acquired = VK_NULL_HANDLE; + }; + + void record(VkCommandBuffer commands, const ResourceBinding& binding, ResourceId source, std::uint32_t image) { + auto& vk = context_.vk; + const ReplayFunctions& fn = context_.replay_; + vk.vkResetCommandBuffer(commands, 0); + VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; + begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; + vk.vkBeginCommandBuffer(commands, &begin); + + constexpr VkAccessFlags any = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT; + const VkImageSubresourceRange range{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; + // PRESENT is D3D12's common state: GENERAL for an ordinary texture. A never-written back buffer is + // zero-filled first, as any committed resource is. + const VkImageLayout common = image_layout(binding, VK_IMAGE_LAYOUT_GENERAL); + auto pieces = detail::current(&context_.tracker_, source, range, common); + detail::initialize(fn, commands, binding, source, pieces, common, &context_.tracker_); + for (const auto& piece : pieces) + detail::image_barrier(fn, commands, binding.image, piece.range, piece.layout, + VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_MEMORY_WRITE_BIT, + VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_TRANSFER_READ_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT); + // The acquire semaphore is waited at the transfer stage, so the swapchain image's barrier starts there. + detail::image_barrier(fn, commands, images_[image], range, VK_IMAGE_LAYOUT_UNDEFINED, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 0, VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT); + + const std::int32_t sw = std::int32_t(binding.width), sh = std::int32_t(binding.height); + const std::int32_t dw = std::int32_t(extent_.width), dh = std::int32_t(extent_.height); + VkImageBlit blit{}; + blit.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; + blit.srcOffsets[1] = {sw, sh, 1}; + blit.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; + blit.dstOffsets[1] = {dw, dh, 1}; + vkCmdBlitImage_(commands, binding.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, images_[image], + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit, + sw == dw && sh == dh ? VK_FILTER_NEAREST : VK_FILTER_LINEAR); + + detail::image_barrier(fn, commands, images_[image], range, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, VK_ACCESS_TRANSFER_WRITE_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, 0, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT); + for (const auto& piece : pieces) + detail::image_barrier(fn, commands, binding.image, piece.range, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, + piece.layout, VK_ACCESS_TRANSFER_READ_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, any, + VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); + vk.vkEndCommandBuffer(commands); + } + + // (Re)creates the swapchain for the surface's current size. A zero-sized surface (minimised) leaves no + // swapchain and is retried on the next present. + bool recreate(bool vsync) { + auto& vk = context_.vk; + const VkDevice device = context_.device(); + { + std::lock_guard lock(context_.submit_mutex()); + vk.vkQueueWaitIdle(queue_); // the old swapchain's images and semaphores may still be in use + } + VkSurfaceCapabilitiesKHR caps{}; + if (vkGetPhysicalDeviceSurfaceCapabilitiesKHR_(physical_, surface_, &caps) != VK_SUCCESS) return false; + vsync_ = vsync; + stale_ = false; + VkSwapchainKHR old = swapchain_; + swapchain_ = VK_NULL_HANDLE; + if (caps.currentExtent.width == 0 || caps.currentExtent.height == 0) { + release(old); + return true; + } + if (!(caps.supportedUsageFlags & VK_IMAGE_USAGE_TRANSFER_DST_BIT)) return false; + + std::uint32_t count = 0; + vkGetPhysicalDeviceSurfaceFormatsKHR_(physical_, surface_, &count, nullptr); + std::vector formats(count); + vkGetPhysicalDeviceSurfaceFormatsKHR_(physical_, surface_, &count, formats.data()); + if (formats.empty()) return false; + VkSurfaceFormatKHR chosen = formats[0]; + for (const auto& f : formats) + if ((f.format == VK_FORMAT_B8G8R8A8_UNORM || f.format == VK_FORMAT_R8G8B8A8_UNORM) && + f.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) { + chosen = f; + break; + } + vkGetPhysicalDeviceSurfacePresentModesKHR_(physical_, surface_, &count, nullptr); + std::vector modes(count); + vkGetPhysicalDeviceSurfacePresentModesKHR_(physical_, surface_, &count, modes.data()); + VkPresentModeKHR mode = VK_PRESENT_MODE_FIFO_KHR; // always available + if (!vsync) { + for (const VkPresentModeKHR wanted : {VK_PRESENT_MODE_MAILBOX_KHR, VK_PRESENT_MODE_IMMEDIATE_KHR}) + if (std::find(modes.begin(), modes.end(), wanted) != modes.end()) { + mode = wanted; + break; + } + } + + VkSwapchainCreateInfoKHR info{VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR}; + info.surface = surface_; + info.minImageCount = std::max(caps.minImageCount + 1, 2u); + if (caps.maxImageCount) info.minImageCount = std::min(info.minImageCount, caps.maxImageCount); + info.imageFormat = chosen.format; + info.imageColorSpace = chosen.colorSpace; + info.imageExtent = caps.currentExtent; + info.imageArrayLayers = 1; + info.imageUsage = VK_IMAGE_USAGE_TRANSFER_DST_BIT; + info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; + info.preTransform = caps.currentTransform; + info.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; + if (!(caps.supportedCompositeAlpha & info.compositeAlpha)) info.compositeAlpha = VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR; + info.presentMode = mode; + info.clipped = VK_TRUE; + info.oldSwapchain = old; + const VkResult created = vkCreateSwapchainKHR_(device, &info, nullptr, &swapchain_); + release(old); + if (created != VK_SUCCESS) { + swapchain_ = VK_NULL_HANDLE; + return false; + } + format_ = chosen.format; + extent_ = caps.currentExtent; + vkGetSwapchainImagesKHR_(device, swapchain_, &count, nullptr); + images_.resize(count); + vkGetSwapchainImagesKHR_(device, swapchain_, &count, images_.data()); + ready_.assign(count, VK_NULL_HANDLE); + for (VkSemaphore& semaphore : ready_) { + VkSemaphoreCreateInfo semaphore_info{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO}; + if (vk.vkCreateSemaphore(device, &semaphore_info, nullptr, &semaphore) != VK_SUCCESS) return false; + } + return true; + } + + // Destroys a swapchain that is being replaced (or the last one), with the per-image semaphores that went with it. + void release(VkSwapchainKHR swapchain) { + const VkDevice device = context_.device(); + for (VkSemaphore semaphore : ready_) + if (semaphore) context_.vk.vkDestroySemaphore(device, semaphore, nullptr); + ready_.clear(); + images_.clear(); + if (swapchain) vkDestroySwapchainKHR_(device, swapchain, nullptr); + } + + VulkanContext& context_; + VkInstance instance_; + VkPhysicalDevice physical_; + VkQueue queue_; + VkSurfaceKHR surface_; + VkSwapchainKHR swapchain_ = VK_NULL_HANDLE; + VkFormat format_ = VK_FORMAT_UNDEFINED; + VkExtent2D extent_{}; + std::vector images_; + std::vector ready_; // per swapchain image: blit done, present may start + std::array frames_{}; + VkCommandPool pool_ = VK_NULL_HANDLE; + std::uint64_t frame_index_ = 0; + std::uint64_t presented_ = 0; + bool vsync_ = true; + bool stale_ = false; + bool ok_ = false; + + PFN_vkGetPhysicalDeviceSurfaceSupportKHR vkGetPhysicalDeviceSurfaceSupportKHR_ = nullptr; + PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR vkGetPhysicalDeviceSurfaceCapabilitiesKHR_ = nullptr; + PFN_vkGetPhysicalDeviceSurfaceFormatsKHR vkGetPhysicalDeviceSurfaceFormatsKHR_ = nullptr; + PFN_vkGetPhysicalDeviceSurfacePresentModesKHR vkGetPhysicalDeviceSurfacePresentModesKHR_ = nullptr; + PFN_vkDestroySurfaceKHR vkDestroySurfaceKHR_ = nullptr; + PFN_vkGetDeviceProcAddr vkGetDeviceProcAddr_ = nullptr; + PFN_vkCreateSwapchainKHR vkCreateSwapchainKHR_ = nullptr; + PFN_vkDestroySwapchainKHR vkDestroySwapchainKHR_ = nullptr; + PFN_vkGetSwapchainImagesKHR vkGetSwapchainImagesKHR_ = nullptr; + PFN_vkAcquireNextImageKHR vkAcquireNextImageKHR_ = nullptr; + PFN_vkQueuePresentKHR vkQueuePresentKHR_ = nullptr; + PFN_vkCmdBlitImage vkCmdBlitImage_ = nullptr; + PFN_vkCreateFence vkCreateFence_ = nullptr; + PFN_vkDestroyFence vkDestroyFence_ = nullptr; + PFN_vkWaitForFences vkWaitForFences_ = nullptr; + PFN_vkResetFences vkResetFences_ = nullptr; +}; + +} // namespace leonida diff --git a/runtime/test/d3d12_present_test.cpp b/runtime/test/d3d12_present_test.cpp new file mode 100644 index 000000000..18ab22d5e --- /dev/null +++ b/runtime/test/d3d12_present_test.cpp @@ -0,0 +1,198 @@ +// Milestone M0 (docs/d3d12_vulkan.md section 6): a window shows a stable clear colour for 60 frames, through the +// Vulkan-backed device behind the Xbox-ABI proxy, with no Vulkan validation errors. Each frame resets the list, +// moves the back buffer PRESENT -> RENDER_TARGET, clears it, moves it back, executes, presents and signals a fence. +// The window is then resized, which recreates the swapchain and scales the blit. Last, the colour on screen is read +// back with GDI when the window is in front (skipped otherwise, e.g. on a locked desktop). No shaders or game data. +// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation; any validation error fails the test. +#include "vk_test_device.h" +#include "../shims/d3d12_com.h" +#include "../shims/d3d12_xs_device.h" + +#include +#include + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +namespace { + +using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slot 9: 8-byte handle in RAX + +template +struct Ref { + T* p = nullptr; + ~Ref() { reset(); } + void reset() { + if (p) p->Release(); + p = nullptr; + } + T* operator->() const { return p; } +}; + +LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM w, LPARAM l) { + return DefWindowProcW(window, message, w, l); +} + +void pump() { + MSG message; + while (PeekMessageW(&message, nullptr, 0, 0, PM_REMOVE)) { + TranslateMessage(&message); + DispatchMessageW(&message); + } +} + +void set_client_size(HWND window, int width, int height) { + RECT rect{0, 0, width, height}; + AdjustWindowRect(&rect, WS_OVERLAPPEDWINDOW, FALSE); + SetWindowPos(window, HWND_TOP, 0, 0, rect.right - rect.left, rect.bottom - rect.top, + SWP_NOMOVE | SWP_NOZORDER | SWP_SHOWWINDOW); +} + +} // namespace + +int main() { + vktest::Device d; + EXPECT(d.create(true)); + + WNDCLASSW window_class{}; + window_class.lpfnWndProc = window_proc; + window_class.hInstance = GetModuleHandleW(nullptr); + window_class.lpszClassName = L"LeonidaPresentTest"; + window_class.hCursor = LoadCursorW(nullptr, reinterpret_cast(IDC_ARROW)); + EXPECT(RegisterClassW(&window_class)); + constexpr int width = 320, height = 240; + RECT frame_rect{0, 0, width, height}; + AdjustWindowRect(&frame_rect, WS_OVERLAPPEDWINDOW, FALSE); + HWND window = CreateWindowExW(0, window_class.lpszClassName, L"Leonida M0: D3D12 clear on Vulkan", + WS_OVERLAPPEDWINDOW, 100, 100, frame_rect.right - frame_rect.left, + frame_rect.bottom - frame_rect.top, nullptr, nullptr, window_class.hInstance, + nullptr); + EXPECT(window); + ShowWindow(window, SW_SHOWNORMAL); + SetForegroundWindow(window); + UpdateWindow(window); + pump(); + + const FLOAT colour[4] = {0.2f, 0.6f, 0.9f, 1.0f}; + bool screen_checked = false; + { + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = d.instance_proc; + info.instance = d.instance; + info.physical = d.physical; + info.device = d.device; + info.queue = d.queue; + info.queue_family = d.family; + info.presentation = true; + ID3D12Device* inner = nullptr; + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); + Ref device; + EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), + reinterpret_cast(&device.p)))); + rt::d3d12::set_device_outer(inner, device.p); + auto presenter = rt::d3d12::create_window_presenter(inner, window); + EXPECT(presenter); + + D3D12_COMMAND_QUEUE_DESC queue_desc{}; + Ref queue; + Ref allocator; + Ref list; + Ref fence; + Ref rtv_heap; + Ref back_buffer; + EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); + EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); + EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, + IID_PPV_ARGS(&list.p)))); + EXPECT(SUCCEEDED(list->Close())); + EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&rtv_heap.p)))); + const D3D12_CPU_DESCRIPTOR_HANDLE rtv{SIZE_T(reinterpret_cast( + (*reinterpret_cast(rtv_heap.p))[9])(rtv_heap.p))}; + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Width = width; + desc.Height = height; + desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + desc.SampleDesc.Count = 1; + desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &desc, + D3D12_RESOURCE_STATE_PRESENT, nullptr, + IID_PPV_ARGS(&back_buffer.p)))); + device->CreateRenderTargetView(back_buffer.p, nullptr, rtv); + + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barrier.Transition.pResource = back_buffer.p; + barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + ID3D12CommandList* lists[] = {list.p}; + UINT64 signalled = 0; + const auto frame = [&](UINT sync_interval) -> bool { + pump(); + if (FAILED(fence->SetEventOnCompletion(signalled, nullptr))) return false; // the list's last run is done + if (FAILED(allocator->Reset()) || FAILED(list->Reset(allocator.p, nullptr))) return false; + barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_PRESENT; + barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_RENDER_TARGET; + list->ResourceBarrier(1, &barrier); + list->ClearRenderTargetView(rtv, colour, 0, nullptr); + barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET; + barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_PRESENT; + list->ResourceBarrier(1, &barrier); + if (FAILED(list->Close())) return false; + queue->ExecuteCommandLists(1, lists); + if (rt::d3d12::last_execute_result(queue.p) != leonida::ReplayResult::success) return false; + if (FAILED(presenter->present(back_buffer.p, sync_interval))) return false; + return SUCCEEDED(queue->Signal(fence.p, ++signalled)); + }; + + for (int i = 0; i < 60; ++i) EXPECT(frame(1)); + EXPECT(presenter->presented() == 60); + const VkExtent2D first = presenter->extent(); + EXPECT(first.width == width && first.height == height); + + // A resize recreates the swapchain; the 320x240 back buffer is scaled to the new size. Unsynchronised + // presents (sync interval 0) switch the present mode on the way. + set_client_size(window, 400, 300); + for (int i = 0; i < 10; ++i) EXPECT(frame(i < 5 ? 1 : 0)); + EXPECT(presenter->extent().width == 400 && presenter->extent().height == 300); + EXPECT(presenter->presented() == 70); + EXPECT(SUCCEEDED(fence->SetEventOnCompletion(signalled, nullptr))); + + // What reached the screen: the centre of the client area, if the window is in front. + Sleep(200); + pump(); + if (GetForegroundWindow() == window && !IsIconic(window)) { + RECT client{}; + GetClientRect(window, &client); + POINT centre{(client.right - client.left) / 2, (client.bottom - client.top) / 2}; + ClientToScreen(window, ¢re); + HDC screen = GetDC(nullptr); + const COLORREF pixel = GetPixel(screen, centre.x, centre.y); + ReleaseDC(nullptr, screen); + const int r = GetRValue(pixel), g = GetGValue(pixel), b = GetBValue(pixel); + std::printf("screen pixel at the window centre: %d,%d,%d (cleared to 51,153,230)\n", r, g, b); + EXPECT(pixel != CLR_INVALID); + EXPECT(std::abs(r - 51) <= 3 && std::abs(g - 153) <= 3 && std::abs(b - 230) <= 3); + screen_checked = true; + } else { + std::printf("the window is not in front: on-screen colour check skipped\n"); + } + + presenter.reset(); // before the device's queue and resources go + } + DestroyWindow(window); + UnregisterClassW(window_class.lpszClassName, window_class.hInstance); + + if (d.validation_errors()) { + std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); + return 1; + } + std::printf("M0: 70 frames cleared and presented through the Xbox-ABI proxy on Vulkan, swapchain recreated on " + "resize%s\n", screen_checked ? ", colour confirmed on screen" : ""); + return 0; +} diff --git a/runtime/test/vk_test_device.h b/runtime/test/vk_test_device.h index faac77f64..81f63835b 100644 --- a/runtime/test/vk_test_device.h +++ b/runtime/test/vk_test_device.h @@ -80,7 +80,8 @@ class Device { unsigned validation_errors() const { return validation_error_count(); } - bool create() { + // presentation: also enable VK_KHR_surface + VK_KHR_win32_surface and VK_KHR_swapchain (Windows only). + bool create(bool presentation = false) { instance_proc = load_vulkan(); if (!instance_proc) return false; const auto create_instance = reinterpret_cast(instance_proc(nullptr, "vkCreateInstance")); @@ -110,6 +111,11 @@ class Device { app.apiVersion = VK_API_VERSION_1_3; VkInstanceCreateInfo instance_info{VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO}; instance_info.pApplicationInfo = &app; + std::vector extensions; + if (presentation) { + extensions.push_back("VK_KHR_surface"); + extensions.push_back("VK_KHR_win32_surface"); + } if (validation) { std::uint32_t count = 0; enumerate_layers(&count, nullptr); @@ -124,9 +130,10 @@ class Device { instance_info.pNext = &messenger_info; instance_info.enabledLayerCount = 1; instance_info.ppEnabledLayerNames = &layer; - instance_info.enabledExtensionCount = 1; - instance_info.ppEnabledExtensionNames = &debug_utils; + extensions.push_back(debug_utils); } + instance_info.enabledExtensionCount = std::uint32_t(extensions.size()); + instance_info.ppEnabledExtensionNames = extensions.data(); if (create_instance(&instance_info, nullptr, &instance) != VK_SUCCESS) return false; if (validation && instance_fn("vkCreateDebugUtilsMessengerEXT")( @@ -195,6 +202,11 @@ class Device { device_info.queueCreateInfoCount = 1; device_info.pQueueCreateInfos = &queue_info; device_info.pEnabledFeatures = &enable; + const char* swapchain = "VK_KHR_swapchain"; + if (presentation) { + device_info.enabledExtensionCount = 1; + device_info.ppEnabledExtensionNames = &swapchain; + } if (instance_fn("vkCreateDevice")(physical, &device_info, nullptr, &device) != VK_SUCCESS) return false; device_proc = instance_fn("vkGetDeviceProcAddr"); From 37322277396ee940a7a6c6519afe0f06df6ae927 Mon Sep 17 00:00:00 2001 From: Ryx <118130241+Ryx69@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:14:20 +0100 Subject: [PATCH 2/9] GPU tests: count only validation-type errors (review feedback) The debug messenger in test/vk_test_device.h counted every error-severity message, so a broken third-party implicit layer (ReShade's, reported on an RTX 5090) failed every GPU test. Only VALIDATION-type errors are counted now; general loader and layer messages are still printed, marked "not counted". A real validation error still fails the test (checked by replaying part B of vk_command_replay_test without the layout tracker). runtime/README.md says so and mentions VK_LOADER_LAYERS_DISABLE. --- runtime/README.md | 3 +++ runtime/test/vk_test_device.h | 11 ++++++++--- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/runtime/README.md b/runtime/README.md index 451b8d8c3..9b980003c 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -95,6 +95,9 @@ when the Vulkan SDK is found: - `vk_texture_test`, `vk_compute_test`, `vk_store_test` — texture, LDS/compute, and buffer-store paths. - `vk_command_replay_test`, `d3d12_com_test`, `d3d12_vulkan_device_test` — the D3D12 command path on Vulkan: replay, the COM command objects, and the Vulkan device behind the Xbox-ABI proxy. +- GPU tests count only validation-type errors. Loader and layer messages, such as a third-party implicit layer + that fails to load, are printed but don't fail the run; to silence one, set + `VK_LOADER_LAYERS_DISABLE=`. - `d3d12_present_test` — milestone M0: opens a window and presents 60 cleared frames through the proxy on Vulkan, resizes it, and checks the colour on screen. Set `LEONIDA_VK_VALIDATION=1` to run them under the Khronos validation layer. diff --git a/runtime/test/vk_test_device.h b/runtime/test/vk_test_device.h index 81f63835b..aeb3095a8 100644 --- a/runtime/test/vk_test_device.h +++ b/runtime/test/vk_test_device.h @@ -19,11 +19,16 @@ inline unsigned& validation_error_count() { return count; } +// Only validation-type errors fail a test. General messages come from the loader and the layers around the +// application: a third-party implicit layer that fails to load (an overlay or capture tool, for example) reports a +// general error that says nothing about this code, so it is printed but not counted. inline VKAPI_ATTR VkBool32 VKAPI_CALL on_validation(VkDebugUtilsMessageSeverityFlagBitsEXT severity, - VkDebugUtilsMessageTypeFlagsEXT, + VkDebugUtilsMessageTypeFlagsEXT types, const VkDebugUtilsMessengerCallbackDataEXT* data, void*) { - if (severity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) ++validation_error_count(); - std::fprintf(stderr, "validation: %s\n", data && data->pMessage ? data->pMessage : "(no message)"); + const bool validation = (types & VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT) != 0; + if ((severity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) && validation) ++validation_error_count(); + std::fprintf(stderr, "%s: %s\n", validation ? "validation" : "vulkan (not counted)", + data && data->pMessage ? data->pMessage : "(no message)"); return VK_FALSE; } From b45eb0f02232dc3566d7b1aab1944641c0fb0283 Mon Sep 17 00:00:00 2001 From: Ryx <118130241+Ryx69@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:57:41 +0100 Subject: [PATCH 3/9] Runtime: compute groundwork (FSSM shader lookup, Dispatch in the IR) First pieces of D3D-3 (compute path), no pipelines wired up yet: - shader_library.h: FSSM extraction from the DXBC container (DXIL, XDAT 0x0D, XBCH, zlib), SHA-256, a minimal JSON reader and the spirv/index.json lookup by fssm_sha256. Self-contained inflate, no dependencies. - IR Dispatch with user data captured at record time; replay binds the pipeline, pushes the 144-byte block (s0..s31, heap base, code base) and dispatches. Arena buffers get a buffer_offset that copies honour. - Root signatures use main's model (runtime/src/root_signature.h); the docs say so. Tests: shader_library_test (FIPS 180-4 vectors; stored, fixed and dynamic deflate blocks; corrupt and truncated streams; FSSM from a synthetic container) joins ctest; command_list_test covers dispatch recording. --- docs/d3d12_vulkan.md | 12 + runtime/CMakeLists.txt | 2 + runtime/src/command_list.h | 23 +- runtime/src/shader_library.h | 565 +++++++++++++++++++++++++++ runtime/src/vulkan_backend.h | 36 +- runtime/src/vulkan_replay.h | 44 ++- runtime/test/command_list_test.cpp | 15 + runtime/test/shader_library_test.cpp | 176 +++++++++ 8 files changed, 865 insertions(+), 8 deletions(-) create mode 100644 runtime/src/shader_library.h create mode 100644 runtime/test/shader_library_test.cpp diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 503a512da..4dd5fb954 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -254,6 +254,18 @@ Two pieces of milestone M2 that the device does not use yet, built and tested on a table that has grown gets a new buffer behind binding 2: `flush_needs_idle()` says when a flush would do either, so the owner can wait until no command buffer that uses the set is still running. +Started for the compute path (no pipelines yet): +- `runtime/src/shader_library.h` finds the translated SPIR-V for a shader the game hands to D3D12 (section 3.6). + It extracts the FSSM program from the DXBC container (DXIL → XDAT entry 0x0D → XBCH → zlib) and looks up its + SHA-256 as `fssm_sha256` in `spirv/index.json`. Its own inflate, SHA-256 and JSON reader keep it free of + dependencies (`shader_library_test`). +- Root signatures use the model already on `main` (`runtime/src/root_signature.h`, `rt::rootsig`): `parse_rts0` + reads the serialized blob and `pack()` lays out the 32 user-data dwords by the section 3.5 default mapping, + refusing anything that would spill. +- The IR records `Dispatch` with its user data captured at record time. Replay binds the pipeline, pushes the + 144-byte block (s0..s31, heap base, code base) and dispatches. Not wired up yet: the GPU address arena, + `CreateRootSignature`, compute PSOs and the command list's root-argument setters. + Known gaps: the game's present entry point (DXGI factory/swapchain or `PresentX`; the presenter above is what either calls), HDR and fullscreen; shader-resource, UAV and constant-buffer views, samplers, root signatures, PSOs, draws, volume attachment views, placed and reserved resources, `GetGPUVirtualAddress` (the shared buffer arena), diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index b96a27141..1814522ae 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -220,6 +220,8 @@ if(BUILD_TESTING) add_test(NAME command_list COMMAND command_list_test) add_executable(descriptor_table_test test/descriptor_table_test.cpp) add_test(NAME descriptor_table COMMAND descriptor_table_test) + add_executable(shader_library_test test/shader_library_test.cpp) + add_test(NAME shader_library COMMAND shader_library_test) if(WIN32) # Optional: skips unless LEONIDA_GAME_DIR and LEONIDA_MOVIE are set. add_executable(bink_decode_test diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h index 83b5df40d..3ffb9e002 100644 --- a/runtime/src/command_list.h +++ b/runtime/src/command_list.h @@ -2,8 +2,8 @@ // The command-list IR (docs/d3d12_vulkan.md section 3.2): what a D3D12 command list records, kept until // ExecuteCommandLists replays it on Vulkan (vulkan_replay.h). This slice covers legacy and enhanced barriers and -// render-target and depth-stencil clears (whole views or rectangles), copies and resolves. It has no Windows or -// Vulkan dependency. +// render-target and depth-stencil clears (whole views or rectangles), copies, resolves and dispatches. It has no +// Windows or Vulkan dependency. #include #include @@ -278,6 +278,16 @@ struct ResolveSubresource { std::uint32_t src_subresource; }; +// Dispatch, with what it uses captured when it is recorded: the pipeline (an opaque id the replay resolves) and +// the 32 user-data dwords the root arguments produced (s0..s31 of the translated shader, section 3.5). +struct Dispatch { + std::uintptr_t pipeline; + std::array user_data; + std::uint32_t x; + std::uint32_t y; + std::uint32_t z; +}; + // D3D12_TEXTURE_DATA_PITCH_ALIGNMENT and D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT. inline constexpr std::uint32_t texture_data_pitch_alignment = 256; inline constexpr std::uint32_t texture_data_placement_alignment = 512; @@ -298,7 +308,7 @@ struct ClearDepthStencil { using Command = std::variant; + CopyResource, ResolveSubresource, Dispatch>; class CommandList { public: @@ -366,6 +376,13 @@ class CommandList { return append(resolve); } + // A dispatch with no groups does nothing in D3D12, and is not recorded. + bool dispatch(const Dispatch& dispatch) { + if (!dispatch.pipeline) return false; + if (!dispatch.x || !dispatch.y || !dispatch.z) return !closed_; + return append(dispatch); + } + // ClearRenderTargetView; the resource must be in render_target state at execution. No rects: the whole view. bool clear_render_target(const TargetView& target, const ClearColor& color, std::span rects = {}) { if (!valid(target)) return false; diff --git a/runtime/src/shader_library.h b/runtime/src/shader_library.h new file mode 100644 index 000000000..ee5c0a976 --- /dev/null +++ b/runtime/src/shader_library.h @@ -0,0 +1,565 @@ +#pragma once + +// Finds the translated SPIR-V for a shader the game hands to D3D12 (docs/d3d12_vulkan.md section 3.6). +// +// A pipeline's bytecode is a DXBC container. Its DXIL part holds an XDAT table whose entry 0x0D is an XBCH header +// followed by a zlib stream; the stream inflates to the FSSM blob, the native RDNA2 program the translator read +// (tools/fssm_unpack.py does the same in Python). The SHA-256 of that blob is the `fssm_sha256` field the translator +// writes into `spirv/index.json`, next to `.spv`. This header needs no Windows, Vulkan or third-party code: +// it carries its own inflate (RFC 1950/1951), SHA-256 (FIPS 180-4) and a minimal JSON reader. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace leonida { + +// --------------------------------------------------------------------------------------------------------------- +// zlib inflate + +namespace detail { + +class BitReader { +public: + explicit BitReader(std::span in) : in_(in) {} + + std::uint32_t bits(int need) { + std::uint64_t value = buffer_; + while (count_ < need) { + if (pos_ >= in_.size()) { + failed_ = true; + return 0; + } + value |= std::uint64_t(in_[pos_++]) << count_; + count_ += 8; + } + buffer_ = value >> need; + count_ -= need; + return std::uint32_t(value & ((std::uint64_t(1) << need) - 1)); + } + + void align() { + buffer_ = 0; + count_ = 0; + } + + bool byte(std::uint8_t& out) { + if (pos_ >= in_.size()) return failed_ = true, false; + out = in_[pos_++]; + return true; + } + + std::size_t position() const { return pos_; } + bool failed() const { return failed_; } + +private: + std::span in_; + std::size_t pos_ = 0; + std::uint64_t buffer_ = 0; + int count_ = 0; + bool failed_ = false; +}; + +struct Huffman { + std::array count{}; + std::array symbol{}; +}; + +// Canonical Huffman table from code lengths. Returns false for an over-subscribed set. +inline bool build_huffman(Huffman& h, const std::int16_t* lengths, int n) { + h.count.fill(0); + for (int i = 0; i < n; ++i) ++h.count[lengths[i]]; + if (h.count[0] == n) return true; // no codes: valid only if never used + int left = 1; + for (int len = 1; len < 16; ++len) { + left <<= 1; + left -= h.count[len]; + if (left < 0) return false; + } + std::array offsets{}; + for (int len = 1; len < 15; ++len) offsets[len + 1] = std::int16_t(offsets[len] + h.count[len]); + for (int i = 0; i < n; ++i) + if (lengths[i]) h.symbol[offsets[lengths[i]]++] = std::int16_t(i); + return true; +} + +inline int decode(BitReader& in, const Huffman& h) { + int code = 0, first = 0, index = 0; + for (int len = 1; len < 16; ++len) { + code |= int(in.bits(1)); + const int count = h.count[len]; + if (code - count < first) return h.symbol[index + (code - first)]; + index += count; + first += count; + first <<= 1; + code <<= 1; + if (in.failed()) return -1; + } + return -1; +} + +inline bool inflate_codes(BitReader& in, std::vector& out, const Huffman& lengths, + const Huffman& distances, std::size_t limit) { + static constexpr std::int16_t length_base[29] = {3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, + 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258}; + static constexpr std::int16_t length_extra[29] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, + 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0}; + static constexpr std::int16_t distance_base[30] = {1, 2, 3, 4, 5, 7, 9, 13, 17, 25, + 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, + 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577}; + static constexpr std::int16_t distance_extra[30] = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, + 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13}; + for (;;) { + int symbol = decode(in, lengths); + if (symbol < 0 || in.failed()) return false; + if (symbol < 256) { + if (out.size() >= limit) return false; + out.push_back(std::uint8_t(symbol)); + continue; + } + if (symbol == 256) return true; + symbol -= 257; + if (symbol >= 29) return false; + const std::size_t length = std::size_t(length_base[symbol]) + in.bits(length_extra[symbol]); + const int d = decode(in, distances); + if (d < 0 || d >= 30) return false; + const std::size_t distance = std::size_t(distance_base[d]) + in.bits(distance_extra[d]); + if (in.failed() || distance > out.size() || out.size() + length > limit) return false; + const std::size_t from = out.size() - distance; + for (std::size_t i = 0; i < length; ++i) out.push_back(out[from + i]); + } +} + +} // namespace detail + +// Inflates a zlib stream (RFC 1950: header, deflate data, Adler-32). Returns false for a malformed stream, a +// preset dictionary, a checksum mismatch, or output beyond `limit` bytes. +inline bool zlib_inflate(std::span in, std::vector& out, + std::size_t limit = std::size_t(1) << 30) { + out.clear(); + if (in.size() < 6) return false; + const unsigned cmf = in[0], flg = in[1]; + if ((cmf & 0x0f) != 8 || (cmf >> 4) > 7 || ((cmf << 8) | flg) % 31 != 0 || (flg & 0x20)) return false; + detail::BitReader reader(in.subspan(2)); + for (bool last = false; !last;) { + last = reader.bits(1) != 0; + const std::uint32_t type = reader.bits(2); + if (reader.failed()) return false; + if (type == 0) { // stored + reader.align(); + std::uint8_t b[4]; + for (auto& x : b) + if (!reader.byte(x)) return false; + const unsigned length = b[0] | (b[1] << 8), complement = b[2] | (b[3] << 8); + if (length != (~complement & 0xffff) || out.size() + length > limit) return false; + for (unsigned i = 0; i < length; ++i) { + std::uint8_t x; + if (!reader.byte(x)) return false; + out.push_back(x); + } + } else if (type == 1) { // fixed Huffman + static const auto tables = [] { + std::pair t; + std::int16_t lengths[288]; + for (int i = 0; i < 144; ++i) lengths[i] = 8; + for (int i = 144; i < 256; ++i) lengths[i] = 9; + for (int i = 256; i < 280; ++i) lengths[i] = 7; + for (int i = 280; i < 288; ++i) lengths[i] = 8; + detail::build_huffman(t.first, lengths, 288); + for (int i = 0; i < 30; ++i) lengths[i] = 5; + detail::build_huffman(t.second, lengths, 30); + return t; + }(); + if (!detail::inflate_codes(reader, out, tables.first, tables.second, limit)) return false; + } else if (type == 2) { // dynamic Huffman + const int literal_count = int(reader.bits(5)) + 257, distance_count = int(reader.bits(5)) + 1; + const int code_count = int(reader.bits(4)) + 4; + if (literal_count > 286 || distance_count > 30) return false; + static constexpr int order[19] = {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; + std::int16_t lengths[320] = {}; + for (int i = 0; i < code_count; ++i) lengths[order[i]] = std::int16_t(reader.bits(3)); + detail::Huffman code_lengths; + if (!detail::build_huffman(code_lengths, lengths, 19)) return false; + for (int i = 0; i < literal_count + distance_count;) { + const int symbol = detail::decode(reader, code_lengths); + if (symbol < 0) return false; + if (symbol < 16) { + lengths[i++] = std::int16_t(symbol); + continue; + } + std::int16_t value = 0; + int repeat; + if (symbol == 16) { + if (i == 0) return false; + value = lengths[i - 1]; + repeat = 3 + int(reader.bits(2)); + } else if (symbol == 17) { + repeat = 3 + int(reader.bits(3)); + } else { + repeat = 11 + int(reader.bits(7)); + } + if (i + repeat > literal_count + distance_count) return false; + while (repeat--) lengths[i++] = value; + } + if (lengths[256] == 0) return false; // no end-of-block code + detail::Huffman literal, distance; + if (!detail::build_huffman(literal, lengths, literal_count) || + !detail::build_huffman(distance, lengths + literal_count, distance_count)) + return false; + if (!detail::inflate_codes(reader, out, literal, distance, limit)) return false; + } else { + return false; + } + if (reader.failed()) return false; + } + // Adler-32, big-endian, after the deflate data's last whole byte. + const std::size_t at = 2 + reader.position(); + if (at + 4 > in.size()) return false; + std::uint32_t a = 1, b = 0; + for (const std::uint8_t x : out) { + a = (a + x) % 65521; + b = (b + a) % 65521; + } + const std::uint32_t expected = (std::uint32_t(in[at]) << 24) | (std::uint32_t(in[at + 1]) << 16) | + (std::uint32_t(in[at + 2]) << 8) | in[at + 3]; + return ((b << 16) | a) == expected; +} + +// --------------------------------------------------------------------------------------------------------------- +// SHA-256 + +inline std::string sha256_hex(std::span data) { + static constexpr std::uint32_t k[64] = { + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2}; + std::uint32_t h[8] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, + 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19}; + const auto rotr = [](std::uint32_t x, int n) { return (x >> n) | (x << (32 - n)); }; + std::vector message(data.begin(), data.end()); + const std::uint64_t bits = std::uint64_t(data.size()) * 8; + message.push_back(0x80); + while (message.size() % 64 != 56) message.push_back(0); + for (int i = 7; i >= 0; --i) message.push_back(std::uint8_t(bits >> (8 * i))); + for (std::size_t block = 0; block < message.size(); block += 64) { + std::uint32_t w[64]; + for (int i = 0; i < 16; ++i) + w[i] = (std::uint32_t(message[block + 4 * i]) << 24) | (std::uint32_t(message[block + 4 * i + 1]) << 16) | + (std::uint32_t(message[block + 4 * i + 2]) << 8) | message[block + 4 * i + 3]; + for (int i = 16; i < 64; ++i) { + const std::uint32_t s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >> 3); + const std::uint32_t s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >> 10); + w[i] = w[i - 16] + s0 + w[i - 7] + s1; + } + std::uint32_t a = h[0], b = h[1], c = h[2], d = h[3], e = h[4], f = h[5], g = h[6], hh = h[7]; + for (int i = 0; i < 64; ++i) { + const std::uint32_t t1 = hh + (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) + ((e & f) ^ (~e & g)) + k[i] + w[i]; + const std::uint32_t t2 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + ((a & b) ^ (a & c) ^ (b & c)); + hh = g; + g = f; + f = e; + e = d + t1; + d = c; + c = b; + b = a; + a = t1 + t2; + } + h[0] += a; h[1] += b; h[2] += c; h[3] += d; h[4] += e; h[5] += f; h[6] += g; h[7] += hh; + } + static constexpr char hex[] = "0123456789abcdef"; + std::string out; + for (const std::uint32_t word : h) + for (int shift = 28; shift >= 0; shift -= 4) out.push_back(hex[(word >> shift) & 0xf]); + return out; +} + +// --------------------------------------------------------------------------------------------------------------- +// JSON (the subset the translator's index uses, which is all of JSON except number precision beyond double) + +struct Json { + enum class Kind { null, boolean, number, string, array, object } kind = Kind::null; + bool boolean = false; + double number = 0; + std::string string; + std::vector array; + std::vector> object; + + const Json* find(std::string_view key) const { + for (const auto& [k, v] : object) + if (k == key) return &v; + return nullptr; + } +}; + +class JsonReader { +public: + explicit JsonReader(std::string_view text) : text_(text) {} + + bool parse(Json& out) { + if (!value(out, 0)) return false; + space(); + return pos_ == text_.size(); + } + +private: + void space() { + while (pos_ < text_.size() && (text_[pos_] == ' ' || text_[pos_] == '\n' || text_[pos_] == '\r' || + text_[pos_] == '\t')) + ++pos_; + } + + bool literal(std::string_view word) { + if (text_.substr(pos_, word.size()) != word) return false; + pos_ += word.size(); + return true; + } + + bool value(Json& out, int depth) { + if (depth > 64) return false; + space(); + if (pos_ >= text_.size()) return false; + const char c = text_[pos_]; + if (c == '{') { + out.kind = Json::Kind::object; + ++pos_; + space(); + if (pos_ < text_.size() && text_[pos_] == '}') return ++pos_, true; + for (;;) { + space(); + std::string key; + if (!string(key)) return false; + space(); + if (pos_ >= text_.size() || text_[pos_++] != ':') return false; + Json item; + if (!value(item, depth + 1)) return false; + out.object.emplace_back(std::move(key), std::move(item)); + space(); + if (pos_ >= text_.size()) return false; + if (text_[pos_] == ',') { + ++pos_; + continue; + } + return text_[pos_++] == '}'; + } + } + if (c == '[') { + out.kind = Json::Kind::array; + ++pos_; + space(); + if (pos_ < text_.size() && text_[pos_] == ']') return ++pos_, true; + for (;;) { + Json item; + if (!value(item, depth + 1)) return false; + out.array.push_back(std::move(item)); + space(); + if (pos_ >= text_.size()) return false; + if (text_[pos_] == ',') { + ++pos_; + continue; + } + return text_[pos_++] == ']'; + } + } + if (c == '"') { + out.kind = Json::Kind::string; + return string(out.string); + } + if (literal("true")) return out.kind = Json::Kind::boolean, out.boolean = true, true; + if (literal("false")) return out.kind = Json::Kind::boolean, out.boolean = false, true; + if (literal("null")) return out.kind = Json::Kind::null, true; + const std::size_t start = pos_; + while (pos_ < text_.size() && std::strchr("+-0123456789.eE", text_[pos_])) ++pos_; + if (pos_ == start) return false; + out.kind = Json::Kind::number; + out.number = std::stod(std::string(text_.substr(start, pos_ - start))); + return true; + } + + bool string(std::string& out) { + if (pos_ >= text_.size() || text_[pos_++] != '"') return false; + while (pos_ < text_.size()) { + const char c = text_[pos_++]; + if (c == '"') return true; + if (c != '\\') { + out.push_back(c); + continue; + } + if (pos_ >= text_.size()) return false; + const char e = text_[pos_++]; + switch (e) { + case '"': case '\\': case '/': out.push_back(e); break; + case 'b': out.push_back('\b'); break; + case 'f': out.push_back('\f'); break; + case 'n': out.push_back('\n'); break; + case 'r': out.push_back('\r'); break; + case 't': out.push_back('\t'); break; + case 'u': { + if (pos_ + 4 > text_.size()) return false; + const unsigned code = unsigned(std::stoul(std::string(text_.substr(pos_, 4)), nullptr, 16)); + pos_ += 4; + if (code < 0x80) { + out.push_back(char(code)); + } else if (code < 0x800) { + out.push_back(char(0xc0 | (code >> 6))); + out.push_back(char(0x80 | (code & 0x3f))); + } else { // surrogate pairs are kept as two 3-byte sequences; index names are ASCII + out.push_back(char(0xe0 | (code >> 12))); + out.push_back(char(0x80 | ((code >> 6) & 0x3f))); + out.push_back(char(0x80 | (code & 0x3f))); + } + break; + } + default: return false; + } + } + return false; + } + + std::string_view text_; + std::size_t pos_ = 0; +}; + +// --------------------------------------------------------------------------------------------------------------- +// DXBC containers and the FSSM program + +// The payload of one DXBC part ("DXIL", "PRIV", ...), or an empty span. +inline std::span dxbc_part(std::span container, const char (&fourcc)[5]) { + const auto u32 = [&](std::size_t at) -> std::uint32_t { + if (at + 4 > container.size()) return 0; + std::uint32_t v; + std::memcpy(&v, container.data() + at, 4); + return v; + }; + if (container.size() < 32 || std::memcmp(container.data(), "DXBC", 4) != 0) return {}; + const std::uint32_t parts = u32(28); + for (std::uint32_t i = 0; i < parts; ++i) { + const std::uint32_t at = u32(32 + 4 * std::size_t(i)); + if (std::size_t(at) + 8 > container.size()) return {}; + const std::uint32_t size = u32(at + 4); + if (std::size_t(at) + 8 + size > container.size()) return {}; + if (std::memcmp(container.data() + at, fourcc, 4) == 0) return container.subspan(at + 8, size); + } + return {}; +} + +// The FSSM blob of a shader: inflated from the container's DXIL/XDAT/XBCH entry, or the bytecode itself when it is +// already a bare FSSM blob. Empty when neither applies. +inline std::vector fssm_program(std::span bytecode) { + if (bytecode.size() >= 4 && std::memcmp(bytecode.data(), "FSSM", 4) == 0) + return {bytecode.begin(), bytecode.end()}; + const auto dxil = dxbc_part(bytecode, "DXIL"); + const auto u32 = [&](std::size_t at) -> std::uint32_t { + if (at + 4 > dxil.size()) return 0; + std::uint32_t v; + std::memcpy(&v, dxil.data() + at, 4); + return v; + }; + std::size_t xdat = 0; + for (; xdat + 4 <= dxil.size(); ++xdat) + if (std::memcmp(dxil.data() + xdat, "XDAT", 4) == 0) break; + if (xdat + 12 > dxil.size()) return {}; + const std::uint32_t count = u32(xdat + 4); + for (std::uint32_t i = 0; i < count; ++i) { + const std::size_t entry = xdat + 12 + 12 * std::size_t(i); + if (entry + 12 > dxil.size()) return {}; + const std::uint32_t tag = u32(entry), offset = u32(entry + 4), size = u32(entry + 8); + if (tag != 0x0d) continue; + if (std::size_t(offset) + size > dxil.size() || size < 24) return {}; + const auto blob = dxil.subspan(offset, size); + if (std::memcmp(blob.data(), "XBCH", 4) != 0) return {}; + std::uint32_t unpacked; + std::memcpy(&unpacked, blob.data() + 16, 4); + std::vector out; + if (!zlib_inflate(blob.subspan(24), out, unpacked) || out.size() != unpacked) return {}; + return out; + } + return {}; +} + +// --------------------------------------------------------------------------------------------------------------- +// The translator's spirv/index.json + +struct ShaderEntry { + std::string name; + std::string stage; // "vs", "ps", "cs", "ms", "gs" + std::string fssm_sha256; + std::size_t binding_count = 0; // set-0 bindings the module declares + std::uint32_t push_constant_bytes = 0; + std::array local_size{1, 1, 1}; + bool uses_code_base = false; + bool wave64 = false; +}; + +class ShaderLibrary { +public: + // Reads /index.json. Entries without fssm_sha256 cannot be found by content and are skipped. + bool load(const std::string& dir, std::string* error = nullptr) { + const auto fail = [&](const std::string& why) { + if (error) *error = why; + return false; + }; + std::ifstream file(dir + "/index.json", std::ios::binary); + if (!file) return fail("cannot open " + dir + "/index.json"); + const std::string text((std::istreambuf_iterator(file)), std::istreambuf_iterator()); + Json root; + if (!JsonReader(text).parse(root) || root.kind != Json::Kind::object) return fail("index.json is not a JSON object"); + dir_ = dir; + entries_.clear(); + for (const auto& [name, meta] : root.object) { + const Json* hash = meta.find("fssm_sha256"); + const Json* stage = meta.find("stage"); + if (!hash || hash->kind != Json::Kind::string || !stage || stage->kind != Json::Kind::string) continue; + ShaderEntry e; + e.name = name; + e.stage = stage->string; + e.fssm_sha256 = hash->string; + if (const Json* b = meta.find("bindings"); b && b->kind == Json::Kind::array) e.binding_count = b->array.size(); + if (const Json* p = meta.find("push_constant_bytes"); p && p->kind == Json::Kind::number) + e.push_constant_bytes = std::uint32_t(p->number); + if (const Json* l = meta.find("local_size"); l && l->kind == Json::Kind::array) + for (std::size_t i = 0; i < l->array.size() && i < 3; ++i) e.local_size[i] = std::uint32_t(l->array[i].number); + if (const Json* c = meta.find("uses_code_base"); c && c->kind == Json::Kind::boolean) e.uses_code_base = c->boolean; + if (const Json* w = meta.find("wave64"); w && w->kind == Json::Kind::boolean) e.wave64 = w->boolean; + entries_[{e.stage, e.fssm_sha256}] = std::move(e); + } + return true; + } + + bool loaded() const { return !dir_.empty(); } + std::size_t size() const { return entries_.size(); } + + const ShaderEntry* find(std::string_view stage, std::string_view fssm_sha256) const { + const auto it = entries_.find({std::string(stage), std::string(fssm_sha256)}); + return it == entries_.end() ? nullptr : &it->second; + } + + // The module's words, or empty when /.spv is missing or not SPIR-V. + std::vector spirv(const ShaderEntry& entry) const { + std::ifstream file(dir_ + "/" + entry.name + ".spv", std::ios::binary); + if (!file) return {}; + const std::string bytes((std::istreambuf_iterator(file)), std::istreambuf_iterator()); + if (bytes.size() < 20 || bytes.size() % 4) return {}; + std::vector words(bytes.size() / 4); + std::memcpy(words.data(), bytes.data(), bytes.size()); + return words[0] == 0x07230203 ? words : std::vector{}; + } + +private: + std::string dir_; + std::map, ShaderEntry> entries_; +}; + +} // namespace leonida diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index 14203fa95..c7599e774 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -32,7 +32,9 @@ struct VulkanDeviceFunctions { X(vkGetImageMemoryRequirements) X(vkBindImageMemory) X(vkCreateBuffer) X(vkDestroyBuffer) \ X(vkGetBufferMemoryRequirements) X(vkBindBufferMemory) X(vkAllocateMemory) X(vkFreeMemory) X(vkMapMemory) \ X(vkUnmapMemory) X(vkCmdCopyBuffer) X(vkCmdCopyBufferToImage) X(vkCmdCopyImageToBuffer) X(vkCmdCopyImage) \ - X(vkCmdResolveImage) + X(vkCmdResolveImage) X(vkCmdBindPipeline) X(vkCmdPushConstants) X(vkCmdDispatch) X(vkCreateShaderModule) \ + X(vkDestroyShaderModule) X(vkCreatePipelineLayout) X(vkDestroyPipelineLayout) X(vkCreateComputePipelines) \ + X(vkDestroyPipeline) X(vkGetBufferDeviceAddress) #define LEONIDA_VK_MEMBER(name) PFN_##name name = nullptr; LEONIDA_VK_DEVICE_FUNCTIONS(LEONIDA_VK_MEMBER) #undef LEONIDA_VK_MEMBER @@ -50,7 +52,9 @@ struct VulkanDeviceFunctions { vkDestroyImage && vkGetImageMemoryRequirements && vkBindImageMemory && vkCreateBuffer && vkDestroyBuffer && vkGetBufferMemoryRequirements && vkBindBufferMemory && vkAllocateMemory && vkFreeMemory && vkMapMemory && vkUnmapMemory && vkCmdCopyBuffer && vkCmdCopyBufferToImage && - vkCmdCopyImageToBuffer && vkCmdCopyImage && vkCmdResolveImage; + vkCmdCopyImageToBuffer && vkCmdCopyImage && vkCmdResolveImage && vkCmdBindPipeline && + vkCmdPushConstants && vkCmdDispatch && vkCreateShaderModule && vkDestroyShaderModule && + vkCreatePipelineLayout && vkDestroyPipelineLayout && vkCreateComputePipelines && vkDestroyPipeline; } }; @@ -72,6 +76,13 @@ class VulkanContext { replay_.copy_image_to_buffer = vk.vkCmdCopyImageToBuffer; replay_.copy_image = vk.vkCmdCopyImage; replay_.resolve_image = vk.vkCmdResolveImage; + replay_.bind_pipeline = vk.vkCmdBindPipeline; + replay_.push_constants = vk.vkCmdPushConstants; + replay_.dispatch = vk.vkCmdDispatch; + replay_.compute_pipeline = [this](std::uintptr_t id) -> const ComputePipeline* { + const auto it = pipelines_.find(id); + return it == pipelines_.end() ? nullptr : &it->second; + }; replay_.image_view = [this](const ResourceBinding& r, const VkImageSubresourceRange& range) { return view(r, range); }; @@ -116,6 +127,26 @@ class VulkanContext { resources_.erase(it); } + // The device address of the GPU address arena: console VAs are offsets from it (docs section 3.3). + void set_heap_base(std::uint64_t heap_base) { + std::lock_guard lock(mutex_); + replay_.heap_base = heap_base; + } + std::uint64_t heap_base() { + std::lock_guard lock(mutex_); + return replay_.heap_base; + } + + // Pipelines are registered by an opaque id (the PSO object) for as long as the PSO lives. + void add_pipeline(std::uintptr_t id, const ComputePipeline& pipeline) { + std::lock_guard lock(mutex_); + pipelines_[id] = pipeline; + } + void remove_pipeline(std::uintptr_t id) { + std::lock_guard lock(mutex_); + pipelines_.erase(id); + } + // For tests and traces. VkImageLayout layout(ResourceId id, std::uint32_t subresource) { std::lock_guard lock(mutex_); @@ -157,6 +188,7 @@ class VulkanContext { std::mutex mutex_; // resources, tracker and views; held while a queue prepares and emits std::mutex submit_mutex_; std::unordered_map resources_; + std::unordered_map pipelines_; LayoutTracker tracker_; std::map, VkImageView> views_; ReplayFunctions replay_; diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 1bcee80a3..ff18c1a58 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -49,6 +49,7 @@ struct ResourceBinding { bool simultaneous_access = false; // D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS: always GENERAL bool not_zeroed = false; // D3D12_HEAP_FLAG_CREATE_NOT_ZEROED: first use skips the zero fill VkBuffer buffer = VK_NULL_HANDLE; // a buffer resource, for copies + VkDeviceSize buffer_offset = 0; // where it starts in `buffer` (the GPU address arena holds many) VkDeviceSize size = 0; // its size in bytes std::uint32_t depth = 1; bool volume = false; // one array layer, including at mips with a single slice @@ -454,6 +455,22 @@ class LayoutTracker { std::unordered_map entries_; }; +// A compute pipeline as replay needs it. code_base is the console VA of the shader's FSSM blob (push-constant +// dwords 34-35), 0 when the shader does not read it. +struct ComputePipeline { + VkPipeline pipeline = VK_NULL_HANDLE; + VkPipelineLayout layout = VK_NULL_HANDLE; + std::uint64_t code_base = 0; +}; + +// The 144-byte push-constant block every translated shader declares: s0..s31, heap base, code base. +struct ShaderUserData { + std::uint32_t s[32]; + std::uint64_t heap_base; + std::uint64_t code_base; +}; +static_assert(sizeof(ShaderUserData) == 144); + struct ReplayFunctions { PFN_vkCmdPipelineBarrier pipeline_barrier = nullptr; PFN_vkCmdClearColorImage clear_color_image = nullptr; @@ -468,6 +485,11 @@ struct ReplayFunctions { PFN_vkCmdCopyImageToBuffer copy_image_to_buffer = nullptr; PFN_vkCmdCopyImage copy_image = nullptr; PFN_vkCmdResolveImage resolve_image = nullptr; // resolves + PFN_vkCmdBindPipeline bind_pipeline = nullptr; // dispatches + PFN_vkCmdPushConstants push_constants = nullptr; + PFN_vkCmdDispatch dispatch = nullptr; + std::function compute_pipeline; + std::uint64_t heap_base = 0; // device address of the GPU address arena (push-constant dwords 32-33) // Returns a 2D-array view of the range (caller-owned, alive until execution completes); rectangle clears. std::function image_view; bool separate_depth_stencil_layouts = false; // must match the LayoutTracker, if one is used @@ -497,6 +519,7 @@ struct Prepared { std::vector buffer_image_copies; // one direction, given by which side is an image std::vector image_copies; VkImageResolve resolve{}; // resolves + ComputePipeline pipeline; // dispatches }; inline bool view_range(const ResourceBinding& resource, const TargetView& view, VkImageAspectFlags aspects, @@ -687,7 +710,7 @@ inline ReplayResult prepare_texture_copy(const CopyTexture& copy, Prepared& p) { !within(offset + (depth - 1) * slice_pitch, (rows - 1) * placed.row_pitch + row_bytes, buffer.size)) return ReplayResult::invalid_copy; VkBufferImageCopy region{}; - region.bufferOffset = offset; + region.bufferOffset = buffer.buffer_offset + offset; region.bufferRowLength = placed.row_pitch / format.bytes * format.block; region.bufferImageHeight = depth > 1 ? std::uint32_t(slice_rows * format.block) : 0; region.imageSubresource = {range.aspectMask, range.baseMipLevel, range.baseArrayLayer, 1}; @@ -702,7 +725,7 @@ inline ReplayResult prepare_texture_copy(const CopyTexture& copy, Prepared& p) { inline ReplayResult prepare_resource_copy(Prepared& p) { if (p.binding.buffer && p.source.buffer) { if (p.binding.size != p.source.size) return ReplayResult::invalid_copy; - p.buffer_copies.push_back({0, 0, p.source.size}); + p.buffer_copies.push_back({p.source.buffer_offset, p.binding.buffer_offset, p.source.size}); return ReplayResult::success; } const ResourceBinding &dst = p.binding, &src = p.source; @@ -891,7 +914,8 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun !detail::within(buffer_copy->dst_offset, buffer_copy->size, p.binding.size) || !detail::within(buffer_copy->src_offset, buffer_copy->size, p.source.size)) return ReplayResult::invalid_copy; - p.buffer_copies.push_back({buffer_copy->src_offset, buffer_copy->dst_offset, buffer_copy->size}); + p.buffer_copies.push_back({p.source.buffer_offset + buffer_copy->src_offset, + p.binding.buffer_offset + buffer_copy->dst_offset, buffer_copy->size}); } else if (const auto* texture_copy = std::get_if(&command)) { result = detail::prepare_texture_copy(*texture_copy, p); } else { @@ -905,6 +929,12 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun p.source = *source; if (const auto result = detail::prepare_resolve(*resolve_command, p); result != ReplayResult::success) return result; + } else if (const auto* dispatch = std::get_if(&command)) { + if (!vk.bind_pipeline || !vk.push_constants || !vk.dispatch || !vk.compute_pipeline) + return ReplayResult::unsupported; + const ComputePipeline* pipeline = vk.compute_pipeline(dispatch->pipeline); + if (!pipeline || !pipeline->pipeline) return ReplayResult::unresolved_resource; + p.pipeline = *pipeline; } } return ReplayResult::success; @@ -1114,6 +1144,14 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c vk, command_buffer, p.binding, dst_id, detail::planes_for_layout(p.binding, p.range, separate), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, tracker); vk.resolve_image(command_buffer, p.source.image, src_layout, p.binding.image, dst_layout, 1, &p.resolve); + } else if (const auto* dispatch = std::get_if(&command)) { + ShaderUserData data{}; + std::copy(dispatch->user_data.begin(), dispatch->user_data.end(), data.s); + data.heap_base = vk.heap_base; + data.code_base = p.pipeline.code_base; + vk.bind_pipeline(command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, p.pipeline.pipeline); + vk.push_constants(command_buffer, p.pipeline.layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(data), &data); + vk.dispatch(command_buffer, dispatch->x, dispatch->y, dispatch->z); } } } diff --git a/runtime/test/command_list_test.cpp b/runtime/test/command_list_test.cpp index 797ba03d5..bf110d611 100644 --- a/runtime/test/command_list_test.cpp +++ b/runtime/test/command_list_test.cpp @@ -139,6 +139,21 @@ int main() { const auto& resolved = std::get(list.commands()[5]); CHECK(resolved.dst == 7 && resolved.dst_subresource == 1 && resolved.src == 8 && resolved.src_subresource == 0); + // Dispatches keep the user data they were recorded with; no pipeline is refused, no groups records nothing. + CHECK(list.reset()); + Dispatch dispatch{0x1234, {}, 2, 1, 1}; + dispatch.user_data[0] = 7; + dispatch.user_data[31] = 9; + CHECK(list.dispatch(dispatch)); + dispatch.user_data[0] = 8; // the caller's block changes after recording + CHECK(!list.dispatch({0, {}, 1, 1, 1})); + CHECK(list.dispatch({0x1234, {}, 0, 1, 1})); + CHECK(list.close()); + CHECK(!list.dispatch(dispatch)); + CHECK(list.commands().size() == 1); + const auto& recorded = std::get(list.commands()[0]); + CHECK(recorded.pipeline == 0x1234 && recorded.user_data[0] == 7 && recorded.user_data[31] == 9 && recorded.x == 2); + CHECK(list.reset()); CHECK(!list.closed() && list.commands().empty()); CHECK(!list.reset()); diff --git a/runtime/test/shader_library_test.cpp b/runtime/test/shader_library_test.cpp new file mode 100644 index 000000000..5c074b18a --- /dev/null +++ b/runtime/test/shader_library_test.cpp @@ -0,0 +1,176 @@ +// Shader library pieces without a GPU: SHA-256 (FIPS 180-4 vectors), zlib inflate (stored, fixed and dynamic +// Huffman blocks, compressed from synthetic data with Python's zlib), the JSON reader, FSSM extraction from a +// synthetic DXBC container, and index lookup by content hash. No game data. +#include "../src/shader_library.h" + +#include +#include +#include +#include +#include + +#define CHECK(condition) do { \ + if (!(condition)) { \ + std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); \ + return 1; \ + } \ +} while (0) + +namespace { + +std::vector bytes(const std::string& s) { return {s.begin(), s.end()}; } + +// The dynamic-Huffman sample: an LCG over a skewed alphabet (the same generator produced `dynamic` below). +std::vector skewed(std::size_t n) { + static constexpr char alphabet[] = "eeeeettaaoinshrdlu"; + std::vector out; + std::uint32_t x = 12345; + for (std::size_t i = 0; i < n; ++i) { + x = (x * 1103515245u + 12345u) & 0x7fffffffu; + out.push_back(std::uint8_t(alphabet[(x >> 16) % 18])); + } + return out; +} + +const std::vector stored = { + 0x78, 0x01, 0x01, 0x28, 0x00, 0xd7, 0xff, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, + 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, + 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x29, 0xcc, 0x03, 0x0d}; +const std::vector fixed = {0x78, 0x01, 0xcb, 0x48, 0xcd, 0xc9, 0xc9, 0x57, 0x40, 0x26, 0x73, + 0x52, 0xf3, 0xf3, 0x32, 0x53, 0x12, 0x01, 0x7a, 0xaf, 0x09, 0x79}; +const std::vector dynamic = { + 0x78, 0xda, 0x1d, 0x92, 0xdb, 0x0a, 0xc0, 0x30, 0x08, 0x43, 0xbf, 0x55, 0x30, 0xa0, 0x20, 0x0a, 0x5e, 0xfe, 0x7f, + 0xe9, 0xf6, 0x54, 0x66, 0x6c, 0x4e, 0xb4, 0x13, 0xb6, 0x22, 0x26, 0x40, 0x08, 0xaa, 0xc0, 0xc3, 0x40, 0x0e, 0x17, + 0x1e, 0xe5, 0x09, 0x5f, 0x44, 0xc9, 0xab, 0x01, 0x10, 0x71, 0xa4, 0x40, 0x25, 0x25, 0xa2, 0xb1, 0x28, 0x31, 0x44, + 0x88, 0xcb, 0x62, 0x7c, 0x29, 0xda, 0x38, 0x43, 0x52, 0x78, 0xd2, 0x5b, 0x23, 0x47, 0x99, 0xb8, 0x61, 0xd8, 0x05, + 0x1f, 0xa4, 0x42, 0xf3, 0x26, 0x84, 0x17, 0xe4, 0xf0, 0x5e, 0x83, 0x81, 0x92, 0x35, 0x7a, 0x05, 0x2d, 0x5a, 0xce, + 0xb1, 0x3d, 0xab, 0xa5, 0xca, 0x0a, 0x95, 0x7b, 0x43, 0x11, 0xdd, 0xe0, 0x69, 0xc3, 0x5b, 0x37, 0x92, 0x2c, 0xd7, + 0x79, 0xd6, 0x92, 0xaf, 0x20, 0x43, 0x73, 0x61, 0x1f, 0x13, 0xcc, 0xa1, 0x55, 0xd9, 0x47, 0xd3, 0x89, 0x55, 0x6a, + 0x01, 0x06, 0x9a, 0x2e, 0x8b, 0x30, 0xba, 0x63, 0xaf, 0x56, 0xf7, 0x3c, 0x49, 0x0e, 0xd4, 0x90, 0xae, 0x2f, 0x65, + 0x70, 0xb7, 0xd9, 0xe7, 0x32, 0xcf, 0xef, 0x18, 0x3d, 0xd8, 0x59, 0xde, 0xc1, 0xf4, 0x63, 0xb2, 0x4b, 0x90, 0xb1, + 0x54, 0xff, 0x87, 0xa0, 0x53, 0x68, 0xdf, 0x57, 0xcc, 0x9c, 0x79, 0x3e, 0x8b, 0x74, 0xb8, 0xef, 0xac, 0x33, 0x25, + 0xc7, 0x44, 0x8c, 0x95, 0x29, 0x3d, 0xfb, 0x23, 0xee, 0xcb, 0xc8, 0x51, 0x48, 0x50, 0x4e, 0x93, 0x78, 0x38, 0xc4, + 0xbf, 0x67, 0x48, 0x8c, 0x37, 0x53, 0xb2, 0x5e, 0xa3, 0x83, 0xfc, 0x19, 0x30, 0xe5, 0x3f, 0xa1, 0x51, 0xb1, 0xe0, + 0x24, 0x8a, 0xb7, 0x20, 0x8d, 0xda, 0x79, 0xcb, 0xb2, 0xb7, 0x3a, 0x7e, 0xc9, 0xc4, 0x69, 0x5a, 0x06, 0x3a, 0xc5, + 0xfd, 0x33, 0x01, 0x33, 0x72, 0xb9, 0xc9, 0x09, 0x44, 0x38, 0xa4, 0xeb, 0xf7, 0x27, 0x6a, 0xe5, 0x11, 0x61, 0x99, + 0xe1, 0xa2, 0xc2, 0x75, 0x8d, 0x0d, 0xf6, 0x1e, 0x40, 0x6c, 0xeb, 0xbc, 0xfd, 0x73, 0xf1, 0x74, 0x81, 0x31, 0x73, + 0xf2, 0x81, 0x64, 0xff, 0xfb, 0x27, 0x60, 0xbf, 0xd1, 0x31, 0x02, 0xfe, 0x78, 0x7c, 0x3d, 0x44, 0x17, 0x72, 0x10, + 0xd3, 0xe8, 0xe7, 0x36, 0xe7, 0x77, 0x1f, 0x7a, 0xbd, 0xf9, 0x80}; + +void put32(std::vector& out, std::uint32_t v) { + for (int i = 0; i < 4; ++i) out.push_back(std::uint8_t(v >> (8 * i))); +} + +// A shader container shaped like the game's: DXBC with a DXIL part holding an XDAT table whose 0x0D entry is +// XBCH + a zlib stream (tools/fssm_unpack.py documents the layout). +std::vector container(const std::vector& zlib, std::uint32_t unpacked) { + std::vector xbch = {'X', 'B', 'C', 'H'}; + put32(xbch, 1); + put32(xbch, std::uint32_t(zlib.size())); + put32(xbch, 0); + put32(xbch, unpacked); + put32(xbch, 0); + xbch.insert(xbch.end(), zlib.begin(), zlib.end()); + std::vector dxil(16, 0); // stands in for the DxilProgramHeader stub + const std::uint32_t xdat_at = std::uint32_t(dxil.size()); + dxil.insert(dxil.end(), {'X', 'D', 'A', 'T'}); + put32(dxil, 2); // entries + put32(dxil, 12); // header size + const std::uint32_t first = xdat_at + 12 + 2 * 12; + put32(dxil, 0x12); // a 16-byte hash entry, ignored + put32(dxil, first); + put32(dxil, 16); + put32(dxil, 0x0d); + put32(dxil, first + 16); + put32(dxil, std::uint32_t(xbch.size())); + dxil.insert(dxil.end(), 16, 0xab); + dxil.insert(dxil.end(), xbch.begin(), xbch.end()); + + std::vector out = {'D', 'X', 'B', 'C'}; + out.resize(28, 0); // hash, version, total size (unchecked) + put32(out, 2); // part count + put32(out, 40); // PRIV part offset + put32(out, 40 + 8 + 4); + out.insert(out.end(), {'P', 'R', 'I', 'V'}); + put32(out, 4); + put32(out, 0); + out.insert(out.end(), {'D', 'X', 'I', 'L'}); + put32(out, std::uint32_t(dxil.size())); + out.insert(out.end(), dxil.begin(), dxil.end()); + return out; +} + +} // namespace + +int main() { + using namespace leonida; + + CHECK(sha256_hex({}) == "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"); + CHECK(sha256_hex(bytes("abc")) == "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"); + CHECK(sha256_hex(bytes("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq")) == + "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1"); + + std::vector out; + CHECK(zlib_inflate(stored, out) && out.size() == 40); + for (std::uint8_t i = 0; i < 40; ++i) CHECK(out[i] == i); + CHECK(zlib_inflate(fixed, out) && out == bytes("hello hello hello leonida")); + CHECK(zlib_inflate(dynamic, out) && out == skewed(600)); + CHECK(sha256_hex(out) == "9cd6848f765bff2a9f42a8b42f6164042dad67d3e9f82e0044ddc7d1ecdeebb2"); + auto broken = dynamic; + broken.back() ^= 1; // Adler-32 + CHECK(!zlib_inflate(broken, out)); + broken = dynamic; + broken.resize(100); // truncated + CHECK(!zlib_inflate(broken, out)); + CHECK(!zlib_inflate(dynamic, out, 599)); // larger than the limit + CHECK(!zlib_inflate(bytes("not zlib"), out)); + + Json json; + // "s" holds an escaped quote and a \u escape for U+00E9, which the reader must turn into UTF-8. + const std::string text = "{\"a\": {\"stage\": \"cs\", \"n\": [1, 2.5, -3e2], \"ok\": true, " + "\"s\": \"x\\\"\\u00e9\", \"z\": null}}"; + const std::string expected_s = std::string("x\"") + char(0xc3) + char(0xa9); + CHECK(JsonReader(text).parse(json)); + const Json* a = json.find("a"); + CHECK(a && a->find("stage")->string == "cs" && a->find("n")->array[2].number == -300 && a->find("ok")->boolean); + CHECK(a->find("s")->string == expected_s && a->find("z")->kind == Json::Kind::null); + CHECK(!JsonReader("{\"a\": }").parse(json)); + CHECK(!JsonReader("[1, 2").parse(json)); + CHECK(!JsonReader("{} extra").parse(json)); + + const auto shader = container(dynamic, 600); + CHECK(dxbc_part(shader, "PRIV").size() == 4 && !dxbc_part(shader, "DXIL").empty() && dxbc_part(shader, "RTS0").empty()); + CHECK(fssm_program(shader) == skewed(600)); + auto fssm = bytes("FSSM and a native program"); + CHECK(fssm_program(fssm) == fssm); // a bare FSSM blob passes through + CHECK(fssm_program(container(dynamic, 601)).empty()); // stated size wrong + CHECK(fssm_program(bytes("DXBC")).empty()); + + // An index with one findable shader, one without a hash, and the module next to it. + const auto dir = std::filesystem::temp_directory_path() / "leonida_shader_library_test"; + std::filesystem::create_directories(dir); + const std::string hash = sha256_hex(skewed(600)); + { + std::ofstream index(dir / "index.json", std::ios::binary); + index << "{\"cs_test\": {\"stage\": \"cs\", \"fssm_sha256\": \"" << hash + << "\", \"bindings\": [2], \"push_constant_bytes\": 144, \"local_size\": [64, 1, 1], " + "\"uses_code_base\": true, \"wave64\": false},\n" + " \"ps_unhashed\": {\"stage\": \"ps\", \"bindings\": []}}"; + std::ofstream spv(dir / "cs_test.spv", std::ios::binary); + const std::uint32_t words[5] = {0x07230203, 0x00010500, 0, 1, 0}; + spv.write(reinterpret_cast(words), sizeof(words)); + } + ShaderLibrary library; + std::string error; + CHECK(library.load(dir.string(), &error) && library.size() == 1); + const ShaderEntry* entry = library.find("cs", sha256_hex(fssm_program(shader))); + CHECK(entry && entry->name == "cs_test" && entry->binding_count == 1 && entry->push_constant_bytes == 144); + CHECK(entry->local_size[0] == 64 && entry->uses_code_base && !entry->wave64); + CHECK(!library.find("ps", hash)); + CHECK(library.spirv(*entry).size() == 5); + CHECK(!library.load((dir / "missing").string(), &error) && !error.empty()); + std::filesystem::remove_all(dir); + + std::printf("SHA-256, inflate (stored/fixed/dynamic), JSON, FSSM extraction and index lookup OK\n"); + return 0; +} From ded7c48f27b57e0ebdb891b12328c463e8634875 Mon Sep 17 00:00:00 2001 From: Ryx <118130241+Ryx69@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:06:44 +0100 Subject: [PATCH 4/9] Runtime: compute path end to end (GPU address arena, root signatures, compute PSOs, Dispatch) - GPU address arena (docs 3.3), when the device has bufferDeviceAddress: one host-visible, device-addressable buffer (LEONIDA_ARENA_MB, default 256, max 4095 so VAs fit 32-bit table pointers). Default-heap buffers are 64 KiB-aligned ranges with VA = offset, zeroed through the mapping; shader-visible descriptor heaps live there (CPU handle = mapping, GPU handle = VA); upload/readback buffers get VA = device address - heap base; GetGPUVirtualAddress returns these. - CreateRootSignature on main's model (rt::rootsig): parse_rts0, then pack() for each parameter's place in the 32 user-data dwords; what pack() refuses is refused with its reason. CreateComputePipelineState (PC slot 11, Xbox slot 62 via the proxy) finds the shader by the SHA-256 of its FSSM program in the translator's index (VulkanDeviceInfo::shader_dir or LEONIDA_SHADERS); its FSSM blob is copied into the arena as the code base. Shaders that declare set-0 bindings are refused with a log until the bindless set exists (M2). - Command list: root signatures (arguments cleared on change), pipeline state, constant / root view / descriptor-table setters for compute and graphics, SetDescriptorHeaps, Dispatch recording the user data as it is, ClearState (which also resets #164's stencil references); misuse makes Close return E_INVALIDARG. - Test helper and standalone device enable bufferDeviceAddress. Test: d3d12_compute_test (through the proxy) creates the root signature from the PC serializer's blob and the PSO through slot 62 in the measured (desc, 0, 0, riid, out) shape (28cf235) from a container shaped like the game's, sets root constants, a root UAV and a table whose application-written entry points at an upload buffer, runs two dispatches that each keep their own arguments, and reads the results back: 64/64 twice. Its shader is GLSL written to the translator's push-constant and address contract, compiled with glslangValidator. Clean under the Khronos validation layer, as are the other GPU tests; 13/13 ctest. --- README.md | 2 +- docs/d3d12_vulkan.md | 40 ++- runtime/CMakeLists.txt | 27 +- runtime/README.md | 2 + runtime/shims/d3d12_com.cpp | 121 ++++++++- runtime/shims/d3d12_com.h | 26 ++ runtime/shims/d3d12_vulkan_device.cpp | 369 +++++++++++++++++++++++++- runtime/test/d3d12_compute_test.cpp | 330 +++++++++++++++++++++++ runtime/test/glsl/cs_user_data.comp | 43 +++ runtime/test/vk_test_device.h | 3 +- 10 files changed, 936 insertions(+), 27 deletions(-) create mode 100644 runtime/test/d3d12_compute_test.cpp create mode 100644 runtime/test/glsl/cs_user_data.comp diff --git a/README.md b/README.md index 652eb5eec..acdaae967 100644 --- a/README.md +++ b/README.md @@ -52,7 +52,7 @@ work on booting can start as soon as one is available to a developer. | Audio banks (AWC: Opus, XMA2) | ✅ Exported whole. Opus repackaged **losslessly** as Ogg Opus; PCM (codec 0/2) as WAV; XMA2 decoded with ffmpeg. `--wav` adds 16-bit PCM WAV ([notes](docs/audio.md)) | | Music/radio config | ? Measured. **1,589** audio-config records with exact durations and AWC stream ids; station grouping and content-id lists; no per-track start offsets ([notes](docs/audio_config.md)) | | PE loader and import shims | ⚠️ Skeleton. Untested against the real executable | -| Xbox D3D12 → Vulkan | ⚠️ In progress. A Vulkan-backed device behind the Xbox-ABI proxy creates queues, command lists, fences, descriptor heaps, views and committed resources; barriers, clears, uploads and copies (BC included) run on Vulkan, and frames are presented to a window (milestone M0 passes in a synthetic test), checked on one GPU. No shader views, pipelines or draws yet, and the game's own present call is not hooked up ([plan](docs/d3d12_vulkan.md)) | +| Xbox D3D12 → Vulkan | ⚠️ In progress. A Vulkan-backed device behind the Xbox-ABI proxy creates queues, command lists, fences, descriptor heaps, views and committed resources; barriers, clears, uploads and copies (BC included) run on Vulkan, frames are presented to a window (milestone M0 passes in a synthetic test), and compute pipelines dispatch with root arguments through a GPU address arena, checked on one GPU. No bindless descriptors, graphics pipelines or draws yet, and the game's own present call is not hooked up ([plan](docs/d3d12_vulkan.md)) | | Booting, story mode, anything playable | ❌ No | ## How to build diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 4dd5fb954..9ae072b45 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -254,7 +254,7 @@ Two pieces of milestone M2 that the device does not use yet, built and tested on a table that has grown gets a new buffer behind binding 2: `flush_needs_idle()` says when a flush would do either, so the owner can wait until no command buffer that uses the set is still running. -Started for the compute path (no pipelines yet): +The compute path, end to end: - `runtime/src/shader_library.h` finds the translated SPIR-V for a shader the game hands to D3D12 (section 3.6). It extracts the FSSM program from the DXBC container (DXIL → XDAT entry 0x0D → XBCH → zlib) and looks up its SHA-256 as `fssm_sha256` in `spirv/index.json`. Its own inflate, SHA-256 and JSON reader keep it free of @@ -262,14 +262,30 @@ Started for the compute path (no pipelines yet): - Root signatures use the model already on `main` (`runtime/src/root_signature.h`, `rt::rootsig`): `parse_rts0` reads the serialized blob and `pack()` lays out the 32 user-data dwords by the section 3.5 default mapping, refusing anything that would spill. -- The IR records `Dispatch` with its user data captured at record time. Replay binds the pipeline, pushes the - 144-byte block (s0..s31, heap base, code base) and dispatches. Not wired up yet: the GPU address arena, - `CreateRootSignature`, compute PSOs and the command list's root-argument setters. - -Known gaps: the game's present entry point (DXGI factory/swapchain or `PresentX`; the presenter above is what -either calls), HDR and fullscreen; shader-resource, UAV and constant-buffer views, samplers, root signatures, PSOs, -draws, volume attachment views, placed and reserved resources, `GetGPUVirtualAddress` (the shared buffer arena), -depth-stencil resolves and `ResolveSubresourceRegion`, and 1D textures; +- **GPU address arena** (section 3.3, when the device has `bufferDeviceAddress`): one host-visible, + device-addressable buffer, 256 MiB by default (`LEONIDA_ARENA_MB`, at most 4095 MiB, so every VA fits 32-bit + table pointers). + - Default-heap buffers are 64 KiB-aligned ranges in it, zeroed through its mapping; their console VA is the offset. + - Shader-visible descriptor heaps also live in it: the CPU handle is its host mapping and the GPU handle is the VA, + so descriptor bytes the application writes itself are what shaders load. + - Upload and readback buffers keep their own memory, and their VA is their device address minus the heap base. + - Shader programs (FSSM blobs) are copied in as the code base. +- **`CreateRootSignature`** parses the blob with `parse_rts0` and keeps each parameter's place from `pack()`; a + signature `pack()` refuses (more than 32 user dwords: the spill layout is open) is refused with its reason. + **`CreateComputePipelineState`** (PC slot 11, Xbox slot 62 through the proxy) finds the shader by its FSSM + hash, builds a pipeline with the 144-byte push-constant range and registers it for replay. Shaders that declare + set-0 bindings are refused with a log until the bindless set exists (M2). +- **Command list**: `Set{Compute,Graphics}RootSignature` (which clears the arguments, as D3D12 leaves them + undefined), `SetPipelineState`, the 32-bit constant, root view and descriptor-table setters, `SetDescriptorHeaps` + and `ClearState`. A wrong parameter type or out-of-range constants makes `Close` return `E_INVALIDARG`. + `Dispatch` records the block as it is at that moment. Replay binds the pipeline, pushes s0..s31, the heap base + and the code base, and dispatches. + +Known gaps: set 0 in pipelines (`vulkan_bindless.h` above is not used by the device yet) and therefore every +translated shader that declares bindings; graphics PSOs, input layouts and draws; `requiredSubgroupSize = 64` for +wave64 compute; the game's present entry point (DXGI factory/swapchain or `PresentX`; the presenter above is what +either calls), HDR and fullscreen; shader-resource, UAV and constant-buffer views, samplers, volume attachment +views, placed and reserved resources, depth-stencil resolves and `ResolveSubresourceRegion`, and 1D textures; default-heap buffers are not zero-filled yet; a fence cannot be signalled to a lower value (Vulkan timelines only increase; such a signal is reported and dropped); enhanced-barrier access bits are not filtered against the sync scope, so a combination D3D12 accepts but Vulkan does not would show up as a validation error; the GCL8 @@ -319,6 +335,12 @@ and any validation error fails them. repeats on a standalone device, the path `LEONIDA_D3D12=vulkan` takes. - `d3d12_descriptor_test`: descriptor copies through the proxy, checked on the slots' bytes: one run, range lists of different shapes on each side, null size arrays, and a destination longer than its source. +- `d3d12_compute_test`: the compute path through the proxy. It creates a root signature from the PC serializer's + blob, and a PSO through slot 62 from a container shaped like the game's, found in a translator-style index by its + FSSM hash (an unknown program is refused). It sets root constants, a root UAV and a descriptor table whose + application-written entry points at an upload buffer, then runs two dispatches that change s0 and the UAV in + between. The results come back through a readback buffer. The shader, `test/glsl/cs_user_data.comp`, is GLSL + written to the translator's push-constant and address contract, compiled with `glslangValidator`. - `d3d12_present_test`: milestone M0. It opens a window and presents 60 frames, each one: reset the list, move the back buffer `PRESENT` → `RENDER_TARGET`, clear, move it back, execute, present, signal a fence. It then resizes the window, which recreates the swapchain and scales the blit, and switches to unsynchronised presents. diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 1814522ae..2f81fec14 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -304,14 +304,14 @@ if(Vulkan_FOUND) OUTPUT ${LEONIDA_STUBS} COMMAND Python3::Interpreter -I ${CMAKE_CURRENT_SOURCE_DIR}/../tools/gen_d3d12_stubs.py --out ${LEONIDA_STUBS} ID3D12GraphicsCommandList8 ID3D12CommandQueue ID3D12CommandAllocator ID3D12Fence1 - ID3D12Device11 ID3D12DescriptorHeap ID3D12Resource + ID3D12Device11 ID3D12DescriptorHeap ID3D12Resource ID3D12RootSignature ID3D12PipelineState DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/../tools/gen_d3d12_stubs.py COMMENT "Generating D3D12 COM stubs" VERBATIM) add_library(gta6rt_d3d12_com STATIC shims/d3d12_com.cpp shims/d3d12_vulkan_device.cpp shims/d3d12_xs_device.cpp ${LEONIDA_STUBS}) # d3d12_vulkan_device.cpp reads the PC device behind the proxy (#224) target_include_directories(gta6rt_d3d12_com PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/generated) - target_link_libraries(gta6rt_d3d12_com PUBLIC Vulkan::Headers) + target_link_libraries(gta6rt_d3d12_com PUBLIC Vulkan::Headers gta6rt_root_signature) target_compile_definitions(gta6rt_d3d12_com PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) target_compile_options(gta6rt_d3d12_com PRIVATE /W4 /permissive- /utf-8) @@ -345,6 +345,29 @@ if(Vulkan_FOUND) target_compile_definitions(d3d12_present_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) target_compile_options(d3d12_present_test PRIVATE /W4 /permissive- /utf-8) + # The compute path: root signature, compute PSO from a translator-style index, root arguments, dispatch. Its + # shader is GLSL written to the translator's push-constant/address contract, compiled here. + if(NOT Vulkan_GLSLANG_VALIDATOR_EXECUTABLE) + find_program(Vulkan_GLSLANG_VALIDATOR_EXECUTABLE glslangValidator HINTS "$ENV{VULKAN_SDK}/Bin" "$ENV{VULKAN_SDK}/bin") + endif() + if(Vulkan_GLSLANG_VALIDATOR_EXECUTABLE) + set(LEONIDA_TEST_CS ${CMAKE_CURRENT_BINARY_DIR}/generated/cs_user_data.spv) + add_custom_command( + OUTPUT ${LEONIDA_TEST_CS} + COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${LEONIDA_TEST_CS} + ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_user_data.comp + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_user_data.comp + COMMENT "Compiling the compute test shader" + VERBATIM) + add_executable(d3d12_compute_test test/d3d12_compute_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_TEST_CS}) + target_link_libraries(d3d12_compute_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_compute_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + LEONIDA_TEST_CS_SPV="${LEONIDA_TEST_CS}") + target_compile_options(d3d12_compute_test PRIVATE /W4 /permissive- /utf-8) + else() + message(STATUS "glslangValidator not found: d3d12_compute_test is not built") + endif() + # The loader can create this device instead of the host's (D3D12XboxCreateDevice, LEONIDA_D3D12=vulkan). if(TARGET gta6rt) target_link_libraries(gta6rt PRIVATE gta6rt_d3d12_com) diff --git a/runtime/README.md b/runtime/README.md index 9b980003c..ad0070392 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -98,6 +98,8 @@ when the Vulkan SDK is found: - GPU tests count only validation-type errors. Loader and layer messages, such as a third-party implicit layer that fails to load, are printed but don't fail the run; to silence one, set `VK_LOADER_LAYERS_DISABLE=`. +- `d3d12_compute_test` — the compute path: root signature, a compute PSO found by its FSSM hash in a + translator-style index, root arguments through the GPU address arena, and two dispatches. - `d3d12_present_test` — milestone M0: opens a window and presents 60 cleared frames through the proxy on Vulkan, resizes it, and checks the colour on screen. Set `LEONIDA_VK_VALIDATION=1` to run them under the Khronos validation layer. diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index 9ee34d761..7458fc3e5 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -3,6 +3,7 @@ #include "d3d12_stubs.h" // generated #include "d3d12_com_object.h" +#include #include #include #include @@ -82,10 +83,80 @@ class GraphicsCommandList final if (!list_.reset()) return E_FAIL; // D3D12 resets only closed lists invalid_ = false; front_stencil_ref_ = back_stencil_ref_ = 0; // Reset returns every list state to its default - if (state) stub("ID3D12GraphicsCommandList::Reset(initial pipeline state)"); + compute_ = {}; + graphics_ = {}; + compute_pipeline_ = compute_pipeline_id(state); + if (state && !compute_pipeline_) stub("ID3D12GraphicsCommandList::Reset(graphics pipeline state)"); return S_OK; } + // Root signatures, pipeline state and root arguments. The arguments are packed into the 32 user-data dwords + // the translated shaders read (root_signature.h; docs section 3.5); a draw or dispatch records a copy. + void STDMETHODCALLTYPE SetComputeRootSignature(ID3D12RootSignature* signature) override { + bind_root(compute_, signature); + } + void STDMETHODCALLTYPE SetGraphicsRootSignature(ID3D12RootSignature* signature) override { + bind_root(graphics_, signature); + } + + void STDMETHODCALLTYPE SetPipelineState(ID3D12PipelineState* state) override { + compute_pipeline_ = compute_pipeline_id(state); + if (state && !compute_pipeline_) stub("ID3D12GraphicsCommandList::SetPipelineState(graphics)"); + } + + // The bound heaps matter to direct heap indexing, which is still open (section 3.4); tables carry their VAs. + void STDMETHODCALLTYPE SetDescriptorHeaps(UINT, ID3D12DescriptorHeap* const*) override {} + + void STDMETHODCALLTYPE SetComputeRoot32BitConstant(UINT index, UINT value, UINT offset) override { + constants(compute_, index, 1, &value, offset); + } + void STDMETHODCALLTYPE SetComputeRoot32BitConstants(UINT index, UINT count, const void* data, UINT offset) override { + constants(compute_, index, count, data, offset); + } + void STDMETHODCALLTYPE SetComputeRootConstantBufferView(UINT index, D3D12_GPU_VIRTUAL_ADDRESS va) override { + address(compute_, index, va, rt::rootsig::ParamType::Descriptor); + } + void STDMETHODCALLTYPE SetComputeRootShaderResourceView(UINT index, D3D12_GPU_VIRTUAL_ADDRESS va) override { + address(compute_, index, va, rt::rootsig::ParamType::Descriptor); + } + void STDMETHODCALLTYPE SetComputeRootUnorderedAccessView(UINT index, D3D12_GPU_VIRTUAL_ADDRESS va) override { + address(compute_, index, va, rt::rootsig::ParamType::Descriptor); + } + void STDMETHODCALLTYPE SetComputeRootDescriptorTable(UINT index, D3D12_GPU_DESCRIPTOR_HANDLE table) override { + address(compute_, index, table.ptr, rt::rootsig::ParamType::Table); + } + void STDMETHODCALLTYPE SetGraphicsRoot32BitConstant(UINT index, UINT value, UINT offset) override { + constants(graphics_, index, 1, &value, offset); + } + void STDMETHODCALLTYPE SetGraphicsRoot32BitConstants(UINT index, UINT count, const void* data, UINT offset) override { + constants(graphics_, index, count, data, offset); + } + void STDMETHODCALLTYPE SetGraphicsRootConstantBufferView(UINT index, D3D12_GPU_VIRTUAL_ADDRESS va) override { + address(graphics_, index, va, rt::rootsig::ParamType::Descriptor); + } + void STDMETHODCALLTYPE SetGraphicsRootShaderResourceView(UINT index, D3D12_GPU_VIRTUAL_ADDRESS va) override { + address(graphics_, index, va, rt::rootsig::ParamType::Descriptor); + } + void STDMETHODCALLTYPE SetGraphicsRootUnorderedAccessView(UINT index, D3D12_GPU_VIRTUAL_ADDRESS va) override { + address(graphics_, index, va, rt::rootsig::ParamType::Descriptor); + } + void STDMETHODCALLTYPE SetGraphicsRootDescriptorTable(UINT index, D3D12_GPU_DESCRIPTOR_HANDLE table) override { + address(graphics_, index, table.ptr, rt::rootsig::ParamType::Table); + } + + void STDMETHODCALLTYPE Dispatch(UINT x, UINT y, UINT z) override { + if (!compute_pipeline_ || !compute_.layout) return check(false); + check(list_.dispatch({compute_pipeline_, compute_.data, x, y, z})); + } + + // ClearState returns every piece of list state to its default, as Reset does (stencil references included). + void STDMETHODCALLTYPE ClearState(ID3D12PipelineState* state) override { + front_stencil_ref_ = back_stencil_ref_ = 0; + compute_ = {}; + graphics_ = {}; + compute_pipeline_ = compute_pipeline_id(state); + } + void STDMETHODCALLTYPE ResourceBarrier(UINT count, const D3D12_RESOURCE_BARRIER* barriers) override { for (UINT i = 0; i < count; ++i) { const auto& b = barriers[i]; @@ -219,11 +290,59 @@ class GraphicsCommandList final if (!ok) invalid_ = true; } + struct RootState { + const RootArgumentLayout* layout = nullptr; + std::array data{}; + }; + + // D3D12 leaves root arguments undefined after a root-signature change; they start at zero here. + void bind_root(RootState& state, ID3D12RootSignature* signature) { + state.layout = root_signature_layout(signature); + state.data = {}; + if (signature && !state.layout) stub("ID3D12GraphicsCommandList::Set*RootSignature(foreign root signature)"); + } + + // The parameter, if it exists and has the expected type; null after recording an invalid call. + const RootArgumentLayout::Parameter* parameter(RootState& state, UINT index, rt::rootsig::ParamType type) { + if (!state.layout || index >= state.layout->parameters.size() || + state.layout->parameters[index].type != type) { + check(false); + return nullptr; + } + return &state.layout->parameters[index]; + } + + // Dwords beyond the 32 user registers are what the console spills to memory; that layout is still open. + void write(RootState& state, std::uint32_t dword, std::uint32_t value) { + if (dword < rt::rootsig::kMaxUserSgprs) + state.data[dword] = value; + else + stub("root arguments beyond 32 user-data dwords (spill not modelled)"); + } + + void constants(RootState& state, UINT index, UINT count, const void* data, UINT offset) { + const RootArgumentLayout::Parameter* p = parameter(state, index, rt::rootsig::ParamType::Constants); + if (!p) return; + if (!data || std::uint64_t(offset) + count > p->constant_count) return check(false); + const auto* values = static_cast(data); + for (UINT i = 0; i < count; ++i) write(state, p->user_offset + offset + i, values[i]); + } + + void address(RootState& state, UINT index, std::uint64_t va, rt::rootsig::ParamType type) { + const RootArgumentLayout::Parameter* p = parameter(state, index, type); + if (!p) return; + write(state, p->user_offset, std::uint32_t(va)); + write(state, p->user_offset + 1, std::uint32_t(va >> 32)); + } + D3D12_COMMAND_LIST_TYPE type_; leonida::CommandList list_; bool invalid_ = false; UINT front_stencil_ref_ = 0; UINT back_stencil_ref_ = 0; + RootState compute_; + RootState graphics_; + std::uintptr_t compute_pipeline_ = 0; }; class Fence final diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index b71652267..3ec50b305 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -15,6 +15,10 @@ #include "../src/vulkan_backend.h" #include +#include +#include + +#include "../src/root_signature.h" namespace leonida { class VulkanPresenter; @@ -45,6 +49,12 @@ struct VulkanDeviceInfo { std::uint32_t max_push_constants_size = 0; bool push_constants_need_fallback = false; bool presentation = false; // VK_KHR_surface + VK_KHR_win32_surface on the instance, VK_KHR_swapchain on the device + // bufferDeviceAddress enabled: buffers and shader-visible heaps then live in the GPU address arena and have + // console VAs (docs section 3.3); without it, GetGPUVirtualAddress returns 0 and pipelines cannot be created. + bool buffer_device_address = false; + // The translator's output folder (spirv/index.json + .spv) for pipeline creation; empty: the + // LEONIDA_SHADERS environment variable. + std::string shader_dir; }; // A Vulkan-backed ID3D12Device (PC ABI, up to ID3D12Device11) on caller-owned Vulkan objects, which must outlive @@ -92,6 +102,22 @@ class WindowPresenter { // Null when `device` is not a Vulkan device created with presentation, or the window cannot be presented to. std::unique_ptr create_window_presenter(ID3D12Device* device, HWND window); +// Where each root parameter's arguments go in the 32 user-data dwords the translated shaders read, as +// rt::rootsig::pack() lays them out (docs section 3.5). Built when a Vulkan device creates the root signature. +struct RootArgumentLayout { + struct Parameter { + rt::rootsig::ParamType type; + std::uint32_t user_offset; // first dword; unused for a parameter with no dwords + std::uint32_t constant_count; // constants only + }; + std::vector parameters; +}; + +// For the command list: the argument layout of a root signature from a Vulkan device, and the id it records for a +// compute pipeline state (0: not a compute PSO of a Vulkan device). +const RootArgumentLayout* root_signature_layout(ID3D12RootSignature* signature); +std::uintptr_t compute_pipeline_id(ID3D12PipelineState* pipeline); + // ExecuteCommandLists returns void; this is what the last call on the queue did. leonida::ReplayResult last_execute_result(ID3D12CommandQueue* queue); diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 8db9da89f..a68daaaaf 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -7,6 +7,7 @@ #include "d3d12_stubs.h" // generated #include "d3d12_com_object.h" #include "d3d12_xs_device.h" +#include "../src/shader_library.h" #include "../src/vulkan_present.h" #include @@ -14,6 +15,8 @@ #include #include #include +#include +#include #include #include #include @@ -116,6 +119,77 @@ struct DeviceState { PFN_vkGetPhysicalDeviceFormatProperties format_properties = nullptr; PFN_vkGetPhysicalDeviceImageFormatProperties image_format_properties = nullptr; + // The GPU address arena (docs/d3d12_vulkan.md section 3.3): one host-visible, device-addressable VkBuffer that + // stands in for the console's GPU address space. A console VA is an offset in it, and heap_base (push-constant + // dwords 32-33) is its device address. It is at most 4 GiB, so every VA fits the 32-bit descriptor-table + // pointers some shaders use. The first 64 KiB are never handed out, so no resource has VA 0. + struct Arena { + VkBuffer buffer = VK_NULL_HANDLE; + VkDeviceMemory memory = VK_NULL_HANDLE; + std::uint8_t* mapped = nullptr; + VkDeviceAddress address = 0; + VkDeviceSize size = 0; + std::mutex mutex; + std::map free; // offset -> size + } arena; + + bool arena_allocate(VkDeviceSize bytes, VkDeviceSize alignment, VkDeviceSize& out) { + std::lock_guard lock(arena.mutex); + for (auto it = arena.free.begin(); it != arena.free.end(); ++it) { + const VkDeviceSize start = (it->first + alignment - 1) / alignment * alignment; + const VkDeviceSize end = it->first + it->second; + if (start + bytes > end) continue; + const VkDeviceSize block = it->first; + arena.free.erase(it); + if (start > block) arena.free[block] = start - block; + if (start + bytes < end) arena.free[start + bytes] = end - (start + bytes); + out = start; + return true; + } + return false; + } + + void arena_release(VkDeviceSize offset, VkDeviceSize bytes) { + std::lock_guard lock(arena.mutex); + auto it = arena.free.emplace(offset, bytes).first; + if (auto next = std::next(it); next != arena.free.end() && it->first + it->second == next->first) { + it->second += next->second; + arena.free.erase(next); + } + if (it != arena.free.begin()) { + if (auto previous = std::prev(it); previous->first + previous->second == it->first) { + previous->second += it->second; + arena.free.erase(it); + } + } + } + + // The translator's output, loaded on first use. + std::mutex library_mutex; + bool library_tried = false; + leonida::ShaderLibrary shader_library; + + const leonida::ShaderLibrary* library() { + std::lock_guard lock(library_mutex); + if (!library_tried) { + library_tried = true; + std::string dir = info.shader_dir; + if (dir.empty()) { + char buffer[1024] = {}; + size_t length = 0; + if (getenv_s(&length, buffer, "LEONIDA_SHADERS") == 0 && length > 1) dir = buffer; + } + std::string error; + if (dir.empty()) + std::fprintf(stderr, "[rt] d3d12: no translated shaders: set LEONIDA_SHADERS to /shaders/spirv\n"); + else if (!shader_library.load(dir, &error)) + std::fprintf(stderr, "[rt] d3d12: %s\n", error.c_str()); + else + std::fprintf(stderr, "[rt] d3d12: %zu translated shaders from %s\n", shader_library.size(), dir.c_str()); + } + return shader_library.loaded() ? &shader_library : nullptr; + } + bool depth_usable(VkFormat format) const { VkFormatProperties properties{}; format_properties(info.physical, format, &properties); @@ -132,12 +206,15 @@ struct DeviceState { // The first memory type with `required`, preferring one that also has `preferred`. VkDeviceMemory allocate(const VkMemoryRequirements& requirements, VkMemoryPropertyFlags required, - VkMemoryPropertyFlags preferred) const { + VkMemoryPropertyFlags preferred, bool device_address = false) const { + VkMemoryAllocateFlagsInfo flags_info{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO}; + flags_info.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; for (const VkMemoryPropertyFlags flags : {required | preferred, required}) { for (std::uint32_t i = 0; i < memory.memoryTypeCount; ++i) { if (!(requirements.memoryTypeBits & (1u << i))) continue; if ((memory.memoryTypes[i].propertyFlags & flags) != flags) continue; VkMemoryAllocateInfo allocate{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; + if (device_address) allocate.pNext = &flags_info; allocate.allocationSize = requirements.size; allocate.memoryTypeIndex = i; VkDeviceMemory out = VK_NULL_HANDLE; @@ -155,22 +232,43 @@ class DescriptorHeap final // {4a7d2c90-5e1b-4f63-8c0a-91d3b6e2f417} static constexpr GUID kTag{0x4a7d2c90, 0x5e1b, 0x4f63, {0x8c, 0x0a, 0x91, 0xd3, 0xb6, 0xe2, 0xf4, 0x17}}; - explicit DescriptorHeap(const D3D12_DESCRIPTOR_HEAP_DESC& desc) - : desc_(desc), storage_(new std::byte[std::size_t(desc.NumDescriptors) * kDescriptorSize]()) {} + // A shader-visible heap lives in the GPU address arena: its CPU handles point at the arena's host mapping and + // its GPU handle is the console VA, so the bytes the game or Create*View writes are what shaders load. Other + // heaps (RTV, DSV, non-visible staging heaps) stay in host memory. + DescriptorHeap(DeviceState& device, const D3D12_DESCRIPTOR_HEAP_DESC& desc) : device_(device), desc_(desc) { + const VkDeviceSize bytes = VkDeviceSize(desc.NumDescriptors) * kDescriptorSize; + if ((desc.Flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE) && device.arena.mapped && + device.arena_allocate(bytes, 256, arena_offset_)) { + in_arena_ = true; + cpu_ = device.arena.mapped + arena_offset_; + std::memset(cpu_, 0, std::size_t(bytes)); + } else { + storage_.reset(new std::byte[std::size_t(bytes)]()); + cpu_ = reinterpret_cast(storage_.get()); + } + } + + ~DescriptorHeap() override { + if (in_arena_) device_.arena_release(arena_offset_, VkDeviceSize(desc_.NumDescriptors) * kDescriptorSize); + } D3D12_DESCRIPTOR_HEAP_DESC STDMETHODCALLTYPE GetDesc() override { return desc_; } D3D12_CPU_DESCRIPTOR_HANDLE STDMETHODCALLTYPE GetCPUDescriptorHandleForHeapStart() override { - return {reinterpret_cast(storage_.get())}; + return {reinterpret_cast(cpu_)}; } - // Shader-visible heaps get a GPU handle; descriptor tables that read it are not implemented yet. D3D12_GPU_DESCRIPTOR_HANDLE STDMETHODCALLTYPE GetGPUDescriptorHandleForHeapStart() override { if (!(desc_.Flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE)) return {0}; - return {reinterpret_cast(storage_.get())}; + if (!in_arena_) log_once("shader-visible heap without a GPU address arena; flags", int(desc_.Flags)); + return {in_arena_ ? UINT64(arena_offset_) : 0}; } private: + DeviceState& device_; D3D12_DESCRIPTOR_HEAP_DESC desc_; std::unique_ptr storage_; + std::uint8_t* cpu_ = nullptr; + VkDeviceSize arena_offset_ = 0; + bool in_arena_ = false; }; class Resource final @@ -187,6 +285,7 @@ class Resource final auto& vk = device_.context->vk; const VkDevice dev = device_.info.device; device_.context->remove_resource(id()); + if (in_arena_) device_.arena_release(arena_offset_, desc_.Width); if (image_) vk.vkDestroyImage(dev, image_, nullptr); if (buffer_) vk.vkDestroyBuffer(dev, buffer_, nullptr); if (memory_) vk.vkFreeMemory(dev, memory_, nullptr); @@ -195,24 +294,51 @@ class Resource final leonida::ResourceId id() const { return resource_id(this); } VkImage image() const { return image_; } + // Default-heap buffers are ranges of the GPU address arena: console VA = offset, zeroed through the arena's host + // mapping. Upload and readback buffers keep their own host memory; with buffer device addresses their console + // VA is their device address minus heap_base, so a shader's heap_base + VA still lands on them (section 3.3). HRESULT create_buffer() { auto& vk = device_.context->vk; + const bool host = cpu_visible(); + leonida::ResourceBinding binding{}; // a buffer: no image + binding.size = desc_.Width; + if (!host && device_.arena.mapped) { + if (!device_.arena_allocate(desc_.Width, D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT, arena_offset_)) { + log_once("GPU address arena full (raise LEONIDA_ARENA_MB); buffer size in KiB:", + int(desc_.Width / 1024)); + return E_OUTOFMEMORY; + } + in_arena_ = true; + std::memset(device_.arena.mapped + arena_offset_, 0, std::size_t(desc_.Width)); + va_ = arena_offset_; + binding.buffer = device_.arena.buffer; + binding.buffer_offset = arena_offset_; + device_.context->add_resource(id(), binding); + return S_OK; + } + const bool addressable = device_.arena.buffer != VK_NULL_HANDLE; VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; info.size = desc_.Width; info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT; + if (addressable) info.usage |= VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; if (vk.vkCreateBuffer(device_.info.device, &info, nullptr, &buffer_) != VK_SUCCESS) return E_OUTOFMEMORY; VkMemoryRequirements requirements{}; vk.vkGetBufferMemoryRequirements(device_.info.device, buffer_, &requirements); - const bool host = cpu_visible(); memory_ = host ? device_.allocate(requirements, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, - heap_.Type == D3D12_HEAP_TYPE_READBACK ? VK_MEMORY_PROPERTY_HOST_CACHED_BIT : 0) - : device_.allocate(requirements, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); + heap_.Type == D3D12_HEAP_TYPE_READBACK ? VK_MEMORY_PROPERTY_HOST_CACHED_BIT : 0, + addressable) + : device_.allocate(requirements, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, addressable); if (!memory_ || vk.vkBindBufferMemory(device_.info.device, buffer_, memory_, 0) != VK_SUCCESS) return E_OUTOFMEMORY; + if (addressable) { + VkBufferDeviceAddressInfo address{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; + address.buffer = buffer_; + va_ = vk.vkGetBufferDeviceAddress(device_.info.device, &address) - device_.arena.address; + } if (host) { if (vk.vkMapMemory(device_.info.device, memory_, 0, VK_WHOLE_SIZE, 0, &mapped_) != VK_SUCCESS) return E_OUTOFMEMORY; @@ -220,9 +346,7 @@ class Resource final } else { log_once("default-heap buffers are not zero-filled yet; dimension", int(desc_.Dimension)); } - leonida::ResourceBinding binding{}; // a buffer: no image binding.buffer = buffer_; - binding.size = desc_.Width; device_.context->add_resource(id(), binding); return S_OK; } @@ -287,6 +411,9 @@ class Resource final D3D12_RESOURCE_DESC STDMETHODCALLTYPE GetDesc() override { return desc_; } + // Buffers only, as on D3D12; textures have no GPU VA (images are reached through descriptors). + D3D12_GPU_VIRTUAL_ADDRESS STDMETHODCALLTYPE GetGPUVirtualAddress() override { return va_; } + HRESULT STDMETHODCALLTYPE GetHeapProperties(D3D12_HEAP_PROPERTIES* properties, D3D12_HEAP_FLAGS* flags) override { if (properties) *properties = heap_; if (flags) *flags = heap_flags_; @@ -316,6 +443,117 @@ class Resource final VkBuffer buffer_ = VK_NULL_HANDLE; VkDeviceMemory memory_ = VK_NULL_HANDLE; void* mapped_ = nullptr; + VkDeviceSize arena_offset_ = 0; + bool in_arena_ = false; + D3D12_GPU_VIRTUAL_ADDRESS va_ = 0; +}; + +class RootSignature final + : public Child { +public: + // {3e9b4a61-2d7c-4f18-b5a0-c71e8d92f036} + static constexpr GUID kTag{0x3e9b4a61, 0x2d7c, 0x4f18, {0xb5, 0xa0, 0xc7, 0x1e, 0x8d, 0x92, 0xf0, 0x36}}; + explicit RootSignature(RootArgumentLayout layout) : layout_(std::move(layout)) {} + const RootArgumentLayout& layout() const { return layout_; } + +private: + RootArgumentLayout layout_; +}; + +// A pipeline state. Compute only for now: the shader is found by the SHA-256 of its FSSM program in the +// translator's index, and the FSSM blob is copied into the arena as the shader's code base. +class PipelineState final + : public Child { +public: + // {8d2f6c14-b0e7-4a93-9c58-1f4a7e3b6d20} + static constexpr GUID kTag{0x8d2f6c14, 0xb0e7, 0x4a93, {0x9c, 0x58, 0x1f, 0x4a, 0x7e, 0x3b, 0x6d, 0x20}}; + explicit PipelineState(DeviceState& device) : device_(device) {} + + ~PipelineState() override { + auto& vk = device_.context->vk; + const VkDevice dev = device_.info.device; + if (registered_) device_.context->remove_pipeline(id()); + if (pipeline_.pipeline) vk.vkDestroyPipeline(dev, pipeline_.pipeline, nullptr); + if (pipeline_.layout) vk.vkDestroyPipelineLayout(dev, pipeline_.layout, nullptr); + if (module_) vk.vkDestroyShaderModule(dev, module_, nullptr); + if (code_bytes_) device_.arena_release(pipeline_.code_base, code_bytes_); + } + + std::uintptr_t id() const { return reinterpret_cast(static_cast(this)); } + bool compute() const { return registered_; } + + HRESULT create_compute(const D3D12_COMPUTE_PIPELINE_STATE_DESC& desc) { + auto& vk = device_.context->vk; + const VkDevice dev = device_.info.device; + if (!desc.CS.pShaderBytecode || !desc.CS.BytecodeLength) return E_INVALIDARG; + if (!device_.arena.mapped) { + log_once("pipelines need the GPU address arena (bufferDeviceAddress); stage", 0); + return E_NOTIMPL; + } + const std::vector fssm = leonida::fssm_program( + {static_cast(desc.CS.pShaderBytecode), desc.CS.BytecodeLength}); + if (fssm.empty()) { + log_once("compute shader bytecode holds no FSSM program; bytes", int(desc.CS.BytecodeLength)); + return E_INVALIDARG; + } + const leonida::ShaderLibrary* library = device_.library(); + if (!library) return E_FAIL; + const std::string hash = leonida::sha256_hex(fssm); + const leonida::ShaderEntry* entry = library->find("cs", hash); + if (!entry) { + std::fprintf(stderr, "[rt] d3d12: no translated compute shader for FSSM sha256 %s\n", hash.c_str()); + return E_INVALIDARG; + } + if (entry->binding_count) { + // Set 0 (bindless images, samplers, the descriptor hash table) is milestone M2. + std::fprintf(stderr, "[rt] d3d12: %s uses set-0 bindings; the bindless set is not implemented yet\n", + entry->name.c_str()); + return E_NOTIMPL; + } + if (entry->wave64) log_once("wave64 compute shader runs 32-wide (subgroup size control not requested yet)", 0); + const std::vector words = library->spirv(*entry); + if (words.empty()) { + std::fprintf(stderr, "[rt] d3d12: %s.spv is missing or not SPIR-V\n", entry->name.c_str()); + return E_FAIL; + } + + VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + module_info.codeSize = words.size() * 4; + module_info.pCode = words.data(); + if (vk.vkCreateShaderModule(dev, &module_info, nullptr, &module_) != VK_SUCCESS) return E_FAIL; + const VkPushConstantRange push{VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(leonida::ShaderUserData)}; + VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; + layout_info.pushConstantRangeCount = 1; + layout_info.pPushConstantRanges = &push; + if (vk.vkCreatePipelineLayout(dev, &layout_info, nullptr, &pipeline_.layout) != VK_SUCCESS) return E_FAIL; + VkComputePipelineCreateInfo pipeline_info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; + pipeline_info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; + pipeline_info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; + pipeline_info.stage.module = module_; + pipeline_info.stage.pName = "main"; + pipeline_info.layout = pipeline_.layout; + if (vk.vkCreateComputePipelines(dev, VK_NULL_HANDLE, 1, &pipeline_info, nullptr, &pipeline_.pipeline) != + VK_SUCCESS) + return E_FAIL; + + // The code base: shaders read constant tables embedded in their own program through s_getpc_b64. + VkDeviceSize offset = 0; + if (!device_.arena_allocate(fssm.size(), 256, offset)) return E_OUTOFMEMORY; + std::memcpy(device_.arena.mapped + offset, fssm.data(), fssm.size()); + code_bytes_ = fssm.size(); + pipeline_.code_base = offset; + device_.context->add_pipeline(id(), pipeline_); + registered_ = true; + return S_OK; + } + +private: + DeviceState& device_; + leonida::ComputePipeline pipeline_; + VkShaderModule module_ = VK_NULL_HANDLE; + VkDeviceSize code_bytes_ = 0; + bool registered_ = false; }; // The Vulkan objects create_vulkan_device_standalone made, destroyed with the device. @@ -360,6 +598,45 @@ class Device final state_.context = std::make_unique(get_device, info.device, info.separate_depth_stencil_layouts); + if (info.buffer_device_address && state_.context->loaded() && !create_arena()) + std::fprintf(stderr, "[rt] d3d12: the GPU address arena could not be created\n"); + } + + // LEONIDA_ARENA_MB sets its size (default 256, at most 4095): it holds every default-heap buffer, shader- + // visible descriptor heap and shader program. M0-M3 keep it host-visible (section 3.3, memory type policy). + bool create_arena() { + auto& vk = state_.context->vk; + if (!vk.vkGetBufferDeviceAddress) return false; + VkDeviceSize megabytes = 256; + char text[16] = {}; + size_t length = 0; + if (getenv_s(&length, text, "LEONIDA_ARENA_MB") == 0 && length > 1) + megabytes = std::clamp(std::strtoull(text, nullptr, 10), 16, 4095); + auto& arena = state_.arena; + VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; + info.size = megabytes << 20; + info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | + VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | + VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT | + VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; + if (vk.vkCreateBuffer(state_.info.device, &info, nullptr, &arena.buffer) != VK_SUCCESS) return false; + VkMemoryRequirements requirements{}; + vk.vkGetBufferMemoryRequirements(state_.info.device, arena.buffer, &requirements); + arena.memory = state_.allocate(requirements, + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, + VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, true); + void* mapped = nullptr; + if (!arena.memory || vk.vkBindBufferMemory(state_.info.device, arena.buffer, arena.memory, 0) != VK_SUCCESS || + vk.vkMapMemory(state_.info.device, arena.memory, 0, VK_WHOLE_SIZE, 0, &mapped) != VK_SUCCESS) + return false; + arena.mapped = static_cast(mapped); + VkBufferDeviceAddressInfo address{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; + address.buffer = arena.buffer; + arena.address = vk.vkGetBufferDeviceAddress(state_.info.device, &address); + arena.size = info.size; + arena.free[64 * 1024] = arena.size - 64 * 1024; + state_.context->set_heap_base(arena.address); + return true; } ~Device() override { @@ -367,6 +644,11 @@ class Device final std::lock_guard lock(state_.context->submit_mutex()); state_.context->vk.vkDeviceWaitIdle(state_.info.device); } + if (state_.context && state_.arena.buffer) { + auto& vk = state_.context->vk; + vk.vkDestroyBuffer(state_.info.device, state_.arena.buffer, nullptr); + if (state_.arena.memory) vk.vkFreeMemory(state_.info.device, state_.arena.memory, nullptr); + } state_.context.reset(); if (owned_.device) owned_.destroy_device(owned_.device, nullptr); if (owned_.instance) owned_.destroy_instance(owned_.instance, nullptr); @@ -428,11 +710,60 @@ class Device final if (!out) return E_POINTER; *out = nullptr; if (!desc || !desc->NumDescriptors) return E_INVALIDARG; - auto* heap = new DescriptorHeap(*desc); + auto* heap = new DescriptorHeap(state_, *desc); heap->attach_device(identity()); return hand_out(heap, riid, out); } + HRESULT STDMETHODCALLTYPE CreateRootSignature(UINT, const void* blob, SIZE_T size, REFIID riid, + void** out) override { + if (!out) return E_POINTER; + *out = nullptr; + if (!blob || !size) return E_INVALIDARG; + // The repository's root-signature model (runtime/src/root_signature.h): parse the RTS0 blob, then pack + // the parameters into the 32 user-data dwords. pack() refuses what it cannot place (more than 32 dwords: + // the console spills those to memory, in a layout that is still open), and so does this. + const rt::rootsig::DecodeResult parsed = + rt::rootsig::parse_rts0(static_cast(blob), size); + if (!parsed.ok) { + std::fprintf(stderr, "[rt] d3d12: root signature not understood: %s\n", parsed.error.c_str()); + return E_INVALIDARG; + } + const rt::rootsig::PackResult packed = rt::rootsig::pack(parsed.sig); + if (!packed.ok) { + std::fprintf(stderr, "[rt] d3d12: root signature refused: %s\n", packed.error.c_str()); + return E_INVALIDARG; + } + RootArgumentLayout layout; + for (std::size_t i = 0; i < parsed.sig.params.size(); ++i) { + std::uint32_t first = UINT32_MAX; + for (std::uint32_t d = 0; d < packed.dword_count; ++d) + if (packed.provenance[d].param_index == i) { + first = d; + break; + } + layout.parameters.push_back({parsed.sig.params[i].type, first, parsed.sig.params[i].num_values}); + } + auto* signature = new RootSignature(std::move(layout)); + signature->attach_device(identity()); + return hand_out(signature, riid, out); + } + + // PC slot 11; the Xbox ABI reaches it through device slot 62 (the proxy forwards). + HRESULT STDMETHODCALLTYPE CreateComputePipelineState(const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc, REFIID riid, + void** out) override { + if (!out) return E_POINTER; + *out = nullptr; + if (!desc) return E_INVALIDARG; + auto* pipeline = new PipelineState(state_); + pipeline->attach_device(identity()); + if (const HRESULT hr = pipeline->create_compute(*desc); FAILED(hr)) { + pipeline->Release(); + return hr; + } + return hand_out(pipeline, riid, out); + } + UINT STDMETHODCALLTYPE GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE) override { return kDescriptorSize; } @@ -782,6 +1113,16 @@ void set_device_outer(ID3D12Device* device, IUnknown* outer) { if (Device* d = Device::from(device)) d->set_outer(outer); } +const RootArgumentLayout* root_signature_layout(ID3D12RootSignature* signature) { + const RootSignature* s = RootSignature::from(signature); + return s ? &s->layout() : nullptr; +} + +std::uintptr_t compute_pipeline_id(ID3D12PipelineState* pipeline) { + const PipelineState* p = PipelineState::from(pipeline); + return p && p->compute() ? p->id() : 0; +} + VkImage vulkan_image(ID3D12Resource* resource) { const Resource* r = Resource::from(resource); return r ? r->image() : VK_NULL_HANDLE; @@ -933,7 +1274,7 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out) { vkGetPhysicalDeviceFeatures2(candidate, &features); const bool bc = features.features.textureCompressionBC; if (!f13.dynamicRendering || !f13.synchronization2 || !f12.timelineSemaphore || - !f12.separateDepthStencilLayouts) + !f12.separateDepthStencilLayouts || !f12.bufferDeviceAddress) continue; std::uint32_t family_count = 0; vkGetPhysicalDeviceQueueFamilyProperties(candidate, &family_count, nullptr); @@ -960,6 +1301,8 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out) { VkPhysicalDeviceVulkan12Features enable12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, &enable13}; enable12.timelineSemaphore = VK_TRUE; enable12.separateDepthStencilLayouts = VK_TRUE; + enable12.bufferDeviceAddress = VK_TRUE; + info.buffer_device_address = true; const float priority = 1.0f; VkDeviceQueueCreateInfo queue_info{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO}; queue_info.queueFamilyIndex = info.queue_family; diff --git a/runtime/test/d3d12_compute_test.cpp b/runtime/test/d3d12_compute_test.cpp new file mode 100644 index 000000000..d07c303fe --- /dev/null +++ b/runtime/test/d3d12_compute_test.cpp @@ -0,0 +1,330 @@ +// The compute path end to end, through the Xbox-ABI proxy over the Vulkan device: +// - a root signature serialized by the PC runtime, created with CreateRootSignature; +// - a compute PSO created through device slot 62 (the Xbox shape) from a shader container shaped like the +// game's (DXBC, DXIL, XDAT 0x0D, XBCH, zlib), found by the SHA-256 of its FSSM program in a translator index; +// - buffers and a shader-visible descriptor heap in the GPU address arena, an upload buffer reached through its +// biased console VA; +// - root constants, a root UAV and a descriptor table set on the command list, two dispatches that each keep the +// arguments they were recorded with, and the results copied to a readback buffer. +// The shader (test/glsl/cs_user_data.comp) is written to the translator's push-constant and address contract. +// No game data. Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation. +#include "vk_test_device.h" +#include "../shims/d3d12_com.h" +#include "../src/shader_library.h" +#include "../shims/d3d12_xs_device.h" + +#include +#include +#include +#include +#include + +#ifndef LEONIDA_TEST_CS_SPV +#error "LEONIDA_TEST_CS_SPV must name the compiled test shader" +#endif + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +namespace { + +using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slots 9/10: handle in RAX +// Device slot 62 as XboxBvhBuilder.dll calls it on 1.0.2.1: (desc, 0, 0, riid, out) (main's 28cf235). +using XboxComputePipelineFn = HRESULT(WINAPI*)(void* device, const D3D12_COMPUTE_PIPELINE_STATE_DESC*, std::uint64_t, + std::uint64_t, const IID*, void**); +using SerializeFn = HRESULT(WINAPI*)(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC*, ID3DBlob**, ID3DBlob**); + +template +struct Ref { + T* p = nullptr; + ~Ref() { reset(); } + void reset() { + if (p) p->Release(); + p = nullptr; + } + T* operator->() const { return p; } +}; + +void* slot(void* object, unsigned index) { return (*reinterpret_cast(object))[index]; } + +void put32(std::vector& out, std::uint32_t v) { + for (int i = 0; i < 4; ++i) out.push_back(std::uint8_t(v >> (8 * i))); +} + +// zlib with one stored block (RFC 1950/1951), enough to wrap a test program. +std::vector zlib_stored(const std::vector& data) { + std::vector out = {0x78, 0x01, 0x01}; + const auto length = std::uint16_t(data.size()); + out.insert(out.end(), {std::uint8_t(length), std::uint8_t(length >> 8), std::uint8_t(~length), + std::uint8_t(~length >> 8)}); + out.insert(out.end(), data.begin(), data.end()); + std::uint32_t a = 1, b = 0; + for (const std::uint8_t x : data) { + a = (a + x) % 65521; + b = (b + a) % 65521; + } + const std::uint32_t adler = (b << 16) | a; + out.insert(out.end(), {std::uint8_t(adler >> 24), std::uint8_t(adler >> 16), std::uint8_t(adler >> 8), + std::uint8_t(adler)}); + return out; +} + +// DXBC { DXIL { stub, XDAT { 0x0D: XBCH + zlib(fssm) } } }, the layout tools/fssm_unpack.py reads. +std::vector shader_container(const std::vector& fssm) { + const auto stream = zlib_stored(fssm); + std::vector xbch = {'X', 'B', 'C', 'H'}; + for (const std::uint32_t v : {1u, std::uint32_t(stream.size()), 0u, std::uint32_t(fssm.size()), 0u}) put32(xbch, v); + xbch.insert(xbch.end(), stream.begin(), stream.end()); + std::vector dxil(16, 0); + dxil.insert(dxil.end(), {'X', 'D', 'A', 'T'}); + put32(dxil, 1); + put32(dxil, 12); + put32(dxil, 0x0d); + put32(dxil, 16 + 12 + 12); + put32(dxil, std::uint32_t(xbch.size())); + dxil.insert(dxil.end(), xbch.begin(), xbch.end()); + std::vector out = {'D', 'X', 'B', 'C'}; + out.resize(28, 0); + put32(out, 1); + put32(out, 36); + out.insert(out.end(), {'D', 'X', 'I', 'L'}); + put32(out, std::uint32_t(dxil.size())); + out.insert(out.end(), dxil.begin(), dxil.end()); + return out; +} + +std::vector serialize(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC& desc) { + const HMODULE d3d12 = LoadLibraryExA("d3d12.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); + const auto fn = d3d12 ? reinterpret_cast( + reinterpret_cast(GetProcAddress(d3d12, "D3D12SerializeVersionedRootSignature"))) + : nullptr; + std::vector out; + ID3DBlob* blob = nullptr; + if (fn && SUCCEEDED(fn(&desc, &blob, nullptr)) && blob) { + const auto* p = static_cast(blob->GetBufferPointer()); + out.assign(p, p + blob->GetBufferSize()); + blob->Release(); + } + return out; +} + +D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes, D3D12_RESOURCE_FLAGS flags) { + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = bytes; + desc.Height = 1; + desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + desc.Flags = flags; + return desc; +} + +D3D12_RESOURCE_BARRIER transition(ID3D12Resource* resource, D3D12_RESOURCE_STATES before, + D3D12_RESOURCE_STATES after) { + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barrier.Transition.pResource = resource; + barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + barrier.Transition.StateBefore = before; + barrier.Transition.StateAfter = after; + return barrier; +} + +} // namespace + +int main() { + vktest::Device d; + EXPECT(d.create()); + + // The shader program the PSO carries, and a translator index that maps its hash to the test module. + constexpr std::uint32_t code_word = 5000; + std::vector fssm = {'F', 'S', 'S', 'M'}; + put32(fssm, code_word); + for (std::uint32_t i = 0; i < 14; ++i) put32(fssm, 0xbf810000u + i); // filler, s_endpgm-like words + const auto container = shader_container(fssm); + EXPECT(leonida::fssm_program(container) == fssm); + const auto library = std::filesystem::temp_directory_path() / "leonida_compute_test"; + std::filesystem::create_directories(library); + std::filesystem::copy_file(LEONIDA_TEST_CS_SPV, library / "cs_user_data.spv", + std::filesystem::copy_options::overwrite_existing); + { + std::ofstream index(library / "index.json", std::ios::binary); + index << "{\"cs_user_data\": {\"stage\": \"cs\", \"fssm_sha256\": \"" << leonida::sha256_hex(fssm) + << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"local_size\": [64, 1, 1], " + "\"uses_code_base\": true, \"wave64\": false}}"; + } + + constexpr UINT elements = 64, bytes = elements * 4; + const std::uint32_t table_values[4] = {1000, 2000, 3000, 4000}; + std::vector first(elements), second(elements); + { + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = d.instance_proc; + info.instance = d.instance; + info.physical = d.physical; + info.device = d.device; + info.queue = d.queue; + info.queue_family = d.family; + info.buffer_device_address = true; + info.shader_dir = library.string(); + ID3D12Device* inner = nullptr; + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); + Ref device; + EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), + reinterpret_cast(&device.p)))); + rt::d3d12::set_device_outer(inner, device.p); + + // Root signature: [0] two constants (s0, s1), [1] a root UAV (s2:s3), [2] a one-CBV table (s4:s5). + D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_CBV, 1, 1, 0, 0}; + D3D12_ROOT_PARAMETER params[3] = {}; + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + params[0].Constants = {0, 0, 2}; + params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + params[1].Descriptor = {0, 0}; + params[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params[2].DescriptorTable = {1, &range}; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{}; + root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; + root_desc.Desc_1_0 = {3, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + const auto root_blob = serialize(root_desc); + EXPECT(!root_blob.empty()); + Ref root; + EXPECT(SUCCEEDED(device->CreateRootSignature(0, root_blob.data(), root_blob.size(), IID_PPV_ARGS(&root.p)))); + Ref junk; + EXPECT(device->CreateRootSignature(0, "junk", 4, IID_PPV_ARGS(&junk.p)) == E_INVALIDARG && !junk.p); + + // The PSO through slot 62, the Xbox call shape; an unknown program is refused. + D3D12_COMPUTE_PIPELINE_STATE_DESC pso_desc{}; + pso_desc.pRootSignature = root.p; + pso_desc.CS = {container.data(), container.size()}; + const IID pso_iid = __uuidof(ID3D12PipelineState); + Ref pso, unknown; + EXPECT(SUCCEEDED(reinterpret_cast(slot(device.p, 62))( + device.p, &pso_desc, 0, 0, &pso_iid, reinterpret_cast(&pso.p)))); + auto other = fssm; + other[8] ^= 1; + const auto other_container = shader_container(other); + pso_desc.CS = {other_container.data(), other_container.size()}; + EXPECT(device->CreateComputePipelineState(&pso_desc, IID_PPV_ARGS(&unknown.p)) == E_INVALIDARG && !unknown.p); + + // Buffers in the arena, an upload buffer outside it, a readback buffer for the results. + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; + const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}; + const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; + Ref out_a, out_b, constants, readback; + const auto uav = buffer_desc(bytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &uav, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr, + IID_PPV_ARGS(&out_a.p)))); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &uav, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr, + IID_PPV_ARGS(&out_b.p)))); + const auto constants_desc = buffer_desc(256, D3D12_RESOURCE_FLAG_NONE); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &constants_desc, + D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, + IID_PPV_ARGS(&constants.p)))); + const auto readback_desc = buffer_desc(2 * bytes, D3D12_RESOURCE_FLAG_NONE); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&readback.p)))); + const D3D12_GPU_VIRTUAL_ADDRESS va_a = out_a->GetGPUVirtualAddress(), va_b = out_b->GetGPUVirtualAddress(); + EXPECT(va_a >= 0x10000 && va_b >= 0x10000 && va_a != va_b && va_a < (1ull << 32) && va_b < (1ull << 32)); + EXPECT(va_a % D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT == 0); + EXPECT(constants->GetGPUVirtualAddress() != 0); // device address - heap base: wraps, still valid + void* mapped = nullptr; + EXPECT(SUCCEEDED(constants->Map(0, nullptr, &mapped))); + std::memcpy(mapped, table_values, sizeof(table_values)); + + // A shader-visible heap in the arena; its first slot gets the upload buffer's VA, written as raw bytes. + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 4, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + Ref heap; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap.p)))); + const std::uint64_t cpu = reinterpret_cast(slot(heap.p, 9))(heap.p); + const std::uint64_t gpu = reinterpret_cast(slot(heap.p, 10))(heap.p); + EXPECT(cpu && gpu >= 0x10000 && gpu < (1ull << 32)); + const std::uint64_t target = constants->GetGPUVirtualAddress(); + std::memcpy(reinterpret_cast(cpu), &target, sizeof(target)); + + D3D12_COMMAND_QUEUE_DESC queue_desc{}; + Ref queue; + Ref allocator; + Ref list; + Ref fence; + EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); + EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); + EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, + IID_PPV_ARGS(&list.p)))); + EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + + // Misuse is reported by Close: a dispatch without a pipeline, a root view set on a constants parameter. + list->Dispatch(1, 1, 1); + EXPECT(list->Close() == E_INVALIDARG); + EXPECT(SUCCEEDED(list->Reset(allocator.p, pso.p))); + list->SetComputeRootSignature(root.p); + list->SetComputeRootUnorderedAccessView(0, va_a); + EXPECT(list->Close() == E_INVALIDARG); + + // Two dispatches: the second changes s0 and the UAV; each must keep what it was recorded with. + EXPECT(SUCCEEDED(list->Reset(allocator.p, nullptr))); + ID3D12DescriptorHeap* heaps[] = {heap.p}; + list->SetDescriptorHeaps(1, heaps); + list->SetComputeRootSignature(root.p); + list->SetPipelineState(pso.p); + const std::uint32_t base_and_step[2] = {7, 3}; + list->SetComputeRoot32BitConstants(0, 2, base_and_step, 0); + list->SetComputeRootUnorderedAccessView(1, va_a); + list->SetComputeRootDescriptorTable(2, D3D12_GPU_DESCRIPTOR_HANDLE{gpu}); + list->Dispatch(1, 1, 1); + list->SetComputeRoot32BitConstant(0, 100, 0); + list->SetComputeRootUnorderedAccessView(1, va_b); + list->Dispatch(1, 1, 1); + D3D12_RESOURCE_BARRIER barriers[2] = { + transition(out_a.p, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE), + transition(out_b.p, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE)}; + list->ResourceBarrier(2, barriers); + list->CopyBufferRegion(readback.p, 0, out_a.p, 0, bytes); + list->CopyBufferRegion(readback.p, bytes, out_b.p, 0, bytes); + EXPECT(list->Close() == S_OK); + ID3D12CommandList* lists[] = {list.p}; + queue->ExecuteCommandLists(1, lists); + EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); + EXPECT(SUCCEEDED(queue->Signal(fence.p, 1))); + EXPECT(SUCCEEDED(fence->SetEventOnCompletion(1, nullptr))); + + void* results = nullptr; + EXPECT(SUCCEEDED(readback->Map(0, nullptr, &results))); + std::memcpy(first.data(), results, bytes); + std::memcpy(second.data(), static_cast(results) + bytes, bytes); + + for (auto* r : {&out_a, &out_b, &constants, &readback}) r->reset(); + pso.reset(); + root.reset(); + heap.reset(); + list.reset(); + allocator.reset(); + queue.reset(); + fence.reset(); + EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1); + } + std::filesystem::remove_all(library); + + unsigned mismatches = 0; + for (std::uint32_t i = 0; i < elements; ++i) { + const std::uint32_t a = 7 + 3 * i + table_values[i % 4] + code_word; + const std::uint32_t b = 100 + 3 * i + table_values[i % 4] + code_word; + if ((first[i] != a || second[i] != b) && mismatches++ < 4) + std::fprintf(stderr, "element %u: got %u and %u, want %u and %u\n", i, first[i], second[i], a, b); + } + EXPECT(!mismatches); + if (d.validation_errors()) { + std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); + return 1; + } + std::printf("compute: root constants, a root UAV and a descriptor table reached the shader through the GPU " + "address arena; %u elements matched in each of two dispatches\n", elements); + return 0; +} diff --git a/runtime/test/glsl/cs_user_data.comp b/runtime/test/glsl/cs_user_data.comp new file mode 100644 index 000000000..a932cc086 --- /dev/null +++ b/runtime/test/glsl/cs_user_data.comp @@ -0,0 +1,43 @@ +#version 460 +// A compute shader written to the translator's runtime contract (docs/design.md, "User data" and "Xbox GPU +// addresses"), standing in for a translated one in d3d12_compute_test: the 144-byte push-constant block holds +// s0..s31 (the root arguments), the heap base and the code base, and every memory access goes to heap base + +// console VA. It reads each kind of root argument the D3D12 layer packs: +// s0, s1 root constants: base and step +// s2:s3 a root UAV: the console VA of the output buffer +// s4:s5 a descriptor table: its first entry is a 64-bit console VA the application wrote itself +// code the shader's own program (FSSM blob), dword 1 +// and writes out[i] = s0 + s1 * i + table_target[i % 4] + code[1]. +#extension GL_EXT_buffer_reference : require +#extension GL_EXT_buffer_reference_uvec2 : require + +layout(local_size_x = 64) in; + +layout(buffer_reference, std430, buffer_reference_align = 4) buffer Words { + uint w[]; +}; + +layout(push_constant) uniform UserData { + uint s[32]; + uvec2 heap_base; + uvec2 code_base; +} pc; + +uvec2 add64(uvec2 a, uvec2 b) { + uint carry; + const uint low = uaddCarry(a.x, b.x, carry); + return uvec2(low, a.y + b.y + carry); +} + +Words at(uvec2 va) { + return Words(add64(pc.heap_base, va)); +} + +void main() { + const uint i = gl_GlobalInvocationID.x; + Words table = at(uvec2(pc.s[4], pc.s[5])); + Words constants = at(uvec2(table.w[0], table.w[1])); + Words code = at(pc.code_base); + Words result = at(uvec2(pc.s[2], pc.s[3])); + result.w[i] = pc.s[0] + pc.s[1] * i + constants.w[i % 4] + code.w[1]; +} diff --git a/runtime/test/vk_test_device.h b/runtime/test/vk_test_device.h index aeb3095a8..80b52a11c 100644 --- a/runtime/test/vk_test_device.h +++ b/runtime/test/vk_test_device.h @@ -183,7 +183,7 @@ class Device { VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &features12}; instance_fn("vkGetPhysicalDeviceFeatures2")(physical, &features); if (!features13.dynamicRendering || !features13.synchronization2 || !features12.timelineSemaphore || - !features12.separateDepthStencilLayouts) { + !features12.separateDepthStencilLayouts || !features12.bufferDeviceAddress) { std::fprintf(stderr, "the device lacks dynamicRendering, synchronization2, timelineSemaphore or " "separateDepthStencilLayouts\n"); return false; @@ -194,6 +194,7 @@ class Device { VkPhysicalDeviceVulkan12Features enable12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, &enable13}; enable12.timelineSemaphore = VK_TRUE; enable12.separateDepthStencilLayouts = VK_TRUE; + enable12.bufferDeviceAddress = VK_TRUE; const float priority = 1.0f; VkDeviceQueueCreateInfo queue_info{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO}; From fb2e8cd46bf4eaa3ed474ea419cf1a73f8875d1e Mon Sep 17 00:00:00 2001 From: Ryx <118130241+Ryx69@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:27:04 +0100 Subject: [PATCH 5/9] Runtime: graphics pipelines and draws on Vulkan (milestone M1, D3D-4) - CreateGraphicsPipelineState (PC slot 10): VS and PS found by the SHA-256 of their FSSM programs in the translator's index. Input-layout elements are matched to the VS input signature by semantic name and index; location = the element's register (the translator's vertex-fetch rule); a layout that leaves an input unfed is refused, as D3D12 does. Rasterizer, blend and depth-stencil state map one to one; viewport, scissor, topology, vertex strides, stencil references and blend factor are dynamic; dynamic rendering takes the RTV/DSV formats. Hull/domain/geometry, stream output, MSAA, set-0 bindings and two code-base stages (question 14) are refused with a log. - Command list: IASetPrimitiveTopology / VertexBuffers / IndexBuffer, RSSetViewports / ScissorRects (first of each), OMSetRenderTargets (views read at the call, single-range handles too), OMSetBlendFactor, OMSetStencilRef and CommandList8's front/back references (now applied), DrawInstanced / DrawIndexedInstanced recording a copy of that state. CreateCommandList's initial pipeline state is applied. Reset and ClearState share one state reset. - Replay: vertex/index views resolve to buffers by VA (arena or upload), attachments move to attachment layouts through the tracker (first use zero-fills), the draw runs in a dynamic-rendering scope with a flipped viewport (translated VS write D3D clip coordinates), stencil references per face, then vkCmdDraw / vkCmdDrawIndexed. Render-target views take the pipeline's formats (the view cache keys on format). - shader_library.h reads the index's input_signature and PS outputs. Test: d3d12_draw_test (through the proxy) builds a VS+PS PSO whose input layout order differs from the VS registers, uploads a vertex buffer into the arena, reads indices from an upload heap, and draws two indexed quads with different root constants and root CBVs plus a back-facing triangle: all 4096 read-back pixels match (which also checks the viewport flip and winding). Shaders are GLSL written to the translator's contract. d3d12_com_test now uses SetMarker as its unimplemented-method example, since DrawInstanced is implemented. 13/13 ctest; all six GPU tests clean under the Khronos validation layer. --- README.md | 2 +- docs/d3d12_vulkan.md | 35 ++- runtime/CMakeLists.txt | 22 +- runtime/README.md | 2 + runtime/shims/d3d12_com.cpp | 123 ++++++-- runtime/shims/d3d12_com.h | 4 + runtime/shims/d3d12_vulkan_device.cpp | 422 +++++++++++++++++++++++++- runtime/src/command_list.h | 56 +++- runtime/src/shader_library.h | 26 ++ runtime/src/vulkan_backend.h | 42 ++- runtime/src/vulkan_replay.h | 234 ++++++++++++++ runtime/test/d3d12_com_test.cpp | 2 +- runtime/test/d3d12_draw_test.cpp | 283 +++++++++++++++++ runtime/test/d3d12_test_shaders.h | 124 ++++++++ runtime/test/glsl/ps_draw.frag | 30 ++ runtime/test/glsl/vs_draw.vert | 22 ++ runtime/test/shader_library_test.cpp | 16 +- 17 files changed, 1407 insertions(+), 38 deletions(-) create mode 100644 runtime/test/d3d12_draw_test.cpp create mode 100644 runtime/test/d3d12_test_shaders.h create mode 100644 runtime/test/glsl/ps_draw.frag create mode 100644 runtime/test/glsl/vs_draw.vert diff --git a/README.md b/README.md index acdaae967..a0d2654e9 100644 --- a/README.md +++ b/README.md @@ -52,7 +52,7 @@ work on booting can start as soon as one is available to a developer. | Audio banks (AWC: Opus, XMA2) | ✅ Exported whole. Opus repackaged **losslessly** as Ogg Opus; PCM (codec 0/2) as WAV; XMA2 decoded with ffmpeg. `--wav` adds 16-bit PCM WAV ([notes](docs/audio.md)) | | Music/radio config | ? Measured. **1,589** audio-config records with exact durations and AWC stream ids; station grouping and content-id lists; no per-track start offsets ([notes](docs/audio_config.md)) | | PE loader and import shims | ⚠️ Skeleton. Untested against the real executable | -| Xbox D3D12 → Vulkan | ⚠️ In progress. A Vulkan-backed device behind the Xbox-ABI proxy creates queues, command lists, fences, descriptor heaps, views and committed resources; barriers, clears, uploads and copies (BC included) run on Vulkan, frames are presented to a window (milestone M0 passes in a synthetic test), and compute pipelines dispatch with root arguments through a GPU address arena, checked on one GPU. No bindless descriptors, graphics pipelines or draws yet, and the game's own present call is not hooked up ([plan](docs/d3d12_vulkan.md)) | +| Xbox D3D12 → Vulkan | ⚠️ In progress. A Vulkan-backed device behind the Xbox-ABI proxy creates queues, command lists, fences, descriptor heaps, views and committed resources; barriers, clears, uploads and copies (BC included) run on Vulkan, frames are presented to a window (milestone M0 passes in a synthetic test), and compute and graphics pipelines dispatch and draw with root arguments through a GPU address arena (milestone M1 passes with stand-in shaders), checked on one GPU. No bindless descriptors yet (so translated game shaders that declare bindings are refused), and the game's own present call is not hooked up ([plan](docs/d3d12_vulkan.md)) | | Booting, story mode, anything playable | ❌ No | ## How to build diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 9ae072b45..713600378 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -280,10 +280,29 @@ The compute path, end to end: and `ClearState`. A wrong parameter type or out-of-range constants makes `Close` return `E_INVALIDARG`. `Dispatch` records the block as it is at that moment. Replay binds the pipeline, pushes s0..s31, the heap base and the code base, and dispatches. +- **Graphics pipelines and draws (M1).** `CreateGraphicsPipelineState` (PC slot 10) finds the VS and PS by FSSM hash. + - **Vertex input:** each input-layout element is matched to the VS input signature by semantic name and index, + and its location is the element's register (the translator's vertex-fetch rule). An input the layout leaves + unfed is refused, as D3D12 refuses it. + - **Fixed-function state:** rasterizer, blend and depth-stencil state map one to one. Viewport, scissor, + topology, vertex strides, stencil references and the blend factor are dynamic. + - **Formats:** dynamic rendering takes the RTV and DSV formats. + - **Refused with a log:** hull, domain and geometry stages, stream output, MSAA, set-0 bindings, and two stages + that both read their code base (question 14). + + The command list keeps the input-assembler, viewport, scissor, render-target (read at `OMSetRenderTargets`, as + D3D12 does), blend-factor and stencil-reference state, including CommandList8's front/back references. Each + `DrawInstanced` / `DrawIndexedInstanced` records a copy of that state. + + At replay, vertex and index views resolve to buffers by VA (arena or upload). Attachments move to attachment + layouts through the tracker, and the draw runs in a dynamic-rendering scope. The viewport is flipped (negative + height), because translated vertex shaders write D3D clip coordinates; front-face winding then matches + D3D12's. Only the first viewport and scissor are used, and primitive restart is not modelled yet. Known gaps: set 0 in pipelines (`vulkan_bindless.h` above is not used by the device yet) and therefore every -translated shader that declares bindings; graphics PSOs, input layouts and draws; `requiredSubgroupSize = 64` for -wave64 compute; the game's present entry point (DXGI factory/swapchain or `PresentX`; the presenter above is what +translated shader that declares bindings; tessellation, geometry and mesh pipelines, multisampled pipelines, several +viewports, primitive restart; `requiredSubgroupSize = 64` for wave64 compute; the game's present entry point (DXGI +factory/swapchain or `PresentX`; the presenter above is what either calls), HDR and fullscreen; shader-resource, UAV and constant-buffer views, samplers, volume attachment views, placed and reserved resources, depth-stencil resolves and `ResolveSubresourceRegion`, and 1D textures; default-heap buffers are not zero-filled yet; a fence cannot be signalled to a lower value (Vulkan timelines only @@ -341,6 +360,16 @@ and any validation error fails them. application-written entry points at an upload buffer, then runs two dispatches that change s0 and the UAV in between. The results come back through a readback buffer. The shader, `test/glsl/cs_user_data.comp`, is GLSL written to the translator's push-constant and address contract, compiled with `glslangValidator`. +- `d3d12_draw_test`: milestone M1, through the proxy. + - **Pipeline:** a VS+PS PSO found by FSSM hash. The input layout is POSITION then COLOR, while the VS has them in + the opposite register order, so a match by position would fail. + - **Buffers:** the vertex buffer is copied into the arena, and the index buffer is read from an upload heap. + - **Draws:** two indexed draws with different root constants and root CBVs, then a back-facing triangle that must + be culled. + - **Check:** all 4096 pixels of the read-back target are compared. Where the red and green quadrants land also + checks the viewport flip and the winding. + + The shaders are GLSL written to the translator's contract (`test/glsl/vs_draw.vert`, `ps_draw.frag`). - `d3d12_present_test`: milestone M0. It opens a window and presents 60 frames, each one: reset the list, move the back buffer `PRESENT` → `RENDER_TARGET`, clear, move it back, execute, present, signal a fence. It then resizes the window, which recreates the swapchain and scales the blit, and switches to unsynchronised presents. @@ -964,7 +993,7 @@ M0–M2 do not need the executable. | # | Scope | What it proves | Done when | |---|---|---|---| | **M0** | `D3D12XboxCreateDevice` and the measured device overrides (heap start handles in RAX), one direct queue, allocator/list, fence, fake DXGI factory/adapter/swapchain, clear + present | COM interception, the known Xbox device entry point and ABI overrides, swapchain, frame loop, clean shutdown | A window shows a stable clear colour for 60 frames, no Vulkan validation errors, every D3D12 call traced. **Synthetic part met** by `d3d12_present_test`: 60 frames through the proxy on Vulkan, validation clean, colour checked on screen. Still open: the game's present front end (DXGI or PresentX) and the per-call trace | -| **M1** | Root signature with root constants (mask the measured `0x03000000` flag byte on a copy), one translated VS+PS, PSO, vertex buffer in the arena, draw, push constants `s0..s31` + heap base | PSO translation, shader hash lookup, vertex input, root-constant packing, heap base, present | The triangle matches a CPU/GPU reference; the existing texture-test style comparison passes with error 0 | +| **M1** | Root signature with root constants (mask the measured `0x03000000` flag byte on a copy), one translated VS+PS, PSO, vertex buffer in the arena, draw, push constants `s0..s31` + heap base | PSO translation, shader hash lookup, vertex input, root-constant packing, heap base, present | The triangle matches a CPU/GPU reference; the existing texture-test style comparison passes with error 0. **Met with stand-in shaders** by `d3d12_draw_test`: every pixel of two indexed draws and a culled triangle matches, through the proxy, validation clean. With translated game shaders it waits for the bindless set (M2), since most of them declare bindings | | **M2** | Descriptor heap (heap slots 9/10 return in RAX), `CreateShaderResourceView`, sampler, root descriptor table, hash-table insert, bindless sampling | The full D3D12 descriptor path and the shader's T#/S# contract | A textured quad matches the synthetic 8×8 gradient or a known texture with error 0; the hash table has the expected entries | | **M3** | Depth/stencil, multiple render targets, resource barriers, render passes, occlusion queries, fences, 2–3 frames in flight; run the game's first frames | Real frame structure and the first game code | The game reaches its first rendered frame (loading screen/menu or whatever the executable does) or stops on a single unsupported call with a clean report | | **M4** | Compute PSOs, UAVs, storage images, indirect dispatch, copy queues, async streaming | Asset loading and GPU compute | The world's streaming path runs without device loss; compute results match a CPU/reference check | diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 2f81fec14..01260b4e5 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -364,8 +364,28 @@ if(Vulkan_FOUND) target_compile_definitions(d3d12_compute_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_TEST_CS_SPV="${LEONIDA_TEST_CS}") target_compile_options(d3d12_compute_test PRIVATE /W4 /permissive- /utf-8) + # Milestone M1: a VS+PS pipeline and indexed draws, shaders written to the same contract. + set(LEONIDA_TEST_VS ${CMAKE_CURRENT_BINARY_DIR}/generated/vs_draw.spv) + set(LEONIDA_TEST_PS ${CMAKE_CURRENT_BINARY_DIR}/generated/ps_draw.spv) + foreach(pair "vs_draw.vert;${LEONIDA_TEST_VS}" "ps_draw.frag;${LEONIDA_TEST_PS}") + list(GET pair 0 source) + list(GET pair 1 output) + add_custom_command( + OUTPUT ${output} + COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${output} + ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${source} + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${source} + COMMENT "Compiling the draw test shader ${source}" + VERBATIM) + endforeach() + add_executable(d3d12_draw_test test/d3d12_draw_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_TEST_VS} + ${LEONIDA_TEST_PS}) + target_link_libraries(d3d12_draw_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_draw_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + LEONIDA_TEST_VS_SPV="${LEONIDA_TEST_VS}" LEONIDA_TEST_PS_SPV="${LEONIDA_TEST_PS}") + target_compile_options(d3d12_draw_test PRIVATE /W4 /permissive- /utf-8) else() - message(STATUS "glslangValidator not found: d3d12_compute_test is not built") + message(STATUS "glslangValidator not found: d3d12_compute_test and d3d12_draw_test are not built") endif() # The loader can create this device instead of the host's (D3D12XboxCreateDevice, LEONIDA_D3D12=vulkan). diff --git a/runtime/README.md b/runtime/README.md index ad0070392..20f515056 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -98,6 +98,8 @@ when the Vulkan SDK is found: - GPU tests count only validation-type errors. Loader and layer messages, such as a third-party implicit layer that fails to load, are printed but don't fail the run; to silence one, set `VK_LOADER_LAYERS_DISABLE=`. +- `d3d12_draw_test` — milestone M1: a VS+PS pipeline found by FSSM hash, the input layout matched by semantic, + and two indexed draws plus a culled triangle, compared pixel by pixel. - `d3d12_compute_test` — the compute path: root signature, a compute PSO found by its FSSM hash in a translator-style index, root arguments through the GPU address arena, and two dispatches. - `d3d12_present_test` — milestone M0: opens a window and presents 60 cleared frames through the proxy on diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index 7458fc3e5..d449ddf5c 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -82,11 +82,7 @@ class GraphicsCommandList final if (!allocator) return E_INVALIDARG; if (!list_.reset()) return E_FAIL; // D3D12 resets only closed lists invalid_ = false; - front_stencil_ref_ = back_stencil_ref_ = 0; // Reset returns every list state to its default - compute_ = {}; - graphics_ = {}; - compute_pipeline_ = compute_pipeline_id(state); - if (state && !compute_pipeline_) stub("ID3D12GraphicsCommandList::Reset(graphics pipeline state)"); + reset_state(state); // Reset returns every list state to its default return S_OK; } @@ -99,10 +95,7 @@ class GraphicsCommandList final bind_root(graphics_, signature); } - void STDMETHODCALLTYPE SetPipelineState(ID3D12PipelineState* state) override { - compute_pipeline_ = compute_pipeline_id(state); - if (state && !compute_pipeline_) stub("ID3D12GraphicsCommandList::SetPipelineState(graphics)"); - } + void STDMETHODCALLTYPE SetPipelineState(ID3D12PipelineState* state) override { set_pipeline(state); } // The bound heaps matter to direct heap indexing, which is still open (section 3.4); tables carry their VAs. void STDMETHODCALLTYPE SetDescriptorHeaps(UINT, ID3D12DescriptorHeap* const*) override {} @@ -150,11 +143,66 @@ class GraphicsCommandList final } // ClearState returns every piece of list state to its default, as Reset does (stencil references included). - void STDMETHODCALLTYPE ClearState(ID3D12PipelineState* state) override { - front_stencil_ref_ = back_stencil_ref_ = 0; - compute_ = {}; - graphics_ = {}; - compute_pipeline_ = compute_pipeline_id(state); + void STDMETHODCALLTYPE ClearState(ID3D12PipelineState* state) override { reset_state(state); } + + // Graphics state. Draws record a copy of it (command_list.h, Draw). + void STDMETHODCALLTYPE IASetPrimitiveTopology(D3D12_PRIMITIVE_TOPOLOGY topology) override { + topology_ = u(topology); + } + + void STDMETHODCALLTYPE IASetVertexBuffers(UINT start, UINT count, const D3D12_VERTEX_BUFFER_VIEW* views) override { + if (std::uint64_t(start) + count > vertex_buffers_.size()) return check(false); + for (UINT i = 0; i < count; ++i) + vertex_buffers_[start + i] = views ? leonida::VertexBufferView{views[i].BufferLocation, views[i].SizeInBytes, + views[i].StrideInBytes} + : leonida::VertexBufferView{}; + } + + void STDMETHODCALLTYPE IASetIndexBuffer(const D3D12_INDEX_BUFFER_VIEW* view) override { + index_ = view ? leonida::IndexBufferView{view->BufferLocation, view->SizeInBytes, u(view->Format)} + : leonida::IndexBufferView{}; + } + + void STDMETHODCALLTYPE RSSetViewports(UINT count, const D3D12_VIEWPORT* viewports) override { + if (!count || !viewports) return; + if (count > 1) stub("ID3D12GraphicsCommandList::RSSetViewports (more than one viewport; the first is used)"); + const D3D12_VIEWPORT& v = viewports[0]; + viewport_ = {v.TopLeftX, v.TopLeftY, v.Width, v.Height, v.MinDepth, v.MaxDepth}; + } + + void STDMETHODCALLTYPE RSSetScissorRects(UINT count, const D3D12_RECT* rects) override { + if (!count || !rects) return; + if (count > 1) stub("ID3D12GraphicsCommandList::RSSetScissorRects (more than one rectangle; the first is used)"); + scissor_ = {rects[0].left, rects[0].top, rects[0].right, rects[0].bottom}; + } + + // D3D12 reads render-target and depth descriptors here, so their views are copied now. + void STDMETHODCALLTYPE OMSetRenderTargets(UINT count, const D3D12_CPU_DESCRIPTOR_HANDLE* targets, BOOL single_range, + const D3D12_CPU_DESCRIPTOR_HANDLE* depth) override { + render_targets_.assign(count, {}); + for (UINT i = 0; i < count && targets; ++i) { + const SIZE_T handle = single_range ? targets[0].ptr + SIZE_T(i) * descriptor_size : targets[i].ptr; + if (handle) render_targets_[i] = *reinterpret_cast(handle); + } + depth_ = depth && depth->ptr ? *reinterpret_cast(depth->ptr) : leonida::TargetView{}; + } + + void STDMETHODCALLTYPE OMSetBlendFactor(const FLOAT factor[4]) override { + blend_factor_ = factor ? std::array{factor[0], factor[1], factor[2], factor[3]} + : std::array{1, 1, 1, 1}; // null means { 1, 1, 1, 1 } + } + + void STDMETHODCALLTYPE OMSetStencilRef(UINT reference) override { + front_stencil_ref_ = back_stencil_ref_ = reference; + } + + void STDMETHODCALLTYPE DrawInstanced(UINT vertices, UINT instances, UINT first_vertex, UINT first_instance) override { + record_draw(false, vertices, instances, first_vertex, 0, first_instance); + } + + void STDMETHODCALLTYPE DrawIndexedInstanced(UINT indices, UINT instances, UINT first_index, INT base_vertex, + UINT first_instance) override { + record_draw(true, indices, instances, first_index, base_vertex, first_instance); } void STDMETHODCALLTYPE ResourceBarrier(UINT count, const D3D12_RESOURCE_BARRIER* barriers) override { @@ -252,14 +300,10 @@ class GraphicsCommandList final stencil, to_rects(count, rects))); } - // GCL8. Vulkan can set the two faces independently with vkCmdSetStencilReference(VK_STENCIL_FACE_FRONT_BIT / - // BACK_BIT), but that state only matters when a pipeline uses it, and this layer has no pipeline or draw path - // yet. Retain the values for that path and report that nothing consumed them, rather than emit a call whose - // effect no later command can observe. + // GCL8. Each draw applies the two faces with vkCmdSetStencilReference(VK_STENCIL_FACE_FRONT_BIT / BACK_BIT). void STDMETHODCALLTYPE OMSetFrontAndBackStencilRef(UINT front, UINT back) override { front_stencil_ref_ = front; back_stencil_ref_ = back; - stub("ID3D12GraphicsCommandList8::OMSetFrontAndBackStencilRef (recorded; no pipeline path applies it)"); } static GraphicsCommandList* from(IUnknown* object) { return Child::from(object); } @@ -343,6 +387,47 @@ class GraphicsCommandList final RootState compute_; RootState graphics_; std::uintptr_t compute_pipeline_ = 0; + std::uintptr_t graphics_pipeline_ = 0; + std::uint32_t topology_ = 0; // D3D_PRIMITIVE_TOPOLOGY_UNDEFINED + std::array vertex_buffers_{}; + leonida::IndexBufferView index_{}; + leonida::Viewport viewport_{}; + leonida::Rect scissor_{}; + std::vector render_targets_; + leonida::TargetView depth_{}; + std::array blend_factor_{1, 1, 1, 1}; + + void set_pipeline(ID3D12PipelineState* state) { + compute_pipeline_ = compute_pipeline_id(state); + graphics_pipeline_ = graphics_pipeline_id(state); + if (state && !compute_pipeline_ && !graphics_pipeline_) + stub("ID3D12GraphicsCommandList::SetPipelineState(pipeline from another device)"); + } + + void reset_state(ID3D12PipelineState* state) { + front_stencil_ref_ = back_stencil_ref_ = 0; + compute_ = {}; + graphics_ = {}; + topology_ = 0; + vertex_buffers_ = {}; + index_ = {}; + viewport_ = {}; + scissor_ = {}; + render_targets_.clear(); + depth_ = {}; + blend_factor_ = {1, 1, 1, 1}; + set_pipeline(state); + } + + // A draw needs a graphics pipeline, a graphics root signature and a topology. + void record_draw(bool indexed, UINT count, UINT instances, UINT first, INT base_vertex, UINT first_instance) { + if (!graphics_pipeline_ || !graphics_.layout || !topology_) return check(false); + leonida::Draw draw{graphics_pipeline_, graphics_.data, render_targets_, depth_, + {vertex_buffers_.begin(), vertex_buffers_.end()}, index_, topology_, viewport_, scissor_, + blend_factor_, front_stencil_ref_, back_stencil_ref_, indexed, count, instances, first, + base_vertex, first_instance}; + check(list_.draw(draw)); + } }; class Fence final diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index 3ec50b305..97b49f473 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -117,6 +117,10 @@ struct RootArgumentLayout { // compute pipeline state (0: not a compute PSO of a Vulkan device). const RootArgumentLayout* root_signature_layout(ID3D12RootSignature* signature); std::uintptr_t compute_pipeline_id(ID3D12PipelineState* pipeline); +std::uintptr_t graphics_pipeline_id(ID3D12PipelineState* pipeline); + +// The size of every descriptor slot (GetDescriptorHandleIncrementSize), for handle ranges. +inline constexpr UINT descriptor_size = 32; // ExecuteCommandLists returns void; this is what the last call on the queue did. leonida::ReplayResult last_execute_result(ID3D12CommandQueue* queue); diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index a68daaaaf..9c79675f3 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -14,6 +14,7 @@ #include #include +#include #include #include #include @@ -29,7 +30,7 @@ namespace { // Every descriptor slot is this many bytes; an RTV or DSV slot holds a leonida::TargetView. The console's own // increments are open question 4 in docs/d3d12_vulkan.md; the application reads them from the device, as it must. -constexpr UINT kDescriptorSize = 32; +constexpr UINT kDescriptorSize = descriptor_size; static_assert(sizeof(leonida::TargetView) <= kDescriptorSize); void log_once(const char* what, int value) { @@ -311,6 +312,7 @@ class Resource final in_arena_ = true; std::memset(device_.arena.mapped + arena_offset_, 0, std::size_t(desc_.Width)); va_ = arena_offset_; + binding.va = va_; binding.buffer = device_.arena.buffer; binding.buffer_offset = arena_offset_; device_.context->add_resource(id(), binding); @@ -347,6 +349,7 @@ class Resource final log_once("default-heap buffers are not zero-filled yet; dimension", int(desc_.Dimension)); } binding.buffer = buffer_; + binding.va = va_; device_.context->add_resource(id(), binding); return S_OK; } @@ -448,6 +451,125 @@ class Resource final D3D12_GPU_VIRTUAL_ADDRESS va_ = 0; }; +// DXGI -> Vulkan for vertex attributes, with each element's size for D3D12_APPEND_ALIGNED_ELEMENT. +bool vertex_format(DXGI_FORMAT format, VkFormat& out, UINT& bytes) { + struct Row { + DXGI_FORMAT dxgi; + VkFormat vk; + UINT bytes; + }; + static constexpr Row rows[] = { + {DXGI_FORMAT_R32G32B32A32_FLOAT, VK_FORMAT_R32G32B32A32_SFLOAT, 16}, + {DXGI_FORMAT_R32G32B32A32_UINT, VK_FORMAT_R32G32B32A32_UINT, 16}, + {DXGI_FORMAT_R32G32B32A32_SINT, VK_FORMAT_R32G32B32A32_SINT, 16}, + {DXGI_FORMAT_R32G32B32_FLOAT, VK_FORMAT_R32G32B32_SFLOAT, 12}, + {DXGI_FORMAT_R32G32B32_UINT, VK_FORMAT_R32G32B32_UINT, 12}, + {DXGI_FORMAT_R32G32B32_SINT, VK_FORMAT_R32G32B32_SINT, 12}, + {DXGI_FORMAT_R32G32_FLOAT, VK_FORMAT_R32G32_SFLOAT, 8}, + {DXGI_FORMAT_R32G32_UINT, VK_FORMAT_R32G32_UINT, 8}, + {DXGI_FORMAT_R32G32_SINT, VK_FORMAT_R32G32_SINT, 8}, + {DXGI_FORMAT_R32_FLOAT, VK_FORMAT_R32_SFLOAT, 4}, + {DXGI_FORMAT_R32_UINT, VK_FORMAT_R32_UINT, 4}, + {DXGI_FORMAT_R32_SINT, VK_FORMAT_R32_SINT, 4}, + {DXGI_FORMAT_R16G16B16A16_FLOAT, VK_FORMAT_R16G16B16A16_SFLOAT, 8}, + {DXGI_FORMAT_R16G16B16A16_UNORM, VK_FORMAT_R16G16B16A16_UNORM, 8}, + {DXGI_FORMAT_R16G16B16A16_SNORM, VK_FORMAT_R16G16B16A16_SNORM, 8}, + {DXGI_FORMAT_R16G16B16A16_UINT, VK_FORMAT_R16G16B16A16_UINT, 8}, + {DXGI_FORMAT_R16G16B16A16_SINT, VK_FORMAT_R16G16B16A16_SINT, 8}, + {DXGI_FORMAT_R16G16_FLOAT, VK_FORMAT_R16G16_SFLOAT, 4}, + {DXGI_FORMAT_R16G16_UNORM, VK_FORMAT_R16G16_UNORM, 4}, + {DXGI_FORMAT_R16G16_SNORM, VK_FORMAT_R16G16_SNORM, 4}, + {DXGI_FORMAT_R16G16_UINT, VK_FORMAT_R16G16_UINT, 4}, + {DXGI_FORMAT_R16G16_SINT, VK_FORMAT_R16G16_SINT, 4}, + {DXGI_FORMAT_R16_FLOAT, VK_FORMAT_R16_SFLOAT, 2}, + {DXGI_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM, 2}, + {DXGI_FORMAT_R16_UINT, VK_FORMAT_R16_UINT, 2}, + {DXGI_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM, 4}, + {DXGI_FORMAT_R8G8B8A8_SNORM, VK_FORMAT_R8G8B8A8_SNORM, 4}, + {DXGI_FORMAT_R8G8B8A8_UINT, VK_FORMAT_R8G8B8A8_UINT, 4}, + {DXGI_FORMAT_R8G8B8A8_SINT, VK_FORMAT_R8G8B8A8_SINT, 4}, + {DXGI_FORMAT_B8G8R8A8_UNORM, VK_FORMAT_B8G8R8A8_UNORM, 4}, + {DXGI_FORMAT_R8G8_UNORM, VK_FORMAT_R8G8_UNORM, 2}, + {DXGI_FORMAT_R8G8_UINT, VK_FORMAT_R8G8_UINT, 2}, + {DXGI_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM, 1}, + {DXGI_FORMAT_R8_UINT, VK_FORMAT_R8_UINT, 1}, + {DXGI_FORMAT_R10G10B10A2_UNORM, VK_FORMAT_A2B10G10R10_UNORM_PACK32, 4}, + {DXGI_FORMAT_R10G10B10A2_UINT, VK_FORMAT_A2B10G10R10_UINT_PACK32, 4}, + {DXGI_FORMAT_R11G11B10_FLOAT, VK_FORMAT_B10G11R11_UFLOAT_PACK32, 4}, + }; + for (const Row& row : rows) + if (row.dxgi == format) { + out = row.vk; + bytes = row.bytes; + return true; + } + return false; +} + +VkBlendFactor blend_factor(D3D12_BLEND blend) { + switch (blend) { + case D3D12_BLEND_ZERO: return VK_BLEND_FACTOR_ZERO; + case D3D12_BLEND_ONE: return VK_BLEND_FACTOR_ONE; + case D3D12_BLEND_SRC_COLOR: return VK_BLEND_FACTOR_SRC_COLOR; + case D3D12_BLEND_INV_SRC_COLOR: return VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR; + case D3D12_BLEND_SRC_ALPHA: return VK_BLEND_FACTOR_SRC_ALPHA; + case D3D12_BLEND_INV_SRC_ALPHA: return VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA; + case D3D12_BLEND_DEST_ALPHA: return VK_BLEND_FACTOR_DST_ALPHA; + case D3D12_BLEND_INV_DEST_ALPHA: return VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA; + case D3D12_BLEND_DEST_COLOR: return VK_BLEND_FACTOR_DST_COLOR; + case D3D12_BLEND_INV_DEST_COLOR: return VK_BLEND_FACTOR_ONE_MINUS_DST_COLOR; + case D3D12_BLEND_SRC_ALPHA_SAT: return VK_BLEND_FACTOR_SRC_ALPHA_SATURATE; + case D3D12_BLEND_BLEND_FACTOR: return VK_BLEND_FACTOR_CONSTANT_COLOR; + case D3D12_BLEND_INV_BLEND_FACTOR: return VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_COLOR; + case D3D12_BLEND_SRC1_COLOR: return VK_BLEND_FACTOR_SRC1_COLOR; + case D3D12_BLEND_INV_SRC1_COLOR: return VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR; + case D3D12_BLEND_SRC1_ALPHA: return VK_BLEND_FACTOR_SRC1_ALPHA; + case D3D12_BLEND_INV_SRC1_ALPHA: return VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA; + case D3D12_BLEND_ALPHA_FACTOR: return VK_BLEND_FACTOR_CONSTANT_ALPHA; + case D3D12_BLEND_INV_ALPHA_FACTOR: return VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA; + default: return VK_BLEND_FACTOR_ONE; + } +} + +VkBlendOp blend_op(D3D12_BLEND_OP op) { + switch (op) { + case D3D12_BLEND_OP_SUBTRACT: return VK_BLEND_OP_SUBTRACT; + case D3D12_BLEND_OP_REV_SUBTRACT: return VK_BLEND_OP_REVERSE_SUBTRACT; + case D3D12_BLEND_OP_MIN: return VK_BLEND_OP_MIN; + case D3D12_BLEND_OP_MAX: return VK_BLEND_OP_MAX; + default: return VK_BLEND_OP_ADD; + } +} + +// D3D12_COMPARISON_FUNC (NEVER = 1 .. ALWAYS = 8) and D3D12_STENCIL_OP (KEEP = 1 .. DECR = 8) list their values +// in Vulkan's order, starting at 1 instead of 0. +VkCompareOp compare_op(D3D12_COMPARISON_FUNC func) { + const int value = int(func); + return value >= 1 && value <= 8 ? VkCompareOp(value - 1) : VK_COMPARE_OP_ALWAYS; +} +VkStencilOp stencil_op(D3D12_STENCIL_OP op) { + const int value = int(op); + return value >= 1 && value <= 8 ? VkStencilOp(value - 1) : VK_STENCIL_OP_KEEP; +} + +VkStencilOpState stencil_face(const D3D12_DEPTH_STENCILOP_DESC& face, UINT8 read_mask, UINT8 write_mask) { + VkStencilOpState state{}; + state.failOp = stencil_op(face.StencilFailOp); + state.passOp = stencil_op(face.StencilPassOp); + state.depthFailOp = stencil_op(face.StencilDepthFailOp); + state.compareOp = compare_op(face.StencilFunc); + state.compareMask = read_mask; + state.writeMask = write_mask; + return state; +} + +bool equal_semantic(const std::string& a, const char* b) { + if (!b || a.size() != std::strlen(b)) return false; + for (std::size_t i = 0; i < a.size(); ++i) + if (std::tolower(static_cast(a[i])) != std::tolower(static_cast(b[i]))) return false; + return true; +} + class RootSignature final : public Child { public: @@ -477,11 +599,269 @@ class PipelineState final if (pipeline_.pipeline) vk.vkDestroyPipeline(dev, pipeline_.pipeline, nullptr); if (pipeline_.layout) vk.vkDestroyPipelineLayout(dev, pipeline_.layout, nullptr); if (module_) vk.vkDestroyShaderModule(dev, module_, nullptr); - if (code_bytes_) device_.arena_release(pipeline_.code_base, code_bytes_); + if (graphics_.pipeline) vk.vkDestroyPipeline(dev, graphics_.pipeline, nullptr); + if (graphics_.layout) vk.vkDestroyPipelineLayout(dev, graphics_.layout, nullptr); + for (VkShaderModule module : modules_) vk.vkDestroyShaderModule(dev, module, nullptr); + if (code_bytes_) device_.arena_release(code_base_, code_bytes_); } std::uintptr_t id() const { return reinterpret_cast(static_cast(this)); } - bool compute() const { return registered_; } + bool compute() const { return registered_ && !is_graphics_; } + bool graphics() const { return registered_ && is_graphics_; } + + // A VS (+ PS) pipeline for dynamic rendering. Vertex input comes from the input layout matched to the VS's + // input signature by semantic name and index: location = the element's register, the translator's rule + // (docs/design.md, "Vertex fetch"). Hull, domain and geometry stages, more than one sample, and two stages + // that both read their code base are refused with a log. Viewport, scissor, topology, vertex strides, stencil + // reference and blend factor are dynamic, set from the list's state at each draw. + HRESULT create_graphics(const D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc) { + auto& vk = device_.context->vk; + const VkDevice dev = device_.info.device; + if (!desc.VS.pShaderBytecode || !desc.VS.BytecodeLength) return E_INVALIDARG; + if (!device_.arena.mapped) { + log_once("pipelines need the GPU address arena (bufferDeviceAddress); stage", 1); + return E_NOTIMPL; + } + if (desc.HS.BytecodeLength || desc.DS.BytecodeLength || desc.GS.BytecodeLength || desc.StreamOutput.NumEntries) { + log_once("graphics pipeline stage not supported yet (hull/domain/geometry/stream output):", 0); + return E_NOTIMPL; + } + if (desc.SampleDesc.Count > 1) { + log_once("multisampled graphics pipelines not supported yet; samples", int(desc.SampleDesc.Count)); + return E_NOTIMPL; + } + const leonida::ShaderLibrary* library = device_.library(); + if (!library) return E_FAIL; + + struct Stage { + const char* name; + VkShaderStageFlagBits bit; + const D3D12_SHADER_BYTECODE& code; + const leonida::ShaderEntry* entry = nullptr; + std::vector fssm; + }; + Stage stages[2] = {{"vs", VK_SHADER_STAGE_VERTEX_BIT, desc.VS}, {"ps", VK_SHADER_STAGE_FRAGMENT_BIT, desc.PS}}; + std::vector stage_infos; + const Stage* code_stage = nullptr; + for (Stage& stage : stages) { + if (!stage.code.pShaderBytecode || !stage.code.BytecodeLength) continue; // no PS: depth only + stage.fssm = leonida::fssm_program( + {static_cast(stage.code.pShaderBytecode), stage.code.BytecodeLength}); + if (stage.fssm.empty()) { + log_once("shader bytecode holds no FSSM program; bytes", int(stage.code.BytecodeLength)); + return E_INVALIDARG; + } + const std::string hash = leonida::sha256_hex(stage.fssm); + stage.entry = library->find(stage.name, hash); + if (!stage.entry) { + std::fprintf(stderr, "[rt] d3d12: no translated %s for FSSM sha256 %s\n", stage.name, hash.c_str()); + return E_INVALIDARG; + } + if (stage.entry->binding_count) { + std::fprintf(stderr, "[rt] d3d12: %s uses set-0 bindings; the bindless set is not implemented yet\n", + stage.entry->name.c_str()); + return E_NOTIMPL; + } + if (stage.entry->uses_code_base) { + if (code_stage) { + log_once("two stages read their code base; one push-constant slot holds one (question 14)", 0); + return E_NOTIMPL; + } + code_stage = &stage; + } + const std::vector words = library->spirv(*stage.entry); + if (words.empty()) return E_FAIL; + VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + module_info.codeSize = words.size() * 4; + module_info.pCode = words.data(); + VkShaderModule module = VK_NULL_HANDLE; + if (vk.vkCreateShaderModule(dev, &module_info, nullptr, &module) != VK_SUCCESS) return E_FAIL; + modules_.push_back(module); + VkPipelineShaderStageCreateInfo info{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; + info.stage = stage.bit; + info.module = module; + info.pName = "main"; + stage_infos.push_back(info); + } + + // Input layout -> vertex input, by semantic. + std::vector attributes; + std::vector bindings; + UINT slot_end[D3D12_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT] = {}; + for (UINT i = 0; i < desc.InputLayout.NumElements; ++i) { + const D3D12_INPUT_ELEMENT_DESC& element = desc.InputLayout.pInputElementDescs[i]; + if (element.InputSlot >= D3D12_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT) return E_INVALIDARG; + VkFormat format; + UINT bytes; + if (!vertex_format(element.Format, format, bytes)) { + log_once("vertex attribute format not supported yet:", element.Format); + return E_INVALIDARG; + } + const UINT offset = element.AlignedByteOffset == D3D12_APPEND_ALIGNED_ELEMENT + ? (slot_end[element.InputSlot] + 3) / 4 * 4 + : element.AlignedByteOffset; + slot_end[element.InputSlot] = offset + bytes; + const leonida::SignatureElement* input = nullptr; + for (const auto& e : stages[0].entry->input_signature) + if (e.system_value == 0 && e.semantic_index == element.SemanticIndex && + equal_semantic(e.semantic, element.SemanticName)) + input = &e; + if (!input) continue; // the shader does not read this element + attributes.push_back({input->register_index, element.InputSlot, format, offset}); + const bool instance = element.InputSlotClass == D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA; + if (instance && element.InstanceDataStepRate > 1) + log_once("instance step rates above 1 are not modelled; rate", int(element.InstanceDataStepRate)); + if (!(graphics_.vertex_slots & (1u << element.InputSlot))) { + graphics_.vertex_slots |= 1u << element.InputSlot; + bindings.push_back({element.InputSlot, 0, // stride: dynamic, from IASetVertexBuffers + instance ? VK_VERTEX_INPUT_RATE_INSTANCE : VK_VERTEX_INPUT_RATE_VERTEX}); + } + } + for (const auto& e : stages[0].entry->input_signature) { + if (e.system_value) continue; + const bool fed = std::any_of(attributes.begin(), attributes.end(), + [&](const auto& a) { return a.location == e.register_index; }); + if (!fed) { // D3D12 rejects an input layout that leaves a shader input unfed + std::fprintf(stderr, "[rt] d3d12: the input layout does not feed %s%u (register %u)\n", + e.semantic.c_str(), e.semantic_index, e.register_index); + return E_INVALIDARG; + } + } + VkPipelineVertexInputStateCreateInfo vertex_input{VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO}; + vertex_input.vertexBindingDescriptionCount = std::uint32_t(bindings.size()); + vertex_input.pVertexBindingDescriptions = bindings.data(); + vertex_input.vertexAttributeDescriptionCount = std::uint32_t(attributes.size()); + vertex_input.pVertexAttributeDescriptions = attributes.data(); + + VkPipelineInputAssemblyStateCreateInfo assembly{VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO}; + switch (desc.PrimitiveTopologyType) { + case D3D12_PRIMITIVE_TOPOLOGY_TYPE_POINT: assembly.topology = VK_PRIMITIVE_TOPOLOGY_POINT_LIST; break; + case D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE: assembly.topology = VK_PRIMITIVE_TOPOLOGY_LINE_LIST; break; + case D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE: assembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; break; + default: + log_once("primitive topology type not supported:", desc.PrimitiveTopologyType); + return E_INVALIDARG; + } + if (desc.IBStripCutValue != D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED) + log_once("index-buffer strip cuts (primitive restart) are not modelled; value", desc.IBStripCutValue); + + VkPipelineViewportStateCreateInfo viewport{VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO}; + viewport.viewportCount = 1; + viewport.scissorCount = 1; + + const D3D12_RASTERIZER_DESC& r = desc.RasterizerState; + VkPipelineRasterizationStateCreateInfo raster{VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO}; + raster.polygonMode = r.FillMode == D3D12_FILL_MODE_WIREFRAME ? VK_POLYGON_MODE_LINE : VK_POLYGON_MODE_FILL; + raster.cullMode = r.CullMode == D3D12_CULL_MODE_FRONT ? VK_CULL_MODE_FRONT_BIT + : r.CullMode == D3D12_CULL_MODE_BACK ? VK_CULL_MODE_BACK_BIT + : VK_CULL_MODE_NONE; + // With the negative-height viewport, framebuffer winding matches D3D12's screen-space winding. + raster.frontFace = r.FrontCounterClockwise ? VK_FRONT_FACE_COUNTER_CLOCKWISE : VK_FRONT_FACE_CLOCKWISE; + raster.depthBiasEnable = r.DepthBias || r.SlopeScaledDepthBias != 0.0f; + raster.depthBiasConstantFactor = float(r.DepthBias); + raster.depthBiasClamp = r.DepthBiasClamp; + raster.depthBiasSlopeFactor = r.SlopeScaledDepthBias; + raster.lineWidth = 1.0f; + if (!r.DepthClipEnable) log_once("DepthClipEnable = FALSE is not modelled (depth clamp); flag", 0); + + VkPipelineMultisampleStateCreateInfo multisample{VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO}; + multisample.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; + const VkSampleMask sample_mask = desc.SampleMask; + multisample.pSampleMask = &sample_mask; + multisample.alphaToCoverageEnable = desc.BlendState.AlphaToCoverageEnable; + + const D3D12_DEPTH_STENCIL_DESC& ds = desc.DepthStencilState; + VkPipelineDepthStencilStateCreateInfo depth{VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO}; + depth.depthTestEnable = ds.DepthEnable; + depth.depthWriteEnable = ds.DepthEnable && ds.DepthWriteMask == D3D12_DEPTH_WRITE_MASK_ALL; + depth.depthCompareOp = compare_op(ds.DepthFunc); + depth.stencilTestEnable = ds.StencilEnable; + depth.front = stencil_face(ds.FrontFace, ds.StencilReadMask, ds.StencilWriteMask); + depth.back = stencil_face(ds.BackFace, ds.StencilReadMask, ds.StencilWriteMask); + + std::vector blends(desc.NumRenderTargets); + for (UINT i = 0; i < desc.NumRenderTargets; ++i) { + const D3D12_RENDER_TARGET_BLEND_DESC& b = + desc.BlendState.RenderTarget[desc.BlendState.IndependentBlendEnable ? i : 0]; + if (b.LogicOpEnable) log_once("logic ops are not modelled; render target", int(i)); + blends[i].blendEnable = b.BlendEnable; + blends[i].srcColorBlendFactor = blend_factor(b.SrcBlend); + blends[i].dstColorBlendFactor = blend_factor(b.DestBlend); + blends[i].colorBlendOp = blend_op(b.BlendOp); + blends[i].srcAlphaBlendFactor = blend_factor(b.SrcBlendAlpha); + blends[i].dstAlphaBlendFactor = blend_factor(b.DestBlendAlpha); + blends[i].alphaBlendOp = blend_op(b.BlendOpAlpha); + blends[i].colorWriteMask = b.RenderTargetWriteMask & 0xf; // R, G, B, A in both APIs + } + VkPipelineColorBlendStateCreateInfo blend{VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO}; + blend.attachmentCount = std::uint32_t(blends.size()); + blend.pAttachments = blends.data(); + + graphics_.color_formats.assign(desc.NumRenderTargets, VK_FORMAT_UNDEFINED); + for (UINT i = 0; i < desc.NumRenderTargets; ++i) { + if (desc.RTVFormats[i] == DXGI_FORMAT_UNKNOWN) continue; + graphics_.color_formats[i] = vulkan_format(desc.RTVFormats[i], false).format; + if (graphics_.color_formats[i] == VK_FORMAT_UNDEFINED) { + log_once("render-target format not supported yet:", desc.RTVFormats[i]); + return E_INVALIDARG; + } + } + if (desc.DSVFormat != DXGI_FORMAT_UNKNOWN) { + Format f = vulkan_format(desc.DSVFormat, true); + if (f.format == VK_FORMAT_D24_UNORM_S8_UINT && !device_.depth_usable(f.format)) + f.format = VK_FORMAT_D32_SFLOAT_S8_UINT; // as CreateCommittedResource does + graphics_.depth_format = f.format; + graphics_.depth_aspects = f.aspects; + } + VkPipelineRenderingCreateInfo rendering{VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO}; + rendering.colorAttachmentCount = std::uint32_t(graphics_.color_formats.size()); + rendering.pColorAttachmentFormats = graphics_.color_formats.data(); + if (graphics_.depth_aspects & VK_IMAGE_ASPECT_DEPTH_BIT) rendering.depthAttachmentFormat = graphics_.depth_format; + if (graphics_.depth_aspects & VK_IMAGE_ASPECT_STENCIL_BIT) rendering.stencilAttachmentFormat = graphics_.depth_format; + + static constexpr VkDynamicState dynamic_states[] = { + VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR, + VK_DYNAMIC_STATE_PRIMITIVE_TOPOLOGY, VK_DYNAMIC_STATE_VERTEX_INPUT_BINDING_STRIDE, + VK_DYNAMIC_STATE_STENCIL_REFERENCE, VK_DYNAMIC_STATE_BLEND_CONSTANTS}; + VkPipelineDynamicStateCreateInfo dynamic{VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO}; + dynamic.dynamicStateCount = std::uint32_t(std::size(dynamic_states)); + dynamic.pDynamicStates = dynamic_states; + + const VkPushConstantRange push{VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, + sizeof(leonida::ShaderUserData)}; + VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; + layout_info.pushConstantRangeCount = 1; + layout_info.pPushConstantRanges = &push; + if (vk.vkCreatePipelineLayout(dev, &layout_info, nullptr, &graphics_.layout) != VK_SUCCESS) return E_FAIL; + + VkGraphicsPipelineCreateInfo info{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, &rendering}; + info.stageCount = std::uint32_t(stage_infos.size()); + info.pStages = stage_infos.data(); + info.pVertexInputState = &vertex_input; + info.pInputAssemblyState = &assembly; + info.pViewportState = &viewport; + info.pRasterizationState = &raster; + info.pMultisampleState = &multisample; + info.pDepthStencilState = &depth; + info.pColorBlendState = &blend; + info.pDynamicState = &dynamic; + info.layout = graphics_.layout; + if (vk.vkCreateGraphicsPipelines(dev, VK_NULL_HANDLE, 1, &info, nullptr, &graphics_.pipeline) != VK_SUCCESS) + return E_FAIL; + + if (code_stage) { + VkDeviceSize offset = 0; + if (!device_.arena_allocate(code_stage->fssm.size(), 256, offset)) return E_OUTOFMEMORY; + std::memcpy(device_.arena.mapped + offset, code_stage->fssm.data(), code_stage->fssm.size()); + code_bytes_ = code_stage->fssm.size(); + code_base_ = offset; + graphics_.code_base = offset; + } + device_.context->add_graphics_pipeline(id(), graphics_); + registered_ = true; + is_graphics_ = true; + return S_OK; + } HRESULT create_compute(const D3D12_COMPUTE_PIPELINE_STATE_DESC& desc) { auto& vk = device_.context->vk; @@ -542,6 +922,7 @@ class PipelineState final if (!device_.arena_allocate(fssm.size(), 256, offset)) return E_OUTOFMEMORY; std::memcpy(device_.arena.mapped + offset, fssm.data(), fssm.size()); code_bytes_ = fssm.size(); + code_base_ = offset; pipeline_.code_base = offset; device_.context->add_pipeline(id(), pipeline_); registered_ = true; @@ -551,9 +932,13 @@ class PipelineState final private: DeviceState& device_; leonida::ComputePipeline pipeline_; + leonida::GraphicsPipeline graphics_; VkShaderModule module_ = VK_NULL_HANDLE; + std::vector modules_; + VkDeviceSize code_base_ = 0; VkDeviceSize code_bytes_ = 0; bool registered_ = false; + bool is_graphics_ = false; }; // The Vulkan objects create_vulkan_device_standalone made, destroyed with the device. @@ -679,8 +1064,16 @@ class Device final HRESULT STDMETHODCALLTYPE CreateCommandList(UINT, D3D12_COMMAND_LIST_TYPE type, ID3D12CommandAllocator* allocator, ID3D12PipelineState* state, REFIID riid, void** out) override { - if (state) stub("ID3D12Device::CreateCommandList(initial pipeline state)"); - return create_command_list(type, allocator, riid, out, identity()); + HRESULT hr = create_command_list(type, allocator, riid, out, identity()); + // The initial pipeline state is set as SetPipelineState would set it. + if (SUCCEEDED(hr) && state) { + ID3D12GraphicsCommandList* list = nullptr; + if (SUCCEEDED(static_cast(*out)->QueryInterface(IID_PPV_ARGS(&list)))) { + list->SetPipelineState(state); + list->Release(); + } + } + return hr; } // Device4: a list created closed, without an allocator. @@ -764,6 +1157,20 @@ class Device final return hand_out(pipeline, riid, out); } + HRESULT STDMETHODCALLTYPE CreateGraphicsPipelineState(const D3D12_GRAPHICS_PIPELINE_STATE_DESC* desc, REFIID riid, + void** out) override { + if (!out) return E_POINTER; + *out = nullptr; + if (!desc) return E_INVALIDARG; + auto* pipeline = new PipelineState(state_); + pipeline->attach_device(identity()); + if (const HRESULT hr = pipeline->create_graphics(*desc); FAILED(hr)) { + pipeline->Release(); + return hr; + } + return hand_out(pipeline, riid, out); + } + UINT STDMETHODCALLTYPE GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE) override { return kDescriptorSize; } @@ -1123,6 +1530,11 @@ std::uintptr_t compute_pipeline_id(ID3D12PipelineState* pipeline) { return p && p->compute() ? p->id() : 0; } +std::uintptr_t graphics_pipeline_id(ID3D12PipelineState* pipeline) { + const PipelineState* p = PipelineState::from(pipeline); + return p && p->graphics() ? p->id() : 0; +} + VkImage vulkan_image(ID3D12Resource* resource) { const Resource* r = Resource::from(resource); return r ? r->image() : VK_NULL_HANDLE; diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h index 3ffb9e002..089ab095e 100644 --- a/runtime/src/command_list.h +++ b/runtime/src/command_list.h @@ -288,6 +288,53 @@ struct Dispatch { std::uint32_t z; }; +// D3D12_VIEWPORT. +struct Viewport { + float x; + float y; + float width; + float height; + float min_depth; + float max_depth; +}; + +// D3D12_VERTEX_BUFFER_VIEW / D3D12_INDEX_BUFFER_VIEW: console VAs, resolved to buffers at replay. +struct VertexBufferView { + std::uint64_t va; + std::uint32_t size; + std::uint32_t stride; +}; + +struct IndexBufferView { + std::uint64_t va; + std::uint32_t size; + std::uint32_t format; // DXGI_FORMAT_R16_UINT (57) or DXGI_FORMAT_R32_UINT (42) +}; + +// DrawInstanced / DrawIndexedInstanced, with everything they use captured when they are recorded: D3D12 reads +// render-target and depth descriptors at OMSetRenderTargets, and every other piece of state is the list's state at +// the draw. resource 0 marks an unbound render-target slot or no depth buffer. +struct Draw { + std::uintptr_t pipeline; + std::array user_data; + std::vector render_targets; + TargetView depth; + std::vector vertex_buffers; // by input slot + IndexBufferView index; + std::uint32_t topology; // D3D_PRIMITIVE_TOPOLOGY + Viewport viewport; // the first; more viewports are not modelled yet + Rect scissor; // the first; D3D12 always scissors + std::array blend_factor; + std::uint32_t stencil_front; + std::uint32_t stencil_back; + bool indexed; + std::uint32_t count; // vertices or indices per instance + std::uint32_t instances; + std::uint32_t first; // first vertex or first index + std::int32_t base_vertex; + std::uint32_t first_instance; +}; + // D3D12_TEXTURE_DATA_PITCH_ALIGNMENT and D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT. inline constexpr std::uint32_t texture_data_pitch_alignment = 256; inline constexpr std::uint32_t texture_data_placement_alignment = 512; @@ -308,7 +355,7 @@ struct ClearDepthStencil { using Command = std::variant; + CopyResource, ResolveSubresource, Dispatch, Draw>; class CommandList { public: @@ -383,6 +430,13 @@ class CommandList { return append(dispatch); } + // A draw with no vertices or instances does nothing in D3D12, and is not recorded. + bool draw(const Draw& draw) { + if (!draw.pipeline) return false; + if (!draw.count || !draw.instances) return !closed_; + return append(draw); + } + // ClearRenderTargetView; the resource must be in render_target state at execution. No rects: the whole view. bool clear_render_target(const TargetView& target, const ClearColor& color, std::span rects = {}) { if (!valid(target)) return false; diff --git a/runtime/src/shader_library.h b/runtime/src/shader_library.h index ee5c0a976..5e54e4609 100644 --- a/runtime/src/shader_library.h +++ b/runtime/src/shader_library.h @@ -492,6 +492,16 @@ inline std::vector fssm_program(std::span byte // --------------------------------------------------------------------------------------------------------------- // The translator's spirv/index.json +// One element of a shader's DXBC input signature (ISG1), as tools/shader_meta.py records it. For a vertex shader +// the register is the Vulkan input location the translator gave it (docs/design.md, "Vertex fetch"). +struct SignatureElement { + std::string semantic; + std::uint32_t semantic_index = 0; + std::uint32_t register_index = 0; + std::uint32_t system_value = 0; // 0: an ordinary input fed by the input layout + std::string component_type; // "float", "uint", "sint" +}; + struct ShaderEntry { std::string name; std::string stage; // "vs", "ps", "cs", "ms", "gs" @@ -501,6 +511,8 @@ struct ShaderEntry { std::array local_size{1, 1, 1}; bool uses_code_base = false; bool wave64 = false; + std::vector input_signature; // vertex shaders: what the input layout must feed + std::vector outputs; // pixel shaders: the render-target locations written }; class ShaderLibrary { @@ -533,6 +545,20 @@ class ShaderLibrary { for (std::size_t i = 0; i < l->array.size() && i < 3; ++i) e.local_size[i] = std::uint32_t(l->array[i].number); if (const Json* c = meta.find("uses_code_base"); c && c->kind == Json::Kind::boolean) e.uses_code_base = c->boolean; if (const Json* w = meta.find("wave64"); w && w->kind == Json::Kind::boolean) e.wave64 = w->boolean; + if (const Json* s = meta.find("input_signature"); s && s->kind == Json::Kind::array) { + for (const Json& item : s->array) { + SignatureElement element; + if (const Json* v = item.find("semantic"); v && v->kind == Json::Kind::string) element.semantic = v->string; + if (const Json* v = item.find("semantic_index")) element.semantic_index = std::uint32_t(v->number); + if (const Json* v = item.find("register")) element.register_index = std::uint32_t(v->number); + if (const Json* v = item.find("system_value")) element.system_value = std::uint32_t(v->number); + if (const Json* v = item.find("component_type"); v && v->kind == Json::Kind::string) + element.component_type = v->string; + e.input_signature.push_back(std::move(element)); + } + } + if (const Json* o = meta.find("outputs"); o && o->kind == Json::Kind::array) + for (const Json& item : o->array) e.outputs.push_back(std::uint32_t(item.number)); entries_[{e.stage, e.fssm_sha256}] = std::move(e); } return true; diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index c7599e774..255cdbef2 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -32,9 +32,11 @@ struct VulkanDeviceFunctions { X(vkGetImageMemoryRequirements) X(vkBindImageMemory) X(vkCreateBuffer) X(vkDestroyBuffer) \ X(vkGetBufferMemoryRequirements) X(vkBindBufferMemory) X(vkAllocateMemory) X(vkFreeMemory) X(vkMapMemory) \ X(vkUnmapMemory) X(vkCmdCopyBuffer) X(vkCmdCopyBufferToImage) X(vkCmdCopyImageToBuffer) X(vkCmdCopyImage) \ - X(vkCmdResolveImage) X(vkCmdBindPipeline) X(vkCmdPushConstants) X(vkCmdDispatch) X(vkCreateShaderModule) \ - X(vkDestroyShaderModule) X(vkCreatePipelineLayout) X(vkDestroyPipelineLayout) X(vkCreateComputePipelines) \ - X(vkDestroyPipeline) X(vkGetBufferDeviceAddress) + X(vkCmdResolveImage) X(vkCmdBindPipeline) X(vkCmdPushConstants) X(vkCmdDispatch) X(vkCreateShaderModule) \ + X(vkDestroyShaderModule) X(vkCreatePipelineLayout) X(vkDestroyPipelineLayout) X(vkCreateComputePipelines) \ + X(vkDestroyPipeline) X(vkGetBufferDeviceAddress) X(vkCmdBindVertexBuffers2) X(vkCmdBindIndexBuffer) \ + X(vkCmdSetViewport) X(vkCmdSetScissor) X(vkCmdSetPrimitiveTopology) X(vkCmdSetStencilReference) \ + X(vkCmdSetBlendConstants) X(vkCmdDraw) X(vkCmdDrawIndexed) X(vkCreateGraphicsPipelines) #define LEONIDA_VK_MEMBER(name) PFN_##name name = nullptr; LEONIDA_VK_DEVICE_FUNCTIONS(LEONIDA_VK_MEMBER) #undef LEONIDA_VK_MEMBER @@ -83,6 +85,29 @@ class VulkanContext { const auto it = pipelines_.find(id); return it == pipelines_.end() ? nullptr : &it->second; }; + replay_.bind_vertex_buffers2 = vk.vkCmdBindVertexBuffers2; + replay_.bind_index_buffer = vk.vkCmdBindIndexBuffer; + replay_.set_viewport = vk.vkCmdSetViewport; + replay_.set_scissor = vk.vkCmdSetScissor; + replay_.set_primitive_topology = vk.vkCmdSetPrimitiveTopology; + replay_.set_stencil_reference = vk.vkCmdSetStencilReference; + replay_.set_blend_constants = vk.vkCmdSetBlendConstants; + replay_.draw = vk.vkCmdDraw; + replay_.draw_indexed = vk.vkCmdDrawIndexed; + replay_.graphics_pipeline = [this](std::uintptr_t id) -> const GraphicsPipeline* { + const auto it = graphics_pipelines_.find(id); + return it == graphics_pipelines_.end() ? nullptr : &it->second; + }; + // Called with mutex_ held. A linear search: fine for the first frames, an interval map when it shows. + replay_.buffer_at = [this](std::uint64_t va, std::uint64_t size, VkBuffer& buffer, VkDeviceSize& offset) { + for (const auto& [id, b] : resources_) { + if (b.image || !b.buffer || va < b.va || va - b.va >= b.size || size > b.size - (va - b.va)) continue; + buffer = b.buffer; + offset = b.buffer_offset + (va - b.va); + return true; + } + return false; + }; replay_.image_view = [this](const ResourceBinding& r, const VkImageSubresourceRange& range) { return view(r, range); }; @@ -145,6 +170,11 @@ class VulkanContext { void remove_pipeline(std::uintptr_t id) { std::lock_guard lock(mutex_); pipelines_.erase(id); + graphics_pipelines_.erase(id); + } + void add_graphics_pipeline(std::uintptr_t id, const GraphicsPipeline& pipeline) { + std::lock_guard lock(mutex_); + graphics_pipelines_[id] = pipeline; } // For tests and traces. @@ -170,7 +200,7 @@ class VulkanContext { // Called with mutex_ held (from prepare). Views live until their image is removed. VkImageView view(const ResourceBinding& r, const VkImageSubresourceRange& range) { const auto key = std::make_tuple(r.image, range.aspectMask, range.baseMipLevel, range.baseArrayLayer, - range.layerCount); + range.layerCount, r.format); if (const auto it = views_.find(key); it != views_.end()) return it->second; VkImageViewCreateInfo info{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; info.image = r.image; @@ -189,8 +219,10 @@ class VulkanContext { std::mutex submit_mutex_; std::unordered_map resources_; std::unordered_map pipelines_; + std::unordered_map graphics_pipelines_; LayoutTracker tracker_; - std::map, VkImageView> views_; + std::map, VkImageView> + views_; ReplayFunctions replay_; }; diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index ff18c1a58..651ec75e7 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -51,6 +51,7 @@ struct ResourceBinding { VkBuffer buffer = VK_NULL_HANDLE; // a buffer resource, for copies VkDeviceSize buffer_offset = 0; // where it starts in `buffer` (the GPU address arena holds many) VkDeviceSize size = 0; // its size in bytes + std::uint64_t va = 0; // a buffer's console VA (GetGPUVirtualAddress), for vertex/index views std::uint32_t depth = 1; bool volume = false; // one array layer, including at mips with a single slice std::uint32_t samples = 1; // more than one: a multisampled 2D texture @@ -463,6 +464,18 @@ struct ComputePipeline { std::uint64_t code_base = 0; }; +// A graphics pipeline as replay needs it: the formats its attachments must have and which vertex-input slots it +// reads. code_base: as for compute (one per pipeline; two stages that both read theirs are refused, question 14). +struct GraphicsPipeline { + VkPipeline pipeline = VK_NULL_HANDLE; + VkPipelineLayout layout = VK_NULL_HANDLE; + std::uint64_t code_base = 0; + std::vector color_formats; // by render-target slot + VkFormat depth_format = VK_FORMAT_UNDEFINED; + VkImageAspectFlags depth_aspects = 0; + std::uint32_t vertex_slots = 0; // bit per input slot the input layout uses +}; + // The 144-byte push-constant block every translated shader declares: s0..s31, heap base, code base. struct ShaderUserData { std::uint32_t s[32]; @@ -489,6 +502,18 @@ struct ReplayFunctions { PFN_vkCmdPushConstants push_constants = nullptr; PFN_vkCmdDispatch dispatch = nullptr; std::function compute_pipeline; + PFN_vkCmdBindVertexBuffers2 bind_vertex_buffers2 = nullptr; // draws + PFN_vkCmdBindIndexBuffer bind_index_buffer = nullptr; + PFN_vkCmdSetViewport set_viewport = nullptr; + PFN_vkCmdSetScissor set_scissor = nullptr; + PFN_vkCmdSetPrimitiveTopology set_primitive_topology = nullptr; + PFN_vkCmdSetStencilReference set_stencil_reference = nullptr; + PFN_vkCmdSetBlendConstants set_blend_constants = nullptr; + PFN_vkCmdDraw draw = nullptr; + PFN_vkCmdDrawIndexed draw_indexed = nullptr; + std::function graphics_pipeline; + // The buffer and offset a console VA range lies in (vertex and index buffer views), false when none does. + std::function buffer_at; std::uint64_t heap_base = 0; // device address of the GPU address arena (push-constant dwords 32-33) // Returns a 2D-array view of the range (caller-owned, alive until execution completes); rectangle clears. std::function image_view; @@ -520,6 +545,22 @@ struct Prepared { std::vector image_copies; VkImageResolve resolve{}; // resolves ComputePipeline pipeline; // dispatches + // Draws. + struct Attachment { + ResourceBinding binding; + ResourceId id = 0; + VkImageSubresourceRange range{}; + VkImageView view = VK_NULL_HANDLE; + }; + GraphicsPipeline graphics; + std::vector colors; // by slot; id 0 = unbound + Attachment depth; + std::vector vertex_buffers; + std::vector vertex_offsets, vertex_sizes, vertex_strides; + VkBuffer index_buffer = VK_NULL_HANDLE; + VkDeviceSize index_offset = 0; + VkIndexType index_type = VK_INDEX_TYPE_UINT16; + VkExtent2D area{}; }; inline bool view_range(const ResourceBinding& resource, const TargetView& view, VkImageAspectFlags aspects, @@ -816,6 +857,124 @@ void round_trip(const ReplayFunctions& vk, VkCommandBuffer command_buffer, VkIma } // namespace detail +namespace detail { + +// Resolves a draw's pipeline, attachments and buffers. Attachment views take the pipeline's formats, so a +// typeless texture is viewed as the format the pipeline renders. +template +ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunctions& vk, Prepared& p) { + if (!vk.graphics_pipeline || !vk.buffer_at || !vk.image_view || !vk.begin_rendering || !vk.end_rendering || + !vk.bind_vertex_buffers2 || !vk.bind_index_buffer || !vk.set_viewport || !vk.set_scissor || + !vk.set_primitive_topology || !vk.set_stencil_reference || !vk.set_blend_constants || !vk.draw || + !vk.draw_indexed || !vk.bind_pipeline || !vk.push_constants) + return ReplayResult::unsupported; + const GraphicsPipeline* pipeline = vk.graphics_pipeline(draw.pipeline); + if (!pipeline || !pipeline->pipeline) return ReplayResult::unresolved_resource; + p.graphics = *pipeline; + p.area = {UINT32_MAX, UINT32_MAX}; + const auto shrink = [&](const ResourceBinding& b, std::uint32_t mip) { + const VkExtent2D e = mip_extent(b, mip); + p.area = {std::min(p.area.width, e.width), std::min(p.area.height, e.height)}; + }; + + p.colors.assign(pipeline->color_formats.size(), {}); + for (std::size_t slot = 0; slot < draw.render_targets.size() && slot < p.colors.size(); ++slot) { + const TargetView& target = draw.render_targets[slot]; + if (!target.resource) continue; + const ResourceBinding* binding = resolve(target.resource); + if (!binding) return ReplayResult::unresolved_resource; + auto& a = p.colors[slot]; + a.binding = *binding; + a.id = target.resource; + if (!a.binding.image || a.binding.aspects != VK_IMAGE_ASPECT_COLOR_BIT) return ReplayResult::invalid_clear; + if (!view_range(a.binding, target, VK_IMAGE_ASPECT_COLOR_BIT, a.range)) return ReplayResult::invalid_subresource; + ResourceBinding viewed = a.binding; + if (pipeline->color_formats[slot] != VK_FORMAT_UNDEFINED) viewed.format = pipeline->color_formats[slot]; + a.view = vk.image_view(viewed, a.range); + if (!a.view) return ReplayResult::unsupported; + shrink(a.binding, target.mip); + } + if (draw.depth.resource && pipeline->depth_format != VK_FORMAT_UNDEFINED) { + const ResourceBinding* binding = resolve(draw.depth.resource); + if (!binding) return ReplayResult::unresolved_resource; + auto& a = p.depth; + a.binding = *binding; + a.id = draw.depth.resource; + if (!a.binding.image || !(a.binding.aspects & depth_stencil_aspects)) return ReplayResult::invalid_clear; + if (!view_range(a.binding, draw.depth, a.binding.aspects, a.range)) return ReplayResult::invalid_subresource; + ResourceBinding viewed = a.binding; + viewed.format = pipeline->depth_format; + a.view = vk.image_view(viewed, a.range); + if (!a.view) return ReplayResult::unsupported; + shrink(a.binding, draw.depth.mip); + } + if (p.area.width == UINT32_MAX) { // no attachment: the viewport bounds the rendering + p.area = {std::uint32_t(std::max(0.0f, draw.viewport.x + draw.viewport.width)), + std::uint32_t(std::max(0.0f, draw.viewport.y + draw.viewport.height))}; + } + + for (std::uint32_t slot = 0; slot < 32; ++slot) { + if (!(pipeline->vertex_slots & (1u << slot))) continue; + if (slot >= draw.vertex_buffers.size() || !draw.vertex_buffers[slot].va) return ReplayResult::unresolved_resource; + const VertexBufferView& view = draw.vertex_buffers[slot]; + VkBuffer buffer = VK_NULL_HANDLE; + VkDeviceSize offset = 0; + if (!vk.buffer_at(view.va, view.size, buffer, offset)) return ReplayResult::unresolved_resource; + p.vertex_buffers.resize(slot + 1, VK_NULL_HANDLE); + p.vertex_offsets.resize(slot + 1, 0); + p.vertex_sizes.resize(slot + 1, VK_WHOLE_SIZE); + p.vertex_strides.resize(slot + 1, 0); + p.vertex_buffers[slot] = buffer; + p.vertex_offsets[slot] = offset; + p.vertex_sizes[slot] = view.size; + p.vertex_strides[slot] = view.stride; + } + if (draw.indexed) { + if (!draw.index.va || !vk.buffer_at(draw.index.va, draw.index.size, p.index_buffer, p.index_offset)) + return ReplayResult::unresolved_resource; + if (draw.index.format == 57) p.index_type = VK_INDEX_TYPE_UINT16; + else if (draw.index.format == 42) p.index_type = VK_INDEX_TYPE_UINT32; + else return ReplayResult::unsupported; + } + return ReplayResult::success; +} + +// D3D_PRIMITIVE_TOPOLOGY -> VkPrimitiveTopology (patch lists are not modelled). +inline VkPrimitiveTopology vulkan_topology(std::uint32_t topology) { + switch (topology) { + case 1: return VK_PRIMITIVE_TOPOLOGY_POINT_LIST; + case 2: return VK_PRIMITIVE_TOPOLOGY_LINE_LIST; + case 3: return VK_PRIMITIVE_TOPOLOGY_LINE_STRIP; + case 5: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP; + case 10: return VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY; + case 11: return VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY; + case 12: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY; + case 13: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY; + default: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; + } +} + +// Moves an attachment's tracked pieces to `layout` before rendering (first use zero-fills, as everywhere). +inline void to_attachment(const ReplayFunctions& vk, VkCommandBuffer command_buffer, Prepared::Attachment& a, + VkImageLayout layout, VkAccessFlags access, VkPipelineStageFlags stages, + LayoutTracker* tracker, bool separate) { + const VkImageSubresourceRange range = planes_for_layout(a.binding, a.range, separate); + auto pieces = current(tracker, a.id, range, layout); + initialize(vk, command_buffer, a.binding, a.id, pieces, layout, tracker); + for (const auto& piece : pieces) { + if (piece.layout == layout) { + // Attachment writes of an earlier rendering scope are not ordered with this one without a barrier. + memory_barrier(vk, command_buffer, access, stages, access, stages); + continue; + } + image_barrier(vk, command_buffer, a.binding.image, piece.range, piece.layout, layout, + VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, access, stages); + } + if (tracker) tracker->set(a.id, range, layout); +} + +} // namespace detail + // Destination and source of a copy or resolve command. inline std::pair copy_ids(const Command& command) { if (const auto* c = std::get_if(&command)) return {c->dst, c->src}; @@ -935,6 +1094,8 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun const ComputePipeline* pipeline = vk.compute_pipeline(dispatch->pipeline); if (!pipeline || !pipeline->pipeline) return ReplayResult::unresolved_resource; p.pipeline = *pipeline; + } else if (const auto* draw = std::get_if(&command)) { + if (const auto r = detail::prepare_draw(*draw, resolve, vk, p); r != ReplayResult::success) return r; } } return ReplayResult::success; @@ -1152,6 +1313,79 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c vk.bind_pipeline(command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, p.pipeline.pipeline); vk.push_constants(command_buffer, p.pipeline.layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(data), &data); vk.dispatch(command_buffer, dispatch->x, dispatch->y, dispatch->z); + } else if (const auto* draw = std::get_if(&command)) { + auto& prepared_draw = const_cast(p); + constexpr VkAccessFlags color_access = + VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; + constexpr VkAccessFlags depth_access = + VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; + constexpr VkPipelineStageFlags depth_stages = + VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT; + std::vector colors(p.colors.size(), {VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO}); + for (std::size_t slot = 0; slot < p.colors.size(); ++slot) { + auto& a = prepared_draw.colors[slot]; + if (!a.id) continue; // an unbound slot: no image view, writes are dropped + const VkImageLayout layout = image_layout(a.binding, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); + detail::to_attachment(vk, command_buffer, a, layout, color_access, + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, tracker, separate); + colors[slot].imageView = a.view; + colors[slot].imageLayout = layout; + colors[slot].loadOp = VK_ATTACHMENT_LOAD_OP_LOAD; + colors[slot].storeOp = VK_ATTACHMENT_STORE_OP_STORE; + } + VkRenderingAttachmentInfo depth{VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO}; + if (p.depth.id) { + const VkImageLayout layout = image_layout(p.depth.binding, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); + detail::to_attachment(vk, command_buffer, prepared_draw.depth, layout, depth_access, depth_stages, + tracker, separate); + depth.imageView = p.depth.view; + depth.imageLayout = layout; + depth.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD; + depth.storeOp = VK_ATTACHMENT_STORE_OP_STORE; + } + VkRenderingInfo rendering{VK_STRUCTURE_TYPE_RENDERING_INFO}; + rendering.renderArea = {{0, 0}, p.area}; + rendering.layerCount = 1; + rendering.colorAttachmentCount = std::uint32_t(colors.size()); + rendering.pColorAttachments = colors.data(); + if (p.depth.id && (p.graphics.depth_aspects & VK_IMAGE_ASPECT_DEPTH_BIT)) rendering.pDepthAttachment = &depth; + if (p.depth.id && (p.graphics.depth_aspects & VK_IMAGE_ASPECT_STENCIL_BIT)) rendering.pStencilAttachment = &depth; + vk.begin_rendering(command_buffer, &rendering); + + ShaderUserData data{}; + std::copy(draw->user_data.begin(), draw->user_data.end(), data.s); + data.heap_base = vk.heap_base; + data.code_base = p.graphics.code_base; + vk.bind_pipeline(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, p.graphics.pipeline); + vk.push_constants(command_buffer, p.graphics.layout, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, + 0, sizeof(data), &data); + // Translated vertex shaders write D3D clip coordinates (y up); a negative-height viewport keeps the + // image upright, and winding as D3D12 sees it. + const Viewport& v = draw->viewport; + const VkViewport viewport{v.x, v.y + v.height, v.width, -v.height, v.min_depth, v.max_depth}; + vk.set_viewport(command_buffer, 0, 1, &viewport); + const Rect& s = draw->scissor; + const VkRect2D scissor{{std::max(0, s.left), std::max(0, s.top)}, + {std::uint32_t(std::max(0, s.right - std::max(0, s.left))), + std::uint32_t(std::max(0, s.bottom - std::max(0, s.top)))}}; + vk.set_scissor(command_buffer, 0, 1, &scissor); + vk.set_primitive_topology(command_buffer, detail::vulkan_topology(draw->topology)); + vk.set_stencil_reference(command_buffer, VK_STENCIL_FACE_FRONT_BIT, draw->stencil_front); + vk.set_stencil_reference(command_buffer, VK_STENCIL_FACE_BACK_BIT, draw->stencil_back); + vk.set_blend_constants(command_buffer, draw->blend_factor.data()); + for (std::uint32_t slot = 0; slot < p.vertex_buffers.size(); ++slot) { + if (!p.vertex_buffers[slot]) continue; + vk.bind_vertex_buffers2(command_buffer, slot, 1, &p.vertex_buffers[slot], &p.vertex_offsets[slot], + &p.vertex_sizes[slot], &p.vertex_strides[slot]); + } + if (draw->indexed) { + vk.bind_index_buffer(command_buffer, p.index_buffer, p.index_offset, p.index_type); + vk.draw_indexed(command_buffer, draw->count, draw->instances, draw->first, draw->base_vertex, + draw->first_instance); + } else { + vk.draw(command_buffer, draw->count, draw->instances, draw->first, draw->first_instance); + } + vk.end_rendering(command_buffer); } } } diff --git a/runtime/test/d3d12_com_test.cpp b/runtime/test/d3d12_com_test.cpp index 7a5c9df21..5dd13f7b6 100644 --- a/runtime/test/d3d12_com_test.cpp +++ b/runtime/test/d3d12_com_test.cpp @@ -130,7 +130,7 @@ int main() { group.NumBarriers = 1; group.pTextureBarriers = &texture; list->Barrier(1, &group); - list->DrawInstanced(3, 1, 0, 0); // not implemented: reported once by its generated stub, recording continues + list->SetMarker(0, nullptr, 0); // not implemented: reported once by its generated stub, recording continues EXPECT(list->Close() == S_OK); EXPECT(list->Close() == E_FAIL); // already closed diff --git a/runtime/test/d3d12_draw_test.cpp b/runtime/test/d3d12_draw_test.cpp new file mode 100644 index 000000000..989a02db4 --- /dev/null +++ b/runtime/test/d3d12_draw_test.cpp @@ -0,0 +1,283 @@ +// Milestone M1 (docs/d3d12_vulkan.md section 6) through the Xbox-ABI proxy over the Vulkan device: +// - a graphics PSO whose VS and PS come from containers shaped like the game's, found in a translator-style +// index by the SHA-256 of their FSSM programs; the input layout (POSITION, COLOR) is matched to the VS input +// signature by semantic, and the VS declares them in the opposite register order; +// - a vertex buffer copied into the GPU address arena, an index buffer read straight from an upload heap, root +// constants (a clip-space offset) and a root CBV (a tint) through the 32 user-data dwords; +// - a render target cleared blue, two indexed draws with different root arguments (top-left red, bottom-right +// green), and one back-facing triangle (bottom-left) that culling must remove; +// - the image read back through CopyTextureRegion and compared pixel by pixel. Where the quadrants land also +// checks the viewport flip (D3D clip space is y-up) and the front-face winding. +// The shaders are GLSL written to the translator's contract (test/glsl/vs_draw.vert, ps_draw.frag). No game data. +// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation. +#include "vk_test_device.h" +#include "d3d12_test_shaders.h" +#include "../shims/d3d12_com.h" +#include "../shims/d3d12_xs_device.h" +#include "../src/shader_library.h" + +#include +#include + +#if !defined(LEONIDA_TEST_VS_SPV) || !defined(LEONIDA_TEST_PS_SPV) +#error "LEONIDA_TEST_VS_SPV and LEONIDA_TEST_PS_SPV must name the compiled test shaders" +#endif + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +using namespace d3d12test; +using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slot 9: handle in RAX + +namespace { + +struct Vertex { + float x, y; + std::uint8_t r, g, b, a; +}; + +} // namespace + +int main() { + vktest::Device d; + EXPECT(d.create()); + + // Shader programs and the index that maps their hashes to the compiled test modules. + const auto vs_program = fssm_program({0x56530001, 0xbf810000}); + const auto ps_program = fssm_program({0x50530001, 0xbf810000}); + const auto vs_container = shader_container(vs_program), ps_container = shader_container(ps_program); + const auto library = std::filesystem::temp_directory_path() / "leonida_draw_test"; + std::filesystem::create_directories(library); + std::filesystem::copy_file(LEONIDA_TEST_VS_SPV, library / "vs_draw.spv", std::filesystem::copy_options::overwrite_existing); + std::filesystem::copy_file(LEONIDA_TEST_PS_SPV, library / "ps_draw.spv", std::filesystem::copy_options::overwrite_existing); + { + std::ofstream index(library / "index.json", std::ios::binary); + index << "{\"vs_draw\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_program) + << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"input_signature\": [" + "{\"semantic\": \"COLOR\", \"semantic_index\": 0, \"register\": 0, \"mask\": 15, \"rw_mask\": 15, " + "\"system_value\": 0, \"component_type\": \"float\"}, " + "{\"semantic\": \"POSITION\", \"semantic_index\": 0, \"register\": 1, \"mask\": 3, \"rw_mask\": 3, " + "\"system_value\": 0, \"component_type\": \"float\"}]},\n" + " \"ps_draw\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << leonida::sha256_hex(ps_program) + << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"outputs\": [0]}}"; + } + + constexpr UINT size = 64; + std::vector pixels(size * 256); + { + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = d.instance_proc; + info.instance = d.instance; + info.physical = d.physical; + info.device = d.device; + info.queue = d.queue; + info.queue_family = d.family; + info.buffer_device_address = true; + info.shader_dir = library.string(); + ID3D12Device* inner = nullptr; + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); + Ref device; + EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), + reinterpret_cast(&device.p)))); + rt::d3d12::set_device_outer(inner, device.p); + + // Root signature: [0] two constants (s0, s1: offset), [1] a root CBV (s2:s3: tint). + D3D12_ROOT_PARAMETER params[2] = {}; + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + params[0].Constants = {0, 0, 2}; + params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; + params[1].Descriptor = {1, 0}; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{}; + root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; + root_desc.Desc_1_0 = {2, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT}; + const auto root_blob = serialize_root_signature(root_desc); + EXPECT(!root_blob.empty()); + Ref root; + EXPECT(SUCCEEDED(device->CreateRootSignature(0, root_blob.data(), root_blob.size(), IID_PPV_ARGS(&root.p)))); + + // The PSO. Input layout order (POSITION, COLOR) differs from the VS's registers (COLOR 0, POSITION 1). + const D3D12_INPUT_ELEMENT_DESC elements[2] = { + {"POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}, + {"COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, D3D12_APPEND_ALIGNED_ELEMENT, + D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}}; + D3D12_GRAPHICS_PIPELINE_STATE_DESC pso_desc{}; + pso_desc.pRootSignature = root.p; + pso_desc.VS = {vs_container.data(), vs_container.size()}; + pso_desc.PS = {ps_container.data(), ps_container.size()}; + pso_desc.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + pso_desc.SampleMask = 0xffffffff; + pso_desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + pso_desc.RasterizerState.CullMode = D3D12_CULL_MODE_BACK; + pso_desc.RasterizerState.DepthClipEnable = TRUE; + pso_desc.InputLayout = {elements, 2}; + pso_desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + pso_desc.NumRenderTargets = 1; + pso_desc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + pso_desc.SampleDesc.Count = 1; + Ref pso, unfed; + EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&pso.p)))); + pso_desc.InputLayout = {elements, 1}; // COLOR missing: D3D12 rejects a layout that leaves an input unfed + EXPECT(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&unfed.p)) == E_INVALIDARG && !unfed.p); + + // Geometry: a quad in the top-left quadrant (front-facing, clockwise in D3D screen space) and a triangle in + // the bottom-left one wound the other way (back-facing). + const Vertex vertices[7] = { + {-1, 1, 255, 0, 0, 255}, {0, 1, 255, 0, 0, 255}, {-1, 0, 255, 0, 0, 255}, {0, 0, 255, 0, 0, 255}, + {-1, 0, 255, 0, 0, 255}, {-1, -1, 255, 0, 0, 255}, {0, -1, 255, 0, 0, 255}}; + const std::uint16_t indices[6] = {0, 1, 2, 2, 1, 3}; + const float tints[2][3] = {{1, 0, 1}, {0, 1, 0}}; // red stays red; then green + + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; + const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}; + const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; + Ref vertex_buffer, upload, readback, target; + const auto vb_desc = buffer_desc(sizeof(vertices)); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &vb_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&vertex_buffer.p)))); + const auto upload_desc = buffer_desc(4096); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &upload_desc, + D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, + IID_PPV_ARGS(&upload.p)))); + const auto readback_desc = buffer_desc(size * 256); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&readback.p)))); + D3D12_RESOURCE_DESC rt_desc{}; + rt_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + rt_desc.Width = rt_desc.Height = size; + rt_desc.DepthOrArraySize = 1; + rt_desc.MipLevels = 1; + rt_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + rt_desc.SampleDesc.Count = 1; + rt_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &rt_desc, + D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&target.p)))); + + // Upload layout: vertices at 0, indices at 256, the tints at 512 and 768 (CBVs are 256-byte aligned). + std::uint8_t* up = nullptr; + EXPECT(SUCCEEDED(upload->Map(0, nullptr, reinterpret_cast(&up)))); + std::memcpy(up, vertices, sizeof(vertices)); + std::memcpy(up + 256, indices, sizeof(indices)); + std::memcpy(up + 512, tints[0], sizeof(tints[0])); + std::memcpy(up + 768, tints[1], sizeof(tints[1])); + const D3D12_GPU_VIRTUAL_ADDRESS upload_va = upload->GetGPUVirtualAddress(); + + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + Ref rtv_heap; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&rtv_heap.p)))); + const D3D12_CPU_DESCRIPTOR_HANDLE rtv{ + SIZE_T(reinterpret_cast(slot(rtv_heap.p, 9))(rtv_heap.p))}; + device->CreateRenderTargetView(target.p, nullptr, rtv); + + D3D12_COMMAND_QUEUE_DESC queue_desc{}; + Ref queue; + Ref allocator; + Ref list; + Ref fence; + EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); + EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); + EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, pso.p, + IID_PPV_ARGS(&list.p)))); + EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + + // Upload the vertices, prepare the target. + list->CopyBufferRegion(vertex_buffer.p, 0, upload.p, 0, sizeof(vertices)); + D3D12_RESOURCE_BARRIER barriers[2] = { + transition(vertex_buffer.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER), + transition(target.p, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_RENDER_TARGET)}; + list->ResourceBarrier(2, barriers); + const FLOAT blue[4] = {0, 0, 1, 1}; + list->ClearRenderTargetView(rtv, blue, 0, nullptr); + + // State for the draws; the pipeline came with CreateCommandList. + list->SetGraphicsRootSignature(root.p); + list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + const D3D12_VERTEX_BUFFER_VIEW vbv{vertex_buffer->GetGPUVirtualAddress(), sizeof(vertices), sizeof(Vertex)}; + list->IASetVertexBuffers(0, 1, &vbv); + const D3D12_INDEX_BUFFER_VIEW ibv{upload_va + 256, sizeof(indices), DXGI_FORMAT_R16_UINT}; + list->IASetIndexBuffer(&ibv); + const D3D12_VIEWPORT viewport{0, 0, float(size), float(size), 0, 1}; + const D3D12_RECT scissor{0, 0, LONG(size), LONG(size)}; + list->RSSetViewports(1, &viewport); + list->RSSetScissorRects(1, &scissor); + list->OMSetRenderTargets(1, &rtv, FALSE, nullptr); + + // Draw 1: no offset, red tint -> top-left quadrant red. + const float origin[2] = {0, 0}, down_right[2] = {1, -1}; + list->SetGraphicsRoot32BitConstants(0, 2, origin, 0); + list->SetGraphicsRootConstantBufferView(1, upload_va + 512); + list->DrawIndexedInstanced(6, 1, 0, 0, 0); + // Draw 2: offset (1, -1), green tint -> bottom-right quadrant green. + list->SetGraphicsRoot32BitConstants(0, 2, down_right, 0); + list->SetGraphicsRootConstantBufferView(1, upload_va + 768); + list->DrawIndexedInstanced(6, 1, 0, 0, 0); + // Draw 3: the back-facing triangle in the bottom-left quadrant; culled, so that quadrant stays blue. + list->SetGraphicsRoot32BitConstants(0, 2, origin, 0); + list->SetGraphicsRootConstantBufferView(1, upload_va + 512); + list->DrawInstanced(3, 1, 4, 0); + + D3D12_RESOURCE_BARRIER to_copy = transition(target.p, D3D12_RESOURCE_STATE_RENDER_TARGET, + D3D12_RESOURCE_STATE_COPY_SOURCE); + list->ResourceBarrier(1, &to_copy); + D3D12_TEXTURE_COPY_LOCATION dst{}; + dst.pResource = readback.p; + dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + dst.PlacedFootprint = {0, {DXGI_FORMAT_R8G8B8A8_UNORM, size, size, 1, 256}}; + D3D12_TEXTURE_COPY_LOCATION src{}; + src.pResource = target.p; + src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + EXPECT(list->Close() == S_OK); + ID3D12CommandList* lists[] = {list.p}; + queue->ExecuteCommandLists(1, lists); + EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); + EXPECT(SUCCEEDED(queue->Signal(fence.p, 1))); + EXPECT(SUCCEEDED(fence->SetEventOnCompletion(1, nullptr))); + void* mapped = nullptr; + EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped))); + std::memcpy(pixels.data(), mapped, pixels.size()); + + // A draw without a topology is invalid; Close reports it. + EXPECT(SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.p, pso.p))); + list->SetGraphicsRootSignature(root.p); + list->DrawInstanced(3, 1, 0, 0); + EXPECT(list->Close() == E_INVALIDARG); + + for (auto* r : {&vertex_buffer, &upload, &readback, &target}) r->reset(); + pso.reset(); + root.reset(); + rtv_heap.reset(); + list.reset(); + allocator.reset(); + queue.reset(); + fence.reset(); + EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1); + } + std::filesystem::remove_all(library); + + unsigned mismatches = 0; + for (UINT row = 0; row < size; ++row) { + for (UINT col = 0; col < size; ++col) { + const bool top = row < size / 2, left = col < size / 2; + const std::array want = top && left ? std::array{255, 0, 0, 255} + : !top && !left ? std::array{0, 255, 0, 255} + : std::array{0, 0, 255, 255}; + const std::uint8_t* got = pixels.data() + row * 256 + col * 4; + if (std::equal(want.begin(), want.end(), got)) continue; + if (mismatches++ < 6) + std::fprintf(stderr, "pixel (%u, %u): got %u,%u,%u,%u want %u,%u,%u,%u\n", col, row, got[0], got[1], + got[2], got[3], want[0], want[1], want[2], want[3]); + } + } + EXPECT(!mismatches); + if (d.validation_errors()) { + std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); + return 1; + } + std::printf("M1: two indexed draws and a culled triangle matched all %u pixels: input layout by semantic, root " + "constants and a root CBV per draw, vertex buffer in the arena, index buffer in an upload heap\n", + size * size); + return 0; +} diff --git a/runtime/test/d3d12_test_shaders.h b/runtime/test/d3d12_test_shaders.h new file mode 100644 index 000000000..d778d1bc6 --- /dev/null +++ b/runtime/test/d3d12_test_shaders.h @@ -0,0 +1,124 @@ +// Helpers for the D3D12 pipeline tests: wrap a synthetic FSSM program in a shader container shaped like the game's +// (DXBC { DXIL { stub, XDAT { 0x0D: XBCH + zlib(fssm) } } }, the layout tools/fssm_unpack.py reads), serialize a +// root signature with the host PC runtime, and write a translator-style index next to compiled test modules. +// No game data: the programs are a few marker words, and the modules are GLSL written to the translator's contract. +#pragma once + +#include +#include + +#include +#include +#include +#include +#include + +namespace d3d12test { + +inline void put32(std::vector& out, std::uint32_t v) { + for (int i = 0; i < 4; ++i) out.push_back(std::uint8_t(v >> (8 * i))); +} + +// zlib with one stored block (RFC 1950/1951), enough to wrap a test program. +inline std::vector zlib_stored(const std::vector& data) { + std::vector out = {0x78, 0x01, 0x01}; + const auto length = std::uint16_t(data.size()); + out.insert(out.end(), {std::uint8_t(length), std::uint8_t(length >> 8), std::uint8_t(~length), + std::uint8_t(~length >> 8)}); + out.insert(out.end(), data.begin(), data.end()); + std::uint32_t a = 1, b = 0; + for (const std::uint8_t x : data) { + a = (a + x) % 65521; + b = (b + a) % 65521; + } + const std::uint32_t adler = (b << 16) | a; + out.insert(out.end(), {std::uint8_t(adler >> 24), std::uint8_t(adler >> 16), std::uint8_t(adler >> 8), + std::uint8_t(adler)}); + return out; +} + +// A synthetic FSSM program: the magic, then `words` (distinct per test shader so their hashes differ). +inline std::vector fssm_program(std::initializer_list words) { + std::vector out = {'F', 'S', 'S', 'M'}; + for (const std::uint32_t w : words) put32(out, w); + return out; +} + +inline std::vector shader_container(const std::vector& fssm) { + const auto stream = zlib_stored(fssm); + std::vector xbch = {'X', 'B', 'C', 'H'}; + for (const std::uint32_t v : {1u, std::uint32_t(stream.size()), 0u, std::uint32_t(fssm.size()), 0u}) put32(xbch, v); + xbch.insert(xbch.end(), stream.begin(), stream.end()); + std::vector dxil(16, 0); + dxil.insert(dxil.end(), {'X', 'D', 'A', 'T'}); + put32(dxil, 1); + put32(dxil, 12); + put32(dxil, 0x0d); + put32(dxil, 16 + 12 + 12); + put32(dxil, std::uint32_t(xbch.size())); + dxil.insert(dxil.end(), xbch.begin(), xbch.end()); + std::vector out = {'D', 'X', 'B', 'C'}; + out.resize(28, 0); + put32(out, 1); + put32(out, 36); + out.insert(out.end(), {'D', 'X', 'I', 'L'}); + put32(out, std::uint32_t(dxil.size())); + out.insert(out.end(), dxil.begin(), dxil.end()); + return out; +} + +using SerializeFn = HRESULT(WINAPI*)(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC*, ID3DBlob**, ID3DBlob**); + +inline std::vector serialize_root_signature(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC& desc) { + const HMODULE d3d12 = LoadLibraryExA("d3d12.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); + const auto fn = d3d12 ? reinterpret_cast( + reinterpret_cast(GetProcAddress(d3d12, "D3D12SerializeVersionedRootSignature"))) + : nullptr; + std::vector out; + ID3DBlob* blob = nullptr; + if (fn && SUCCEEDED(fn(&desc, &blob, nullptr)) && blob) { + const auto* p = static_cast(blob->GetBufferPointer()); + out.assign(p, p + blob->GetBufferSize()); + blob->Release(); + } + return out; +} + +inline D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes, D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE) { + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = bytes; + desc.Height = 1; + desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + desc.Flags = flags; + return desc; +} + +inline D3D12_RESOURCE_BARRIER transition(ID3D12Resource* resource, D3D12_RESOURCE_STATES before, + D3D12_RESOURCE_STATES after) { + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barrier.Transition.pResource = resource; + barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + barrier.Transition.StateBefore = before; + barrier.Transition.StateAfter = after; + return barrier; +} + +template +struct Ref { + T* p = nullptr; + ~Ref() { reset(); } + void reset() { + if (p) p->Release(); + p = nullptr; + } + T* operator->() const { return p; } +}; + +inline void* slot(void* object, unsigned index) { return (*reinterpret_cast(object))[index]; } + +} // namespace d3d12test diff --git a/runtime/test/glsl/ps_draw.frag b/runtime/test/glsl/ps_draw.frag new file mode 100644 index 000000000..2361330f4 --- /dev/null +++ b/runtime/test/glsl/ps_draw.frag @@ -0,0 +1,30 @@ +#version 460 +// A pixel shader written to the translator's runtime contract, standing in for a translated one in +// d3d12_draw_test. s2:s3 is a root CBV: the console VA of three floats (a tint), read at heap base + VA. The output +// is (red * tint.x, tint.y, blue * tint.z, 1). +#extension GL_EXT_buffer_reference : require +#extension GL_EXT_buffer_reference_uvec2 : require + +layout(buffer_reference, std430, buffer_reference_align = 4) buffer Floats { + float f[]; +}; + +layout(location = 0) in vec4 color; +layout(location = 0) out vec4 target; + +layout(push_constant) uniform UserData { + uint s[32]; + uvec2 heap_base; + uvec2 code_base; +} pc; + +uvec2 add64(uvec2 a, uvec2 b) { + uint carry; + const uint low = uaddCarry(a.x, b.x, carry); + return uvec2(low, a.y + b.y + carry); +} + +void main() { + Floats tint = Floats(add64(pc.heap_base, uvec2(pc.s[2], pc.s[3]))); + target = vec4(color.r * tint.f[0], tint.f[1], color.b * tint.f[2], 1.0); +} diff --git a/runtime/test/glsl/vs_draw.vert b/runtime/test/glsl/vs_draw.vert new file mode 100644 index 000000000..3cde02a50 --- /dev/null +++ b/runtime/test/glsl/vs_draw.vert @@ -0,0 +1,22 @@ +#version 460 +// A vertex shader written to the translator's runtime contract (docs/design.md, "Vertex fetch" and "User data"), +// standing in for a translated one in d3d12_draw_test. Inputs sit at location = D3D input register: COLOR is +// register 0 and POSITION register 1 here, the reverse of the input layout's order, so the test shows that the +// layout is matched by semantic. s0, s1 (root constants) move the vertex in clip space. + +layout(location = 0) in vec4 color; // COLOR0, input register 0 +layout(location = 1) in vec4 position; // POSITION0, input register 1 + +layout(location = 0) out vec4 out_color; + +layout(push_constant) uniform UserData { + uint s[32]; + uvec2 heap_base; + uvec2 code_base; +} pc; + +void main() { + const vec2 offset = vec2(uintBitsToFloat(pc.s[0]), uintBitsToFloat(pc.s[1])); + gl_Position = vec4(position.xy + offset, 0.0, 1.0); + out_color = color; +} diff --git a/runtime/test/shader_library_test.cpp b/runtime/test/shader_library_test.cpp index 5c074b18a..e38324898 100644 --- a/runtime/test/shader_library_test.cpp +++ b/runtime/test/shader_library_test.cpp @@ -155,6 +155,12 @@ int main() { index << "{\"cs_test\": {\"stage\": \"cs\", \"fssm_sha256\": \"" << hash << "\", \"bindings\": [2], \"push_constant_bytes\": 144, \"local_size\": [64, 1, 1], " "\"uses_code_base\": true, \"wave64\": false},\n" + " \"vs_test\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << hash << "\", \"input_signature\": [" + "{\"semantic\": \"COLOR\", \"semantic_index\": 0, \"register\": 0, \"mask\": 15, \"rw_mask\": 15, " + "\"system_value\": 0, \"component_type\": \"float\"}, " + "{\"semantic\": \"SV_VertexID\", \"semantic_index\": 0, \"register\": 2, \"mask\": 1, \"rw_mask\": 1, " + "\"system_value\": 6, \"component_type\": \"uint\"}]},\n" + " \"ps_out\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << hash << "\", \"outputs\": [0, 2]},\n" " \"ps_unhashed\": {\"stage\": \"ps\", \"bindings\": []}}"; std::ofstream spv(dir / "cs_test.spv", std::ios::binary); const std::uint32_t words[5] = {0x07230203, 0x00010500, 0, 1, 0}; @@ -162,11 +168,17 @@ int main() { } ShaderLibrary library; std::string error; - CHECK(library.load(dir.string(), &error) && library.size() == 1); + CHECK(library.load(dir.string(), &error) && library.size() == 3); + const ShaderEntry* vs = library.find("vs", hash); + CHECK(vs && vs->input_signature.size() == 2 && vs->input_signature[0].semantic == "COLOR"); + CHECK(vs->input_signature[1].register_index == 2 && vs->input_signature[1].system_value == 6 && + vs->input_signature[1].component_type == "uint"); + const ShaderEntry* ps = library.find("ps", hash); + CHECK(ps && ps->outputs.size() == 2 && ps->outputs[1] == 2); const ShaderEntry* entry = library.find("cs", sha256_hex(fssm_program(shader))); CHECK(entry && entry->name == "cs_test" && entry->binding_count == 1 && entry->push_constant_bytes == 144); CHECK(entry->local_size[0] == 64 && entry->uses_code_base && !entry->wave64); - CHECK(!library.find("ps", hash)); + CHECK(!library.find("ms", hash)); // no mesh shader with this hash CHECK(library.spirv(*entry).size() == 5); CHECK(!library.load((dir / "missing").string(), &error) && !error.empty()); std::filesystem::remove_all(dir); From f9211059079823b62e946aa74d5870c723cbfdb1 Mon Sep 17 00:00:00 2001 From: Ryx <118130241+Ryx69@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:52:38 +0100 Subject: [PATCH 6/9] Runtime: only allocate from a memory heap that can hold the allocation (arena without Resizable BAR) Without Resizable BAR the only DEVICE_LOCAL | HOST_VISIBLE memory type sits in a heap of 256 MiB or less (214 MiB on an RTX 3090, driver 616.56). The 256 MiB default arena preferred that type, so vkAllocateMemory was asked for more than the heap holds (VUID-vkAllocateMemory-pAllocateInfo-01713). The NVIDIA driver still returned VK_SUCCESS, so the fallback to plain host-visible memory never ran, and d3d12_compute_test and d3d12_draw_test failed under validation. Reported by CharlyRien. memory_type_order (vulkan_backend.h) now leaves out every type whose heap is smaller than the allocation, so the preference falls through to system memory there. DeviceState::allocate uses it for every allocation. d3d12_state_map_test checks the order on that card's heap layout and with Resizable BAR on. --- docs/d3d12_vulkan.md | 8 ++++++- runtime/shims/d3d12_vulkan_device.cpp | 22 +++++++++---------- runtime/src/vulkan_backend.h | 22 +++++++++++++++++++ runtime/test/d3d12_state_map_test.cpp | 31 +++++++++++++++++++++++++-- 4 files changed, 68 insertions(+), 15 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 713600378..6e1c38016 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -314,7 +314,8 @@ affect. Build `runtime/` (Vulkan SDK and Python 3 on `PATH`) and run `ctest --test-dir --output-on-failure` for the CPU tests: - `command_list_test` covers the recording rules. -- `d3d12_state_map_test` covers both state tables, subresource and barrier-range decoding, and layout tracking. On +- `d3d12_state_map_test` covers both state tables, subresource and barrier-range decoding, layout tracking, and the + memory type order on a no-ReBAR heap layout. On Windows it also checks every D3D12 constant the IR copies against the SDK's `d3d12.h`. - `gfx10_descriptors_test` covers the T#, S# and V#: every field alone at its bit position, round trips, what decoding refuses and ignores, the T#s the image test shaders build, sampler words as radv writes them, and the @@ -429,6 +430,11 @@ uses an image VA as a raw pointer. available). The CPU can then write descriptor heaps, shader blobs and uploaded buffers directly. Images are already device-local, so rendering still uses fast memory for textures. This is slow for dynamic buffers but removes staging and host/console address translation from the bring-up path. + - A memory type is only tried when its heap can hold the whole allocation (`memory_type_order` in + `runtime/src/vulkan_backend.h`). Without Resizable BAR the only `DEVICE_LOCAL | HOST_VISIBLE` type sits in a + heap of 256 MiB or less (214 MiB on an RTX 3090 with driver 616.56), so the 256 MiB default arena lands in + system memory there. Asking that heap for it broke VUID-vkAllocateMemory-pAllocateInfo-01713 even though the + driver returned `VK_SUCCESS` (reported by CharlyRien). - M4+: allocate the arena `DEVICE_LOCAL` and stage CPU writes (descriptor heaps, shader blobs, buffer uploads) through a host-visible staging buffer, copied before the commands that use them. The hash table is not in the arena; it is a normal storage buffer, so it can stay host-visible and be updated directly. diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 9c79675f3..4a9ca10e1 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -205,22 +205,20 @@ struct DeviceState { (properties.sampleCounts & image.samples); } - // The first memory type with `required`, preferring one that also has `preferred`. + // A memory type with `required`, preferring one that also has `preferred`, in a heap large enough for the + // allocation (leonida::memory_type_order). VkDeviceMemory allocate(const VkMemoryRequirements& requirements, VkMemoryPropertyFlags required, VkMemoryPropertyFlags preferred, bool device_address = false) const { VkMemoryAllocateFlagsInfo flags_info{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO}; flags_info.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; - for (const VkMemoryPropertyFlags flags : {required | preferred, required}) { - for (std::uint32_t i = 0; i < memory.memoryTypeCount; ++i) { - if (!(requirements.memoryTypeBits & (1u << i))) continue; - if ((memory.memoryTypes[i].propertyFlags & flags) != flags) continue; - VkMemoryAllocateInfo allocate{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; - if (device_address) allocate.pNext = &flags_info; - allocate.allocationSize = requirements.size; - allocate.memoryTypeIndex = i; - VkDeviceMemory out = VK_NULL_HANDLE; - if (context->vk.vkAllocateMemory(info.device, &allocate, nullptr, &out) == VK_SUCCESS) return out; - } + for (const std::uint32_t i : + leonida::memory_type_order(memory, requirements.memoryTypeBits, required, preferred, requirements.size)) { + VkMemoryAllocateInfo allocate{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; + if (device_address) allocate.pNext = &flags_info; + allocate.allocationSize = requirements.size; + allocate.memoryTypeIndex = i; + VkDeviceMemory out = VK_NULL_HANDLE; + if (context->vk.vkAllocateMemory(info.device, &allocate, nullptr, &out) == VK_SUCCESS) return out; } return VK_NULL_HANDLE; } diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index 255cdbef2..c249bb6cc 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -10,6 +10,7 @@ #endif #include "vulkan_replay.h" +#include #include #include #include @@ -21,6 +22,27 @@ namespace leonida { +// The memory types to try for an allocation of `size` bytes, best first: those with `required | preferred`, then +// those with only `required`. A type whose heap is smaller than the allocation is left out, as the allocation would +// break VUID-vkAllocateMemory-pAllocateInfo-01713 (some drivers still return VK_SUCCESS). Without Resizable BAR the +// heap of DEVICE_LOCAL | HOST_VISIBLE memory is typically 256 MiB or less, so a larger host-visible allocation falls +// through to system memory. A heap that is big enough but already partly used is left to the driver: a failed +// vkAllocateMemory moves on to the next type. +inline std::vector memory_type_order(const VkPhysicalDeviceMemoryProperties& memory, + std::uint32_t type_bits, VkMemoryPropertyFlags required, + VkMemoryPropertyFlags preferred, VkDeviceSize size) { + std::vector order; + for (const VkMemoryPropertyFlags flags : {required | preferred, required}) { + for (std::uint32_t i = 0; i < memory.memoryTypeCount && i < VK_MAX_MEMORY_TYPES; ++i) { + const VkMemoryType& type = memory.memoryTypes[i]; + if (!(type_bits & (1u << i)) || (type.propertyFlags & flags) != flags) continue; + if (type.heapIndex >= memory.memoryHeapCount || memory.memoryHeaps[type.heapIndex].size < size) continue; + if (std::find(order.begin(), order.end(), i) == order.end()) order.push_back(i); + } + } + return order; +} + struct VulkanDeviceFunctions { #define LEONIDA_VK_DEVICE_FUNCTIONS(X) \ X(vkCreateCommandPool) X(vkDestroyCommandPool) X(vkAllocateCommandBuffers) X(vkResetCommandBuffer) \ diff --git a/runtime/test/d3d12_state_map_test.cpp b/runtime/test/d3d12_state_map_test.cpp index 49d52d6be..e30abe814 100644 --- a/runtime/test/d3d12_state_map_test.cpp +++ b/runtime/test/d3d12_state_map_test.cpp @@ -3,7 +3,7 @@ #ifndef VK_NO_PROTOTYPES #define VK_NO_PROTOTYPES #endif -#include "../src/vulkan_replay.h" +#include "../src/vulkan_backend.h" // memory_type_order; includes vulkan_replay.h #ifdef _WIN32 #include @@ -298,6 +298,33 @@ int main() { merged.forget(1); CHECK(!merged.tracked(1)); - std::printf("state map, enhanced barriers, subresource decoding and layout tracking OK\n"); + // Memory type choice. Heaps as an RTX 3090 without Resizable BAR reports them: VRAM, system memory, and the + // 214 MiB BAR heap that holds the only DEVICE_LOCAL | HOST_VISIBLE type. + { + constexpr VkMemoryPropertyFlags local = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; + constexpr VkMemoryPropertyFlags host = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; + VkPhysicalDeviceMemoryProperties memory{}; + memory.memoryHeapCount = 3; + memory.memoryHeaps[0] = {24ull << 30, VK_MEMORY_HEAP_DEVICE_LOCAL_BIT}; + memory.memoryHeaps[1] = {32ull << 30, 0}; + memory.memoryHeaps[2] = {224395264, VK_MEMORY_HEAP_DEVICE_LOCAL_BIT}; + memory.memoryTypeCount = 4; + memory.memoryTypes[0] = {local, 0}; + memory.memoryTypes[1] = {host, 1}; + memory.memoryTypes[2] = {host | VK_MEMORY_PROPERTY_HOST_CACHED_BIT, 1}; + memory.memoryTypes[3] = {local | host, 2}; + using order = std::vector; + constexpr VkDeviceSize mib = 1 << 20; + CHECK(memory_type_order(memory, 0xF, host, local, 256 * mib) == (order{1, 2})); // the 256 MiB arena + CHECK(memory_type_order(memory, 0xF, host, local, 128 * mib) == (order{3, 1, 2})); // fits the BAR heap + CHECK(memory_type_order(memory, 0xF, host, local, 224395264) == (order{3, 1, 2})); // exactly fits + CHECK(memory_type_order(memory, 0x7, host, local, 128 * mib) == (order{1, 2})); // type 3 not allowed + CHECK(memory_type_order(memory, 0xF, 0, local, 1 * mib) == (order{0, 3, 1, 2})); + CHECK(memory_type_order(memory, 0xF, host, local, 64ull << 30).empty()); // nothing that large + memory.memoryHeaps[2].size = 24ull << 30; // Resizable BAR on + CHECK(memory_type_order(memory, 0xF, host, local, 256 * mib) == (order{3, 1, 2})); + } + + std::printf("state map, enhanced barriers, subresource decoding, layout tracking and memory types OK\n"); return 0; } From b18aedf00610586eb909267f7bc905ad2c9ff5c2 Mon Sep 17 00:00:00 2001 From: Ryx <118130241+Ryx69@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:21:53 +0100 Subject: [PATCH 7/9] Runtime: refuse PSOs below 144 bytes of push constants; push-constant stages from the stage table Review feedback from IAmNotSiob: - Both PSO paths declared a 144-byte push-constant range without consulting #224's limit. On a device with maxPushConstantsSize 128 (the Vulkan minimum) that breaks VUID-VkPushConstantRange-size-00298 and returns a bare E_FAIL. Both paths now refuse with E_NOTIMPL and log the limit until the uniform-buffer tail exists. d3d12_compute_test checks this with a device that reports 128 bytes. - The graphics range's stage flags are now the whole stage table create_graphics accepts, kept in GraphicsPipeline::push_stages, and the replay pushes with the same flags. A geometry or mesh stage added to the table is covered without another change. docs/d3d12_vulkan.md section 5.2 now counts code-base readers per stage with the current translator: of the 662 shaders with s_getpc_b64, 53 VS, 92 PS, 246 MS and 263 CS read the code base. VS+PS pairs are only known at PSO creation. --- docs/d3d12_vulkan.md | 21 ++++++++++++++++++++- runtime/shims/d3d12_vulkan_device.cpp | 21 +++++++++++++++++++-- runtime/src/vulkan_replay.h | 4 ++-- runtime/test/d3d12_compute_test.cpp | 19 +++++++++++++++++++ 4 files changed, 60 insertions(+), 5 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 6e1c38016..6fae35e90 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -288,7 +288,11 @@ The compute path, end to end: topology, vertex strides, stencil references and the blend factor are dynamic. - **Formats:** dynamic rendering takes the RTV and DSV formats. - **Refused with a log:** hull, domain and geometry stages, stream output, MSAA, set-0 bindings, and two stages - that both read their code base (question 14). + that both read their code base (question 14, section 5.2). + - **Push constants:** both PSO paths declare the 144-byte block as one range. Its stage flags are the whole + stage table the graphics path accepts, and the replay pushes with the same flags. A device whose + `maxPushConstantsSize` is below 144 (#224's `push_constants_need_fallback`) has every PSO refused, with the + limit in the log, until the uniform-buffer tail exists. The command list keeps the input-assembler, viewport, scissor, render-target (read at `OMSetRenderTargets`, as D3D12 does), blend-factor and stencil-reference state, including CommandList8's front/back references. Each @@ -973,6 +977,21 @@ contract, not a runtime bug: adds a descriptor binding and a load per `s_getpc`, but avoids growing push constants. Decide after measuring how many real PSOs have two code-base stages. +**Measured (stages):** 662 of the 25,734 disassembled shaders contain `s_getpc_b64`. The translator at 83d0637 +(`uses_code_base`, set unless the instruction is part of a folded far branch) gives, for those 662: + +| Stage | Read the code base | Stage total in the index | +|---|---|---| +| VS | 53 | 2,236 | +| PS | 92 | 12,101 | +| MS | 246 | 9,282 | +| CS | 263 of 271 | 2,689 | + +Which VS and PS share a PSO is only known when the game creates it, so the pair count is still open. +`CreateGraphicsPipelineState` refuses a pair where both read it, with a log, so the first boot measures it. MS+PS +pipelines (not accepted yet) are the likelier case: every MS that uses `s_getpc_b64` reads its code base. An index +written by an older translator may have no `uses_code_base` entries at all, so count with the current one. + **Measured:** across the GPU test fleet (Issue #166), desktop NVIDIA (Turing, Ampere, Ada, Blackwell: 256 bytes), desktop AMD (RDNA2: 256 bytes) and Apple Silicon (MoltenVK: 4096 bytes) all satisfy the 144-byte contract natively (`maxPushConstantsSize >= 144`). On Intel Arc (Alchemist, Battlemage), Vulkan exposes the 128-byte specification minimum (`maxPushConstantsSize == 128`), which cannot fit the 16-byte tail (dwords 32–35: heap base and code base) inside push constants. The runtime detects `maxPushConstantsSize < 144` at device creation (`d3d12_vulkan_device.cpp`) and flags `push_constants_need_fallback` for the uniform-buffer fallback. ### 5.3 Descriptor T#/S# parsing diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 4a9ca10e1..ff972cb50 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -603,6 +603,19 @@ class PipelineState final if (code_bytes_) device_.arena_release(code_base_, code_bytes_); } + // Pipeline layouts declare the whole 144-byte block as one push-constant range. A device whose + // maxPushConstantsSize is smaller (128 bytes is the Vulkan minimum, which some Intel and mobile drivers + // report) needs the uniform-buffer tail #224 flags with push_constants_need_fallback, which is not built yet, + // so pipelines are refused there with the limit named instead of breaking VUID-VkPushConstantRange-size-00298. + bool push_constants_fit() const { + const std::uint32_t limit = device_.info.max_push_constants_size; + if (limit == 0 || limit >= sizeof(leonida::ShaderUserData)) return true; // 0: not queried + log_once("pipelines need 144 bytes of push constants (uniform-buffer fallback not built yet); " + "maxPushConstantsSize", + int(limit)); + return false; + } + std::uintptr_t id() const { return reinterpret_cast(static_cast(this)); } bool compute() const { return registered_ && !is_graphics_; } bool graphics() const { return registered_ && is_graphics_; } @@ -620,6 +633,7 @@ class PipelineState final log_once("pipelines need the GPU address arena (bufferDeviceAddress); stage", 1); return E_NOTIMPL; } + if (!push_constants_fit()) return E_NOTIMPL; if (desc.HS.BytecodeLength || desc.DS.BytecodeLength || desc.GS.BytecodeLength || desc.StreamOutput.NumEntries) { log_once("graphics pipeline stage not supported yet (hull/domain/geometry/stream output):", 0); return E_NOTIMPL; @@ -825,8 +839,10 @@ class PipelineState final dynamic.dynamicStateCount = std::uint32_t(std::size(dynamic_states)); dynamic.pDynamicStates = dynamic_states; - const VkPushConstantRange push{VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, - sizeof(leonida::ShaderUserData)}; + // Every stage this path accepts reads the user SGPRs, so the range covers the whole stage table, not only the + // stages present. A stage added to the table (geometry, mesh) is covered without touching this. + for (const Stage& stage : stages) graphics_.push_stages |= stage.bit; + const VkPushConstantRange push{graphics_.push_stages, 0, sizeof(leonida::ShaderUserData)}; VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; layout_info.pushConstantRangeCount = 1; layout_info.pPushConstantRanges = &push; @@ -869,6 +885,7 @@ class PipelineState final log_once("pipelines need the GPU address arena (bufferDeviceAddress); stage", 0); return E_NOTIMPL; } + if (!push_constants_fit()) return E_NOTIMPL; const std::vector fssm = leonida::fssm_program( {static_cast(desc.CS.pShaderBytecode), desc.CS.BytecodeLength}); if (fssm.empty()) { diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 651ec75e7..fcdb3514a 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -469,6 +469,7 @@ struct ComputePipeline { struct GraphicsPipeline { VkPipeline pipeline = VK_NULL_HANDLE; VkPipelineLayout layout = VK_NULL_HANDLE; + VkShaderStageFlags push_stages = 0; // the layout's push-constant range; vkCmdPushConstants must name the same std::uint64_t code_base = 0; std::vector color_formats; // by render-target slot VkFormat depth_format = VK_FORMAT_UNDEFINED; @@ -1357,8 +1358,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c data.heap_base = vk.heap_base; data.code_base = p.graphics.code_base; vk.bind_pipeline(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, p.graphics.pipeline); - vk.push_constants(command_buffer, p.graphics.layout, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, - 0, sizeof(data), &data); + vk.push_constants(command_buffer, p.graphics.layout, p.graphics.push_stages, 0, sizeof(data), &data); // Translated vertex shaders write D3D clip coordinates (y up); a negative-height viewport keeps the // image upright, and winding as D3D12 sees it. const Viewport& v = draw->viewport; diff --git a/runtime/test/d3d12_compute_test.cpp b/runtime/test/d3d12_compute_test.cpp index d07c303fe..e23f7d6e6 100644 --- a/runtime/test/d3d12_compute_test.cpp +++ b/runtime/test/d3d12_compute_test.cpp @@ -209,6 +209,25 @@ int main() { const auto other_container = shader_container(other); pso_desc.CS = {other_container.data(), other_container.size()}; EXPECT(device->CreateComputePipelineState(&pso_desc, IID_PPV_ARGS(&unknown.p)) == E_INVALIDARG && !unknown.p); + pso_desc.CS = {container.data(), container.size()}; + + // A device whose maxPushConstantsSize is the Vulkan minimum (128 bytes) cannot hold the 144-byte block, so + // its PSOs are refused instead of creating a pipeline layout the spec forbids (#224's fallback flag). + { + rt::d3d12::VulkanDeviceInfo limited_info = info; + limited_info.max_push_constants_size = 128; + limited_info.push_constants_need_fallback = true; + Ref limited; + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(limited_info, IID_PPV_ARGS(&limited.p)))); + EXPECT(rt::d3d12::device_push_constants_need_fallback(limited.p)); + Ref limited_root; + EXPECT(SUCCEEDED(limited->CreateRootSignature(0, root_blob.data(), root_blob.size(), + IID_PPV_ARGS(&limited_root.p)))); + D3D12_COMPUTE_PIPELINE_STATE_DESC limited_desc = pso_desc; + limited_desc.pRootSignature = limited_root.p; + Ref refused; + EXPECT(limited->CreateComputePipelineState(&limited_desc, IID_PPV_ARGS(&refused.p)) == E_NOTIMPL && !refused.p); + } // Buffers in the arena, an upload buffer outside it, a readback buffer for the results. const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; From 80fc786b0007889729aa41583d1b5093848782af Mon Sep 17 00:00:00 2001 From: VictorJulianiR <40750238+VictorJulianiR@users.noreply.github.com> Date: Sat, 21 Nov 2026 22:33:16 -0300 Subject: [PATCH 8/9] Exercise an upload vertex buffer, index buffer and root CBV in one indexed draw --- runtime/test/d3d12_draw_test.cpp | 34 ++++++++++++++++++++++---------- 1 file changed, 24 insertions(+), 10 deletions(-) diff --git a/runtime/test/d3d12_draw_test.cpp b/runtime/test/d3d12_draw_test.cpp index 989a02db4..fe9585a90 100644 --- a/runtime/test/d3d12_draw_test.cpp +++ b/runtime/test/d3d12_draw_test.cpp @@ -2,10 +2,9 @@ // - a graphics PSO whose VS and PS come from containers shaped like the game's, found in a translator-style // index by the SHA-256 of their FSSM programs; the input layout (POSITION, COLOR) is matched to the VS input // signature by semantic, and the VS declares them in the opposite register order; -// - a vertex buffer copied into the GPU address arena, an index buffer read straight from an upload heap, root -// constants (a clip-space offset) and a root CBV (a tint) through the 32 user-data dwords; -// - a render target cleared blue, two indexed draws with different root arguments (top-left red, bottom-right -// green), and one back-facing triangle (bottom-left) that culling must remove; +// - vertex buffers in the GPU address arena and in an upload heap, with upload-backed indices and root CBVs; +// - three indexed draws (top-left red, bottom-right green, top-right white) on a blue target, and one +// back-facing triangle in the bottom-left quadrant that culling must remove; // - the image read back through CopyTextureRegion and compared pixel by pixel. Where the quadrants land also // checks the viewport flip (D3D clip space is y-up) and the front-face winding. // The shaders are GLSL written to the translator's contract (test/glsl/vs_draw.vert, ps_draw.frag). No game data. @@ -128,6 +127,12 @@ int main() { const std::uint16_t indices[6] = {0, 1, 2, 2, 1, 3}; const float tints[2][3] = {{1, 0, 1}, {0, 1, 0}}; // red stays red; then green + constexpr UINT upload_vertex_offset = 1024, upload_index_offset = 1088, upload_tint_offset = 1280; + const Vertex upload_vertices[] = { + {1, 0, 255, 0, 255, 255}, {1, 1, 255, 0, 255, 255}, {0, 0, 255, 0, 255, 255}, {0, 1, 255, 0, 255, 255}}; + const std::uint16_t upload_indices[] = {3, 1, 2, 2, 1, 0}; + const float upload_tint[] = {1, 1, 1}; + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}; const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; @@ -162,6 +167,9 @@ int main() { std::memcpy(up + 256, indices, sizeof(indices)); std::memcpy(up + 512, tints[0], sizeof(tints[0])); std::memcpy(up + 768, tints[1], sizeof(tints[1])); + std::memcpy(up + upload_vertex_offset, upload_vertices, sizeof(upload_vertices)); + std::memcpy(up + upload_index_offset, upload_indices, sizeof(upload_indices)); + std::memcpy(up + upload_tint_offset, upload_tint, sizeof(upload_tint)); const D3D12_GPU_VIRTUAL_ADDRESS upload_va = upload->GetGPUVirtualAddress(); const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; @@ -218,6 +226,13 @@ int main() { list->SetGraphicsRootConstantBufferView(1, upload_va + 512); list->DrawInstanced(3, 1, 4, 0); + const D3D12_VERTEX_BUFFER_VIEW upload_vbv{upload_va + upload_vertex_offset, sizeof(upload_vertices), sizeof(Vertex)}; + const D3D12_INDEX_BUFFER_VIEW upload_ibv{upload_va + upload_index_offset, sizeof(upload_indices), DXGI_FORMAT_R16_UINT}; + list->IASetVertexBuffers(0, 1, &upload_vbv); + list->IASetIndexBuffer(&upload_ibv); + list->SetGraphicsRootConstantBufferView(1, upload_va + upload_tint_offset); + list->DrawIndexedInstanced(UINT(std::size(upload_indices)), 1, 0, 0, 0); + D3D12_RESOURCE_BARRIER to_copy = transition(target.p, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE); list->ResourceBarrier(1, &to_copy); @@ -257,13 +272,13 @@ int main() { } std::filesystem::remove_all(library); + constexpr std::array quadrants[2][2] = { + {{255, 0, 0, 255}, {255, 255, 255, 255}}, + {{0, 0, 255, 255}, {0, 255, 0, 255}}}; unsigned mismatches = 0; for (UINT row = 0; row < size; ++row) { for (UINT col = 0; col < size; ++col) { - const bool top = row < size / 2, left = col < size / 2; - const std::array want = top && left ? std::array{255, 0, 0, 255} - : !top && !left ? std::array{0, 255, 0, 255} - : std::array{0, 0, 255, 255}; + const auto& want = quadrants[row >= size / 2][col >= size / 2]; const std::uint8_t* got = pixels.data() + row * 256 + col * 4; if (std::equal(want.begin(), want.end(), got)) continue; if (mismatches++ < 6) @@ -276,8 +291,7 @@ int main() { std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); return 1; } - std::printf("M1: two indexed draws and a culled triangle matched all %u pixels: input layout by semantic, root " - "constants and a root CBV per draw, vertex buffer in the arena, index buffer in an upload heap\n", + std::printf("M1: indexed draws from default and upload vertex buffers and a culled triangle matched all %u pixels\n", size * size); return 0; } From 084e6a6a8c16a8f2759399716f13ebf20d061d27 Mon Sep 17 00:00:00 2001 From: VictorJulianiR <40750238+VictorJulianiR@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:39:25 -0300 Subject: [PATCH 9/9] Exercise an upload-backed descriptor table in the indexed draw Adapt the graphics descriptor-table fixture from woreksami's #648 (f2dc19011928dc38762978b2cd03a82da1175f1f and 1591fdd7b18e0f3fd41b3d6d5035bde46b7eee72). Vonsek's review identified the need for an observable difference when an earlier binding is reused. Keep the existing vertex, index and root tint offsets and place both filters in separate aligned regions of the same upload allocation. Co-authored-by: woreksami <249861314+woreksami@users.noreply.github.com> --- runtime/test/d3d12_draw_test.cpp | 41 +++++++++++++++++++++++++------- runtime/test/glsl/ps_draw.frag | 15 +++++++++--- 2 files changed, 45 insertions(+), 11 deletions(-) diff --git a/runtime/test/d3d12_draw_test.cpp b/runtime/test/d3d12_draw_test.cpp index fe9585a90..25d09cd17 100644 --- a/runtime/test/d3d12_draw_test.cpp +++ b/runtime/test/d3d12_draw_test.cpp @@ -2,8 +2,9 @@ // - a graphics PSO whose VS and PS come from containers shaped like the game's, found in a translator-style // index by the SHA-256 of their FSSM programs; the input layout (POSITION, COLOR) is matched to the VS input // signature by semantic, and the VS declares them in the opposite register order; -// - vertex buffers in the GPU address arena and in an upload heap, with upload-backed indices and root CBVs; -// - three indexed draws (top-left red, bottom-right green, top-right white) on a blue target, and one +// - vertex buffers in the GPU address arena and in an upload heap, with upload-backed indices, root CBVs and +// pixel-shader filters addressed through a descriptor table; +// - three indexed draws (top-left red, bottom-right green, top-right (64, 255, 0)) on a blue target, and one // back-facing triangle in the bottom-left quadrant that culling must remove; // - the image read back through CopyTextureRegion and compared pixel by pixel. Where the quadrants land also // checks the viewport flip (D3D clip space is y-up) and the front-face winding. @@ -81,15 +82,18 @@ int main() { reinterpret_cast(&device.p)))); rt::d3d12::set_device_outer(inner, device.p); - // Root signature: [0] two constants (s0, s1: offset), [1] a root CBV (s2:s3: tint). - D3D12_ROOT_PARAMETER params[2] = {}; + // Must match ps_draw.frag: s2:s3 holds the root tint CBV and s4:s5 the filter table. + const D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_CBV, 1, 2, 0, 0}; + D3D12_ROOT_PARAMETER params[3] = {}; params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; params[0].Constants = {0, 0, 2}; params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; params[1].Descriptor = {1, 0}; + params[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params[2].DescriptorTable = {1, &range}; D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{}; root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; - root_desc.Desc_1_0 = {2, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT}; + root_desc.Desc_1_0 = {3, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT}; const auto root_blob = serialize_root_signature(root_desc); EXPECT(!root_blob.empty()); Ref root; @@ -129,9 +133,11 @@ int main() { constexpr UINT upload_vertex_offset = 1024, upload_index_offset = 1088, upload_tint_offset = 1280; const Vertex upload_vertices[] = { - {1, 0, 255, 0, 255, 255}, {1, 1, 255, 0, 255, 255}, {0, 0, 255, 0, 255, 255}, {0, 1, 255, 0, 255, 255}}; + {1, 0, 64, 0, 255, 255}, {1, 1, 64, 0, 255, 255}, {0, 0, 64, 0, 255, 255}, {0, 1, 64, 0, 255, 255}}; const std::uint16_t upload_indices[] = {3, 1, 2, 2, 1, 0}; const float upload_tint[] = {1, 1, 1}; + constexpr UINT filter_offsets[] = {2048, 2304}; + const float filters[2][3] = {{1, 1, 1}, {1, 1, 0}}; const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}; @@ -172,6 +178,20 @@ int main() { std::memcpy(up + upload_tint_offset, upload_tint, sizeof(upload_tint)); const D3D12_GPU_VIRTUAL_ADDRESS upload_va = upload->GetGPUVirtualAddress(); + const D3D12_DESCRIPTOR_HEAP_DESC table_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 2, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + Ref table_heap; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&table_desc, IID_PPV_ARGS(&table_heap.p)))); + const auto table_cpu = reinterpret_cast(slot(table_heap.p, 9))(table_heap.p); + const auto table_gpu = reinterpret_cast(slot(table_heap.p, 10))(table_heap.p); + const UINT table_stride = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + EXPECT(table_cpu && table_gpu && table_stride >= sizeof(upload_va)); + for (size_t i = 0; i < std::size(filters); ++i) { + std::memcpy(up + filter_offsets[i], filters[i], sizeof(filters[i])); + const auto filter_va = upload_va + filter_offsets[i]; + std::memcpy(reinterpret_cast(table_cpu + i * table_stride), &filter_va, sizeof(filter_va)); + } + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; Ref rtv_heap; EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&rtv_heap.p)))); @@ -200,7 +220,10 @@ int main() { list->ClearRenderTargetView(rtv, blue, 0, nullptr); // State for the draws; the pipeline came with CreateCommandList. + ID3D12DescriptorHeap* heaps[] = {table_heap.p}; + list->SetDescriptorHeaps(1, heaps); list->SetGraphicsRootSignature(root.p); + list->SetGraphicsRootDescriptorTable(2, D3D12_GPU_DESCRIPTOR_HANDLE{table_gpu}); list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); const D3D12_VERTEX_BUFFER_VIEW vbv{vertex_buffer->GetGPUVirtualAddress(), sizeof(vertices), sizeof(Vertex)}; list->IASetVertexBuffers(0, 1, &vbv); @@ -231,6 +254,7 @@ int main() { list->IASetVertexBuffers(0, 1, &upload_vbv); list->IASetIndexBuffer(&upload_ibv); list->SetGraphicsRootConstantBufferView(1, upload_va + upload_tint_offset); + list->SetGraphicsRootDescriptorTable(2, D3D12_GPU_DESCRIPTOR_HANDLE{table_gpu + table_stride}); list->DrawIndexedInstanced(UINT(std::size(upload_indices)), 1, 0, 0, 0); D3D12_RESOURCE_BARRIER to_copy = transition(target.p, D3D12_RESOURCE_STATE_RENDER_TARGET, @@ -264,6 +288,7 @@ int main() { pso.reset(); root.reset(); rtv_heap.reset(); + table_heap.reset(); list.reset(); allocator.reset(); queue.reset(); @@ -273,7 +298,7 @@ int main() { std::filesystem::remove_all(library); constexpr std::array quadrants[2][2] = { - {{255, 0, 0, 255}, {255, 255, 255, 255}}, + {{255, 0, 0, 255}, {64, 255, 0, 255}}, {{0, 0, 255, 255}, {0, 255, 0, 255}}}; unsigned mismatches = 0; for (UINT row = 0; row < size; ++row) { @@ -291,7 +316,7 @@ int main() { std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); return 1; } - std::printf("M1: indexed draws from default and upload vertex buffers and a culled triangle matched all %u pixels\n", + std::printf("M1: indexed draws with upload-backed descriptors and a culled triangle matched all %u pixels\n", size * size); return 0; } diff --git a/runtime/test/glsl/ps_draw.frag b/runtime/test/glsl/ps_draw.frag index 2361330f4..03c6c8e28 100644 --- a/runtime/test/glsl/ps_draw.frag +++ b/runtime/test/glsl/ps_draw.frag @@ -1,7 +1,9 @@ #version 460 // A pixel shader written to the translator's runtime contract, standing in for a translated one in -// d3d12_draw_test. s2:s3 is a root CBV: the console VA of three floats (a tint), read at heap base + VA. The output -// is (red * tint.x, tint.y, blue * tint.z, 1). +// d3d12_draw_test. s2:s3 is a root CBV: the console VA of three floats (a tint), read at heap base + VA. s4:s5 is a +// descriptor table whose entry is the 64-bit console VA of three more floats (a filter), written by the +// application; the test points it at an upload heap, so that VA is biased by -heap_base (open question 17). The +// output is (red * tint.x * filter.x, tint.y * filter.y, blue * tint.z * filter.z, 1). #extension GL_EXT_buffer_reference : require #extension GL_EXT_buffer_reference_uvec2 : require @@ -9,6 +11,11 @@ layout(buffer_reference, std430, buffer_reference_align = 4) buffer Floats { float f[]; }; +// Preserve the descriptor's address bits, including words that would encode floating-point NaNs. +layout(buffer_reference, std430, buffer_reference_align = 4) buffer Words { + uint w[]; +}; + layout(location = 0) in vec4 color; layout(location = 0) out vec4 target; @@ -26,5 +33,7 @@ uvec2 add64(uvec2 a, uvec2 b) { void main() { Floats tint = Floats(add64(pc.heap_base, uvec2(pc.s[2], pc.s[3]))); - target = vec4(color.r * tint.f[0], tint.f[1], color.b * tint.f[2], 1.0); + Words table = Words(add64(pc.heap_base, uvec2(pc.s[4], pc.s[5]))); + Floats shade = Floats(add64(pc.heap_base, uvec2(table.w[0], table.w[1]))); + target = vec4(color.r * tint.f[0] * shade.f[0], tint.f[1] * shade.f[1], color.b * tint.f[2] * shade.f[2], 1.0); }