upleb.uk

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

summaryrefslogtreecommitdiff
path: root/runtime
diff options
context:
space:
mode:
authorTreXito <81475944+TreXito@users.noreply.github.com>2026-11-23 15:47:22 +0000
committerTreXito <81475944+TreXito@users.noreply.github.com>2026-11-23 15:47:22 +0000
commitb721585aae2efb5e78cf7ee2467fe8c4d5e0ca35 (patch)
tree62803d5697e35182026fc910b64827a108ffc819 /runtime
parentc6f15b16283081c72123e61ca08cf5eb83e301e2 (diff)
parent6de3970e15dc2ef8542ea1a289105736e2241624 (diff)
Merge remote-tracking branch 'origin/main' into exe/import-fail-fast
# Conflicts: # docs/README.md
Diffstat (limited to 'runtime')
-rw-r--r--runtime/CMakeLists.txt45
-rw-r--r--runtime/README.md5
-rw-r--r--runtime/shims/d3d12_com.cpp15
-rw-r--r--runtime/shims/d3d12_com.h4
-rw-r--r--runtime/shims/d3d12_vulkan_device.cpp341
-rw-r--r--runtime/shims/d3d12_xs_device.cpp199
-rw-r--r--runtime/shims/d3d12_xs_device.h23
-rw-r--r--runtime/shims/file_system.cpp39
-rw-r--r--runtime/shims/startup_trace.h27
-rw-r--r--runtime/shims/xgameruntime.cpp7
-rw-r--r--runtime/shims/xgameruntime_offline.cpp14
-rw-r--r--runtime/shims/xgameruntime_store.cpp26
-rw-r--r--runtime/shims/xgameruntime_user.cpp5
-rw-r--r--runtime/shims/xmem.cpp46
-rw-r--r--runtime/src/command_list.h14
-rw-r--r--runtime/src/shader_library.h6
-rw-r--r--runtime/src/statistics_sum.comp11
-rw-r--r--runtime/src/statistics_sum_spirv.h86
-rw-r--r--runtime/src/vulkan_backend.h75
-rw-r--r--runtime/src/vulkan_replay.h214
-rw-r--r--runtime/test/d3d12_mesh_test.cpp523
-rw-r--r--runtime/test/device_proxy_test.cpp55
-rw-r--r--runtime/test/dxgi_device_test.cpp14
-rw-r--r--runtime/test/file_system_test.cpp37
-rw-r--r--runtime/test/glsl/ms_draw.mesh34
-rw-r--r--runtime/test/int3_skip_test.cpp65
-rw-r--r--runtime/test/replay_cpu_bench.cpp1
-rw-r--r--runtime/test/replay_query_edges_test.cpp12
-rw-r--r--runtime/test/replay_query_predication_test.cpp142
-rw-r--r--runtime/test/shaders/check.py24
-rw-r--r--runtime/test/shaders/cs_pk_mul_lo_const.asm37
-rw-r--r--runtime/test/shaders/cs_w32_buffer_store_sub.asm86
-rw-r--r--runtime/test/shaders/cs_w32_buffer_sub16.asm70
-rw-r--r--runtime/test/spirv_capability.h49
-rw-r--r--runtime/test/spirv_capability_test.cpp71
-rw-r--r--runtime/test/vk_bindless_test.cpp35
-rw-r--r--runtime/test/vk_compute_test.cpp29
-rw-r--r--runtime/test/vk_harness.cpp16
-rw-r--r--runtime/test/vk_store_test.cpp14
-rw-r--r--runtime/test/vk_test_device.h17
-rw-r--r--runtime/test/vk_texture_test.cpp10
-rw-r--r--runtime/test/xgameruntime_store_test.cpp16
-rw-r--r--runtime/test/xmem_test.cpp50
-rw-r--r--runtime/test/xs_proxy_mock_test.cpp187
44 files changed, 2566 insertions, 230 deletions
diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt
index 7a8f61de8..ffa310910 100644
--- a/runtime/CMakeLists.txt
+++ b/runtime/CMakeLists.txt
@@ -236,6 +236,16 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME)
236 target_link_options(file_system_test PRIVATE /OPT:NOREF) 236 target_link_options(file_system_test PRIVATE /OPT:NOREF)
237 target_link_libraries(file_system_test PRIVATE advapi32) # the ACL calls of the unlistable-marker-folder check 237 target_link_libraries(file_system_test PRIVATE advapi32) # the ACL calls of the unlistable-marker-folder check
238 238
239 # LEONIDA_SKIP_INT3 (shims/startup_trace.h): its own executable, the variable is read once per process.
240 add_executable(int3_skip_test
241 test/int3_skip_test.cpp
242 shims/registry.cpp
243 )
244 target_include_directories(int3_skip_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims)
245 target_compile_definitions(int3_skip_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
246 target_compile_options(int3_skip_test PRIVATE /W4 /permissive- /utf-8)
247 target_link_options(int3_skip_test PRIVATE /OPT:NOREF)
248
239 # Offline WinHTTP for mapped images (the package's XCurl.dll and libHttpClient.GDK.dll); no network is touched. 249 # Offline WinHTTP for mapped images (the package's XCurl.dll and libHttpClient.GDK.dll); no network is touched.
240 add_executable(winhttp_offline_test 250 add_executable(winhttp_offline_test
241 test/winhttp_offline_test.cpp 251 test/winhttp_offline_test.cpp
@@ -828,6 +838,9 @@ if(BUILD_TESTING)
828 add_test(NAME xs_proxy_mock_no_reserve COMMAND xs_proxy_mock_test --fail-virtualalloc) 838 add_test(NAME xs_proxy_mock_no_reserve COMMAND xs_proxy_mock_test --fail-virtualalloc)
829 add_test(NAME xs_proxy_mock_no_protect COMMAND xs_proxy_mock_test --fail-virtualprotect) 839 add_test(NAME xs_proxy_mock_no_protect COMMAND xs_proxy_mock_test --fail-virtualprotect)
830 add_test(NAME xs_proxy_mock_no_handler COMMAND xs_proxy_mock_test --fail-veh) 840 add_test(NAME xs_proxy_mock_no_handler COMMAND xs_proxy_mock_test --fail-veh)
841 # The routes are read once per process, so each override case is its own test.
842 add_test(NAME xs_proxy_mock_env_slots COMMAND xs_proxy_mock_test --env-slots)
843 add_test(NAME xs_proxy_mock_env_slots_invalid COMMAND xs_proxy_mock_test --env-slots-invalid)
831 endif() 844 endif()
832 if(TARGET root_sig_test) 845 if(TARGET root_sig_test)
833 add_test(NAME root_sig COMMAND root_sig_test) 846 add_test(NAME root_sig COMMAND root_sig_test)
@@ -966,6 +979,9 @@ if(BUILD_TESTING)
966 if(WIN32 AND TARGET file_system_test) 979 if(WIN32 AND TARGET file_system_test)
967 add_test(NAME file_system COMMAND file_system_test) 980 add_test(NAME file_system COMMAND file_system_test)
968 endif() 981 endif()
982 if(WIN32 AND TARGET int3_skip_test)
983 add_test(NAME int3_skip COMMAND int3_skip_test)
984 endif()
969 if(WIN32 AND TARGET winhttp_offline_test) 985 if(WIN32 AND TARGET winhttp_offline_test)
970 add_test(NAME winhttp_offline COMMAND winhttp_offline_test) 986 add_test(NAME winhttp_offline COMMAND winhttp_offline_test)
971 endif() 987 endif()
@@ -1124,6 +1140,13 @@ if(LEONIDA_D3D12_SHIM_TESTS)
1124endif() 1140endif()
1125endif() 1141endif()
1126 1142
1143# CPU-only: which SPIR-V capabilities make the standalone GPU tools ask for shaderInt64 (TEST-468). It includes no
1144# Vulkan header, so it builds and runs without them, unlike the tools below that use it.
1145add_executable(spirv_capability_test test/spirv_capability_test.cpp)
1146if(BUILD_TESTING)
1147 add_test(NAME spirv_capability COMMAND spirv_capability_test)
1148endif()
1149
1127# GPU test and pipeline tools load Vulkan at run time, so only the Vulkan headers are needed at build time. 1150# GPU test and pipeline tools load Vulkan at run time, so only the Vulkan headers are needed at build time.
1128# Nothing is downloaded unless asked: set VULKAN_SDK, install the Vulkan headers, pass 1151# Nothing is downloaded unless asked: set VULKAN_SDK, install the Vulkan headers, pass
1129# -DLEONIDA_VULKAN_HEADERS_FETCH=ON to download the pinned Khronos Vulkan-Headers release once at configure time 1152# -DLEONIDA_VULKAN_HEADERS_FETCH=ON to download the pinned Khronos Vulkan-Headers release once at configure time
@@ -2572,8 +2595,28 @@ if(TARGET Vulkan::Headers)
2572 target_compile_options(d3d12_stores_atomics_test PRIVATE /W4 /permissive- /utf-8) 2595 target_compile_options(d3d12_stores_atomics_test PRIVATE /W4 /permissive- /utf-8)
2573 add_test(NAME d3d12_stores_atomics COMMAND d3d12_stores_atomics_test) 2596 add_test(NAME d3d12_stores_atomics COMMAND d3d12_stores_atomics_test)
2574 set_tests_properties(d3d12_stores_atomics PROPERTIES SKIP_RETURN_CODE 77) 2597 set_tests_properties(d3d12_stores_atomics PROPERTIES SKIP_RETURN_CODE 77)
2598
2599 # D3D-29: mesh-shader PSOs from pipeline state streams and DispatchMesh (skips without VK_EXT_mesh_shader).
2600 set(LEONIDA_TEST_MS ${CMAKE_CURRENT_BINARY_DIR}/generated/ms_draw.spv)
2601 add_custom_command(
2602 OUTPUT ${LEONIDA_TEST_MS}
2603 # Vulkan 1.2 (SPIR-V 1.5), the translator's target: 1.3 would emit LocalSizeId, which needs maintenance4.
2604 COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.2 -o ${LEONIDA_TEST_MS}
2605 ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/ms_draw.mesh
2606 DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/ms_draw.mesh
2607 COMMENT "Compiling the mesh test shader ms_draw.mesh"
2608 VERBATIM)
2609 add_executable(d3d12_mesh_test test/d3d12_mesh_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_TEST_MS}
2610 ${LEONIDA_TEST_PS} ${LEONIDA_TEST_VS_FULLSCREEN})
2611 target_link_libraries(d3d12_mesh_test PRIVATE gta6rt_d3d12_com)
2612 target_compile_definitions(d3d12_mesh_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX
2613 LEONIDA_TEST_MS_SPV="${LEONIDA_TEST_MS}" LEONIDA_TEST_PS_SPV="${LEONIDA_TEST_PS}"
2614 LEONIDA_TEST_VS_FULLSCREEN_SPV="${LEONIDA_TEST_VS_FULLSCREEN}")
2615 target_compile_options(d3d12_mesh_test PRIVATE /W4 /permissive- /utf-8)
2616 add_test(NAME d3d12_mesh COMMAND d3d12_mesh_test)
2617 set_tests_properties(d3d12_mesh PROPERTIES SKIP_RETURN_CODE 77)
2575 else() 2618 else()
2576 message(STATUS "glslangValidator not found: d3d12_compute_test, d3d12_draw_test and d3d12_set0_compute_test are not built") 2619 message(STATUS "glslangValidator not found: d3d12_compute_test, d3d12_draw_test, d3d12_set0_compute_test and d3d12_mesh_test are not built")
2577 endif() 2620 endif()
2578 2621
2579 # Native D3D12 SV_InnerCoverage reference; its HLSL is compiled at runtime, so glslang is not needed. 2622 # Native D3D12 SV_InnerCoverage reference; its HLSL is compiled at runtime, so glslang is not needed.
diff --git a/runtime/README.md b/runtime/README.md
index 89f4207b4..fef8a3bcb 100644
--- a/runtime/README.md
+++ b/runtime/README.md
@@ -352,13 +352,16 @@ from the ANSI code page.
352| `dllmain` | after `DllMain(DLL_PROCESS_ATTACH)` returns | `module`, `result` | 352| `dllmain` | after `DllMain(DLL_PROCESS_ATTACH)` returns | `module`, `result` |
353| `unimplemented_call` | first call of each unimplemented import | `import` (`dll!name`), `caller` (module+RVA) | 353| `unimplemented_call` | first call of each unimplemented import | `import` (`dll!name`), `caller` (module+RVA) |
354| `xmem_attributes` | the first `XMemAlloc` and the first `XMemFree` for each distinct raw attribute word (not every allocation) | `api`, `attributes`, `size` (`XMemAlloc` only), `caller` (module+RVA) | 354| `xmem_attributes` | the first `XMemAlloc` and the first `XMemFree` for each distinct raw attribute word (not every allocation) | `api`, `attributes`, `size` (`XMemAlloc` only), `caller` (module+RVA) |
355| `file_open_failed` | a guest `CreateFileW`/`CreateFile2` that fails (at most 256 events) | `api`, `path` (as the title passed it), `error` (Win32), `caller` (module+RVA) |
356| `int3_skipped` | with `LEONIDA_SKIP_INT3` set: first int3 at each address, which is then stepped over | `at` (module+RVA) |
355| `debug_string` | `OutputDebugStringA/W` with no debugger attached | `text` | 357| `debug_string` | `OutputDebugStringA/W` with no debugger attached | `text` |
356| `exception` | any exception, before handlers run | `code`, `at`, `access`/`address` for access violations, `cpp` for C++ throws, `stack` (up to 16 frames) | 358| `exception` | any exception, before handlers run | `code`, `at`, `access`/`address` for access violations, `cpp` for C++ throws, `stack` (up to 16 frames) |
357| `exit` / `error` | `--run` returns, or the loader throws | `code` / `what` | 359| `exit` / `error` | `--run` returns, or the loader throws | `code` / `what` |
358 360
359Every line also has `seq` and `t` (seconds since the trace opened). Addresses are `module+0xRVA` for mapped images, 361Every line also has `seq` and `t` (seconds since the trace opened). Addresses are `module+0xRVA` for mapped images,
360`host:name.dll+0xRVA` for host modules. The exception handler only records: it returns `EXCEPTION_CONTINUE_SEARCH`, 362`host:name.dll+0xRVA` for host modules. The exception handler only records: it returns `EXCEPTION_CONTINUE_SEARCH`,
361so the process behaves the same with or without the trace. It works with any `LEONIDA_UNIMPLEMENTED` policy. 363so the process behaves the same with or without the trace (except under the diagnostic `LEONIDA_SKIP_INT3`, which
364steps over int3). It works with any `LEONIDA_UNIMPLEMENTED` policy.
362 365
363The file can quote what the game prints, so it stays on your machine. In issues and pull requests, share counts or 366The file can quote what the game prints, so it stays on your machine. In issues and pull requests, share counts or
364lines from synthetic fixtures only. 367lines from synthetic fixtures only.
diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp
index 55b523d96..987dd2d64 100644
--- a/runtime/shims/d3d12_com.cpp
+++ b/runtime/shims/d3d12_com.cpp
@@ -90,6 +90,7 @@ const char* name(leonida::ReplayResult result) {
90 case leonida::ReplayResult::invalid_copy: return "invalid copy or resolve"; 90 case leonida::ReplayResult::invalid_copy: return "invalid copy or resolve";
91 case leonida::ReplayResult::invalid_query: return "invalid query"; 91 case leonida::ReplayResult::invalid_query: return "invalid query";
92 case leonida::ReplayResult::invalid_indirect_arguments: return "invalid indirect argument or count buffer range"; 92 case leonida::ReplayResult::invalid_indirect_arguments: return "invalid indirect argument or count buffer range";
93 case leonida::ReplayResult::invalid_draw: return "draw kind does not match the pipeline (mesh or vertex)";
93 case leonida::ReplayResult::unsupported: return "unsupported"; 94 case leonida::ReplayResult::unsupported: return "unsupported";
94 } 95 }
95 return "?"; 96 return "?";
@@ -433,6 +434,20 @@ public:
433 record_draw(true, indices, instances, first_index, base_vertex, first_instance); 434 record_draw(true, indices, instances, first_index, base_vertex, first_instance);
434 } 435 }
435 436
437 // ID3D12GraphicsCommandList6: a mesh draw. The bound graphics pipeline must have a mesh shader (checked at
438 // execution, where the pipeline is resolved). D3D12 caps each count at 65535 and their product at 2^22
439 // (D3D12_MS_DISPATCH_MAX_THREAD_GROUPS_PER_GRID); a larger grid is a recording error.
440 void STDMETHODCALLTYPE DispatchMesh(UINT x, UINT y, UINT z) override {
441 d3d12_trace::record("ID3D12GraphicsCommandList6::DispatchMesh");
442 if (x > 65535 || y > 65535 || z > 65535 || std::uint64_t(x) * y * z > (1u << 22)) return check(false);
443 if (!graphics_pipeline_ || !graphics_.layout) return check(false);
444 if (!(viewport_.width > 0) || !(viewport_.height > 0)) return; // as record_draw: nothing is rasterized
445 leonida::Draw draw{graphics_pipeline_, graphics_.data, draw_views(), depth_, {}, 0, viewport_,
446 scissor_, blend_factor_, front_stencil_ref_, back_stencil_ref_, false, x, y, z, 0, 0};
447 draw.mesh = true;
448 check(list_.draw(std::move(draw)));
449 }
450
436 void STDMETHODCALLTYPE ResourceBarrier(UINT count, const D3D12_RESOURCE_BARRIER* barriers) override { 451 void STDMETHODCALLTYPE ResourceBarrier(UINT count, const D3D12_RESOURCE_BARRIER* barriers) override {
437 d3d12_trace::record("ID3D12GraphicsCommandList::ResourceBarrier"); 452 d3d12_trace::record("ID3D12GraphicsCommandList::ResourceBarrier");
438 if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); 453 if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false);
diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h
index f379754a9..0e0711df3 100644
--- a/runtime/shims/d3d12_com.h
+++ b/runtime/shims/d3d12_com.h
@@ -169,6 +169,10 @@ struct VulkanDeviceInfo {
169 // VkAccelerationStructureKHR; needs buffer_device_address and the GPU address arena. The standalone device sets it 169 // VkAccelerationStructureKHR; needs buffer_device_address and the GPU address arena. The standalone device sets it
170 // unless LEONIDA_RT_AS=khr (docs/d3d12_vulkan.md 4.8); with it set, ray_tracing is not enabled. 170 // unless LEONIDA_RT_AS=khr (docs/d3d12_vulkan.md 4.8); with it set, ray_tracing is not enabled.
171 bool xdxr_acceleration_structures = false; 171 bool xdxr_acceleration_structures = false;
172 // VK_EXT_mesh_shader with its meshShader feature is enabled on `device` (taskShader is not needed: the game's
173 // shaders have no amplification stage). Mesh-shader PSOs and DispatchMesh work, and CheckFeatureSupport reports
174 // D3D12_MESH_SHADER_TIER_1; without it mesh PSOs are refused and the tier is NOT_SUPPORTED.
175 bool mesh_shader = false;
172 // The core features enabled on `device`. Graphics PSOs that need independentBlend, fillModeNonSolid, 176 // The core features enabled on `device`. Graphics PSOs that need independentBlend, fillModeNonSolid,
173 // depthBiasClamp or dualSrcBlend are refused unless it is set here. 177 // depthBiasClamp or dualSrcBlend are refused unless it is set here.
174 VkPhysicalDeviceFeatures features{}; 178 VkPhysicalDeviceFeatures features{};
diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp
index 5bde4b956..c2099d8ac 100644
--- a/runtime/shims/d3d12_vulkan_device.cpp
+++ b/runtime/shims/d3d12_vulkan_device.cpp
@@ -591,6 +591,10 @@ struct DeviceState {
591 }; 591 };
592 SubgroupFacts subgroups; 592 SubgroupFacts subgroups;
593 std::once_flag subgroups_once; 593 std::once_flag subgroups_once;
594 // VkPhysicalDeviceMeshShaderPropertiesEXT, read on first use by a mesh PSO; zeros when it cannot be asked.
595 VkPhysicalDeviceMeshShaderPropertiesEXT mesh_properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_PROPERTIES_EXT};
596 bool mesh_properties_read = false;
597 std::mutex mesh_properties_mutex;
594 PFN_vkGetPhysicalDeviceFormatProperties format_properties = nullptr; 598 PFN_vkGetPhysicalDeviceFormatProperties format_properties = nullptr;
595 PFN_vkGetPhysicalDeviceImageFormatProperties image_format_properties = nullptr; 599 PFN_vkGetPhysicalDeviceImageFormatProperties image_format_properties = nullptr;
596 PFN_vkGetPhysicalDeviceImageFormatProperties2 image_format_properties2 = nullptr; 600 PFN_vkGetPhysicalDeviceImageFormatProperties2 image_format_properties2 = nullptr;
@@ -912,6 +916,20 @@ struct DeviceState {
912 subgroups.lane_min = subgroups.lane_max = kIntelD3D12Lanes; 916 subgroups.lane_min = subgroups.lane_max = kIntelD3D12Lanes;
913 } 917 }
914 918
919 // The device's mesh-shader limits (output vertices and primitives, workgroup size), for mesh PSO creation.
920 const VkPhysicalDeviceMeshShaderPropertiesEXT& mesh_limits() {
921 std::lock_guard lock(mesh_properties_mutex);
922 if (mesh_properties_read) return mesh_properties;
923 mesh_properties_read = true;
924 const auto properties2 = reinterpret_cast<PFN_vkGetPhysicalDeviceProperties2>(
925 info.get_instance_proc ? info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties2") : nullptr);
926 if (!properties2 || !info.physical || !info.mesh_shader) return mesh_properties;
927 VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &mesh_properties};
928 properties2(info.physical, &properties);
929 mesh_properties.pNext = nullptr;
930 return mesh_properties;
931 }
932
915 // Integer sampled images need not support multisampling. Pick a supported count for the 933 // Integer sampled images need not support multisampling. Pick a supported count for the
916 // zero image in the corresponding set-0 bindings; one means that class is unavailable. 934 // zero image in the corresponding set-0 bindings; one means that class is unavailable.
917 VkSampleCountFlagBits ms_fallback_samples(VkFormat format) const { 935 VkSampleCountFlagBits ms_fallback_samples(VkFormat format) const {
@@ -2842,6 +2860,201 @@ public:
2842 2860
2843// A pipeline state. Compute only for now: the shader is found by the SHA-256 of its FSSM program in the 2861// A pipeline state. Compute only for now: the shader is found by the SHA-256 of its FSSM program in the
2844// translator's index, and the FSSM blob is copied into the arena as the shader's code base. 2862// translator's index, and the FSSM blob is copied into the arena as the shader's code base.
2863// A D3D12_PIPELINE_STATE_STREAM_DESC (ID3D12Device2::CreatePipelineState) as the descriptions the PSO creators take.
2864// The stream is a run of subobjects, each a D3D12_PIPELINE_STATE_SUBOBJECT_TYPE followed by its description at that
2865// description's alignment, each subobject starting at pointer alignment (the d3dx12.h layout, `alignas(void*)`). A
2866// subobject that is absent takes the runtime's default (the CD3DX12 defaults: depth test on with LESS, back-face
2867// culling, no blending, sample mask 0xFFFFFFFF, one sample). A type given twice, a truncated stream or an unknown
2868// type is E_INVALIDARG, as on the PC runtime; state this layer cannot honour yet is E_NOTIMPL with a log.
2869struct PipelineStream {
2870 D3D12_GRAPHICS_PIPELINE_STATE_DESC graphics{};
2871 D3D12_COMPUTE_PIPELINE_STATE_DESC compute{};
2872 D3D12_SHADER_BYTECODE ms{};
2873 D3D12_SHADER_BYTECODE as{};
2874 bool has_cs = false;
2875 bool has_graphics_stage = false; // VS, PS, DS, HS, GS, AS or MS
2876};
2877
2878HRESULT parse_pipeline_stream(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, PipelineStream& out) {
2879 if (!desc.pPipelineStateSubobjectStream || !desc.SizeInBytes) return E_INVALIDARG;
2880 D3D12_GRAPHICS_PIPELINE_STATE_DESC& g = out.graphics;
2881 for (auto& target : g.BlendState.RenderTarget) {
2882 target.SrcBlend = target.SrcBlendAlpha = D3D12_BLEND_ONE;
2883 target.DestBlend = target.DestBlendAlpha = D3D12_BLEND_ZERO;
2884 target.BlendOp = target.BlendOpAlpha = D3D12_BLEND_OP_ADD;
2885 target.LogicOp = D3D12_LOGIC_OP_NOOP;
2886 target.RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL;
2887 }
2888 g.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID;
2889 g.RasterizerState.CullMode = D3D12_CULL_MODE_BACK;
2890 g.RasterizerState.DepthClipEnable = TRUE;
2891 g.DepthStencilState.DepthEnable = TRUE;
2892 g.DepthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL;
2893 g.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_LESS;
2894 g.DepthStencilState.StencilReadMask = D3D12_DEFAULT_STENCIL_READ_MASK;
2895 g.DepthStencilState.StencilWriteMask = D3D12_DEFAULT_STENCIL_WRITE_MASK;
2896 g.DepthStencilState.FrontFace = g.DepthStencilState.BackFace = {
2897 D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_COMPARISON_FUNC_ALWAYS};
2898 g.SampleMask = UINT_MAX;
2899 g.SampleDesc = {1, 0};
2900
2901 const auto* base = static_cast<const std::uint8_t*>(desc.pPipelineStateSubobjectStream);
2902 const std::size_t size = desc.SizeInBytes;
2903 const auto round_up = [](std::size_t v, std::size_t a) { return (v + a - 1) / a * a; };
2904 std::uint64_t seen = 0;
2905 std::size_t at = 0;
2906 while (at < size) {
2907 D3D12_PIPELINE_STATE_SUBOBJECT_TYPE type;
2908 if (size - at < sizeof(type)) return E_INVALIDARG;
2909 std::memcpy(&type, base + at, sizeof(type));
2910 // The versioned depth-stencil and rasterizer subobjects describe the same state as their base type, so the
2911 // stream contract counts any two of one family as duplicates; the payload below still follows `type`.
2912 D3D12_PIPELINE_STATE_SUBOBJECT_TYPE family = type;
2913 if (type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1 ||
2914 type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL2)
2915 family = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL;
2916 else if (type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER1 ||
2917 type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER2)
2918 family = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER;
2919 if (unsigned(type) >= 64 || (seen >> unsigned(family) & 1)) return E_INVALIDARG;
2920 seen |= std::uint64_t(1) << unsigned(family);
2921 bool ok = true;
2922 const auto take = [&](auto& value) {
2923 using T = std::remove_reference_t<decltype(value)>;
2924 const std::size_t payload = round_up(at + sizeof(type), alignof(T));
2925 if (payload > size || size - payload < sizeof(T)) {
2926 ok = false;
2927 return;
2928 }
2929 std::memcpy(&value, base + payload, sizeof(T));
2930 at = round_up(payload + sizeof(T), sizeof(void*));
2931 };
2932 const auto stage = [&](D3D12_SHADER_BYTECODE& code) {
2933 take(code);
2934 out.has_graphics_stage = true;
2935 };
2936 switch (type) {
2937 case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE:
2938 take(g.pRootSignature);
2939 out.compute.pRootSignature = g.pRootSignature;
2940 break;
2941 case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS: stage(g.VS); break;
2942 case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS: stage(g.PS); break;
2943 case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DS: stage(g.DS); break;
2944 case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_HS: stage(g.HS); break;
2945 case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_GS: stage(g.GS); break;
2946 case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS: stage(out.as); break;
2947 case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS: stage(out.ms); break;
2948 case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS:
2949 take(out.compute.CS);
2950 out.has_cs = true;
2951 break;
2952 case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_STREAM_OUTPUT: take(g.StreamOutput); break;
2953 case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND: take(g.BlendState); break;
2954 case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK: take(g.SampleMask); break;
2955 case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER: take(g.RasterizerState); break;
2956 case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL: take(g.DepthStencilState); break;
2957 case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT: take(g.InputLayout); break;
2958 case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_IB_STRIP_CUT_VALUE: take(g.IBStripCutValue); break;
2959 case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY: take(g.PrimitiveTopologyType); break;
2960 case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS: {
2961 D3D12_RT_FORMAT_ARRAY formats{};
2962 take(formats);
2963 if (formats.NumRenderTargets > D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT) return E_INVALIDARG;
2964 g.NumRenderTargets = formats.NumRenderTargets;
2965 std::copy(std::begin(formats.RTFormats), std::end(formats.RTFormats), std::begin(g.RTVFormats));
2966 break;
2967 }
2968 case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT: take(g.DSVFormat); break;
2969 case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC: take(g.SampleDesc); break;
2970 case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_NODE_MASK:
2971 take(g.NodeMask);
2972 out.compute.NodeMask = g.NodeMask;
2973 break;
2974 case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CACHED_PSO:
2975 take(g.CachedPSO);
2976 out.compute.CachedPSO = g.CachedPSO;
2977 break;
2978 case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_FLAGS:
2979 take(g.Flags);
2980 out.compute.Flags = g.Flags;
2981 break;
2982 case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1: {
2983 D3D12_DEPTH_STENCIL_DESC1 d{};
2984 take(d);
2985 if (ok && d.DepthBoundsTestEnable) {
2986 log_once("depth-bounds tests are not supported yet; stream subobject", int(type));
2987 return E_NOTIMPL;
2988 }
2989 g.DepthStencilState = {d.DepthEnable, d.DepthWriteMask, d.DepthFunc, d.StencilEnable, d.StencilReadMask,
2990 d.StencilWriteMask, d.FrontFace, d.BackFace};
2991 break;
2992 }
2993 case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL2: {
2994 D3D12_DEPTH_STENCIL_DESC2 d{};
2995 take(d);
2996 if (!ok) break;
2997 if (d.DepthBoundsTestEnable) {
2998 log_once("depth-bounds tests are not supported yet; stream subobject", int(type));
2999 return E_NOTIMPL;
3000 }
3001 // Separate front and back stencil masks are not modelled (one read and one write mask per PSO).
3002 if (d.StencilEnable && (d.FrontFace.StencilReadMask != d.BackFace.StencilReadMask ||
3003 d.FrontFace.StencilWriteMask != d.BackFace.StencilWriteMask)) {
3004 log_once("separate front and back stencil masks are not supported yet; stream subobject", int(type));
3005 return E_NOTIMPL;
3006 }
3007 const auto face = [](const D3D12_DEPTH_STENCILOP_DESC1& f) {
3008 return D3D12_DEPTH_STENCILOP_DESC{f.StencilFailOp, f.StencilDepthFailOp, f.StencilPassOp, f.StencilFunc};
3009 };
3010 g.DepthStencilState = {d.DepthEnable, d.DepthWriteMask, d.DepthFunc, d.StencilEnable,
3011 UINT8(d.FrontFace.StencilReadMask), UINT8(d.FrontFace.StencilWriteMask),
3012 face(d.FrontFace), face(d.BackFace)};
3013 break;
3014 }
3015 case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER1:
3016 case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER2: {
3017 // Their DepthBias is a float; the PSO path takes D3D12_RASTERIZER_DESC's integer one.
3018 FLOAT bias = 0;
3019 D3D12_RASTERIZER_DESC& r = g.RasterizerState;
3020 if (type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER1) {
3021 D3D12_RASTERIZER_DESC1 d{};
3022 take(d);
3023 r = {d.FillMode, d.CullMode, d.FrontCounterClockwise, 0, d.DepthBiasClamp, d.SlopeScaledDepthBias,
3024 d.DepthClipEnable, d.MultisampleEnable, d.AntialiasedLineEnable, d.ForcedSampleCount,
3025 d.ConservativeRaster};
3026 bias = d.DepthBias;
3027 } else {
3028 D3D12_RASTERIZER_DESC2 d{};
3029 take(d);
3030 r = {d.FillMode, d.CullMode, d.FrontCounterClockwise, 0, d.DepthBiasClamp, d.SlopeScaledDepthBias,
3031 d.DepthClipEnable, FALSE, FALSE, d.ForcedSampleCount, d.ConservativeRaster};
3032 bias = d.DepthBias;
3033 }
3034 r.DepthBias = INT(bias);
3035 if (ok && FLOAT(r.DepthBias) != bias) log_once("a fractional depth bias is truncated; bias x1000", int(bias * 1000));
3036 break;
3037 }
3038 case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VIEW_INSTANCING: {
3039 D3D12_VIEW_INSTANCING_DESC d{};
3040 take(d);
3041 if (ok && d.ViewInstanceCount) {
3042 log_once("view instancing is not supported yet; views", int(d.ViewInstanceCount));
3043 return E_NOTIMPL;
3044 }
3045 break;
3046 }
3047 default:
3048 log_once("unknown pipeline state stream subobject type:", int(type));
3049 return E_INVALIDARG;
3050 }
3051 if (!ok) return E_INVALIDARG;
3052 }
3053 if (out.has_cs && out.has_graphics_stage) return E_INVALIDARG; // a compute stage with graphics stages
3054 if (!out.has_cs && !out.has_graphics_stage) return E_INVALIDARG;
3055 return S_OK;
3056}
3057
2845class PipelineState final 3058class PipelineState final
2846 : public Child<PipelineState, XboxPipelineStateStubs, ID3D12Object, ID3D12DeviceChild, ID3D12Pageable, 3059 : public Child<PipelineState, XboxPipelineStateStubs, ID3D12Object, ID3D12DeviceChild, ID3D12Pageable,
2847 ID3D12PipelineState> { 3060 ID3D12PipelineState> {
@@ -2934,10 +3147,26 @@ public:
2934 // device lacks (including the geometryShader feature a GS needs). A GS takes triangles; the sample count may 3147 // device lacks (including the geometryShader feature a GS needs). A GS takes triangles; the sample count may
2935 // be above one. Viewport, scissor, topology, vertex strides, stencil reference and blend factor are dynamic, 3148 // be above one. Viewport, scissor, topology, vertex strides, stencil reference and blend factor are dynamic,
2936 // set from the list's state at each draw. 3149 // set from the list's state at each draw.
2937 HRESULT create_graphics(const D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc) { 3150 // With `ms` (a pipeline state stream's MS subobject) it is an MS (+ PS) pipeline on VK_EXT_mesh_shader instead:
3151 // no VS, no vertex input or input assembly (the input layout, topology type and strip cut are ignored, as D3D12
3152 // does for mesh PSOs), drawn by DispatchMesh. An AS (amplification shader) is refused: the game has none.
3153 HRESULT create_graphics(const D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc, const D3D12_SHADER_BYTECODE* ms = nullptr,
3154 const D3D12_SHADER_BYTECODE* as = nullptr) {
2938 auto& vk = device_.context->vk; 3155 auto& vk = device_.context->vk;
2939 const VkDevice dev = device_.info.device; 3156 const VkDevice dev = device_.info.device;
2940 if (!desc.VS.pShaderBytecode || !desc.VS.BytecodeLength) return E_INVALIDARG; 3157 const bool mesh = ms && ms->pShaderBytecode && ms->BytecodeLength;
3158 if (as && as->pShaderBytecode && as->BytecodeLength) {
3159 log_once("amplification shaders are not supported (the game has none); bytes", int(as->BytecodeLength));
3160 return E_NOTIMPL;
3161 }
3162 if (mesh && (desc.VS.BytecodeLength || desc.HS.BytecodeLength || desc.DS.BytecodeLength ||
3163 desc.GS.BytecodeLength || desc.StreamOutput.NumEntries))
3164 return E_INVALIDARG; // D3D12: a mesh PSO has no vertex, tessellation or geometry stage
3165 if (!mesh && (!desc.VS.pShaderBytecode || !desc.VS.BytecodeLength)) return E_INVALIDARG;
3166 if (mesh && (!device_.info.mesh_shader || !vk.vkCmdDrawMeshTasksEXT)) {
3167 log_once("mesh-shader PSOs need VK_EXT_mesh_shader, which the device has not enabled; stage", 1);
3168 return E_NOTIMPL;
3169 }
2941 if (!device_.arena.mapped) { 3170 if (!device_.arena.mapped) {
2942 log_once("pipelines need the GPU address arena (bufferDeviceAddress); stage", 1); 3171 log_once("pipelines need the GPU address arena (bufferDeviceAddress); stage", 1);
2943 return E_NOTIMPL; 3172 return E_NOTIMPL;
@@ -2994,7 +3223,8 @@ public:
2994 std::vector<std::uint8_t> fssm; 3223 std::vector<std::uint8_t> fssm;
2995 std::vector<std::uint32_t> words; 3224 std::vector<std::uint32_t> words;
2996 }; 3225 };
2997 Stage stages[3] = {{"vs", VK_SHADER_STAGE_VERTEX_BIT, desc.VS}, 3226 Stage stages[3] = {mesh ? Stage{"ms", VK_SHADER_STAGE_MESH_BIT_EXT, *ms}
3227 : Stage{"vs", VK_SHADER_STAGE_VERTEX_BIT, desc.VS},
2998 {"gs", VK_SHADER_STAGE_GEOMETRY_BIT, desc.GS}, 3228 {"gs", VK_SHADER_STAGE_GEOMETRY_BIT, desc.GS},
2999 {"ps", VK_SHADER_STAGE_FRAGMENT_BIT, desc.PS}}; 3229 {"ps", VK_SHADER_STAGE_FRAGMENT_BIT, desc.PS}};
3000 // stage_infos.size() indexes the recipe's per-stage required-size structs: one for every table entry. 3230 // stage_infos.size() indexes the recipe's per-stage required-size structs: one for every table entry.
@@ -3048,6 +3278,26 @@ public:
3048 uses_bindless = true; 3278 uses_bindless = true;
3049 register_literal_samplers(device_, *stage.entry); 3279 register_literal_samplers(device_, *stage.entry);
3050 } 3280 }
3281 if (stage.bit == VK_SHADER_STAGE_MESH_BIT_EXT) {
3282 // The SPIR-V's output arrays are sized from PSV0 (the index's max_vertices / max_primitives); Vulkan
3283 // has no per-pipeline limit to set, so a mesh shader beyond the device's is refused here
3284 // (docs/d3d12_vulkan.md, "Pipelines").
3285 const VkPhysicalDeviceMeshShaderPropertiesEXT& limits = device_.mesh_limits();
3286 const auto& n = stage.entry->local_size;
3287 if (stage.entry->max_vertices > limits.maxMeshOutputVertices ||
3288 stage.entry->max_primitives > limits.maxMeshOutputPrimitives ||
3289 n[0] > limits.maxMeshWorkGroupSize[0] || n[1] > limits.maxMeshWorkGroupSize[1] ||
3290 n[2] > limits.maxMeshWorkGroupSize[2] ||
3291 std::uint64_t(n[0]) * n[1] * n[2] > limits.maxMeshWorkGroupInvocations) {
3292 std::fprintf(stderr,
3293 "[rt] d3d12: %s needs %u vertices, %u primitives, %ux%ux%u threads; the device "
3294 "allows %u, %u, %u invocations\n",
3295 stage.entry->name.c_str(), stage.entry->max_vertices, stage.entry->max_primitives,
3296 n[0], n[1], n[2], limits.maxMeshOutputVertices, limits.maxMeshOutputPrimitives,
3297 limits.maxMeshWorkGroupInvocations);
3298 return E_NOTIMPL;
3299 }
3300 }
3051 if (stage.entry->uses_code_base) { 3301 if (stage.entry->uses_code_base) {
3052 if (code_stage) { 3302 if (code_stage) {
3053 log_once("two stages read their code base; one push-constant slot holds one (question 14)", 0); 3303 log_once("two stages read their code base; one push-constant slot holds one (question 14)", 0);
@@ -3144,13 +3394,13 @@ public:
3144 stage_infos.push_back(info); 3394 stage_infos.push_back(info);
3145 } 3395 }
3146 3396
3147 // Input layout -> vertex input, by semantic. 3397 // Input layout -> vertex input, by semantic. A mesh pipeline has none.
3148 std::vector<VkVertexInputAttributeDescription> attributes; 3398 std::vector<VkVertexInputAttributeDescription> attributes;
3149 std::vector<VkVertexInputBindingDescription> bindings; 3399 std::vector<VkVertexInputBindingDescription> bindings;
3150 std::vector<VkVertexInputBindingDivisorDescriptionEXT> divisors; 3400 std::vector<VkVertexInputBindingDivisorDescriptionEXT> divisors;
3151 std::uint32_t divisor_slots = 0; 3401 std::uint32_t divisor_slots = 0;
3152 UINT slot_end[D3D12_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT] = {}; 3402 UINT slot_end[D3D12_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT] = {};
3153 for (UINT i = 0; i < desc.InputLayout.NumElements; ++i) { 3403 for (UINT i = 0; !mesh && i < desc.InputLayout.NumElements; ++i) {
3154 const D3D12_INPUT_ELEMENT_DESC& element = desc.InputLayout.pInputElementDescs[i]; 3404 const D3D12_INPUT_ELEMENT_DESC& element = desc.InputLayout.pInputElementDescs[i];
3155 if (element.InputSlot >= D3D12_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT) return E_INVALIDARG; 3405 if (element.InputSlot >= D3D12_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT) return E_INVALIDARG;
3156 VkFormat format; 3406 VkFormat format;
@@ -3202,7 +3452,7 @@ public:
3202 } 3452 }
3203 } 3453 }
3204 VkPipelineInputAssemblyStateCreateInfo assembly{VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO}; 3454 VkPipelineInputAssemblyStateCreateInfo assembly{VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO};
3205 switch (desc.PrimitiveTopologyType) { 3455 switch (mesh ? D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE : desc.PrimitiveTopologyType) { // mesh: not used
3206 case D3D12_PRIMITIVE_TOPOLOGY_TYPE_POINT: assembly.topology = VK_PRIMITIVE_TOPOLOGY_POINT_LIST; break; 3456 case D3D12_PRIMITIVE_TOPOLOGY_TYPE_POINT: assembly.topology = VK_PRIMITIVE_TOPOLOGY_POINT_LIST; break;
3207 case D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE: assembly.topology = VK_PRIMITIVE_TOPOLOGY_LINE_LIST; break; 3457 case D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE: assembly.topology = VK_PRIMITIVE_TOPOLOGY_LINE_LIST; break;
3208 case D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE: assembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; break; 3458 case D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE: assembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; break;
@@ -3210,13 +3460,15 @@ public:
3210 log_once("primitive topology type not supported:", desc.PrimitiveTopologyType); 3460 log_once("primitive topology type not supported:", desc.PrimitiveTopologyType);
3211 return E_INVALIDARG; 3461 return E_INVALIDARG;
3212 } 3462 }
3213 if (desc.IBStripCutValue != D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED && 3463 if (!mesh) { // a mesh PSO has no index buffer: its strip cut is ignored
3214 desc.IBStripCutValue != D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_0xFFFF && 3464 if (desc.IBStripCutValue != D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED &&
3215 desc.IBStripCutValue != D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_0xFFFFFFFF) { 3465 desc.IBStripCutValue != D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_0xFFFF &&
3216 log_once("index-buffer strip cut value not supported:", desc.IBStripCutValue); 3466 desc.IBStripCutValue != D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_0xFFFFFFFF) {
3217 return E_INVALIDARG; 3467 log_once("index-buffer strip cut value not supported:", desc.IBStripCutValue);
3468 return E_INVALIDARG;
3469 }
3470 graphics_.strip_cut = desc.IBStripCutValue;
3218 } 3471 }
3219 graphics_.strip_cut = desc.IBStripCutValue;
3220 3472
3221 const D3D12_RASTERIZER_DESC& r = desc.RasterizerState; 3473 const D3D12_RASTERIZER_DESC& r = desc.RasterizerState;
3222 if (r.ConservativeRaster != D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF && 3474 if (r.ConservativeRaster != D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF &&
@@ -3421,6 +3673,8 @@ public:
3421 if (vk.vkCreatePipelineLayout(dev, &layout_info, nullptr, &graphics_.layout) != VK_SUCCESS) return E_FAIL; 3673 if (vk.vkCreatePipelineLayout(dev, &layout_info, nullptr, &graphics_.layout) != VK_SUCCESS) return E_FAIL;
3422 3674
3423 // Kept for variants: a draw that leaves a slot unbound needs this pipeline with that format undefined. 3675 // Kept for variants: a draw that leaves a slot unbound needs this pipeline with that format undefined.
3676 graphics_.mesh = mesh;
3677 recipe_.mesh = mesh;
3424 recipe_.stages = std::move(stage_infos); 3678 recipe_.stages = std::move(stage_infos);
3425 recipe_.attributes = std::move(attributes); 3679 recipe_.attributes = std::move(attributes);
3426 recipe_.bindings = std::move(bindings); 3680 recipe_.bindings = std::move(bindings);
@@ -3566,6 +3820,7 @@ public:
3566private: 3820private:
3567 // What a graphics pipeline is made from, so variants can be built at draw time. 3821 // What a graphics pipeline is made from, so variants can be built at draw time.
3568 struct Recipe { 3822 struct Recipe {
3823 bool mesh = false; // no vertex input or input assembly state, and no dynamic topology or strides
3569 std::vector<VkPipelineShaderStageCreateInfo> stages; 3824 std::vector<VkPipelineShaderStageCreateInfo> stages;
3570 // One per entry of create_graphics's stage table (VS, GS, PS), static_assert there; what `stages` chain. 3825 // One per entry of create_graphics's stage table (VS, GS, PS), static_assert there; what `stages` chain.
3571 VkPipelineShaderStageRequiredSubgroupSizeCreateInfo required_sizes[3]{}; 3826 VkPipelineShaderStageRequiredSubgroupSizeCreateInfo required_sizes[3]{};
@@ -3634,15 +3889,25 @@ private:
3634 VkPipelineColorBlendStateCreateInfo blend = r.blend; 3889 VkPipelineColorBlendStateCreateInfo blend = r.blend;
3635 blend.attachmentCount = std::uint32_t(r.blends.size()); 3890 blend.attachmentCount = std::uint32_t(r.blends.size());
3636 blend.pAttachments = r.blends.data(); 3891 blend.pAttachments = r.blends.data();
3892 // A mesh pipeline takes neither the topology nor the strides as dynamic state
3893 // (VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-07065 and -07066).
3894 static constexpr VkDynamicState mesh_dynamic_states[] = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR,
3895 VK_DYNAMIC_STATE_STENCIL_REFERENCE,
3896 VK_DYNAMIC_STATE_BLEND_CONSTANTS};
3637 VkPipelineDynamicStateCreateInfo dynamic{VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO}; 3897 VkPipelineDynamicStateCreateInfo dynamic{VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO};
3638 dynamic.dynamicStateCount = std::uint32_t(std::size(dynamic_states)) - (r.bindings.empty() ? 1 : 0); 3898 if (r.mesh) {
3639 dynamic.pDynamicStates = dynamic_states; 3899 dynamic.dynamicStateCount = std::uint32_t(std::size(mesh_dynamic_states));
3900 dynamic.pDynamicStates = mesh_dynamic_states;
3901 } else {
3902 dynamic.dynamicStateCount = std::uint32_t(std::size(dynamic_states)) - (r.bindings.empty() ? 1 : 0);
3903 dynamic.pDynamicStates = dynamic_states;
3904 }
3640 3905
3641 VkGraphicsPipelineCreateInfo info{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, &rendering}; 3906 VkGraphicsPipelineCreateInfo info{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, &rendering};
3642 info.stageCount = std::uint32_t(r.stages.size()); 3907 info.stageCount = std::uint32_t(r.stages.size());
3643 info.pStages = r.stages.data(); 3908 info.pStages = r.stages.data();
3644 info.pVertexInputState = &vertex_input; 3909 info.pVertexInputState = r.mesh ? nullptr : &vertex_input; // ignored with a mesh stage; null for clarity
3645 info.pInputAssemblyState = &r.assembly; 3910 info.pInputAssemblyState = r.mesh ? nullptr : &r.assembly;
3646 info.pViewportState = &viewport; 3911 info.pViewportState = &viewport;
3647 info.pRasterizationState = &raster; 3912 info.pRasterizationState = &raster;
3648 info.pMultisampleState = &multisample; 3913 info.pMultisampleState = &multisample;
@@ -5592,6 +5857,27 @@ public:
5592 return d3d12_trace::result(method, S_OK); 5857 return d3d12_trace::result(method, S_OK);
5593 } 5858 }
5594 5859
5860 // ID3D12Device2: a PSO from a pipeline state stream. A CS makes a compute PSO, an MS a mesh PSO, a VS the same
5861 // graphics PSO CreateGraphicsPipelineState makes (parse_pipeline_stream).
5862 HRESULT STDMETHODCALLTYPE CreatePipelineState(const D3D12_PIPELINE_STATE_STREAM_DESC* desc, REFIID riid,
5863 void** out) override {
5864 constexpr const char* method = "ID3D12Device2::CreatePipelineState";
5865 if (!out) return d3d12_trace::result(method, E_POINTER);
5866 *out = nullptr;
5867 if (!desc) return d3d12_trace::result(method, E_INVALIDARG);
5868 PipelineStream stream;
5869 if (const HRESULT hr = parse_pipeline_stream(*desc, stream); FAILED(hr)) return d3d12_trace::result(method, hr);
5870 auto* pipeline = new PipelineState(state_);
5871 pipeline->attach_device(identity());
5872 const HRESULT hr = stream.has_cs ? pipeline->create_compute(stream.compute)
5873 : pipeline->create_graphics(stream.graphics, &stream.ms, &stream.as);
5874 if (FAILED(hr)) {
5875 pipeline->Release();
5876 return d3d12_trace::result(method, hr);
5877 }
5878 return d3d12_trace::result(method, hand_out(pipeline, riid, out));
5879 }
5880
5595 UINT STDMETHODCALLTYPE GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE) override { 5881 UINT STDMETHODCALLTYPE GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE) override {
5596 return kDescriptorSize; 5882 return kDescriptorSize;
5597 } 5883 }
@@ -6869,7 +7155,11 @@ public:
6869 if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS7)) return d3d12_trace::result(method, E_INVALIDARG); 7155 if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS7)) return d3d12_trace::result(method, E_INVALIDARG);
6870 auto* opts = static_cast<D3D12_FEATURE_DATA_D3D12_OPTIONS7*>(data); 7156 auto* opts = static_cast<D3D12_FEATURE_DATA_D3D12_OPTIONS7*>(data);
6871 *opts = {}; 7157 *opts = {};
6872 opts->MeshShaderTier = D3D12_MESH_SHADER_TIER_NOT_SUPPORTED; 7158 // Tier 1 is mesh PSOs and DispatchMesh, on VK_EXT_mesh_shader. Amplification shaders are part of the tier
7159 // but refused at PSO creation (the game has none); OPTIONS9's mesh statistics and full-range render
7160 // target array index stay FALSE.
7161 opts->MeshShaderTier =
7162 state_.info.mesh_shader ? D3D12_MESH_SHADER_TIER_1 : D3D12_MESH_SHADER_TIER_NOT_SUPPORTED;
6873 opts->SamplerFeedbackTier = D3D12_SAMPLER_FEEDBACK_TIER_NOT_SUPPORTED; 7163 opts->SamplerFeedbackTier = D3D12_SAMPLER_FEEDBACK_TIER_NOT_SUPPORTED;
6874 return d3d12_trace::result(method, S_OK); 7164 return d3d12_trace::result(method, S_OK);
6875 } 7165 }
@@ -8578,6 +8868,7 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin
8578 VkPhysicalDeviceAccelerationStructureFeaturesKHR as_features{ 8868 VkPhysicalDeviceAccelerationStructureFeaturesKHR as_features{
8579 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ACCELERATION_STRUCTURE_FEATURES_KHR}; 8869 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ACCELERATION_STRUCTURE_FEATURES_KHR};
8580 VkPhysicalDeviceRayQueryFeaturesKHR rq_features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_QUERY_FEATURES_KHR}; 8870 VkPhysicalDeviceRayQueryFeaturesKHR rq_features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_QUERY_FEATURES_KHR};
8871 VkPhysicalDeviceMeshShaderFeaturesEXT mesh_features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT};
8581 { 8872 {
8582 std::uint32_t extension_count = 0; 8873 std::uint32_t extension_count = 0;
8583 vkEnumerateDeviceExtensionProperties(info.physical, nullptr, &extension_count, nullptr); 8874 vkEnumerateDeviceExtensionProperties(info.physical, nullptr, &extension_count, nullptr);
@@ -8597,8 +8888,14 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin
8597 has_dho = true; 8888 has_dho = true;
8598 } else if (!std::strcmp(e.extensionName, VK_KHR_RAY_QUERY_EXTENSION_NAME)) { 8889 } else if (!std::strcmp(e.extensionName, VK_KHR_RAY_QUERY_EXTENSION_NAME)) {
8599 has_rq = true; 8890 has_rq = true;
8891 } else if (!std::strcmp(e.extensionName, VK_EXT_MESH_SHADER_EXTENSION_NAME)) {
8892 VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &mesh_features};
8893 vkGetPhysicalDeviceFeatures2(info.physical, &features);
8894 info.mesh_shader = mesh_features.meshShader == VK_TRUE;
8600 } 8895 }
8601 } 8896 }
8897 if (!info.mesh_shader)
8898 std::fprintf(stderr, "[rt] d3d12: the GPU has no VK_EXT_mesh_shader: mesh-shader PSOs are unsupported\n");
8602 if (has_as && has_dho && has_rq && chosen12.bufferDeviceAddress) { 8899 if (has_as && has_dho && has_rq && chosen12.bufferDeviceAddress) {
8603 as_features.pNext = &rq_features; 8900 as_features.pNext = &rq_features;
8604 VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &as_features}; 8901 VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &as_features};
@@ -8627,7 +8924,16 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin
8627 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ACCELERATION_STRUCTURE_FEATURES_KHR}; 8924 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ACCELERATION_STRUCTURE_FEATURES_KHR};
8628 enable_as.accelerationStructure = VK_TRUE; 8925 enable_as.accelerationStructure = VK_TRUE;
8629 8926
8927 // Only meshShader: the game has no amplification (task) shaders, and multiview and shading-rate mesh features
8928 // are not used.
8929 VkPhysicalDeviceMeshShaderFeaturesEXT enable_mesh{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT};
8930 enable_mesh.meshShader = VK_TRUE;
8931
8630 void* ext_chain = nullptr; 8932 void* ext_chain = nullptr;
8933 if (info.mesh_shader) {
8934 enable_mesh.pNext = ext_chain;
8935 ext_chain = &enable_mesh;
8936 }
8631 if (info.ray_tracing) { 8937 if (info.ray_tracing) {
8632 enable_rq.pNext = ext_chain; 8938 enable_rq.pNext = ext_chain;
8633 enable_as.pNext = &enable_rq; 8939 enable_as.pNext = &enable_rq;
@@ -9003,6 +9309,7 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin
9003 // VK_KHR_swapchain requires VK_KHR_surface on the instance (VUID-vkCreateDevice-ppEnabledExtensionNames-01387). 9309 // VK_KHR_swapchain requires VK_KHR_surface on the instance (VUID-vkCreateDevice-ppEnabledExtensionNames-01387).
9004 if (has_swapchain && instance_has_surface) device_extensions.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME); 9310 if (has_swapchain && instance_has_surface) device_extensions.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME);
9005 if (swapchain_m1_name) device_extensions.push_back(swapchain_m1_name); 9311 if (swapchain_m1_name) device_extensions.push_back(swapchain_m1_name);
9312 if (info.mesh_shader) device_extensions.push_back(VK_EXT_MESH_SHADER_EXTENSION_NAME);
9006 if (info.ray_tracing) { 9313 if (info.ray_tracing) {
9007 device_extensions.push_back(VK_KHR_ACCELERATION_STRUCTURE_EXTENSION_NAME); 9314 device_extensions.push_back(VK_KHR_ACCELERATION_STRUCTURE_EXTENSION_NAME);
9008 device_extensions.push_back(VK_KHR_DEFERRED_HOST_OPERATIONS_EXTENSION_NAME); 9315 device_extensions.push_back(VK_KHR_DEFERRED_HOST_OPERATIONS_EXTENSION_NAME);
diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp
index 590f86bd7..e17a80353 100644
--- a/runtime/shims/d3d12_xs_device.cpp
+++ b/runtime/shims/d3d12_xs_device.cpp
@@ -16,6 +16,12 @@
16// positions (slot 8: desc, riid, out as a1-a3; slot 50: a1-a5; and so on). A tail call then writes back only the 16// positions (slot 8: desc, riid, out as a1-a3; slot 50: a1-a5; and so on). A tail call then writes back only the
17// values it read from those slots. A helper that moved a word to another stack position would overwrite the title's 17// values it read from those slots. A helper that moved a word to another stack position would overwrite the title's
18// frame. xs_proxy_mock_test's mock hit this in an optimized build, and its thunks now pass their words by pointer. 18// frame. xs_proxy_mock_test's mock hit this in an optimized build, and its thunks now pass their words by pointer.
19//
20// The public HLE Freminet/ScarlettX reports five more Xbox device slots (a third-party observation, not a Microsoft
21// ABI); the generic thunk routes them before it forwards anything: 48 CreateCommandQueueX, 73 CreateCommandListX,
22// 78 SetFrameIntervalX, 79 ScheduleFrameEventX and 80 WaitFrameEventX. The slots can be moved with LEONIDA_XS_*_SLOT
23// for a trace that disagrees. The frame-event calls answer from a per-device token counter: there is no vblank source
24// behind the device before a presenter exists, so WaitFrameEventX returns at once with a fresh non-zero token.
19#include "d3d12_xs_device.h" 25#include "d3d12_xs_device.h"
20#include "d3d12_trace.h" 26#include "d3d12_trace.h"
21#include "../src/shader_library.h" // leonida::fspx_payload_from_parts for slot 67 27#include "../src/shader_library.h" // leonida::fspx_payload_from_parts for slot 67
@@ -24,9 +30,12 @@
24#include <dxgi1_4.h> 30#include <dxgi1_4.h>
25 31
26#include <atomic> 32#include <atomic>
33#include <cerrno>
27#include <cstddef> 34#include <cstddef>
28#include <cstdint> 35#include <cstdint>
29#include <cstdio> 36#include <cstdio>
37#include <cstdlib>
38#include <cstring>
30#include <iterator> 39#include <iterator>
31#include <new> 40#include <new>
32#include <memory> 41#include <memory>
@@ -53,6 +62,13 @@ struct DeviceProxy {
53 DxgiAdapterProvider adapter_provider; 62 DxgiAdapterProvider adapter_provider;
54 std::atomic<int> gpu_thread_priority; 63 std::atomic<int> gpu_thread_priority;
55 std::atomic<unsigned> max_frame_latency; 64 std::atomic<unsigned> max_frame_latency;
65 // The first-frame subset of SetFrameIntervalX/ScheduleFrameEventX/WaitFrameEventX. Tokens were never measured;
66 // they start at 1 and only have to be fresh and non-zero for the boot sequence. Waiting returns at once: there is
67 // no vblank source until a presenter exists, and a bounded zero wait cannot stall the first frame.
68 std::atomic<std::uint32_t> frame_interval_us{0};
69 std::atomic<std::uint32_t> frame_latency{1};
70 std::atomic<bool> frame_event_scheduled{false};
71 std::atomic<std::uint64_t> frame_next_token{1};
56}; 72};
57 73
58constexpr unsigned kHeapSlots = 11; // IUnknown + ID3D12Object + DeviceChild + Pageable + GetDesc + 2 handles 74constexpr unsigned kHeapSlots = 11; // IUnknown + ID3D12Object + DeviceChild + Pageable + GetDesc + 2 handles
@@ -121,11 +137,16 @@ const char* slot_name(unsigned slot) {
121 case 43: return "GetAdapterLuid"; 137 case 43: return "GetAdapterLuid";
122 case 45: return "SetEventOnMultipleFenceCompletion (fence proxies unwrapped)"; 138 case 45: return "SetEventOnMultipleFenceCompletion (fence proxies unwrapped)";
123 case 46: return "SetResidencyPriority (proxies unwrapped)"; 139 case 46: return "SetResidencyPriority (proxies unwrapped)";
140 case 48: return "Xbox CreateCommandQueueX -> queue proxy";
124 case 50: return "EnqueueMakeResident (proxies unwrapped)"; 141 case 50: return "EnqueueMakeResident (proxies unwrapped)";
125 case 62: return "Xbox CreateComputePipelineState"; 142 case 62: return "Xbox CreateComputePipelineState";
126 case 67: return "Xbox DeserializeComputePipelineStateX"; 143 case 67: return "Xbox DeserializeComputePipelineStateX";
144 case 73: return "Xbox CreateCommandListX -> PC CreateCommandList";
127 case 75: return "CreateCommandQueue1 -> queue proxy"; 145 case 75: return "CreateCommandQueue1 -> queue proxy";
128 case 76: return "Xbox resource creation"; 146 case 76: return "Xbox resource creation";
147 case 78: return "Xbox SetFrameIntervalX";
148 case 79: return "Xbox ScheduleFrameEventX";
149 case 80: return "Xbox WaitFrameEventX";
129 default: return "forwarded"; 150 default: return "forwarded";
130 } 151 }
131} 152}
@@ -141,6 +162,78 @@ void note_slot(unsigned slot) {
141 } 162 }
142} 163}
143 164
165// Xbox device slots (public HLE Freminet/ScarlettX, an observation, not Microsoft documentation). The defaults are
166// the HLE's; an environment variable that names another slot in 3..127 replaces one (a whole-table move for a trace
167// that disagrees). A value outside that range is logged once and ignored. The table is read once, on the first
168// generic slot call, so a test that wants other slots sets the variables before it creates a device.
169struct XboxDeviceSlotRoutes {
170 unsigned frame_interval = 78; // SetFrameIntervalX(output, interval_us, latency, flags)
171 unsigned schedule_event = 79; // ScheduleFrameEventX(event, offset_us, reserved, flags)
172 unsigned wait_event = 80; // WaitFrameEventX(event, timeout_ms, reserved, flags, &token)
173 unsigned queue_x = 48; // CreateCommandQueueX(desc, riid, out)
174 unsigned list_x = 73; // CreateCommandListX(desc, allocator, initial_state, riid, out)
175};
176
177unsigned env_device_slot(const char* name, unsigned fallback) {
178 char value[32] = {};
179 const DWORD length = GetEnvironmentVariableA(name, value, sizeof(value));
180 if (length == 0) return fallback;
181 if (length >= sizeof(value)) {
182 std::fprintf(stderr, "[rt] d3d12_xs: %s is too long for a device slot; the default is kept\n", name);
183 return fallback;
184 }
185 errno = 0;
186 char* end = nullptr;
187 const unsigned long slot = std::strtoul(value, &end, 0);
188 if (errno != 0 || end == value || *end != '\0' || slot < 3 || slot > 127) {
189 std::fprintf(stderr, "[rt] d3d12_xs: %s=%s is not a device slot in 3..127; the default is kept\n", name,
190 value);
191 return fallback;
192 }
193 return static_cast<unsigned>(slot);
194}
195
196const XboxDeviceSlotRoutes& xbox_device_slot_routes() {
197 static const XboxDeviceSlotRoutes routes = [] {
198 XboxDeviceSlotRoutes r;
199 const unsigned frame_interval = env_device_slot("LEONIDA_XS_FRAME_INTERVAL_SLOT", r.frame_interval);
200 const unsigned schedule_event = env_device_slot("LEONIDA_XS_SCHEDULE_EVENT_SLOT", r.schedule_event);
201 const unsigned wait_event = env_device_slot("LEONIDA_XS_WAIT_EVENT_SLOT", r.wait_event);
202 const unsigned queue_x = env_device_slot("LEONIDA_XS_QUEUE_X_SLOT", r.queue_x);
203 const unsigned list_x = env_device_slot("LEONIDA_XS_LIST_X_SLOT", r.list_x);
204 const bool moved = frame_interval != r.frame_interval || schedule_event != r.schedule_event ||
205 wait_event != r.wait_event || queue_x != r.queue_x || list_x != r.list_x;
206 r.frame_interval = frame_interval;
207 r.schedule_event = schedule_event;
208 r.wait_event = wait_event;
209 r.queue_x = queue_x;
210 r.list_x = list_x;
211 if (moved)
212 std::fprintf(stderr,
213 "[rt] d3d12_xs: Xbox device slots: SetFrameIntervalX=%u ScheduleFrameEventX=%u "
214 "WaitFrameEventX=%u CreateCommandQueueX=%u CreateCommandListX=%u\n",
215 r.frame_interval, r.schedule_event, r.wait_event, r.queue_x, r.list_x);
216 return r;
217 }();
218 return routes;
219}
220
221// The public HLE call shapes. SetFrameIntervalX's output and flags are unused while there is no output or pacing;
222// ScheduleFrameEventX's reserved event pointer is a3 in the console call and a4 is its flags. The logged words are the
223// caller's, so a trace names the slot even when an override moved it.
224void log_xbox_route_once(unsigned slot, const char* name, std::uint64_t a1, std::uint64_t a2, std::uint64_t a3,
225 std::uint64_t a4, std::uint64_t a5) {
226 static std::atomic<bool> logged[kMaxSlots];
227 if (slot >= kMaxSlots) return;
228 bool expected = false;
229 if (!logged[slot].compare_exchange_strong(expected, true, std::memory_order_relaxed)) return;
230 std::fprintf(stderr,
231 "[rt] d3d12_xs: device slot %u routed to %s (args 0x%llx 0x%llx 0x%llx 0x%llx 0x%llx)\n", slot,
232 name, static_cast<unsigned long long>(a1), static_cast<unsigned long long>(a2),
233 static_cast<unsigned long long>(a3), static_cast<unsigned long long>(a4),
234 static_cast<unsigned long long>(a5));
235}
236
144const char* heap_slot_name(unsigned slot) { 237const char* heap_slot_name(unsigned slot) {
145 switch (slot) { 238 switch (slot) {
146 case 0: return "QueryInterface"; 239 case 0: return "QueryInterface";
@@ -1053,6 +1146,75 @@ HRESULT proxy_create_command_queue(DeviceProxy* self, const D3D12_COMMAND_QUEUE_
1053 return wrap_child<ChildKind::queue>(static_cast<IUnknown*>(created), self, riid, out); 1146 return wrap_child<ChildKind::queue>(static_cast<IUnknown*>(created), self, riid, out);
1054} 1147}
1055 1148
1149// Xbox device slot 78 (public HLE): SetFrameIntervalX(output, interval_us, latency, flags). The output and flags are
1150// not used before a presenter exists. The period is a vblank period in microseconds in the public samples (16667 for
1151// 60 Hz), and latency is the allowed frames in flight. S_OK even for 0: a boot must not abort here, and nothing paces.
1152HRESULT proxy_set_frame_interval_x(DeviceProxy* self, std::uint64_t output, std::uint64_t interval_us,
1153 std::uint64_t latency, std::uint64_t flags) {
1154 (void)output;
1155 (void)flags;
1156 self->frame_interval_us.store(static_cast<std::uint32_t>(interval_us), std::memory_order_relaxed);
1157 self->frame_latency.store(static_cast<std::uint32_t>(latency ? latency : 1), std::memory_order_relaxed);
1158 return S_OK;
1159}
1160
1161// Xbox device slot 79 (public HLE): ScheduleFrameEventX(event, offset_us, pEvent, flags); our pacer has only the origin.
1162HRESULT proxy_schedule_frame_event_x(DeviceProxy* self, std::uint64_t event, std::uint64_t offset_us,
1163 std::uint64_t flags) {
1164 (void)event;
1165 (void)offset_us;
1166 (void)flags;
1167 self->frame_event_scheduled.store(true, std::memory_order_relaxed);
1168 return S_OK;
1169}
1170
1171// Xbox device slot 80 (public HLE): WaitFrameEventX(event, timeout_ms, pEvent, flags, &token). It returns at once with
1172// a fresh non-zero token (the first-frame choice): there is no vblank source behind the device before a presenter, and
1173// a zero wait cannot stall the title. A null token pointer is E_POINTER, as a _Out_ parameter.
1174HRESULT proxy_wait_frame_event_x(DeviceProxy* self, std::uint64_t event, std::uint64_t timeout_ms,
1175 std::uint64_t flags, std::uint64_t token_word) {
1176 (void)event;
1177 (void)timeout_ms;
1178 (void)flags;
1179 auto* token = reinterpret_cast<std::uint64_t*>(token_word);
1180 if (!token) return E_POINTER;
1181 std::uint64_t value = self->frame_next_token.fetch_add(1, std::memory_order_relaxed);
1182 if (value == 0) value = self->frame_next_token.fetch_add(1, std::memory_order_relaxed); // skip the null token
1183 *token = value;
1184 return S_OK;
1185}
1186
1187// Xbox device slot 73 (public HLE): CreateCommandListX(desc, allocator, initial_state, riid, out). The console call is
1188// not the PC six-argument form: the type is the first word of D3D12XBOX_COMMAND_LIST_DESC and there is no node mask
1189// (the HLE passes 0). The second desc word is logged, not interpreted: its public layout is not established.
1190HRESULT proxy_create_command_list_x(DeviceProxy* self, std::uint64_t desc_word, std::uint64_t allocator_word,
1191 std::uint64_t initial_state_word, const IID* riid, void** out) {
1192 if (out) *out = nullptr;
1193 if (!desc_word || !allocator_word) return E_INVALIDARG;
1194 if (!riid) return E_POINTER;
1195 if (!out) return E_POINTER;
1196
1197 std::uint32_t words[2] = {};
1198 std::memcpy(words, reinterpret_cast<const void*>(desc_word), sizeof(words));
1199 auto type = static_cast<D3D12_COMMAND_LIST_TYPE>(words[0]);
1200 if (type != D3D12_COMMAND_LIST_TYPE_DIRECT && type != D3D12_COMMAND_LIST_TYPE_BUNDLE &&
1201 type != D3D12_COMMAND_LIST_TYPE_COMPUTE && type != D3D12_COMMAND_LIST_TYPE_COPY)
1202 type = D3D12_COMMAND_LIST_TYPE_DIRECT; // as the public HLE does
1203
1204 static std::atomic<bool> logged{false};
1205 if (first_call(logged))
1206 std::fprintf(stderr,
1207 "[rt] d3d12_xs: slot 73 CreateCommandListX desc words 0x%08x 0x%08x -> node mask 0, type %d\n",
1208 words[0], words[1], static_cast<int>(type));
1209
1210 // Leonida wraps its Vulkan allocators; a PC allocator comes back unwrapped and is passed as it is. Pipeline states
1211 // are not wrapped by this proxy, so initial_state is already the real object (a proxy there is passed through too).
1212 auto* allocator = allocator_proxy_real_allocator(reinterpret_cast<void*>(allocator_word));
1213 if (!allocator) allocator = reinterpret_cast<ID3D12CommandAllocator*>(allocator_word);
1214 auto* initial_state = reinterpret_cast<ID3D12PipelineState*>(initial_state_word);
1215 return self->real->CreateCommandList(0, type, allocator, initial_state, *riid, out);
1216}
1217
1056// Device slot 75: ID3D12Device9::CreateCommandQueue1(desc, creator_id, riid, out), called by slot index. 1218// Device slot 75: ID3D12Device9::CreateCommandQueue1(desc, creator_id, riid, out), called by slot index.
1057HRESULT proxy_create_command_queue1(DeviceProxy* self, std::uint64_t desc, std::uint64_t creator_id, 1219HRESULT proxy_create_command_queue1(DeviceProxy* self, std::uint64_t desc, std::uint64_t creator_id,
1058 const IID* riid, void** out) { 1220 const IID* riid, void** out) {
@@ -1369,6 +1531,33 @@ std::uint64_t WINAPI proxy_slot(DeviceProxy* self, std::uint64_t a1, std::uint64
1369 reinterpret_cast<void**>(a7))); 1531 reinterpret_cast<void**>(a7)));
1370 } else { 1532 } else {
1371 note_slot(Slot); 1533 note_slot(Slot);
1534 // Xbox device slots, before the PC vtable is indexed: the public HLE's 78/79/80 would otherwise reach
1535 // CreateReservedResource2/CreateSampler2 or fall past an 80-slot table, and 48/73 would reach unrelated PC
1536 // methods. The check is before the slot-count refusal because slot 80 is outside a PC ID3D12Device11 table.
1537 const XboxDeviceSlotRoutes& routes = xbox_device_slot_routes();
1538 if (Slot == routes.frame_interval) {
1539 log_xbox_route_once(Slot, "SetFrameIntervalX", a1, a2, a3, a4, a5);
1540 return hr_to_u64(proxy_set_frame_interval_x(self, a1, a2, a3, a4));
1541 }
1542 if (Slot == routes.schedule_event) {
1543 log_xbox_route_once(Slot, "ScheduleFrameEventX", a1, a2, a3, a4, a5);
1544 return hr_to_u64(proxy_schedule_frame_event_x(self, a1, a2, a4));
1545 }
1546 if (Slot == routes.wait_event) {
1547 log_xbox_route_once(Slot, "WaitFrameEventX", a1, a2, a3, a4, a5);
1548 return hr_to_u64(proxy_wait_frame_event_x(self, a1, a2, a4, a5));
1549 }
1550 if (Slot == routes.queue_x) {
1551 log_xbox_route_once(Slot, "CreateCommandQueueX", a1, a2, a3, a4, a5);
1552 return hr_to_u64(proxy_create_command_queue(self, reinterpret_cast<const D3D12_COMMAND_QUEUE_DESC*>(a1),
1553 reinterpret_cast<const IID*>(a2),
1554 reinterpret_cast<void**>(a3)));
1555 }
1556 if (Slot == routes.list_x) {
1557 log_xbox_route_once(Slot, "CreateCommandListX", a1, a2, a3, a4, a5);
1558 return hr_to_u64(proxy_create_command_list_x(self, a1, a2, a3, reinterpret_cast<const IID*>(a4),
1559 reinterpret_cast<void**>(a5)));
1560 }
1372 if (Slot >= self->slot_count) return hr_to_u64(refuse_beyond_device(Slot, self->slot_count)); 1561 if (Slot >= self->slot_count) return hr_to_u64(refuse_beyond_device(Slot, self->slot_count));
1373 1562
1374 // The PC vtable entry, called with the PC device as `this`. Integer/pointer arguments, the hidden 1563 // The PC vtable entry, called with the PC device as `this`. Integer/pointer arguments, the hidden
@@ -1515,9 +1704,13 @@ ID3D12Device* device_proxy_real_device(const void* device) {
1515} 1704}
1516 1705
1517bool device_slot_overridden(unsigned slot) { 1706bool device_slot_overridden(unsigned slot) {
1518 return slot <= 2 || slot == 8 || slot == 9 || slot == 14 || slot == 31 || slot == 32 || slot == 34 || slot == 35 || 1707 if (slot <= 2 || slot == 8 || slot == 9 || slot == 14 || slot == 31 || slot == 32 || slot == 34 || slot == 35 ||
1519 slot == 36 || slot == 45 || slot == 46 || slot == 50 || slot == 62 || slot == 67 || 1708 slot == 36 || slot == 45 || slot == 46 || slot == 50 || slot == 62 || slot == 67 ||
1520 slot == 75 || slot == 76; 1709 slot == 75 || slot == 76)
1710 return true;
1711 const XboxDeviceSlotRoutes& routes = xbox_device_slot_routes();
1712 return slot == routes.frame_interval || slot == routes.schedule_event || slot == routes.wait_event ||
1713 slot == routes.queue_x || slot == routes.list_x;
1521} 1714}
1522 1715
1523bool is_queue_proxy(const void* queue) { return is_child_proxy<ChildKind::queue>(queue); } 1716bool is_queue_proxy(const void* queue) { return is_child_proxy<ChildKind::queue>(queue); }
diff --git a/runtime/shims/d3d12_xs_device.h b/runtime/shims/d3d12_xs_device.h
index 8ff508e6f..0019ec506 100644
--- a/runtime/shims/d3d12_xs_device.h
+++ b/runtime/shims/d3d12_xs_device.h
@@ -7,6 +7,17 @@
7// (+0x00 root signature, +0x28 code, +0x30 size) to D3D12_COMPUTE_PIPELINE_STATE_DESC and forwards 7// (+0x00 root signature, +0x28 code, +0x30 size) to D3D12_COMPUTE_PIPELINE_STATE_DESC and forwards
8// to PC CreateComputePipelineState (slot 11). The PC slot 67 is CreateProtectedResourceSession1. 8// to PC CreateComputePipelineState (slot 11). The PC slot 67 is CreateProtectedResourceSession1.
9// slot 76 resource creation -> PC CreateCommittedResource (PC slot 27), with the Xbox layout word ignored. 9// slot 76 resource creation -> PC CreateCommittedResource (PC slot 27), with the Xbox layout word ignored.
10// slot 48 CreateCommandQueueX(desc, riid, out) -> the same queue proxy as slot 8. The Xbox desc's first fields are
11// D3D12_COMMAND_QUEUE_DESC's (public HLE).
12// slot 73 CreateCommandListX(desc, allocator, initialState, riid, out) -> PC CreateCommandList(0, type, allocator,
13// initialState, riid, out). The type is the first word of the Xbox desc; there is no node-mask argument
14// in the console call (public HLE; the PC six-argument form differs).
15// slots 78/79/80 SetFrameIntervalX, ScheduleFrameEventX, WaitFrameEventX. A per-device token state machine answers
16// them before the PC vtable is indexed; WaitFrameEventX returns at once with a fresh non-zero token.
17// Slot 80 is outside a PC ID3D12Device11 table, so it is checked before the beyond-table refusal.
18// The slots 48/73/78/79/80 are the public HLE Freminet/ScarlettX's observation, not Microsoft documentation, and can
19// be moved with LEONIDA_XS_QUEUE_X_SLOT, LEONIDA_XS_LIST_X_SLOT, LEONIDA_XS_FRAME_INTERVAL_SLOT,
20// LEONIDA_XS_SCHEDULE_EVENT_SLOT and LEONIDA_XS_WAIT_EVENT_SLOT (3..127; anything else is logged once and ignored).
10// The measured slots 9/10 (GetCPU/GPUDescriptorHandleForHeapStart) are ID3D12DescriptorHeap methods, not device 21// The measured slots 9/10 (GetCPU/GPUDescriptorHandleForHeapStart) are ID3D12DescriptorHeap methods, not device
11// methods: the PC device's 9/10 are CreateCommandAllocator/CreateGraphicsPipelineState and are forwarded unchanged. 22// methods: the PC device's 9/10 are CreateCommandAllocator/CreateGraphicsPipelineState and are forwarded unchanged.
12// On the PC heap those getters use the hidden return pointer in RDX; the Xbox ABI returns the 8-byte handle in 23// On the PC heap those getters use the hidden return pointer in RDX; the Xbox ABI returns the 8-byte handle in
@@ -18,8 +29,9 @@
18// wrapper and compares it with a hidden-pointer call against the real heap. 29// wrapper and compares it with a hidden-pointer call against the real heap.
19// 30//
20// Every other PC device slot is forwarded by a generated thunk that swaps `this` to the PC device. The proxy's 31// Every other PC device slot is forwarded by a generated thunk that swaps `this` to the PC device. The proxy's
21// vtable therefore follows the PC device order, with slots 62 and 76 deliberately shadowed. The full Xbox vtable 32// vtable therefore follows the PC device order, with slots 62 and 76 and the public HLE's 48/73/78/79/80 deliberately
22// order is not known from the spec; slots beyond the PC device's own vtable return E_NOTIMPL and log once. 33// shadowed. The full Xbox vtable order is not known from the spec; slots beyond the PC device's own vtable return
34// E_NOTIMPL and log once.
23// 35//
24// Command queues and fences (device slots 8, 75, 36, and 32 for a shared fence) come back wrapped in queue and fence 36// Command queues and fences (device slots 8, 75, 36, and 32 for a shared fence) come back wrapped in queue and fence
25// proxies of the same kind: the public chain (19 queue slots, 11 or 12 fence slots in SDK 10.0.26100) is forwarded 37// proxies of the same kind: the public chain (19 queue slots, 11 or 12 fence slots in SDK 10.0.26100) is forwarded
@@ -78,9 +90,10 @@ unsigned device_proxy_slot_count(const void* device);
78ID3D12Device* device_proxy_real_device(const void* device); 90ID3D12Device* device_proxy_real_device(const void* device);
79 91
80// True for slots the proxy handles itself rather than forwarding verbatim: IUnknown (0-2), 8 and 75 (queue 92// True for slots the proxy handles itself rather than forwarding verbatim: IUnknown (0-2), 8 and 75 (queue
81// proxies), 9 (allocator proxies), 14, 31/34/35/45/46/50 (proxies unwrapped), 32 and 36 (fence proxies), 62, 67 93// proxies), 9 (allocator proxies), 14, 31/34/35/45/46/50 (proxies unwrapped), 32 and 36 (fence proxies), 48/73 and
82// and 76. Slot 10 is intentionally false: the measured 9/10 handle conversion is on the heap proxy, and device 94// 78/79/80 (the Xbox slots above, at their configured indices), 62, 67 and 76. Slot 10 is intentionally false: the
83// slot 9 is CreateCommandAllocator, which the proxy handles for the allocator proxy. 95// measured 9/10 handle conversion is on the heap proxy, and device slot 9 is CreateCommandAllocator, which the proxy
96// handles for the allocator proxy.
84bool device_slot_overridden(unsigned slot); 97bool device_slot_overridden(unsigned slot);
85 98
86// Queue and fence proxies created by device slots 8/75 and 36. The real_* accessors return the wrapped object 99// Queue and fence proxies created by device slots 8/75 and 36. The real_* accessors return the wrapped object
diff --git a/runtime/shims/file_system.cpp b/runtime/shims/file_system.cpp
index 995f55a0b..1eaf0bda9 100644
--- a/runtime/shims/file_system.cpp
+++ b/runtime/shims/file_system.cpp
@@ -23,6 +23,7 @@
23// Only images mapped by the loader see these: they are bound through the registry, the runtime's own code calls the 23// Only images mapped by the loader see these: they are bound through the registry, the runtime's own code calls the
24// host directly. 24// host directly.
25#include <windows.h> 25#include <windows.h>
26#include <intrin.h>
26 27
27#include <atomic> 28#include <atomic>
28#include <cstring> 29#include <cstring>
@@ -39,6 +40,7 @@
39 40
40#include "file_system.h" 41#include "file_system.h"
41#include "shims.h" 42#include "shims.h"
43#include "startup_trace.h"
42 44
43namespace rt::fs { 45namespace rt::fs {
44namespace { 46namespace {
@@ -629,6 +631,25 @@ std::filesystem::path overlay_dir() {
629 return g_overlay_dir; 631 return g_overlay_dir;
630} 632}
631 633
634// gta6rt --trace FILE: a failed open of a guest path goes to the startup trace as a "file_open_failed" event (the
635// path the title passed, the Win32 error, the caller as module+RVA), so a boot that stops on a missing or refused
636// file names it. Failures only, and at most 256 of them, so a title probing many optional files can't fill the file.
637void note_open_failure(const char* api, LPCWSTR name, DWORD error, const void* caller) {
638 if (!rt::startup_trace::enabled()) return;
639 static std::atomic<int> left{256};
640 if (left.fetch_sub(1, std::memory_order_relaxed) <= 0) return;
641 std::string utf8;
642 if (const int n = WideCharToMultiByte(CP_UTF8, 0, name, -1, nullptr, 0, nullptr, nullptr); n > 1) {
643 utf8.resize(static_cast<size_t>(n) - 1);
644 WideCharToMultiByte(CP_UTF8, 0, name, -1, utf8.data(), n, nullptr, nullptr);
645 }
646 rt::startup_trace::event(
647 "file_open_failed",
648 std::string("\"api\":\"") + api + "\",\"path\":" + rt::startup_trace::quote(utf8) +
649 ",\"error\":" + std::to_string(error) + ",\"caller\":" +
650 rt::startup_trace::quote(rt::startup_trace::where(reinterpret_cast<uint64_t>(caller))));
651}
652
632HANDLE WINAPI create_file_w(LPCWSTR name, DWORD access, DWORD share, LPSECURITY_ATTRIBUTES attributes, 653HANDLE WINAPI create_file_w(LPCWSTR name, DWORD access, DWORD share, LPSECURITY_ATTRIBUTES attributes,
633 DWORD disposition, DWORD flags, HANDLE template_file) { 654 DWORD disposition, DWORD flags, HANDLE template_file) {
634 if (!name) { 655 if (!name) {
@@ -637,10 +658,17 @@ HANDLE WINAPI create_file_w(LPCWSTR name, DWORD access, DWORD share, LPSECURITY_
637 } 658 }
638 const Target t = open_target(name, access, disposition); 659 const Target t = open_target(name, access, disposition);
639 if (t.error) { 660 if (t.error) {
661 note_open_failure("CreateFileW", name, t.error, _ReturnAddress());
640 SetLastError(t.error); 662 SetLastError(t.error);
641 return INVALID_HANDLE_VALUE; 663 return INVALID_HANDLE_VALUE;
642 } 664 }
643 return ::CreateFileW(t.path.c_str(), access, share, attributes, disposition, flags, template_file); 665 const HANDLE h = ::CreateFileW(t.path.c_str(), access, share, attributes, disposition, flags, template_file);
666 if (h == INVALID_HANDLE_VALUE) {
667 const DWORD error = GetLastError();
668 note_open_failure("CreateFileW", name, error, _ReturnAddress());
669 SetLastError(error);
670 }
671 return h;
644} 672}
645 673
646HANDLE WINAPI create_file_a(LPCSTR name, DWORD access, DWORD share, LPSECURITY_ATTRIBUTES attributes, 674HANDLE WINAPI create_file_a(LPCSTR name, DWORD access, DWORD share, LPSECURITY_ATTRIBUTES attributes,
@@ -661,10 +689,17 @@ HANDLE WINAPI create_file2(LPCWSTR name, DWORD access, DWORD share, DWORD dispos
661 } 689 }
662 const Target t = open_target(name, access, disposition); 690 const Target t = open_target(name, access, disposition);
663 if (t.error) { 691 if (t.error) {
692 note_open_failure("CreateFile2", name, t.error, _ReturnAddress());
664 SetLastError(t.error); 693 SetLastError(t.error);
665 return INVALID_HANDLE_VALUE; 694 return INVALID_HANDLE_VALUE;
666 } 695 }
667 return ::CreateFile2(t.path.c_str(), access, share, disposition, params); 696 const HANDLE h = ::CreateFile2(t.path.c_str(), access, share, disposition, params);
697 if (h == INVALID_HANDLE_VALUE) {
698 const DWORD error = GetLastError();
699 note_open_failure("CreateFile2", name, error, _ReturnAddress());
700 SetLastError(error);
701 }
702 return h;
668} 703}
669 704
670DWORD WINAPI get_file_attributes_w(LPCWSTR name) { 705DWORD WINAPI get_file_attributes_w(LPCWSTR name) {
diff --git a/runtime/shims/startup_trace.h b/runtime/shims/startup_trace.h
index 1c9be1aa0..7b47d993a 100644
--- a/runtime/shims/startup_trace.h
+++ b/runtime/shims/startup_trace.h
@@ -13,13 +13,15 @@
13// {"seq":8,"t":0.030,"kind":"exit","code":0} 13// {"seq":8,"t":0.030,"kind":"exit","code":0}
14// 14//
15// The exception handler is vectored, logs and returns EXCEPTION_CONTINUE_SEARCH: it never changes what the process 15// The exception handler is vectored, logs and returns EXCEPTION_CONTINUE_SEARCH: it never changes what the process
16// does. OutputDebugStringA/W raise DBG_PRINTEXCEPTION_C / DBG_PRINTEXCEPTION_WIDE_C when no debugger is attached, so 16// does (except LEONIDA_SKIP_INT3, below).
17// the same handler records their text without a shim. 17// OutputDebugStringA/W raise DBG_PRINTEXCEPTION_C / DBG_PRINTEXCEPTION_WIDE_C when no debugger is attached, so the
18// same handler records their text without a shim.
18// 19//
19// The file can quote whatever the game prints: it stays on the player's machine (AGENTS.md, "No game data"). 20// The file can quote whatever the game prints: it stays on the player's machine (AGENTS.md, "No game data").
20#pragma once 21#pragma once
21 22
22#include <windows.h> 23#include <windows.h>
24#include <set>
23 25
24#include <atomic> 26#include <atomic>
25#include <cerrno> 27#include <cerrno>
@@ -189,8 +191,29 @@ inline void log_exception(const EXCEPTION_POINTERS& info) {
189 } 191 }
190} 192}
191 193
194// LEONIDA_SKIP_INT3 (diagnostic, with --trace): an int3 in guest code is logged once per address and stepped over,
195// so a boot can be followed past the title's soft asserts (an int3 followed by code that carries on). Off by default:
196// a console title never reaches one in a correct run, so each skipped address is a finding, not a fix.
197inline bool skip_int3(EXCEPTION_POINTERS* info) {
198 static const bool skip = GetEnvironmentVariableW(L"LEONIDA_SKIP_INT3", nullptr, 0) != 0;
199 if (!skip || info->ExceptionRecord->ExceptionCode != EXCEPTION_BREAKPOINT || !info->ContextRecord) return false;
200 const auto* at = static_cast<const unsigned char*>(info->ExceptionRecord->ExceptionAddress);
201 if (!at || *at != 0xCC || info->ContextRecord->Rip != reinterpret_cast<DWORD64>(at)) return false;
202 static std::mutex m;
203 static std::set<const void*> seen;
204 bool first = false;
205 {
206 const std::lock_guard lock(m);
207 first = seen.insert(at).second;
208 }
209 if (first) event("int3_skipped", "\"at\":" + quote(where(reinterpret_cast<uint64_t>(at))));
210 info->ContextRecord->Rip += 1;
211 return true;
212}
213
192inline LONG CALLBACK handler(EXCEPTION_POINTERS* info) { 214inline LONG CALLBACK handler(EXCEPTION_POINTERS* info) {
193 if (!enabled() || in_handler || !info || !info->ExceptionRecord) return EXCEPTION_CONTINUE_SEARCH; 215 if (!enabled() || in_handler || !info || !info->ExceptionRecord) return EXCEPTION_CONTINUE_SEARCH;
216 if (skip_int3(info)) return EXCEPTION_CONTINUE_EXECUTION;
194 in_handler = true; 217 in_handler = true;
195#ifdef _MSC_VER 218#ifdef _MSC_VER
196 // Under /EHsc, catch(...) does not catch SEH faults (e.g. a bad DBG_PRINTEXCEPTION_C pointer or corrupt unwind). 219 // Under /EHsc, catch(...) does not catch SEH faults (e.g. a bad DBG_PRINTEXCEPTION_C pointer or corrupt unwind).
diff --git a/runtime/shims/xgameruntime.cpp b/runtime/shims/xgameruntime.cpp
index 30871d257..e0c13c502 100644
--- a/runtime/shims/xgameruntime.cpp
+++ b/runtime/shims/xgameruntime.cpp
@@ -7,9 +7,10 @@
7// 7//
8// Nothing here goes online. 8// Nothing here goes online.
9// 9//
10// ASSUMPTION: the console executable is not available, so the DLL name it imports these through is unknown. 10// Measured on the retail executable (docs/runtime_imports.md, "The retail executable's runtime classes"): it does not
11// "xgameruntime.dll" is the name the PC GDK uses. If the executable's import table names another module, register 11// import xgameruntime.dll. Its 161 runtime thunks are linked into the image and reach the classes through
12// the same functions under that name too; nothing else changes. 12// QueryApiImpl, as libHttpClient.GDK.dll's do, so "xgameruntime.dll" below is the only module name needed. The name
13// occurs in the image as a UTF-16 string, which would be a run-time load.
13#include <windows.h> 14#include <windows.h>
14 15
15#include <algorithm> 16#include <algorithm>
diff --git a/runtime/shims/xgameruntime_offline.cpp b/runtime/shims/xgameruntime_offline.cpp
index 9d5ff4a28..01eb22037 100644
--- a/runtime/shims/xgameruntime_offline.cpp
+++ b/runtime/shims/xgameruntime_offline.cpp
@@ -175,8 +175,9 @@ HRESULT CALLBACK error_dialog_provider(XAsyncOp op, const XAsyncProviderData* da
175// 3: HRESULT XGameUiShowMessageDialogAsync(XAsyncBlock* async, const char* titleText, const char* contentText, 175// 3: HRESULT XGameUiShowMessageDialogAsync(XAsyncBlock* async, const char* titleText, const char* contentText,
176// const char* firstButtonText, const char* secondButtonText, const char* thirdButtonText, 176// const char* firstButtonText, const char* secondButtonText, const char* thirdButtonText,
177// XGameUiMessageDialogButton defaultButton, XGameUiMessageDialogButton cancelButton) 177// XGameUiMessageDialogButton defaultButton, XGameUiMessageDialogButton cancelButton)
178// ASSUMPTION: the parameter list is the one the GDK reference gives; only the result-page and the enum were checked 178// The parameter list is the one the GDK reference gives; only the result-page and the enum were checked for this
179// for this file. The dialog is "answered" with its default button. 179// file. No caller confirms it: tools/gdk_runtime_calls.py finds no thunk for this slot in the executable
180// (docs/runtime_imports.md). The dialog is "answered" with its default button.
180HRESULT STDMETHODCALLTYPE ui_message_dialog_async(void*, XAsyncBlock* async, const char* title, const char* content, 181HRESULT STDMETHODCALLTYPE ui_message_dialog_async(void*, XAsyncBlock* async, const char* title, const char* content,
181 const char* first, const char* second, const char* third, 182 const char* first, const char* second, const char* third,
182 XGameUiMessageDialogButton default_button, XGameUiMessageDialogButton) { 183 XGameUiMessageDialogButton default_button, XGameUiMessageDialogButton) {
@@ -298,8 +299,8 @@ uint32_t STDMETHODCALLTYPE streaming_client_count(void*) { return 0; }
298 299
299// 12: HRESULT XGameStreamingRegisterConnectionStateChanged(XTaskQueueHandle queue, void* context, 300// 12: HRESULT XGameStreamingRegisterConnectionStateChanged(XTaskQueueHandle queue, void* context,
300// XGameStreamingConnectionStateChangedCallback* callback, XTaskQueueRegistrationToken* token) 301// XGameStreamingConnectionStateChangedCallback* callback, XTaskQueueRegistrationToken* token)
301// ASSUMPTION: that parameter list (the GDK reference's, not re-checked for this file). No client connects, so the 302// That parameter list is the GDK reference's, not re-checked for this file, and no caller confirms it: the executable
302// callback never runs. 303// links no XGameStreamingImpl thunk (docs/runtime_imports.md). No client connects, so the callback never runs.
303HRESULT STDMETHODCALLTYPE streaming_register_connection(void*, XTaskQueueHandle, void*, void* callback, 304HRESULT STDMETHODCALLTYPE streaming_register_connection(void*, XTaskQueueHandle, void*, void* callback,
304 XTaskQueueRegistrationToken* token) { 305 XTaskQueueRegistrationToken* token) {
305 if (!callback || !token) return E_INVALIDARG; 306 if (!callback || !token) return E_INVALIDARG;
@@ -325,7 +326,7 @@ template <int Slot> HRESULT STDMETHODCALLTYPE client_not_connected(void*) {
325static_assert((static_cast<uint32_t>(E_GAMESTREAMING_NOT_INITIALIZED) & 0xFF) == 0, "reads as false in al"); 326static_assert((static_cast<uint32_t>(E_GAMESTREAMING_NOT_INITIALIZED) & 0xFF) == 0, "reads as false in al");
326 327
327// 11: XGameStreamingConnectionState XGameStreamingGetConnectionState(XGameStreamingClientId client): 0, the first 328// 11: XGameStreamingConnectionState XGameStreamingGetConnectionState(XGameStreamingClientId client): 0, the first
328// enumerator. ASSUMPTION: it is Disconnected; there is no client to ask about either way. 329// enumerator, taken to be Disconnected; there is no client to ask about either way, and the executable has no caller.
329uint32_t STDMETHODCALLTYPE streaming_connection_state(void*) { return 0; } 330uint32_t STDMETHODCALLTYPE streaming_connection_state(void*) { return 0; }
330 331
331HRESULT STDMETHODCALLTYPE streaming_query_interface(void*, REFIID iid, void** out); 332HRESULT STDMETHODCALLTYPE streaming_query_interface(void*, REFIID iid, void** out);
@@ -431,7 +432,8 @@ const GUID kUserDeviceInterfaces[] = {
431 {0x0cc6a956, 0xe7e1, 0x4fdf, {0x93, 0x41, 0x9d, 0x5d, 0xa6, 0x49, 0xeb, 0xc8}}, // IXUserDeviceImpl2 (no methods) 432 {0x0cc6a956, 0xe7e1, 0x4fdf, {0x93, 0x41, 0x9d, 0x5d, 0xa6, 0x49, 0xeb, 0xc8}}, // IXUserDeviceImpl2 (no methods)
432}; 433};
433 434
434// ASSUMPTION: APP_LOCAL_DEVICE_ID is 32 bytes (APP_LOCAL_DEVICE_ID_SIZE), not on the pages read for this file. 435// APP_LOCAL_DEVICE_ID is taken to be 32 bytes (APP_LOCAL_DEVICE_ID_SIZE), not on the pages read for this file. No
436// caller confirms it: the executable links no XUserDeviceImpl thunk (docs/runtime_imports.md).
435struct APP_LOCAL_DEVICE_ID { 437struct APP_LOCAL_DEVICE_ID {
436 uint8_t value[32]; 438 uint8_t value[32];
437}; 439};
diff --git a/runtime/shims/xgameruntime_store.cpp b/runtime/shims/xgameruntime_store.cpp
index 98403743a..800e4083f 100644
--- a/runtime/shims/xgameruntime_store.cpp
+++ b/runtime/shims/xgameruntime_store.cpp
@@ -12,13 +12,19 @@
12// service or a store UI (purchases, consumables, tokens, collections ids, downloads) fails before starting, so no 12// service or a store UI (purchases, consumables, tokens, collections ids, downloads) fails before starting, so no
13// XAsyncBlock waits, and logs once. License-changed and license-lost callbacks are never called: nothing changes. 13// XAsyncBlock waits, and logs once. License-changed and license-lost callbacks are never called: nothing changes.
14// 14//
15// ASSUMPTION (UNVERIFIED): STORE_SKU_ID_SIZE = 18, SKU_ID_SIZE = 5 and TRIAL_UNIQUE_ID_MAX_SIZE = 64, which fix the 15// XStoreGameLicense's layout is measured on the retail executable (docs/runtime_imports.md): the title's
16// layouts of XStoreGameLicense (104 bytes) and XStoreCanAcquireLicenseResult (12 bytes). The public pages name the 16// XStoreQueryGameLicenseResult call passes a 104-byte stack buffer and reads the SKU id as a C string at +0x00, the
17// constants without values; they are from memory of the GDK header and must be confirmed against the executable 17// three booleans at +0x13..+0x15, the trial id as a C string at +0x1C and the expiration time at +0x60. That fixes
18// (the stack buffer it passes to XStoreQueryGameLicenseResult) before a first boot relies on them. 18// STORE_SKU_ID_SIZE = 18 and the struct's 104-byte total.
19//
20// UNVERIFIED: SKU_ID_SIZE = 5 and the exact TRIAL_UNIQUE_ID_MAX_SIZE = 64. The executable does not call either
21// can-acquire slot (IXStoreImpl slots 24-27), so XStoreCanAcquireLicenseResult is unmeasured. It bounds the trial id
22// to at most 68 bytes (the expiration time is at +0x60) but reads it as a C string, so it does not name the bound;
23// 64 is the public source's value.
19#include <windows.h> 24#include <windows.h>
20 25
21#include <atomic> 26#include <atomic>
27#include <cstddef>
22#include <cstdint> 28#include <cstdint>
23#include <cstdio> 29#include <cstdio>
24#include <cstring> 30#include <cstring>
@@ -49,9 +55,9 @@ using XStoreContextHandle = XStoreContext*;
49using XStoreLicenseHandle = XStoreLicense*; 55using XStoreLicenseHandle = XStoreLicense*;
50using XStoreProductQueryHandle = XStoreProductQuery*; 56using XStoreProductQueryHandle = XStoreProductQuery*;
51 57
52constexpr size_t STORE_SKU_ID_SIZE = 18; // UNVERIFIED, see the header 58constexpr size_t STORE_SKU_ID_SIZE = 18; // measured, see the header
53constexpr size_t SKU_ID_SIZE = 5; // UNVERIFIED 59constexpr size_t SKU_ID_SIZE = 5; // UNVERIFIED; the executable has no call site for it
54constexpr size_t TRIAL_UNIQUE_ID_MAX_SIZE = 64; // UNVERIFIED 60constexpr size_t TRIAL_UNIQUE_ID_MAX_SIZE = 64; // public source; the executable bounds it to <= 68
55 61
56struct XStoreGameLicense { 62struct XStoreGameLicense {
57 char skuStoreId[STORE_SKU_ID_SIZE]; 63 char skuStoreId[STORE_SKU_ID_SIZE];
@@ -63,7 +69,11 @@ struct XStoreGameLicense {
63 char trialUniqueId[TRIAL_UNIQUE_ID_MAX_SIZE]; 69 char trialUniqueId[TRIAL_UNIQUE_ID_MAX_SIZE];
64 time_t expirationDate; 70 time_t expirationDate;
65}; 71};
66static_assert(sizeof(XStoreGameLicense) == 104, "the layout the UNVERIFIED constants give"); 72static_assert(sizeof(XStoreGameLicense) == 104, "the layout the executable's result buffer gives");
73// The offsets the executable's XStoreQueryGameLicenseResult caller reads (docs/runtime_imports.md).
74static_assert(offsetof(XStoreGameLicense, isTrialOwnedByThisUser) == 0x13, "measured flag offset");
75static_assert(offsetof(XStoreGameLicense, trialUniqueId) == 0x1C, "measured trial-id offset");
76static_assert(offsetof(XStoreGameLicense, expirationDate) == 0x60, "measured expiration offset");
67 77
68enum class XStoreCanLicenseStatus : uint32_t { NotLicensableToUser = 0, Licensable = 1, LicenseActionNotApplicableToProduct = 2 }; 78enum class XStoreCanLicenseStatus : uint32_t { NotLicensableToUser = 0, Licensable = 1, LicenseActionNotApplicableToProduct = 2 };
69struct XStoreCanAcquireLicenseResult { 79struct XStoreCanAcquireLicenseResult {
diff --git a/runtime/shims/xgameruntime_user.cpp b/runtime/shims/xgameruntime_user.cpp
index 0aa5b7ff1..e32395646 100644
--- a/runtime/shims/xgameruntime_user.cpp
+++ b/runtime/shims/xgameruntime_user.cpp
@@ -12,8 +12,9 @@
12// characters at most, "Player" otherwise). Nothing goes online: token and gamer-picture requests fail as they would 12// characters at most, "Player" otherwise). Nothing goes online: token and gamer-picture requests fail as they would
13// without a network, and the user never changes, so registered change callbacks are never called. 13// without a network, and the user never changes, so registered change callbacks are never called.
14// 14//
15// ASSUMPTION: the console executable is not available, so which of these slots it calls is unknown until its first 15// The executable links thunks for IXUserImpl slots 3-5, 7-14, 19-25 and 33-34 and IXUserGamertagImpl slot 3
16// boot. Private and PC-only slots log once when called, so that boot lists them. 16// (tools/gdk_runtime_calls.py, from the file alone; docs/runtime_imports.md). None of them is a private or PC-only
17// slot; those still log once when called.
17#include <windows.h> 18#include <windows.h>
18 19
19#include <atomic> 20#include <atomic>
diff --git a/runtime/shims/xmem.cpp b/runtime/shims/xmem.cpp
index e6ab2d43b..a1061af21 100644
--- a/runtime/shims/xmem.cpp
+++ b/runtime/shims/xmem.cpp
@@ -30,34 +30,35 @@
30namespace { 30namespace {
31 31
32constexpr size_t kAlign = 64; 32constexpr size_t kAlign = 64;
33constexpr size_t kNoSize = static_cast<size_t>(-1); // XMemFree has no size field
33 34
34// gta6rt --trace FILE: the first XMemAlloc and the first XMemFree for each distinct raw attribute word go to the 35// gta6rt --trace FILE: the first XMemAlloc, XMemFree and XMemVirtualAlloc call for each distinct raw attribute word go to the
35// startup trace as an "xmem_attributes" event (api, the word, the size for an allocation, the caller as module+RVA). The 36// startup trace as an "xmem_attributes" event (api, the word, the size for an allocation, the caller as module+RVA). The
36// bits of the attribute word are not known yet; this records them from a real run without logging every allocation, 37// bits of the attribute word are not known yet; this records them from a real run without logging every allocation,
37// which would fill the file. Off: one relaxed load per call. 38// which would fill the file. Off: one relaxed load per call.
38void note_attributes(bool is_alloc, uint64_t attributes, size_t size, const void* caller) { 39void note_attributes(const char* api, uint64_t attributes, size_t size, const void* caller) {
39 if (!rt::startup_trace::enabled()) return; 40 if (!rt::startup_trace::enabled()) return;
40 static std::mutex mutex; 41 static std::mutex mutex;
41 static std::set<std::pair<bool, uint64_t>> seen; 42 static std::set<std::pair<std::string, uint64_t>> seen;
42 { 43 {
43 const std::lock_guard lock(mutex); 44 const std::lock_guard lock(mutex);
44 if (!seen.insert({is_alloc, attributes}).second) return; 45 if (!seen.insert({api, attributes}).second) return;
45 } 46 }
46 std::string fields = std::string("\"api\":\"") + (is_alloc ? "XMemAlloc" : "XMemFree") + 47 std::string fields = std::string("\"api\":\"") + api +
47 "\",\"attributes\":" + rt::startup_trace::quote(rt::startup_trace::hex(attributes)); 48 "\",\"attributes\":" + rt::startup_trace::quote(rt::startup_trace::hex(attributes));
48 if (is_alloc) fields += ",\"size\":" + std::to_string(size); 49 if (size != kNoSize) fields += ",\"size\":" + std::to_string(size);
49 fields += ",\"caller\":" + 50 fields += ",\"caller\":" +
50 rt::startup_trace::quote(rt::startup_trace::where(reinterpret_cast<uint64_t>(caller))); 51 rt::startup_trace::quote(rt::startup_trace::where(reinterpret_cast<uint64_t>(caller)));
51 rt::startup_trace::event("xmem_attributes", fields); 52 rt::startup_trace::event("xmem_attributes", fields);
52} 53}
53 54
54void* __stdcall XMemAlloc(size_t size, uint64_t attributes) { 55void* __stdcall XMemAlloc(size_t size, uint64_t attributes) {
55 note_attributes(true, attributes, size, _ReturnAddress()); 56 note_attributes("XMemAlloc", attributes, size, _ReturnAddress());
56 return _aligned_malloc(size ? size : 1, kAlign); 57 return _aligned_malloc(size ? size : 1, kAlign);
57} 58}
58 59
59void __stdcall XMemFree(void* p, uint64_t attributes) { 60void __stdcall XMemFree(void* p, uint64_t attributes) {
60 note_attributes(false, attributes, 0, _ReturnAddress()); 61 note_attributes("XMemFree", attributes, kNoSize, _ReturnAddress());
61 _aligned_free(p); 62 _aligned_free(p);
62} 63}
63 64
@@ -141,18 +142,29 @@ bool round_up_size(SIZE_T value, SIZE_T alignment, SIZE_T& rounded) {
141 return true; 142 return true;
142} 143}
143 144
145// The console's PAGE_GRAPHICS_* protection bits (winnt.h: PAGE_GRAPHICS_NOACCESS 0x800 .. PAGE_GRAPHICS_NOCACHE
146// 0x40000). The host refuses them with ERROR_INVALID_PARAMETER, and the D3D12 layer reads guest memory through the
147// CPU mapping, so only the CPU protection is applied. The retail executable passes 0x801 and 0x22004.
148constexpr DWORD kPageGraphicsMask = 0x0007F800;
149
150DWORD host_protect(DWORD p) {
151 const DWORD cpu = p & ~kPageGraphicsMask;
152 return cpu ? cpu : PAGE_NOACCESS;
153}
154
144void* WINAPI XMemVirtualAlloc(void* address, SIZE_T size, DWORD allocation_type, ULONGLONG attributes, DWORD protect) { 155void* WINAPI XMemVirtualAlloc(void* address, SIZE_T size, DWORD allocation_type, ULONGLONG attributes, DWORD protect) {
145 // Host-backed support covers ordinary and 64 KiB guest reservations. The 2 MiB guest mode needs an aligned 156 // Host-backed support covers ordinary and 64 KiB guest reservations. The 2 MiB guest mode needs an aligned
146 // reservation strategy that this shim does not provide, so fail explicitly instead of returning a misaligned 157 // reservation strategy that this shim does not provide, so fail explicitly instead of returning a misaligned
147 // region. Nonzero attribute flags also fail until their host mapping is known. 158 // region.
159 //
160 // The attribute word is recorded, not applied, as for XMemAlloc: the host has no allocator ids or memory types.
161 // The retail executable passes 0x21, 0x3, 0x183, 0x283 and 0x181 and stops at an int3 when a reservation
162 // returns NULL, so refusing a nonzero word is not an option.
163 note_attributes("XMemVirtualAlloc", attributes, size, _ReturnAddress());
148 if (size == 0) { 164 if (size == 0) {
149 SetLastError(ERROR_INVALID_PARAMETER); 165 SetLastError(ERROR_INVALID_PARAMETER);
150 return nullptr; 166 return nullptr;
151 } 167 }
152 if (attributes != 0) {
153 SetLastError(ERROR_NOT_SUPPORTED);
154 return nullptr;
155 }
156 168
157 const DWORD page_mode = allocation_type & kXmemPageModeMask; 169 const DWORD page_mode = allocation_type & kXmemPageModeMask;
158 if (page_mode == kXmemLargePages) { 170 if (page_mode == kXmemLargePages) {
@@ -208,7 +220,7 @@ void* WINAPI XMemVirtualAlloc(void* address, SIZE_T size, DWORD allocation_type,
208 return nullptr; 220 return nullptr;
209 } 221 }
210 222
211 return VirtualAlloc(address, size, host_type, protect); 223 return VirtualAlloc(address, size, host_type, host_protect(protect));
212} 224}
213 225
214UINT WINAPI XMemGetWriteWatch(DWORD flags, void* base_address, SIZE_T region_size, void** addresses, ULONG_PTR* count, 226UINT WINAPI XMemGetWriteWatch(DWORD flags, void* base_address, SIZE_T region_size, void** addresses, ULONG_PTR* count,
@@ -271,13 +283,13 @@ BOOL WINAPI XMemTransferMemory(uint32_t type, SIZE_T size) {
271// with ERROR_INVALID_PARAMETER (measured on Windows 11 26200: VirtualAlloc(NULL, 64 KiB, MEM_COMMIT | MEM_RESERVE | 283// with ERROR_INVALID_PARAMETER (measured on Windows 11 26200: VirtualAlloc(NULL, 64 KiB, MEM_COMMIT | MEM_RESERVE |
272// 0x10000000, PAGE_READWRITE) returns NULL; so does 0x40000000), so an engine allocating its heaps this way gets 284// 0x10000000, PAGE_READWRITE) returns NULL; so does 0x40000000), so an engine allocating its heaps this way gets
273// NULL at boot. Both are hints about where the memory lives; the host has no such split, so they are dropped and 285// NULL at boot. Both are hints about where the memory lives; the host has no such split, so they are dropped and
274// the rest is passed through. Not done: the console protection bits, and whether graphics memory has to come from 286// the rest is passed through. The PAGE_GRAPHICS_* protection bits are dropped (host_protect). Not done: whether
275// an arena the D3D12 layer can see (#313). 287// graphics memory has to come from an arena the D3D12 layer can see (#313).
276constexpr DWORD kMemGraphics = 0x10000000; 288constexpr DWORD kMemGraphics = 0x10000000;
277constexpr DWORD kMemTitle = 0x40000000; 289constexpr DWORD kMemTitle = 0x40000000;
278 290
279LPVOID WINAPI TitleVirtualAlloc(LPVOID address, SIZE_T size, DWORD allocation_type, DWORD protect) { 291LPVOID WINAPI TitleVirtualAlloc(LPVOID address, SIZE_T size, DWORD allocation_type, DWORD protect) {
280 return VirtualAlloc(address, size, allocation_type & ~(kMemGraphics | kMemTitle), protect); 292 return VirtualAlloc(address, size, allocation_type & ~(kMemGraphics | kMemTitle), host_protect(protect));
281} 293}
282 294
283} // namespace 295} // namespace
diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h
index 5c36d44e3..36fee95af 100644
--- a/runtime/src/command_list.h
+++ b/runtime/src/command_list.h
@@ -414,9 +414,11 @@ struct DrawViews {
414 std::uint32_t render_target_count = 8; 414 std::uint32_t render_target_count = 8;
415}; 415};
416 416
417// DrawInstanced / DrawIndexedInstanced, with everything they use captured when they are recorded: D3D12 reads 417// DrawInstanced / DrawIndexedInstanced / DispatchMesh, with everything they use captured when they are recorded:
418// render-target and depth descriptors at OMSetRenderTargets, and every other piece of state is the list's state at 418// D3D12 reads render-target and depth descriptors at OMSetRenderTargets, and every other piece of state is the
419// the draw. resource 0 marks an unbound render-target slot or no depth buffer. 419// list's state at the draw. resource 0 marks an unbound render-target slot or no depth buffer. A mesh draw
420// (DispatchMesh) takes its thread-group counts in count (x), instances (y) and first (z), and ignores the vertex
421// and index buffers and the topology.
420// Render targets and vertex buffer views are inlined (8 simultaneous targets, 32 input slots), eliminating heap allocations 422// Render targets and vertex buffer views are inlined (8 simultaneous targets, 32 input slots), eliminating heap allocations
421// during command list recording (D3D-289). 423// during command list recording (D3D-289).
422struct Draw { 424struct Draw {
@@ -437,6 +439,7 @@ struct Draw {
437 std::uint32_t first = 0; // first vertex or first index 439 std::uint32_t first = 0; // first vertex or first index
438 std::int32_t base_vertex = 0; 440 std::int32_t base_vertex = 0;
439 std::uint32_t first_instance = 0; 441 std::uint32_t first_instance = 0;
442 bool mesh = false;
440}; 443};
441 444
442// D3D12_TEXTURE_DATA_PITCH_ALIGNMENT and D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT. 445// D3D12_TEXTURE_DATA_PITCH_ALIGNMENT and D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT.
@@ -738,10 +741,11 @@ public:
738 return append(dispatch); 741 return append(dispatch);
739 } 742 }
740 743
741 // A draw with no vertices or instances does nothing in D3D12, and is not recorded. 744 // A draw with no vertices or instances, or a mesh draw with no thread groups, does nothing in D3D12, and is
745 // not recorded.
742 bool draw(const Draw& draw) { 746 bool draw(const Draw& draw) {
743 if (!draw.pipeline) return false; 747 if (!draw.pipeline) return false;
744 if (!draw.count || !draw.instances) return !closed_; 748 if (!draw.count || !draw.instances || (draw.mesh && !draw.first)) return !closed_;
745 return append(draw); 749 return append(draw);
746 } 750 }
747 bool draw(Draw&& draw) { 751 bool draw(Draw&& draw) {
diff --git a/runtime/src/shader_library.h b/runtime/src/shader_library.h
index 4cc35d58a..c4cba63af 100644
--- a/runtime/src/shader_library.h
+++ b/runtime/src/shader_library.h
@@ -714,6 +714,10 @@ struct ShaderEntry {
714 // The S#s the shader builds from immediates (the index's literal_samplers): no heap slot names them, so a 714 // The S#s the shader builds from immediates (the index's literal_samplers): no heap slot names them, so a
715 // pipeline that uses the shader registers them in the bindless set itself (docs/design.md, Literal samplers). 715 // pipeline that uses the shader registers them in the bindless set itself (docs/design.md, Literal samplers).
716 std::vector<std::array<std::uint32_t, 4>> literal_samplers; 716 std::vector<std::array<std::uint32_t, 4>> literal_samplers;
717 // Mesh shaders: the output array sizes the SPIR-V declares (OutputVertices / OutputPrimitivesEXT), checked
718 // against the device's maxMeshOutputVertices / maxMeshOutputPrimitives when a pipeline is created. 0: not given.
719 std::uint32_t max_vertices = 0;
720 std::uint32_t max_primitives = 0;
717}; 721};
718 722
719class ShaderLibrary { 723class ShaderLibrary {
@@ -907,6 +911,8 @@ private:
907 e.literal_samplers.push_back(words); 911 e.literal_samplers.push_back(words);
908 } 912 }
909 } 913 }
914 e.max_vertices = u32(meta.find("max_vertices"));
915 e.max_primitives = u32(meta.find("max_primitives"));
910 if (by_fspx) fspx_entries_[{e.stage, e.fspx_code_sha256}].push_back(e); 916 if (by_fspx) fspx_entries_[{e.stage, e.fspx_code_sha256}].push_back(e);
911 if (by_fssm) entries_[{e.stage, e.fssm_sha256}].push_back(std::move(e)); 917 if (by_fssm) entries_[{e.stage, e.fssm_sha256}].push_back(std::move(e));
912 if (by_fspx && prefix == "fspx/") ++fspx_count_; 918 if (by_fspx && prefix == "fspx/") ++fspx_count_;
diff --git a/runtime/src/statistics_sum.comp b/runtime/src/statistics_sum.comp
index e4e2ce13c..c4960347c 100644
--- a/runtime/src/statistics_sum.comp
+++ b/runtime/src/statistics_sum.comp
@@ -2,18 +2,23 @@
2 2
3// Adds the D3D12_QUERY_DATA_PIPELINE_STATISTICS segments of one split pipeline-statistics query (D3D-162): one 3// Adds the D3D12_QUERY_DATA_PIPELINE_STATISTICS segments of one split pipeline-statistics query (D3D-162): one
4// invocation per counter, in the order of VkQueryPipelineStatisticFlagBits, which is the D3D12 field order. 4// invocation per counter, in the order of VkQueryPipelineStatisticFlagBits, which is the D3D12 field order.
5// `mesh` segments come from the pool a mesh draw can run in (D3D-291), which counts only clipping, fragment and
6// compute: they are copied to counters 5..8 of their record, so CSInvocations sits at 8 and the input-assembly,
7// vertex, geometry and tessellation counters (0..4, 8 and 9 of the D3D12 order) add nothing.
5layout(local_size_x = 11) in; 8layout(local_size_x = 11) in;
6layout(set = 0, binding = 0, std430) buffer QueryResults { 9layout(set = 0, binding = 0, std430) buffer QueryResults {
7 uvec2 total[11]; 10 uvec2 total[11];
8 uvec2 segments[]; // `count` results of 11 counters each 11 uvec2 segments[]; // `count` results of 11 counters each
9}; 12};
10layout(push_constant) uniform ResolveRange { uint count; }; 13layout(push_constant) uniform ResolveRange { uint count; uint mesh; };
11 14
12void main() { 15void main() {
13 const uint counter = gl_LocalInvocationID.x; 16 const uint counter = gl_LocalInvocationID.x;
14 uvec2 sum = total[counter]; 17 uvec2 sum = total[counter];
15 for (uint i = 0; i < count; ++i) { 18 const bool counted = mesh == 0u || (counter >= 5u && counter <= 7u) || counter == 10u;
16 uvec2 segment = segments[i * 11 + counter]; 19 const uint source = mesh != 0u && counter == 10u ? 8u : counter;
20 for (uint i = 0; counted && i < count; ++i) {
21 uvec2 segment = segments[i * 11 + source];
17 uint low = sum.x + segment.x; 22 uint low = sum.x + segment.x;
18 sum.y += segment.y + uint(low < sum.x); 23 sum.y += segment.y + uint(low < sum.x);
19 sum.x = low; 24 sum.x = low;
diff --git a/runtime/src/statistics_sum_spirv.h b/runtime/src/statistics_sum_spirv.h
index d3c0709a5..9c67f0429 100644
--- a/runtime/src/statistics_sum_spirv.h
+++ b/runtime/src/statistics_sum_spirv.h
@@ -7,47 +7,63 @@ namespace leonida {
7// From statistics_sum.comp. Compile with glslangValidator -V --target-env vulkan1.0 -Os -g0, 7// From statistics_sum.comp. Compile with glslangValidator -V --target-env vulkan1.0 -Os -g0,
8// then encode the little-endian SPIR-V as uint32_t words. No shader compiler is needed at runtime build time. 8// then encode the little-endian SPIR-V as uint32_t words. No shader compiler is needed at runtime build time.
9inline constexpr std::uint32_t statistics_sum_spirv[] = { 9inline constexpr std::uint32_t statistics_sum_spirv[] = {
10 0x07230203, 0x00010000, 0x0008000b, 0x0000005e, 0x00000000, 0x00020011, 0x00000001, 0x0006000b, 10 0x07230203, 0x00010000, 0x0008000b, 0x00000080, 0x00000000, 0x00020011, 0x00000001, 0x0006000b,
11 0x00000001, 0x4c534c47, 0x6474732e, 0x3035342e, 0x00000000, 0x0003000e, 0x00000000, 0x00000001, 11 0x00000001, 0x4c534c47, 0x6474732e, 0x3035342e, 0x00000000, 0x0003000e, 0x00000000, 0x00000001,
12 0x0006000f, 0x00000005, 0x00000004, 0x6e69616d, 0x00000000, 0x0000000b, 0x00060010, 0x00000004, 12 0x0006000f, 0x00000005, 0x00000004, 0x6e69616d, 0x00000000, 0x0000000b, 0x00060010, 0x00000004,
13 0x00000011, 0x0000000b, 0x00000001, 0x00000001, 0x00040047, 0x0000000b, 0x0000000b, 0x0000001b, 13 0x00000011, 0x0000000b, 0x00000001, 0x00000001, 0x00040047, 0x0000000b, 0x0000000b, 0x0000001b,
14 0x00040047, 0x00000014, 0x00000006, 0x00000008, 0x00040047, 0x00000015, 0x00000006, 0x00000008, 14 0x00040047, 0x00000014, 0x00000006, 0x00000008, 0x00040047, 0x00000015, 0x00000006, 0x00000008,
15 0x00030047, 0x00000016, 0x00000003, 0x00050048, 0x00000016, 0x00000000, 0x00000023, 0x00000000, 15 0x00030047, 0x00000016, 0x00000003, 0x00050048, 0x00000016, 0x00000000, 0x00000023, 0x00000000,
16 0x00050048, 0x00000016, 0x00000001, 0x00000023, 0x00000058, 0x00040047, 0x00000018, 0x00000021, 16 0x00050048, 0x00000016, 0x00000001, 0x00000023, 0x00000058, 0x00040047, 0x00000018, 0x00000021,
17 0x00000000, 0x00040047, 0x00000018, 0x00000022, 0x00000000, 0x00030047, 0x00000026, 0x00000002, 17 0x00000000, 0x00040047, 0x00000018, 0x00000022, 0x00000000, 0x00030047, 0x00000022, 0x00000002,
18 0x00050048, 0x00000026, 0x00000000, 0x00000023, 0x00000000, 0x00040047, 0x00000050, 0x0000000b, 18 0x00050048, 0x00000022, 0x00000000, 0x00000023, 0x00000000, 0x00050048, 0x00000022, 0x00000001,
19 0x00000019, 0x00020013, 0x00000002, 0x00030021, 0x00000003, 0x00000002, 0x00040015, 0x00000006, 19 0x00000023, 0x00000004, 0x00040047, 0x00000072, 0x0000000b, 0x00000019, 0x00020013, 0x00000002,
20 0x00000020, 0x00000000, 0x00040017, 0x00000009, 0x00000006, 0x00000003, 0x00040020, 0x0000000a, 20 0x00030021, 0x00000003, 0x00000002, 0x00040015, 0x00000006, 0x00000020, 0x00000000, 0x00040017,
21 0x00000001, 0x00000009, 0x0004003b, 0x0000000a, 0x0000000b, 0x00000001, 0x0004002b, 0x00000006, 21 0x00000009, 0x00000006, 0x00000003, 0x00040020, 0x0000000a, 0x00000001, 0x00000009, 0x0004003b,
22 0x0000000c, 0x00000000, 0x00040020, 0x0000000d, 0x00000001, 0x00000006, 0x00040017, 0x00000010, 22 0x0000000a, 0x0000000b, 0x00000001, 0x0004002b, 0x00000006, 0x0000000c, 0x00000000, 0x00040020,
23 0x00000006, 0x00000002, 0x0004002b, 0x00000006, 0x00000013, 0x0000000b, 0x0004001c, 0x00000014, 23 0x0000000d, 0x00000001, 0x00000006, 0x00040017, 0x00000010, 0x00000006, 0x00000002, 0x0004002b,
24 0x00000010, 0x00000013, 0x0003001d, 0x00000015, 0x00000010, 0x0004001e, 0x00000016, 0x00000014, 24 0x00000006, 0x00000013, 0x0000000b, 0x0004001c, 0x00000014, 0x00000010, 0x00000013, 0x0003001d,
25 0x00000015, 0x00040020, 0x00000017, 0x00000002, 0x00000016, 0x0004003b, 0x00000017, 0x00000018, 25 0x00000015, 0x00000010, 0x0004001e, 0x00000016, 0x00000014, 0x00000015, 0x00040020, 0x00000017,
26 0x00000002, 0x00040015, 0x00000019, 0x00000020, 0x00000001, 0x0004002b, 0x00000019, 0x0000001a, 26 0x00000002, 0x00000016, 0x0004003b, 0x00000017, 0x00000018, 0x00000002, 0x00040015, 0x00000019,
27 0x00000000, 0x00040020, 0x0000001c, 0x00000002, 0x00000010, 0x0003001e, 0x00000026, 0x00000006, 27 0x00000020, 0x00000001, 0x0004002b, 0x00000019, 0x0000001a, 0x00000000, 0x00040020, 0x0000001c,
28 0x00040020, 0x00000027, 0x00000009, 0x00000026, 0x0004003b, 0x00000027, 0x00000028, 0x00000009, 28 0x00000002, 0x00000010, 0x00020014, 0x0000001f, 0x0004001e, 0x00000022, 0x00000006, 0x00000006,
29 0x00040020, 0x00000029, 0x00000009, 0x00000006, 0x00020014, 0x0000002c, 0x0004002b, 0x00000019, 29 0x00040020, 0x00000023, 0x00000009, 0x00000022, 0x0004003b, 0x00000023, 0x00000024, 0x00000009,
30 0x0000002f, 0x00000001, 0x0004002b, 0x00000006, 0x0000003c, 0x00000001, 0x0006002c, 0x00000009, 30 0x0004002b, 0x00000019, 0x00000025, 0x00000001, 0x00040020, 0x00000026, 0x00000009, 0x00000006,
31 0x00000050, 0x00000013, 0x0000003c, 0x0000003c, 0x00050036, 0x00000002, 0x00000004, 0x00000000, 31 0x0004002b, 0x00000006, 0x0000002e, 0x00000005, 0x0004002b, 0x00000006, 0x00000031, 0x00000007,
32 0x00000003, 0x000200f8, 0x00000005, 0x00050041, 0x0000000d, 0x0000000e, 0x0000000b, 0x0000000c, 32 0x0004002b, 0x00000006, 0x00000036, 0x0000000a, 0x0004002b, 0x00000006, 0x00000040, 0x00000008,
33 0x0004003d, 0x00000006, 0x0000000f, 0x0000000e, 0x00060041, 0x0000001c, 0x0000001d, 0x00000018, 33 0x0004002b, 0x00000006, 0x0000005e, 0x00000001, 0x0006002c, 0x00000009, 0x00000072, 0x00000013,
34 0x0000001a, 0x0000000f, 0x0004003d, 0x00000010, 0x0000001e, 0x0000001d, 0x000200f9, 0x00000020, 34 0x0000005e, 0x0000005e, 0x00050036, 0x00000002, 0x00000004, 0x00000000, 0x00000003, 0x000200f8,
35 0x000200f8, 0x00000020, 0x000700f5, 0x00000010, 0x0000005c, 0x0000001e, 0x00000005, 0x0000005d, 35 0x00000005, 0x00050041, 0x0000000d, 0x0000000e, 0x0000000b, 0x0000000c, 0x0004003d, 0x00000006,
36 0x00000021, 0x000700f5, 0x00000006, 0x00000051, 0x0000000c, 0x00000005, 0x0000004c, 0x00000021, 36 0x0000000f, 0x0000000e, 0x00060041, 0x0000001c, 0x0000001d, 0x00000018, 0x0000001a, 0x0000000f,
37 0x00050041, 0x00000029, 0x0000002a, 0x00000028, 0x0000001a, 0x0004003d, 0x00000006, 0x0000002b, 37 0x0004003d, 0x00000010, 0x0000001e, 0x0000001d, 0x00050041, 0x00000026, 0x00000027, 0x00000024,
38 0x0000002a, 0x000500b0, 0x0000002c, 0x0000002d, 0x00000051, 0x0000002b, 0x000400f6, 0x00000022, 38 0x00000025, 0x0004003d, 0x00000006, 0x00000028, 0x00000027, 0x000500aa, 0x0000001f, 0x00000029,
39 0x00000021, 0x00000000, 0x000400fa, 0x0000002d, 0x00000021, 0x00000022, 0x000200f8, 0x00000021, 39 0x00000028, 0x0000000c, 0x000400a8, 0x0000001f, 0x0000002a, 0x00000029, 0x000300f7, 0x0000002c,
40 0x00050084, 0x00000006, 0x00000031, 0x00000051, 0x00000013, 0x00050080, 0x00000006, 0x00000033, 40 0x00000000, 0x000400fa, 0x0000002a, 0x0000002b, 0x0000002c, 0x000200f8, 0x0000002b, 0x000500ae,
41 0x00000031, 0x0000000f, 0x00060041, 0x0000001c, 0x00000034, 0x00000018, 0x0000002f, 0x00000033, 41 0x0000001f, 0x0000002f, 0x0000000f, 0x0000002e, 0x000500b2, 0x0000001f, 0x00000032, 0x0000000f,
42 0x0004003d, 0x00000010, 0x00000035, 0x00000034, 0x00050051, 0x00000006, 0x00000038, 0x0000005c, 42 0x00000031, 0x000500a7, 0x0000001f, 0x00000033, 0x0000002f, 0x00000032, 0x000200f9, 0x0000002c,
43 0x00000000, 0x00050051, 0x00000006, 0x0000003a, 0x00000035, 0x00000000, 0x00050080, 0x00000006, 43 0x000200f8, 0x0000002c, 0x000700f5, 0x0000001f, 0x00000034, 0x00000029, 0x00000005, 0x00000033,
44 0x0000003b, 0x00000038, 0x0000003a, 0x00050051, 0x00000006, 0x0000003e, 0x00000035, 0x00000001, 44 0x0000002b, 0x000500aa, 0x0000001f, 0x00000037, 0x0000000f, 0x00000036, 0x000500a6, 0x0000001f,
45 0x000500b0, 0x0000002c, 0x00000042, 0x0000003b, 0x00000038, 0x000600a9, 0x00000006, 0x00000043, 45 0x00000038, 0x00000034, 0x00000037, 0x000500ab, 0x0000001f, 0x0000003c, 0x00000028, 0x0000000c,
46 0x00000042, 0x0000003c, 0x0000000c, 0x00050080, 0x00000006, 0x00000044, 0x0000003e, 0x00000043, 46 0x000500a7, 0x0000001f, 0x0000003f, 0x0000003c, 0x00000037, 0x000600a9, 0x00000006, 0x00000042,
47 0x00050051, 0x00000006, 0x00000046, 0x0000005c, 0x00000001, 0x00050080, 0x00000006, 0x00000047, 47 0x0000003f, 0x00000040, 0x0000000f, 0x000200f9, 0x00000044, 0x000200f8, 0x00000044, 0x000700f5,
48 0x00000046, 0x00000044, 0x00050050, 0x00000010, 0x0000005d, 0x0000003b, 0x00000047, 0x00050080, 48 0x00000010, 0x0000007f, 0x0000001e, 0x0000002c, 0x0000007c, 0x00000045, 0x000700f5, 0x00000006,
49 0x00000006, 0x0000004c, 0x00000051, 0x0000002f, 0x000200f9, 0x00000020, 0x000200f8, 0x00000022, 49 0x0000007d, 0x0000000c, 0x0000002c, 0x0000006e, 0x00000045, 0x000400f6, 0x00000046, 0x00000045,
50 0x0003003e, 0x0000001d, 0x0000005c, 0x000100fd, 0x00010038, 50 0x00000000, 0x000200f9, 0x00000048, 0x000200f8, 0x00000048, 0x000300f7, 0x0000004b, 0x00000000,
51 0x000400fa, 0x00000038, 0x0000004a, 0x0000004b, 0x000200f8, 0x0000004a, 0x00050041, 0x00000026,
52 0x0000004d, 0x00000024, 0x0000001a, 0x0004003d, 0x00000006, 0x0000004e, 0x0000004d, 0x000500b0,
53 0x0000001f, 0x0000004f, 0x0000007d, 0x0000004e, 0x000200f9, 0x0000004b, 0x000200f8, 0x0000004b,
54 0x000700f5, 0x0000001f, 0x00000050, 0x00000038, 0x00000048, 0x0000004f, 0x0000004a, 0x000400fa,
55 0x00000050, 0x00000045, 0x00000046, 0x000200f8, 0x00000045, 0x00050084, 0x00000006, 0x00000053,
56 0x0000007d, 0x00000013, 0x00050080, 0x00000006, 0x00000055, 0x00000053, 0x00000042, 0x00060041,
57 0x0000001c, 0x00000056, 0x00000018, 0x00000025, 0x00000055, 0x0004003d, 0x00000010, 0x00000057,
58 0x00000056, 0x00050051, 0x00000006, 0x0000005a, 0x0000007f, 0x00000000, 0x00050051, 0x00000006,
59 0x0000005c, 0x00000057, 0x00000000, 0x00050080, 0x00000006, 0x0000005d, 0x0000005a, 0x0000005c,
60 0x00050051, 0x00000006, 0x00000060, 0x00000057, 0x00000001, 0x000500b0, 0x0000001f, 0x00000064,
61 0x0000005d, 0x0000005a, 0x000600a9, 0x00000006, 0x00000065, 0x00000064, 0x0000005e, 0x0000000c,
62 0x00050080, 0x00000006, 0x00000066, 0x00000060, 0x00000065, 0x00050051, 0x00000006, 0x00000068,
63 0x0000007f, 0x00000001, 0x00050080, 0x00000006, 0x00000069, 0x00000068, 0x00000066, 0x00050050,
64 0x00000010, 0x0000007c, 0x0000005d, 0x00000069, 0x00050080, 0x00000006, 0x0000006e, 0x0000007d,
65 0x00000025, 0x000200f9, 0x00000044, 0x000200f8, 0x00000046, 0x0003003e, 0x0000001d, 0x0000007f,
66 0x000100fd, 0x00010038,
51}; 67};
52 68
53} // namespace leonida 69} // namespace leonida
diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h
index dc042bf73..e659a762d 100644
--- a/runtime/src/vulkan_backend.h
+++ b/runtime/src/vulkan_backend.h
@@ -96,16 +96,17 @@ struct VulkanDeviceFunctions {
96 X(vkCmdSetBlendConstants) X(vkCmdDraw) \ 96 X(vkCmdSetBlendConstants) X(vkCmdDraw) \
97 X(vkCmdDrawIndexed) X(vkCreateGraphicsPipelines) X(vkQueueBindSparse) X(vkGetImageSparseMemoryRequirements) \ 97 X(vkCmdDrawIndexed) X(vkCreateGraphicsPipelines) X(vkQueueBindSparse) X(vkGetImageSparseMemoryRequirements) \
98 X(vkCreatePipelineCache) X(vkDestroyPipelineCache) \ 98 X(vkCreatePipelineCache) X(vkDestroyPipelineCache) \
99 X(vkCreateEvent) X(vkDestroyEvent) X(vkResetEvent) X(vkCmdSetEvent) X(vkCmdWaitEvents) \ 99 X(vkCreateEvent) X(vkDestroyEvent) X(vkResetEvent) X(vkCmdSetEvent) X(vkCmdWaitEvents) X(vkCmdDrawMeshTasksEXT) \
100 X(vkCreateRenderPass2) X(vkDestroyRenderPass) X(vkCreateFramebuffer) X(vkDestroyFramebuffer) \ 100 X(vkCreateRenderPass2) X(vkDestroyRenderPass) X(vkCreateFramebuffer) X(vkDestroyFramebuffer) \
101 X(vkCmdBeginRenderPass) X(vkCmdEndRenderPass) 101 X(vkCmdBeginRenderPass) X(vkCmdEndRenderPass)
102#define LEONIDA_VK_MEMBER(name) PFN_##name name = nullptr; 102#define LEONIDA_VK_MEMBER(name) PFN_##name name = nullptr;
103 LEONIDA_VK_DEVICE_FUNCTIONS(LEONIDA_VK_MEMBER) 103 LEONIDA_VK_DEVICE_FUNCTIONS(LEONIDA_VK_MEMBER)
104#undef LEONIDA_VK_MEMBER 104#undef LEONIDA_VK_MEMBER
105 105
106 // The Vulkan 1.3 entry points may be null on older devices, the extension ones (conditional rendering) when the 106 // The Vulkan 1.3 entry points may be null on older devices, the extension ones (conditional rendering, mesh
107 // extension is not enabled, and the query functions are optional (a list that uses queries without them is 107 // shaders) when the extension is not enabled, and the query functions are optional (a list that uses queries
108 // unsupported). The compute and descriptor functions are needed for normalized or summed occlusion results. 108 // without them is unsupported). The compute and descriptor functions are needed for normalized or summed
109 // occlusion results.
109 bool load(PFN_vkGetDeviceProcAddr get, VkDevice device) { 110 bool load(PFN_vkGetDeviceProcAddr get, VkDevice device) {
110#define LEONIDA_VK_LOAD(name) name = reinterpret_cast<PFN_##name>(leonida::device_proc_or_khr(get, device, #name)); 111#define LEONIDA_VK_LOAD(name) name = reinterpret_cast<PFN_##name>(leonida::device_proc_or_khr(get, device, #name));
111 LEONIDA_VK_DEVICE_FUNCTIONS(LEONIDA_VK_LOAD) 112 LEONIDA_VK_DEVICE_FUNCTIONS(LEONIDA_VK_LOAD)
@@ -211,7 +212,8 @@ public:
211 write.pBufferInfo = &storage; 212 write.pBufferInfo = &storage;
212 vk_.vkUpdateDescriptorSets(device_, 1, &write, 0, nullptr); 213 vk_.vkUpdateDescriptorSets(device_, 1, &write, 0, nullptr);
213 214
214 const VkPushConstantRange count{VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(std::uint32_t)}; 215 // The count, and for statistics_sum.comp whether the segments are mesh-pool results.
216 const VkPushConstantRange count{VK_SHADER_STAGE_COMPUTE_BIT, 0, 2 * sizeof(std::uint32_t)};
215 VkPipelineLayoutCreateInfo layout{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; 217 VkPipelineLayoutCreateInfo layout{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO};
216 layout.setLayoutCount = 1; 218 layout.setLayoutCount = 1;
217 layout.pSetLayouts = &set_layout_; 219 layout.pSetLayouts = &set_layout_;
@@ -231,21 +233,28 @@ public:
231 create_pipeline(statistics_sum_spirv, statistics_pipeline_)); 233 create_pipeline(statistics_sum_spirv, statistics_pipeline_));
232 } 234 }
233 235
234 // Adds `count` pipeline-statistics results (11 counters each) into one D3D12_QUERY_DATA_PIPELINE_STATISTICS at 236 // Adds `count` pipeline-statistics results into one D3D12_QUERY_DATA_PIPELINE_STATISTICS at dst + offset: the
235 // dst + offset: the segments of a statistics query that was split around helper dispatches (D3D-162). 237 // segments of a statistics query that was split around helper dispatches (D3D-162) or mesh draws (D3D-291).
236 void sum_statistics(VkCommandBuffer cb, VkQueryPool queries, std::uint32_t first, std::uint32_t count, 238 // Segment i is in `mesh_queries` when mesh[i] is set (four counters: clipping, fragment and compute; see
237 VkBuffer dst, VkDeviceSize offset) const { 239 // statistics_sum.comp), otherwise in `queries` (all eleven).
240 void sum_statistics(VkCommandBuffer cb, VkQueryPool queries, VkQueryPool mesh_queries, const std::uint8_t* mesh,
241 std::uint32_t first, std::uint32_t count, VkBuffer dst, VkDeviceSize offset) const {
238 constexpr VkDeviceSize result = statistics_counters * word_size; 242 constexpr VkDeviceSize result = statistics_counters * word_size;
243 constexpr VkDeviceSize mesh_slot = 5 * word_size; // CInvocations, where the mesh pool's first counter goes
239 begin_scratch_write(cb); 244 begin_scratch_write(cb);
240 vk_.vkCmdFillBuffer(cb, scratch_, 0, result, 0); 245 vk_.vkCmdFillBuffer(cb, scratch_, 0, result, 0);
241 bind(cb, statistics_pipeline_); 246 bind(cb, statistics_pipeline_);
242 while (count) { 247 while (count) {
243 const auto chunk = std::min(count, statistics_capacity); 248 const bool in_mesh = mesh && mesh[first];
244 vk_.vkCmdCopyQueryPoolResults(cb, queries, first, chunk, scratch_, result, result, 249 std::uint32_t chunk = 1;
250 while (chunk < std::min(count, statistics_capacity) && bool(mesh && mesh[first + chunk]) == in_mesh)
251 ++chunk;
252 vk_.vkCmdCopyQueryPoolResults(cb, in_mesh ? mesh_queries : queries, first, chunk, scratch_,
253 result + (in_mesh ? mesh_slot : 0), result,
245 VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT); 254 VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT);
246 barrier(cb, transfer | compute, compute, VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_SHADER_WRITE_BIT, 255 barrier(cb, transfer | compute, compute, VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_SHADER_WRITE_BIT,
247 shader_access); 256 shader_access);
248 dispatch(cb, chunk, 1); 257 dispatch(cb, chunk, 1, in_mesh);
249 first += chunk; 258 first += chunk;
250 count -= chunk; 259 count -= chunk;
251 if (count) barrier(cb, compute, transfer, shader_access, VK_ACCESS_TRANSFER_WRITE_BIT); 260 if (count) barrier(cb, compute, transfer, shader_access, VK_ACCESS_TRANSFER_WRITE_BIT);
@@ -339,8 +348,9 @@ private:
339 vk_.vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_COMPUTE, layout_, 0, 1, &set_, 0, nullptr); 348 vk_.vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_COMPUTE, layout_, 0, 1, &set_, 0, nullptr);
340 } 349 }
341 350
342 void dispatch(VkCommandBuffer cb, std::uint32_t chunk, std::uint32_t groups) const { 351 void dispatch(VkCommandBuffer cb, std::uint32_t chunk, std::uint32_t groups, bool mesh = false) const {
343 vk_.vkCmdPushConstants(cb, layout_, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(chunk), &chunk); 352 const std::uint32_t range[2] = {chunk, mesh ? 1u : 0u};
353 vk_.vkCmdPushConstants(cb, layout_, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(range), range);
344 vk_.vkCmdDispatch(cb, groups, 1, 1); 354 vk_.vkCmdDispatch(cb, groups, 1, 1);
345 } 355 }
346 356
@@ -956,6 +966,7 @@ public:
956 replay_.set_stencil_reference = vk.vkCmdSetStencilReference; 966 replay_.set_stencil_reference = vk.vkCmdSetStencilReference;
957 replay_.set_blend_constants = vk.vkCmdSetBlendConstants; 967 replay_.set_blend_constants = vk.vkCmdSetBlendConstants;
958 replay_.draw = vk.vkCmdDraw; 968 replay_.draw = vk.vkCmdDraw;
969 replay_.draw_mesh_tasks = vk.vkCmdDrawMeshTasksEXT; // null unless VK_EXT_mesh_shader is enabled
959 replay_.draw_indexed = vk.vkCmdDrawIndexed; 970 replay_.draw_indexed = vk.vkCmdDrawIndexed;
960 replay_.graphics_pipeline = [this](std::uintptr_t id) -> const GraphicsPipeline* { 971 replay_.graphics_pipeline = [this](std::uintptr_t id) -> const GraphicsPipeline* {
961 const auto it = graphics_pipelines_.find(id); 972 const auto it = graphics_pipelines_.find(id);
@@ -2276,9 +2287,10 @@ private:
2276 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { 2287 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) {
2277 occlusion_resolve_->normalize(cb, pool, first, count, dst, offset); 2288 occlusion_resolve_->normalize(cb, pool, first, count, dst, offset);
2278 }; 2289 };
2279 replay.sum_statistics = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first, 2290 replay.sum_statistics = [this](VkCommandBuffer cb, VkQueryPool pool, VkQueryPool mesh_pool,
2280 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { 2291 const std::uint8_t* mesh, std::uint32_t first, std::uint32_t count,
2281 occlusion_resolve_->sum_statistics(cb, pool, first, count, dst, offset); 2292 VkBuffer dst, VkDeviceSize offset) {
2293 occlusion_resolve_->sum_statistics(cb, pool, mesh_pool, mesh, first, count, dst, offset);
2282 }; 2294 };
2283 replay.sum_binary_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first, 2295 replay.sum_binary_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first,
2284 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { 2296 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) {
@@ -2314,10 +2326,31 @@ private:
2314 }; 2326 };
2315 std::shared_ptr<OcclusionSegmentPool> physical, statistics; 2327 std::shared_ptr<OcclusionSegmentPool> physical, statistics;
2316 if (segments && !segment_pool(VK_QUERY_TYPE_OCCLUSION, segments, physical)) return ReplayResult::unsupported; 2328 if (segments && !segment_pool(VK_QUERY_TYPE_OCCLUSION, segments, physical)) return ReplayResult::unsupported;
2317 // Without the compute helper a split query could not be summed: leave statistics queries whole, as before. 2329 // Without the compute helper a split query could not be summed: leave statistics queries whole, as before
2318 if (statistics_segments && can_resolve_occlusion && 2330 // (QueryReplay::plan refuses a list whose statistics query holds a mesh draw then).
2319 !segment_pool(VK_QUERY_TYPE_PIPELINE_STATISTICS, statistics_segments, statistics)) 2331 if (statistics_segments && can_resolve_occlusion) {
2320 return ReplayResult::unsupported; 2332 if (!segment_pool(VK_QUERY_TYPE_PIPELINE_STATISTICS, statistics_segments, statistics))
2333 return ReplayResult::unsupported;
2334 for (const auto& list : prepared)
2335 statistics->mesh.insert(statistics->mesh.end(), list.statistics_mesh.begin(),
2336 list.statistics_mesh.end());
2337 if (std::find(statistics->mesh.begin(), statistics->mesh.end(), 1) == statistics->mesh.end()) {
2338 statistics->mesh.clear();
2339 } else {
2340 // The counters a mesh draw allows (VUID-vkCmdDrawMeshTasksEXT-pipelineStatistics-07076): clipping
2341 // invocations and primitives, fragment and compute invocations (D3D-291).
2342 VkQueryPoolCreateInfo info{VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO};
2343 info.queryType = VK_QUERY_TYPE_PIPELINE_STATISTICS;
2344 info.queryCount = statistics_segments;
2345 info.pipelineStatistics = VK_QUERY_PIPELINE_STATISTIC_CLIPPING_INVOCATIONS_BIT |
2346 VK_QUERY_PIPELINE_STATISTIC_CLIPPING_PRIMITIVES_BIT |
2347 VK_QUERY_PIPELINE_STATISTIC_FRAGMENT_SHADER_INVOCATIONS_BIT |
2348 VK_QUERY_PIPELINE_STATISTIC_COMPUTE_SHADER_INVOCATIONS_BIT;
2349 if (context_.vk.vkCreateQueryPool(statistics->device, &info, nullptr, &statistics->mesh_pool) !=
2350 VK_SUCCESS)
2351 return ReplayResult::unsupported;
2352 }
2353 }
2321 // QueryReplay::plan() reads QueryPool::ended / occlusion and QueryReplay::commit() writes them after 2354 // QueryReplay::plan() reads QueryPool::ended / occlusion and QueryReplay::commit() writes them after
2322 // resource_lock is unlocked. Hold tracker_mutex_ across plan -> emit -> submit -> commit so concurrent queues 2355 // resource_lock is unlocked. Hold tracker_mutex_ across plan -> emit -> submit -> commit so concurrent queues
2323 // see submission-order query state and remove_query_pool() waits until commit finishes. 2356 // see submission-order query state and remove_query_pool() waits until commit finishes.
diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h
index 49efd399d..1e0e598c7 100644
--- a/runtime/src/vulkan_replay.h
+++ b/runtime/src/vulkan_replay.h
@@ -709,11 +709,18 @@ struct OcclusionSegmentPool {
709 VkDevice device = VK_NULL_HANDLE; 709 VkDevice device = VK_NULL_HANDLE;
710 PFN_vkDestroyQueryPool destroy = nullptr; 710 PFN_vkDestroyQueryPool destroy = nullptr;
711 VkQueryPool pool = VK_NULL_HANDLE; 711 VkQueryPool pool = VK_NULL_HANDLE;
712 // Pipeline-statistics segments only: a second pool with the counters a mesh draw allows (D3D-291), and for each
713 // segment index whether it runs there. Empty when no segment of the submission holds a mesh draw.
714 VkQueryPool mesh_pool = VK_NULL_HANDLE;
715 std::vector<std::uint8_t> mesh;
712 716
713 OcclusionSegmentPool() = default; 717 OcclusionSegmentPool() = default;
714 OcclusionSegmentPool(const OcclusionSegmentPool&) = delete; 718 OcclusionSegmentPool(const OcclusionSegmentPool&) = delete;
715 OcclusionSegmentPool& operator=(const OcclusionSegmentPool&) = delete; 719 OcclusionSegmentPool& operator=(const OcclusionSegmentPool&) = delete;
716 ~OcclusionSegmentPool() { if (pool) destroy(device, pool, nullptr); } 720 ~OcclusionSegmentPool() {
721 if (pool) destroy(device, pool, nullptr);
722 if (mesh_pool) destroy(device, mesh_pool, nullptr);
723 }
717}; 724};
718 725
719struct OcclusionResult { 726struct OcclusionResult {
@@ -758,6 +765,7 @@ struct GraphicsPipeline {
758 std::uint32_t vertex_slots = 0; // bit per input slot the input layout uses 765 std::uint32_t vertex_slots = 0; // bit per input slot the input layout uses
759 std::uint32_t zero_step_slots = 0; // per-instance slots with InstanceDataStepRate 0: stride 0 at draw time 766 std::uint32_t zero_step_slots = 0; // per-instance slots with InstanceDataStepRate 0: stride 0 at draw time
760 std::uint32_t strip_cut = 0; // D3D12_INDEX_BUFFER_STRIP_CUT_VALUE (0: off, 1: 0xFFFF, 2: 0xFFFFFFFF) 767 std::uint32_t strip_cut = 0; // D3D12_INDEX_BUFFER_STRIP_CUT_VALUE (0: off, 1: 0xFFFF, 2: 0xFFFFFFFF)
768 bool mesh = false; // a mesh shader instead of a vertex shader: drawn by DispatchMesh only
761 // The same pipeline with some attachment formats VK_FORMAT_UNDEFINED, for a draw that leaves those slots 769 // The same pipeline with some attachment formats VK_FORMAT_UNDEFINED, for a draw that leaves those slots
762 // unbound (D3D12 allows it; dynamic rendering needs the formats to agree). Bit i: colour slot i, bit 8: depth 770 // unbound (D3D12 allows it; dynamic rendering needs the formats to agree). Bit i: colour slot i, bit 8: depth
763 // and stencil. Null when it cannot be built. 771 // and stencil. Null when it cannot be built.
@@ -788,6 +796,7 @@ enum class ReplayResult {
788 invalid_predication, 796 invalid_predication,
789 invalid_query, 797 invalid_query,
790 invalid_indirect_arguments, 798 invalid_indirect_arguments,
799 invalid_draw, // DispatchMesh with a pipeline that has no mesh shader, or a vertex draw with one that has
791 unsupported 800 unsupported
792}; 801};
793 802
@@ -843,6 +852,7 @@ struct ReplayFunctions {
843 PFN_vkCmdSetStencilReference set_stencil_reference = nullptr; 852 PFN_vkCmdSetStencilReference set_stencil_reference = nullptr;
844 PFN_vkCmdSetBlendConstants set_blend_constants = nullptr; 853 PFN_vkCmdSetBlendConstants set_blend_constants = nullptr;
845 PFN_vkCmdDraw draw = nullptr; 854 PFN_vkCmdDraw draw = nullptr;
855 PFN_vkCmdDrawMeshTasksEXT draw_mesh_tasks = nullptr; // VK_EXT_mesh_shader; null: mesh draws are unsupported
846 PFN_vkCmdDrawIndexed draw_indexed = nullptr; 856 PFN_vkCmdDrawIndexed draw_indexed = nullptr;
847 std::function<const GraphicsPipeline*(std::uintptr_t)> graphics_pipeline; 857 std::function<const GraphicsPipeline*(std::uintptr_t)> graphics_pipeline;
848 // The buffer and offset a console VA range starts in (from ResourceBinding::va), false when none does. `size` is 858 // The buffer and offset a console VA range starts in (from ResourceBinding::va), false when none does. `size` is
@@ -861,9 +871,11 @@ struct ReplayFunctions {
861 std::function<void(VkCommandBuffer, VkQueryPool, std::uint32_t first, std::uint32_t count, 871 std::function<void(VkCommandBuffer, VkQueryPool, std::uint32_t first, std::uint32_t count,
862 VkBuffer dst, VkDeviceSize offset)> resolve_binary_occlusion; 872 VkBuffer dst, VkDeviceSize offset)> resolve_binary_occlusion;
863 // Adds `count` pipeline-statistics results into one D3D12_QUERY_DATA_PIPELINE_STATISTICS, outside conditional 873 // Adds `count` pipeline-statistics results into one D3D12_QUERY_DATA_PIPELINE_STATISTICS, outside conditional
864 // rendering: the segments of a statistics query split around resolves (D3D-162). 874 // rendering: the segments of a statistics query split around resolves (D3D-162) and mesh draws (D3D-291).
865 std::function<void(VkCommandBuffer, VkQueryPool, std::uint32_t first, std::uint32_t count, 875 // Segment i is in the second pool when mesh[i] is set (mesh may be null: none is).
866 VkBuffer dst, VkDeviceSize offset)> sum_statistics; 876 std::function<void(VkCommandBuffer, VkQueryPool, VkQueryPool mesh_pool, const std::uint8_t* mesh,
877 std::uint32_t first, std::uint32_t count, VkBuffer dst, VkDeviceSize offset)>
878 sum_statistics;
867 // Sums `count` binary-occlusion segments and normalizes the total to a 64-bit 0 or 1, outside conditional 879 // Sums `count` binary-occlusion segments and normalizes the total to a 64-bit 0 or 1, outside conditional
868 // rendering: a binary query split over physical segments because it overlaps other occlusion queries (D3D-252). 880 // rendering: a binary query split over physical segments because it overlaps other occlusion queries (D3D-252).
869 std::function<void(VkCommandBuffer, VkQueryPool, std::uint32_t first, std::uint32_t count, 881 std::function<void(VkCommandBuffer, VkQueryPool, std::uint32_t first, std::uint32_t count,
@@ -937,6 +949,9 @@ struct QueryResolveRun {
937 std::uint32_t count = 0; 949 std::uint32_t count = 0;
938 VkDeviceSize offset = 0; 950 VkDeviceSize offset = 0;
939 bool sum = false; 951 bool sum = false;
952 // Statistics segments: the mesh-compatible pool and the kind of each segment (OcclusionSegmentPool::mesh).
953 VkQueryPool mesh_pool = VK_NULL_HANDLE;
954 const std::uint8_t* mesh = nullptr;
940}; 955};
941 956
942struct PreparedQuery { 957struct PreparedQuery {
@@ -958,7 +973,8 @@ struct PreparedQuery {
958}; 973};
959 974
960struct Prepared { 975struct Prepared {
961 // Helper commands split the active statistics query just like query resolves. 976 // Helper commands split the active statistics query just like query resolves, and so does a draw whose kind (mesh
977 // or vertex) differs from the draws before it in the current segment (plan_statistics_segments, D3D-291).
962 std::uint32_t statistics_end = PreparedQuery::no_segment; 978 std::uint32_t statistics_end = PreparedQuery::no_segment;
963 std::uint32_t statistics_begin = PreparedQuery::no_segment; 979 std::uint32_t statistics_begin = PreparedQuery::no_segment;
964 PredicateCapture predicate; 980 PredicateCapture predicate;
@@ -2068,6 +2084,8 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct
2068 return ReplayResult::unsupported; 2084 return ReplayResult::unsupported;
2069 const GraphicsPipeline* pipeline = vk.graphics_pipeline(draw.pipeline); 2085 const GraphicsPipeline* pipeline = vk.graphics_pipeline(draw.pipeline);
2070 if (!pipeline || !pipeline->pipeline) return ReplayResult::unresolved_resource; 2086 if (!pipeline || !pipeline->pipeline) return ReplayResult::unresolved_resource;
2087 if (pipeline->mesh != draw.mesh) return ReplayResult::invalid_draw;
2088 if (draw.mesh && !vk.draw_mesh_tasks) return ReplayResult::unsupported;
2071 if (pipeline->bindless_set && !vk.bind_descriptor_sets) return ReplayResult::unsupported; 2089 if (pipeline->bindless_set && !vk.bind_descriptor_sets) return ReplayResult::unsupported;
2072 if (pipeline->color_formats.size() > max_render_targets) return ReplayResult::unsupported; 2090 if (pipeline->color_formats.size() > max_render_targets) return ReplayResult::unsupported;
2073 p.graphics = pipeline; 2091 p.graphics = pipeline;
@@ -2262,6 +2280,9 @@ public:
2262 // The list's statistics queries overlap (D3D-252): without a statistics pool they cannot run whole, because 2280 // The list's statistics queries overlap (D3D-252): without a statistics pool they cannot run whole, because
2263 // two Vulkan queries of one type may not be active at once; QueryReplay::plan refuses such a list. 2281 // two Vulkan queries of one type may not be active at once; QueryReplay::plan refuses such a list.
2264 bool statistics_overlaps = false; 2282 bool statistics_overlaps = false;
2283 // For each of those segments, whether it holds mesh draws and so runs in statistics_mesh_pool (D3D-291).
2284 std::vector<std::uint8_t> statistics_mesh;
2285 VkQueryPool statistics_mesh_pool = VK_NULL_HANDLE;
2265 // Copies, resolves and UAV clears that run as transfers, recorded while a predicate was set. D3D12 skips them 2286 // Copies, resolves and UAV clears that run as transfers, recorded while a predicate was set. D3D12 skips them
2266 // when the predicate says so, but Vulkan's conditional rendering does not cover transfer commands, so they run 2287 // when the predicate says so, but Vulkan's conditional rendering does not cover transfer commands, so they run
2267 // unconditionally (docs/d3d12_vulkan.md section 4.7). Counted so the caller can report it. 2288 // unconditionally (docs/d3d12_vulkan.md section 4.7). Counted so the caller can report it.
@@ -2305,37 +2326,74 @@ inline ReplayResult plan_occlusion_segments(PreparedList& out) {
2305// Helper dispatches must not contribute to the application's CSInvocations (D3D-162). Query resolves and 2326// Helper dispatches must not contribute to the application's CSInvocations (D3D-162). Query resolves and
2306// ordinary helper commands share one sequence of physical statistics segments. Resolve dispatch requirements 2327// ordinary helper commands share one sequence of physical statistics segments. Resolve dispatch requirements
2307// depend on heap state at planning time, so every non-timestamp resolve splits conservatively. 2328// depend on heap state at planning time, so every non-timestamp resolve splits conservatively.
2329// A mesh draw cannot run while a query with the input-assembly, vertex, geometry or tessellation counters is active
2330// (VUID-vkCmdDrawMeshTasksEXT-pipelineStatistics-07076), though D3D12 allows it and reads those fields as 0. A query
2331// that holds a mesh draw is split as well (D3D-291): a segment's first draw decides whether it runs in the full pool
2332// or in the mesh one (statistics_mesh), and a later draw of the other kind ends it and begins one of its own kind.
2333// Dispatches and segments without draws use the full pool; ExecuteIndirect draws count as vertex draws. Each draw
2334// has its own rendering scope, so a split before one stays outside rendering, as a helper's does.
2308inline void plan_statistics_segments(PreparedList& out) { 2335inline void plan_statistics_segments(PreparedList& out) {
2309 detail::PreparedQuery* begin = nullptr; 2336 detail::PreparedQuery* begin = nullptr;
2310 struct Split { std::uint32_t* end; std::uint32_t* begin; }; 2337 // A split point (a helper or a resolve), or a draw: kind 0 vertex, 1 mesh.
2311 std::vector<Split> inner; 2338 struct Event { std::uint32_t* end; std::uint32_t* begin; int kind; };
2339 std::vector<Event> inner;
2340 bool splits = false, mesh = false;
2312 std::size_t next_query = 0; 2341 std::size_t next_query = 0;
2342 const auto commands = out.list->commands();
2313 for (std::size_t i = 0; i < out.commands.size(); ++i) { 2343 for (std::size_t i = 0; i < out.commands.size(); ++i) {
2314 auto& p = out.commands[i]; 2344 auto& p = out.commands[i];
2315 if (begin && (p.predicate.scratch || !p.predicated_copy.empty() || p.has_depth24 || 2345 if (begin && (p.predicate.scratch || !p.predicated_copy.empty() || p.has_depth24 ||
2316 p.counted_dispatch.indirect)) 2346 p.counted_dispatch.indirect)) {
2317 inner.push_back({&p.statistics_end, &p.statistics_begin}); 2347 inner.push_back({&p.statistics_end, &p.statistics_begin, -1});
2348 splits = true;
2349 }
2350 if (begin) {
2351 int kind = -1;
2352 if (const auto* draw = std::get_if<Draw>(&commands[i])) kind = draw->mesh ? 1 : 0;
2353 else if (const auto* indirect = std::get_if<ExecuteIndirect>(&commands[i]))
2354 kind = indirect->kind == IndirectKind::dispatch ? -1 : 0;
2355 if (kind >= 0) inner.push_back({&p.statistics_end, &p.statistics_begin, kind});
2356 mesh |= kind == 1;
2357 }
2318 if (next_query == out.queries.size() || out.queries[next_query].command != i) continue; 2358 if (next_query == out.queries.size() || out.queries[next_query].command != i) continue;
2319 auto& query = out.queries[next_query++]; 2359 auto& query = out.queries[next_query++];
2320 const Command& command = out.list->commands()[i]; 2360 const Command& command = commands[i];
2321 const auto range = query_range(command); 2361 const auto range = query_range(command);
2322 if (std::holds_alternative<ResolveQueries>(command)) { 2362 if (std::holds_alternative<ResolveQueries>(command)) {
2323 // A stream-output resolve only fills zeros (no dispatch), so it needs no split. 2363 // A stream-output resolve only fills zeros (no dispatch), so it needs no split.
2324 if (begin && range.type != d3d12_query::timestamp && !is_so_statistics(range.type)) 2364 if (begin && range.type != d3d12_query::timestamp && !is_so_statistics(range.type)) {
2325 inner.push_back({&query.statistics_end, &query.statistics_begin}); 2365 inner.push_back({&query.statistics_end, &query.statistics_begin, -1});
2366 splits = true;
2367 }
2326 } else if (range.type == d3d12_query::pipeline_statistics) { 2368 } else if (range.type == d3d12_query::pipeline_statistics) {
2327 if (std::holds_alternative<BeginQuery>(command)) { 2369 if (std::holds_alternative<BeginQuery>(command)) {
2328 begin = &query; 2370 begin = &query;
2329 inner.clear(); 2371 inner.clear();
2372 splits = mesh = false;
2330 } else if (begin) { 2373 } else if (begin) {
2331 if (!inner.empty()) { 2374 if (splits || mesh) {
2332 const std::uint32_t first = out.statistics_segment_count; 2375 const std::uint32_t first = out.statistics_segment_count;
2333 begin->statistics_begin = out.statistics_segment_count++; 2376 const auto open = [&] {
2334 for (auto split : inner) { 2377 out.statistics_mesh.push_back(0);
2335 *split.end = out.statistics_segment_count - 1; 2378 return out.statistics_segment_count++;
2336 *split.begin = out.statistics_segment_count++; 2379 };
2380 std::uint32_t current = begin->statistics_begin = open();
2381 int kind = -1; // of the current segment's draws, -1 before its first
2382 for (const auto& event : inner) {
2383 if (event.kind < 0) {
2384 *event.end = current;
2385 current = *event.begin = open();
2386 kind = -1;
2387 continue;
2388 }
2389 if (kind >= 0 && event.kind != kind) {
2390 *event.end = current;
2391 current = *event.begin = open();
2392 }
2393 kind = event.kind;
2394 out.statistics_mesh[current] = std::uint8_t(kind);
2337 } 2395 }
2338 query.statistics_end = out.statistics_segment_count - 1; 2396 query.statistics_end = current;
2339 query.statistics_first = first; 2397 query.statistics_first = first;
2340 query.statistics_count = out.statistics_segment_count - first; 2398 query.statistics_count = out.statistics_segment_count - first;
2341 } 2399 }
@@ -2355,6 +2413,14 @@ inline ReplayResult plan_overlapping_statistics_segments(PreparedList& out) {
2355 std::map<std::pair<QueryHeapId, std::uint32_t>, std::uint32_t> active; 2413 std::map<std::pair<QueryHeapId, std::uint32_t>, std::uint32_t> active;
2356 std::uint32_t current = detail::PreparedQuery::no_segment; 2414 std::uint32_t current = detail::PreparedQuery::no_segment;
2357 std::size_t next_query = 0; 2415 std::size_t next_query = 0;
2416 // Each physical segment's draw kind (D3D-291): -1 before its first draw, 0 vertex, 1 mesh.
2417 int kind = -1;
2418 const auto open = [&] {
2419 out.statistics_mesh.push_back(0);
2420 kind = -1;
2421 return out.statistics_segment_count++;
2422 };
2423 const auto commands = out.list->commands();
2358 for (std::size_t i = 0; i < out.commands.size(); ++i) { 2424 for (std::size_t i = 0; i < out.commands.size(); ++i) {
2359 auto& p = out.commands[i]; 2425 auto& p = out.commands[i];
2360 detail::PreparedQuery* query = nullptr; 2426 detail::PreparedQuery* query = nullptr;
@@ -2366,8 +2432,23 @@ inline ReplayResult plan_overlapping_statistics_segments(PreparedList& out) {
2366 if (!active.empty() && (p.predicate.scratch || !p.predicated_copy.empty() || p.has_depth24 || 2432 if (!active.empty() && (p.predicate.scratch || !p.predicated_copy.empty() || p.has_depth24 ||
2367 p.counted_dispatch.indirect)) { 2433 p.counted_dispatch.indirect)) {
2368 p.statistics_end = current; 2434 p.statistics_end = current;
2369 current = out.statistics_segment_count++; 2435 current = open();
2370 p.statistics_begin = current; 2436 p.statistics_begin = current;
2437 continue;
2438 }
2439 // A draw of the other kind than the open segment's starts a segment in its own pool (D3D-291).
2440 int draw = -1;
2441 if (const auto* d = std::get_if<Draw>(&commands[i])) draw = d->mesh ? 1 : 0;
2442 else if (const auto* indirect = std::get_if<ExecuteIndirect>(&commands[i]))
2443 draw = indirect->kind == IndirectKind::dispatch ? -1 : 0;
2444 if (!active.empty() && draw >= 0) {
2445 if (kind >= 0 && draw != kind) {
2446 p.statistics_end = current;
2447 current = open();
2448 p.statistics_begin = current;
2449 }
2450 kind = draw;
2451 out.statistics_mesh[current] = std::uint8_t(draw);
2371 } 2452 }
2372 continue; 2453 continue;
2373 } 2454 }
@@ -2391,11 +2472,11 @@ inline ReplayResult plan_overlapping_statistics_segments(PreparedList& out) {
2391 } else { 2472 } else {
2392 if (current == detail::PreparedQuery::no_segment || range.type == d3d12_query::timestamp) continue; 2473 if (current == detail::PreparedQuery::no_segment || range.type == d3d12_query::timestamp) continue;
2393 query->statistics_end = current; 2474 query->statistics_end = current;
2394 current = out.statistics_segment_count++; 2475 current = open();
2395 query->statistics_begin = current; 2476 query->statistics_begin = current;
2396 continue; 2477 continue;
2397 } 2478 }
2398 current = active.empty() ? detail::PreparedQuery::no_segment : out.statistics_segment_count++; 2479 current = active.empty() ? detail::PreparedQuery::no_segment : open();
2399 query->statistics_begin = current; 2480 query->statistics_begin = current;
2400 } 2481 }
2401 return active.empty() ? ReplayResult::success : ReplayResult::invalid_query; 2482 return active.empty() ? ReplayResult::success : ReplayResult::invalid_query;
@@ -2466,8 +2547,9 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2466 out.segment_pool = VK_NULL_HANDLE; 2547 out.segment_pool = VK_NULL_HANDLE;
2467 out.segment_base = out.segment_count = 0; 2548 out.segment_base = out.segment_count = 0;
2468 out.precise_segments = false; 2549 out.precise_segments = false;
2469 out.statistics_pool = VK_NULL_HANDLE; 2550 out.statistics_pool = out.statistics_mesh_pool = VK_NULL_HANDLE;
2470 out.statistics_base = out.statistics_segment_count = 0; 2551 out.statistics_base = out.statistics_segment_count = 0;
2552 out.statistics_mesh.clear();
2471 const bool rendering = vk.begin_rendering && vk.end_rendering && vk.clear_attachments && vk.image_view; 2553 const bool rendering = vk.begin_rendering && vk.end_rendering && vk.clear_attachments && vk.image_view;
2472 const bool copies = vk.copy_buffer && vk.copy_buffer_to_image && vk.copy_image_to_buffer && vk.copy_image; 2554 const bool copies = vk.copy_buffer && vk.copy_buffer_to_image && vk.copy_image_to_buffer && vk.copy_image;
2473 const bool conditional = vk.begin_conditional_rendering && vk.end_conditional_rendering; 2555 const bool conditional = vk.begin_conditional_rendering && vk.end_conditional_rendering;
@@ -3037,10 +3119,16 @@ public:
3037 list.segment_base = base; 3119 list.segment_base = base;
3038 } 3120 }
3039 if (list.statistics_segment_count) { 3121 if (list.statistics_segment_count) {
3040 if (statistics_pool) { 3122 const bool mesh = std::find(list.statistics_mesh.begin(), list.statistics_mesh.end(), 1) !=
3123 list.statistics_mesh.end();
3124 if (statistics_pool && (!mesh || statistics_pool->mesh_pool)) {
3041 retain(statistics_pool); 3125 retain(statistics_pool);
3042 list.statistics_pool = statistics_pool->pool; 3126 list.statistics_pool = statistics_pool->pool;
3127 list.statistics_mesh_pool = statistics_pool->mesh_pool;
3043 list.statistics_base = statistics_base; 3128 list.statistics_base = statistics_base;
3129 } else if (mesh) {
3130 // Unsplit, the query would be active around a mesh draw with counters Vulkan forbids there.
3131 return ReplayResult::unsupported;
3044 } else if (list.statistics_overlaps) { 3132 } else if (list.statistics_overlaps) {
3045 // Whole queries on the heap pool would keep two pipeline-statistics queries active at once. 3133 // Whole queries on the heap pool would keep two pipeline-statistics queries active at once.
3046 return ReplayResult::unsupported; 3134 return ReplayResult::unsupported;
@@ -3087,7 +3175,14 @@ public:
3087 if (resolve.type != d3d12_query::occlusion && !binary && !statistics) 3175 if (resolve.type != d3d12_query::occlusion && !binary && !statistics)
3088 return ReplayResult::invalid_query; 3176 return ReplayResult::invalid_query;
3089 const auto& saved = value.occlusion; 3177 const auto& saved = value.occlusion;
3090 run = {saved.segments->pool, saved.first, saved.count, run.offset, saved.count > 1}; 3178 const std::uint8_t* kinds = saved.segments->mesh.empty() ? nullptr
3179 : saved.segments->mesh.data();
3180 // A mesh segment's four counters go through the sum to land in their D3D12 fields.
3181 const bool any_mesh = kinds && std::find(kinds + saved.first, kinds + saved.first + saved.count,
3182 std::uint8_t(1)) != kinds + saved.first + saved.count;
3183 run = {saved.segments->pool, saved.first, saved.count, run.offset,
3184 saved.count > 1 || any_mesh, saved.segments->mesh_pool, kinds};
3185 if (any_mesh && !statistics) return ReplayResult::invalid_query;
3091 if (!can_sum || (run.sum && !uncounted)) return ReplayResult::unsupported; 3186 if (!can_sum || (run.sum && !uncounted)) return ReplayResult::unsupported;
3092 if (statistics) needs_statistics_sum |= run.sum; 3187 if (statistics) needs_statistics_sum |= run.sum;
3093 else if (binary) (run.sum ? needs_sum_binary : needs_binary) = true; 3188 else if (binary) (run.sum ? needs_sum_binary : needs_binary) = true;
@@ -3142,6 +3237,29 @@ private:
3142 std::map<std::pair<QueryPool*, std::uint32_t>, Value> pending_; 3237 std::map<std::pair<QueryPool*, std::uint32_t>, Value> pending_;
3143}; 3238};
3144 3239
3240namespace detail {
3241
3242// A physical pipeline-statistics segment (plan_statistics_segments), in the pool its kind needs.
3243inline VkQueryPool statistics_segment_pool(const PreparedList& list, std::uint32_t segment) {
3244 return list.statistics_mesh[segment] ? list.statistics_mesh_pool : list.statistics_pool;
3245}
3246
3247inline void end_statistics_segment(const PreparedList& list, std::uint32_t segment, VkCommandBuffer cb,
3248 const ReplayFunctions& vk) {
3249 if (segment == PreparedQuery::no_segment) return;
3250 vk.end_query(cb, statistics_segment_pool(list, segment), list.statistics_base + segment);
3251}
3252
3253inline void begin_statistics_segment(const PreparedList& list, std::uint32_t segment, VkCommandBuffer cb,
3254 const ReplayFunctions& vk) {
3255 if (segment == PreparedQuery::no_segment) return;
3256 const auto pool = statistics_segment_pool(list, segment);
3257 vk.reset_query_pool(cb, pool, list.statistics_base + segment, 1);
3258 vk.begin_query(cb, pool, list.statistics_base + segment, 0);
3259}
3260
3261} // namespace detail
3262
3145inline void emit_query(const PreparedList& list, const detail::PreparedQuery& query, VkCommandBuffer cb, 3263inline void emit_query(const PreparedList& list, const detail::PreparedQuery& query, VkCommandBuffer cb,
3146 const ReplayFunctions& vk, const VkConditionalRenderingBeginInfoEXT& predicate) { 3264 const ReplayFunctions& vk, const VkConditionalRenderingBeginInfoEXT& predicate) {
3147 constexpr auto none = detail::PreparedQuery::no_segment; 3265 constexpr auto none = detail::PreparedQuery::no_segment;
@@ -3155,16 +3273,8 @@ inline void emit_query(const PreparedList& list, const detail::PreparedQuery& qu
3155 return; 3273 return;
3156 } 3274 }
3157 // A split pipeline-statistics query (plan_statistics_segments): its counters run in the physical segments. 3275 // A split pipeline-statistics query (plan_statistics_segments): its counters run in the physical segments.
3158 const auto end_statistics = [&] { 3276 const auto end_statistics = [&] { detail::end_statistics_segment(list, query.statistics_end, cb, vk); };
3159 if (query.statistics_end != none) 3277 const auto begin_statistics = [&] { detail::begin_statistics_segment(list, query.statistics_begin, cb, vk); };
3160 vk.end_query(cb, list.statistics_pool, list.statistics_base + query.statistics_end);
3161 };
3162 const auto begin_statistics = [&] {
3163 if (query.statistics_begin == none) return;
3164 const auto index = list.statistics_base + query.statistics_begin;
3165 vk.reset_query_pool(cb, list.statistics_pool, index, 1);
3166 vk.begin_query(cb, list.statistics_pool, index, 0);
3167 };
3168 const auto& command = list.list->commands()[query.command]; 3278 const auto& command = list.list->commands()[query.command];
3169 const QueryPool& heap = *query.heap; 3279 const QueryPool& heap = *query.heap;
3170 if (!std::holds_alternative<ResolveQueries>(command) && 3280 if (!std::holds_alternative<ResolveQueries>(command) &&
@@ -3206,7 +3316,7 @@ inline void emit_query(const PreparedList& list, const detail::PreparedQuery& qu
3206 if (!run.pool) { 3316 if (!run.pool) {
3207 vk.fill_buffer(cb, dst, run.offset, VkDeviceSize(run.count) * size, 0); 3317 vk.fill_buffer(cb, dst, run.offset, VkDeviceSize(run.count) * size, 0);
3208 } else if (run.sum && resolve.type == d3d12_query::pipeline_statistics) { 3318 } else if (run.sum && resolve.type == d3d12_query::pipeline_statistics) {
3209 vk.sum_statistics(cb, run.pool, run.first, run.count, dst, run.offset); 3319 vk.sum_statistics(cb, run.pool, run.mesh_pool, run.mesh, run.first, run.count, dst, run.offset);
3210 } else if (run.sum && binary) { 3320 } else if (run.sum && binary) {
3211 vk.sum_binary_occlusion(cb, run.pool, run.first, run.count, dst, run.offset); 3321 vk.sum_binary_occlusion(cb, run.pool, run.first, run.count, dst, run.offset);
3212 } else if (run.sum || binary) { 3322 } else if (run.sum || binary) {
@@ -3260,15 +3370,17 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
3260 } 3370 }
3261 // Helpers run outside the per-command rendering scopes; both segment endpoints stay outside too. 3371 // Helpers run outside the per-command rendering scopes; both segment endpoints stay outside too.
3262 const auto end_statistics = [&] { 3372 const auto end_statistics = [&] {
3263 if (p.statistics_end != detail::PreparedQuery::no_segment) 3373 detail::end_statistics_segment(prepared, p.statistics_end, command_buffer, vk);
3264 vk.end_query(command_buffer, prepared.statistics_pool, prepared.statistics_base + p.statistics_end);
3265 }; 3374 };
3266 const auto begin_statistics = [&] { 3375 const auto begin_statistics = [&] {
3267 if (p.statistics_begin == detail::PreparedQuery::no_segment) return; 3376 detail::begin_statistics_segment(prepared, p.statistics_begin, command_buffer, vk);
3268 const auto index = prepared.statistics_base + p.statistics_begin;
3269 vk.reset_query_pool(command_buffer, prepared.statistics_pool, index, 1);
3270 vk.begin_query(command_buffer, prepared.statistics_pool, index, 0);
3271 }; 3377 };
3378 // A draw of the other kind inside a statistics query starts a segment in its pool (D3D-291), before the
3379 // draw's own rendering scope begins.
3380 if (std::holds_alternative<Draw>(command) || std::holds_alternative<ExecuteIndirect>(command)) {
3381 end_statistics();
3382 begin_statistics();
3383 }
3272 if (const auto* predication = std::get_if<Predication>(&command)) { 3384 if (const auto* predication = std::get_if<Predication>(&command)) {
3273 // Conditional rendering cannot nest, so a new predicate ends the previous one first. 3385 // Conditional rendering cannot nest, so a new predicate ends the previous one first.
3274 if (predicate.buffer) vk.end_conditional_rendering(command_buffer); 3386 if (predicate.buffer) vk.end_conditional_rendering(command_buffer);
@@ -3974,12 +4086,16 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
3974 {std::uint32_t(std::max(0, s.right - std::max(0, s.left))), 4086 {std::uint32_t(std::max(0, s.right - std::max(0, s.left))),
3975 std::uint32_t(std::max(0, s.bottom - std::max(0, s.top)))}}; 4087 std::uint32_t(std::max(0, s.bottom - std::max(0, s.top)))}};
3976 vk.set_scissor(command_buffer, 0, 1, &scissor); 4088 vk.set_scissor(command_buffer, 0, 1, &scissor);
3977 const VkPrimitiveTopology topology = detail::vulkan_topology(draw->topology); 4089 // A mesh pipeline has no input assembly: its topology comes from the shader, and neither the topology
3978 vk.set_primitive_topology(command_buffer, topology); 4090 // nor primitive restart is dynamic state there (VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-07065).
3979 const bool restart = draw->indexed && detail::strip_topology(topology) && 4091 if (!draw->mesh) {
3980 ((graphics.strip_cut == 1 && d.index_type == VK_INDEX_TYPE_UINT16) || 4092 const VkPrimitiveTopology topology = detail::vulkan_topology(draw->topology);
3981 (graphics.strip_cut == 2 && d.index_type == VK_INDEX_TYPE_UINT32)); 4093 vk.set_primitive_topology(command_buffer, topology);
3982 vk.set_primitive_restart_enable(command_buffer, restart ? VK_TRUE : VK_FALSE); 4094 const bool restart = draw->indexed && detail::strip_topology(topology) &&
4095 ((graphics.strip_cut == 1 && d.index_type == VK_INDEX_TYPE_UINT16) ||
4096 (graphics.strip_cut == 2 && d.index_type == VK_INDEX_TYPE_UINT32));
4097 vk.set_primitive_restart_enable(command_buffer, restart ? VK_TRUE : VK_FALSE);
4098 }
3983 vk.set_stencil_reference(command_buffer, VK_STENCIL_FACE_FRONT_BIT, draw->stencil_front); 4099 vk.set_stencil_reference(command_buffer, VK_STENCIL_FACE_FRONT_BIT, draw->stencil_front);
3984 vk.set_stencil_reference(command_buffer, VK_STENCIL_FACE_BACK_BIT, draw->stencil_back); 4100 vk.set_stencil_reference(command_buffer, VK_STENCIL_FACE_BACK_BIT, draw->stencil_back);
3985 vk.set_blend_constants(command_buffer, draw->blend_factor.data()); 4101 vk.set_blend_constants(command_buffer, draw->blend_factor.data());
@@ -3988,7 +4104,9 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
3988 vk.bind_vertex_buffers2(command_buffer, slot, 1, &d.vertex_buffers[slot], &d.vertex_offsets[slot], 4104 vk.bind_vertex_buffers2(command_buffer, slot, 1, &d.vertex_buffers[slot], &d.vertex_offsets[slot],
3989 &d.vertex_sizes[slot], &d.vertex_strides[slot]); 4105 &d.vertex_sizes[slot], &d.vertex_strides[slot]);
3990 } 4106 }
3991 if (draw->indexed) { 4107 if (draw->mesh) {
4108 vk.draw_mesh_tasks(command_buffer, draw->count, draw->instances, draw->first);
4109 } else if (draw->indexed) {
3992 vk.bind_index_buffer(command_buffer, d.index_buffer, d.index_offset, d.index_type); 4110 vk.bind_index_buffer(command_buffer, d.index_buffer, d.index_offset, d.index_type);
3993 vk.draw_indexed(command_buffer, draw->count, draw->instances, draw->first, draw->base_vertex, 4111 vk.draw_indexed(command_buffer, draw->count, draw->instances, draw->first, draw->base_vertex,
3994 draw->first_instance); 4112 draw->first_instance);
diff --git a/runtime/test/d3d12_mesh_test.cpp b/runtime/test/d3d12_mesh_test.cpp
new file mode 100644
index 000000000..df430c11a
--- /dev/null
+++ b/runtime/test/d3d12_mesh_test.cpp
@@ -0,0 +1,523 @@
1// D3D-29: mesh-shader PSOs from pipeline state streams and DispatchMesh, through the Xbox-ABI proxy over the Vulkan
2// device (docs/d3d12_vulkan.md section 5, "Pipelines").
3// - A device without VK_EXT_mesh_shader reports D3D12_MESH_SHADER_TIER_NOT_SUPPORTED and refuses a mesh PSO with
4// E_NOTIMPL; that part runs on every GPU. The rest needs the extension (exit 77 without it).
5// - With it: MeshShaderTier 1; CreatePipelineState builds an MS + PS PSO and a VS + PS PSO from streams laid out as
6// d3dx12.h lays them out (each subobject a type and its description, pointer-aligned); streams the PC runtime
7// refuses (MS with VS, CS with PS, a subobject twice or in two versions, an unknown type, a truncated stream) are E_INVALIDARG, and
8// state not built yet (an amplification shader, a depth-bounds test) is E_NOTIMPL.
9// - Draws: DispatchMesh(2, 2, 1) with root constants (0, 0) and a red tint fills the top-left quadrant;
10// DispatchMesh(1, 1, 2) moved by (1, -1) with a green tint fills the top half of the bottom-right one, so the
11// Y and Z counts reach the shader; the stream's VS PSO draws a full-screen triangle through a viewport on the
12// bottom-left quadrant (yellow). Each pixel is read back and compared.
13// - A vertex draw with the mesh PSO, and DispatchMesh with the VS one, fail at execution (ReplayResult::
14// invalid_draw); a mesh grid beyond D3D12's limits fails at Close; an empty grid records nothing.
15// The shaders are GLSL written to the translator's contract (test/glsl/ms_draw.mesh, ps_draw.frag, vs_fullscreen.vert).
16// No game data. Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation.
17#include "vk_test_device.h"
18#include "d3d12_test_shaders.h"
19#include "../shims/d3d12_com.h"
20#include "../shims/d3d12_xs_device.h"
21#include "../src/shader_library.h"
22
23#include <array>
24#include <cstring>
25
26#if !defined(LEONIDA_TEST_MS_SPV) || !defined(LEONIDA_TEST_PS_SPV) || !defined(LEONIDA_TEST_VS_FULLSCREEN_SPV)
27#error "LEONIDA_TEST_MS_SPV, LEONIDA_TEST_PS_SPV and LEONIDA_TEST_VS_FULLSCREEN_SPV must name the compiled test shaders"
28#endif
29
30#define EXPECT(condition) do { \
31 if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \
32} while (0)
33
34using namespace d3d12test;
35using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slot 9: handle in RAX
36
37namespace {
38
39// One pipeline state stream subobject as d3dx12.h declares it (CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT).
40template <D3D12_PIPELINE_STATE_SUBOBJECT_TYPE Type, typename Inner>
41struct alignas(void*) Subobject {
42 D3D12_PIPELINE_STATE_SUBOBJECT_TYPE type = Type;
43 Inner inner;
44};
45using RootSubobject = Subobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, ID3D12RootSignature*>;
46using VsSubobject = Subobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, D3D12_SHADER_BYTECODE>;
47using PsSubobject = Subobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, D3D12_SHADER_BYTECODE>;
48using CsSubobject = Subobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS, D3D12_SHADER_BYTECODE>;
49using AsSubobject = Subobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS, D3D12_SHADER_BYTECODE>;
50using MsSubobject = Subobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, D3D12_SHADER_BYTECODE>;
51using TopologySubobject = Subobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY, D3D12_PRIMITIVE_TOPOLOGY_TYPE>;
52using TargetsSubobject = Subobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, D3D12_RT_FORMAT_ARRAY>;
53using DepthStencil1Subobject = Subobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1, D3D12_DEPTH_STENCIL_DESC1>;
54using DepthStencilSubobject = Subobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, D3D12_DEPTH_STENCIL_DESC>;
55using RasterizerSubobject = Subobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, D3D12_RASTERIZER_DESC>;
56using Rasterizer2Subobject = Subobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER2, D3D12_RASTERIZER_DESC2>;
57using MaskSubobject = Subobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, UINT>;
58
59// Subobjects appended one after another: each is pointer-aligned and a multiple of the pointer size, so the bytes
60// are what a struct of the same members would hold.
61struct Stream {
62 std::vector<std::uint8_t> bytes;
63 template <typename S>
64 Stream& add(const S& subobject) {
65 static_assert(sizeof(S) % sizeof(void*) == 0);
66 const std::size_t at = bytes.size();
67 bytes.resize(at + sizeof(S));
68 std::memcpy(bytes.data() + at, &subobject, sizeof(S));
69 return *this;
70 }
71 D3D12_PIPELINE_STATE_STREAM_DESC desc(std::size_t trim = 0) { return {bytes.size() - trim, bytes.data()}; }
72};
73
74D3D12_RT_FORMAT_ARRAY one_target() {
75 D3D12_RT_FORMAT_ARRAY formats{};
76 formats.RTFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
77 formats.NumRenderTargets = 1;
78 return formats;
79}
80
81HRESULT create(ID3D12Device* device, Stream& stream, Ref<ID3D12PipelineState>& out, std::size_t trim = 0) {
82 Ref<ID3D12Device2> device2;
83 if (FAILED(device->QueryInterface(IID_PPV_ARGS(&device2.p)))) return E_NOINTERFACE;
84 const D3D12_PIPELINE_STATE_STREAM_DESC desc = stream.desc(trim);
85 out.reset();
86 return device2->CreatePipelineState(&desc, IID_PPV_ARGS(&out.p));
87}
88
89D3D12_MESH_SHADER_TIER mesh_tier(ID3D12Device* device) {
90 D3D12_FEATURE_DATA_D3D12_OPTIONS7 options{};
91 if (FAILED(device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS7, &options, sizeof(options))))
92 return D3D12_MESH_SHADER_TIER(-1);
93 return options.MeshShaderTier;
94}
95
96} // namespace
97
98int main() {
99 vktest::Device d;
100 d.request_mesh_shader = true;
101 const auto device_status = d.initialize();
102 if (device_status == vktest::DeviceStatus::unavailable) {
103 std::fprintf(stderr, "SKIP: no usable Vulkan 1.3 device\n");
104 return 77;
105 }
106 EXPECT(device_status == vktest::DeviceStatus::ready);
107
108 const auto ms_program = fssm_program({0x4d530001, 0xbf810000});
109 const auto ps_program = fssm_program({0x50530001, 0xbf810000});
110 const auto vs_program = fssm_program({0x56530002, 0xbf810000});
111 const auto ms_container = shader_container(ms_program), ps_container = shader_container(ps_program);
112 const auto vs_container = shader_container(vs_program);
113 const auto library = std::filesystem::temp_directory_path() / "leonida_mesh_test";
114 std::filesystem::create_directories(library);
115 std::filesystem::copy_file(LEONIDA_TEST_MS_SPV, library / "ms_draw.spv", std::filesystem::copy_options::overwrite_existing);
116 std::filesystem::copy_file(LEONIDA_TEST_PS_SPV, library / "ps_draw.spv", std::filesystem::copy_options::overwrite_existing);
117 std::filesystem::copy_file(LEONIDA_TEST_VS_FULLSCREEN_SPV, library / "vs_fullscreen.spv",
118 std::filesystem::copy_options::overwrite_existing);
119 {
120 std::ofstream index(library / "index.json", std::ios::binary);
121 index << "{\"ms_draw\": {\"stage\": \"ms\", \"fssm_sha256\": \"" << leonida::sha256_hex(ms_program)
122 << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"local_size\": [32, 1, 1], "
123 "\"max_vertices\": 4, \"max_primitives\": 2},\n"
124 " \"vs_fullscreen\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_program)
125 << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"input_signature\": []},\n"
126 " \"ps_draw\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << leonida::sha256_hex(ps_program)
127 << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"outputs\": [0]}}";
128 }
129
130 const auto device_info = [&](bool mesh) {
131 rt::d3d12::VulkanDeviceInfo info{};
132 info.get_instance_proc = d.instance_proc;
133 info.instance = d.instance;
134 info.physical = d.physical;
135 info.device = d.device;
136 info.queue = d.queue;
137 info.queue_family = d.family;
138 info.buffer_device_address = true;
139 info.shader_dir = library.string();
140 info.mesh_shader = mesh;
141 info.pipeline_statistics_query = d.pipeline_statistics_query;
142 return info;
143 };
144 const auto make_device = [&](bool mesh, Ref<ID3D12Device>& device) {
145 ID3D12Device* inner = nullptr;
146 if (FAILED(rt::d3d12::create_vulkan_device(device_info(mesh), IID_PPV_ARGS(&inner)))) return false;
147 if (FAILED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device),
148 reinterpret_cast<void**>(&device.p))))
149 return false;
150 rt::d3d12::set_device_outer(inner, device.p);
151 return true;
152 };
153 const auto root_signature = [&](ID3D12Device* device, Ref<ID3D12RootSignature>& root) {
154 // [0] two constants (s0, s1: offset), [1] a root CBV (s2:s3: tint), as in d3d12_draw_test.
155 D3D12_ROOT_PARAMETER params[2] = {};
156 params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
157 params[0].Constants = {0, 0, 2};
158 params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV;
159 params[1].Descriptor = {1, 0};
160 D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{};
161 root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0;
162 root_desc.Desc_1_0 = {2, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE};
163 const auto blob = serialize_root_signature(root_desc);
164 return !blob.empty() &&
165 SUCCEEDED(device->CreateRootSignature(0, blob.data(), blob.size(), IID_PPV_ARGS(&root.p)));
166 };
167 const D3D12_SHADER_BYTECODE ms{ms_container.data(), ms_container.size()};
168 const D3D12_SHADER_BYTECODE ps{ps_container.data(), ps_container.size()};
169 const D3D12_SHADER_BYTECODE vs{vs_container.data(), vs_container.size()};
170
171 // Without the extension: no tier, and a mesh PSO is refused as not implemented.
172 {
173 Ref<ID3D12Device> device;
174 Ref<ID3D12RootSignature> root;
175 EXPECT(make_device(false, device));
176 EXPECT(root_signature(device.p, root));
177 EXPECT(mesh_tier(device.p) == D3D12_MESH_SHADER_TIER_NOT_SUPPORTED);
178 Stream stream;
179 stream.add(RootSubobject{.inner = root.p}).add(MsSubobject{.inner = ms}).add(PsSubobject{.inner = ps});
180 stream.add(TargetsSubobject{.inner = one_target()});
181 Ref<ID3D12PipelineState> pso;
182 EXPECT(create(device.p, stream, pso) == E_NOTIMPL && !pso.p);
183 root.reset();
184 EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1);
185 }
186 if (!d.mesh_shader) {
187 std::filesystem::remove_all(library);
188 std::printf("no VK_EXT_mesh_shader on this device: only the refusal without it was checked\n");
189 return 77;
190 }
191
192 constexpr UINT size = 64;
193 std::vector<std::uint8_t> pixels(size * 256);
194 {
195 Ref<ID3D12Device> device;
196 Ref<ID3D12RootSignature> root;
197 EXPECT(make_device(true, device));
198 EXPECT(root_signature(device.p, root));
199 EXPECT(mesh_tier(device.p) == D3D12_MESH_SHADER_TIER_1);
200
201 // The PSOs. Every other subobject takes its default: back-face culling, depth test on (no DSV here), no
202 // blending, all samples.
203 Ref<ID3D12PipelineState> mesh_pso, vs_pso, refused;
204 Stream mesh_stream;
205 mesh_stream.add(RootSubobject{.inner = root.p}).add(MsSubobject{.inner = ms}).add(PsSubobject{.inner = ps});
206 mesh_stream.add(TargetsSubobject{.inner = one_target()});
207 EXPECT(SUCCEEDED(create(device.p, mesh_stream, mesh_pso)));
208 Stream vs_stream;
209 vs_stream.add(RootSubobject{.inner = root.p}).add(VsSubobject{.inner = vs}).add(PsSubobject{.inner = ps});
210 vs_stream.add(TopologySubobject{.inner = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE});
211 vs_stream.add(TargetsSubobject{.inner = one_target()});
212 EXPECT(SUCCEEDED(create(device.p, vs_stream, vs_pso)));
213
214 // Streams the PC runtime refuses.
215 Stream bad = mesh_stream;
216 bad.add(VsSubobject{.inner = vs}); // a mesh shader and a vertex shader
217 EXPECT(create(device.p, bad, refused) == E_INVALIDARG && !refused.p);
218 bad = mesh_stream;
219 bad.add(PsSubobject{.inner = ps}); // the same subobject twice
220 EXPECT(create(device.p, bad, refused) == E_INVALIDARG && !refused.p);
221 bad = mesh_stream;
222 bad.add(CsSubobject{.inner = ps}); // compute with graphics stages
223 EXPECT(create(device.p, bad, refused) == E_INVALIDARG && !refused.p);
224 EXPECT(create(device.p, mesh_stream, refused, 4) == E_INVALIDARG && !refused.p); // truncated
225 bad = mesh_stream;
226 bad.add(Subobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE(23), UINT>{.inner = 0}); // 23 is no subobject type
227 EXPECT(create(device.p, bad, refused) == E_INVALIDARG && !refused.p);
228 Stream empty;
229 EXPECT(create(device.p, empty.add(MaskSubobject{.inner = UINT_MAX}), refused) == E_INVALIDARG && !refused.p);
230 // Versions of one subobject count as the same subobject (D3D12_PIPELINE_STATE_STREAM_DESC): DEPTH_STENCIL with
231 // DEPTH_STENCIL1 in either order, and RASTERIZER with RASTERIZER2. Each description alone is accepted.
232 const D3D12_DEPTH_STENCIL_DESC depth{FALSE, D3D12_DEPTH_WRITE_MASK_ZERO, D3D12_COMPARISON_FUNC_ALWAYS};
233 const D3D12_DEPTH_STENCIL_DESC1 depth1{FALSE, D3D12_DEPTH_WRITE_MASK_ZERO, D3D12_COMPARISON_FUNC_ALWAYS};
234 D3D12_RASTERIZER_DESC raster{};
235 raster.FillMode = D3D12_FILL_MODE_SOLID;
236 raster.CullMode = D3D12_CULL_MODE_NONE;
237 raster.DepthClipEnable = TRUE; // D3D12's default; depth clamping is not built
238 D3D12_RASTERIZER_DESC2 raster2{};
239 raster2.FillMode = D3D12_FILL_MODE_SOLID;
240 raster2.CullMode = D3D12_CULL_MODE_NONE;
241 raster2.DepthClipEnable = TRUE; // D3D12's default; depth clamping is not built
242 for (int order = 0; order < 2; ++order) {
243 bad = mesh_stream;
244 if (order == 0) bad.add(DepthStencilSubobject{.inner = depth}).add(DepthStencil1Subobject{.inner = depth1});
245 else bad.add(DepthStencil1Subobject{.inner = depth1}).add(DepthStencilSubobject{.inner = depth});
246 EXPECT(create(device.p, bad, refused) == E_INVALIDARG && !refused.p);
247 }
248 bad = mesh_stream;
249 bad.add(RasterizerSubobject{.inner = raster}).add(Rasterizer2Subobject{.inner = raster2});
250 EXPECT(create(device.p, bad, refused) == E_INVALIDARG && !refused.p);
251 for (int which = 0; which < 4; ++which) {
252 Stream one = mesh_stream;
253 if (which == 0) one.add(DepthStencilSubobject{.inner = depth});
254 if (which == 1) one.add(DepthStencil1Subobject{.inner = depth1});
255 if (which == 2) one.add(RasterizerSubobject{.inner = raster});
256 if (which == 3) one.add(Rasterizer2Subobject{.inner = raster2});
257 Ref<ID3D12PipelineState> accepted;
258 const HRESULT one_hr = create(device.p, one, accepted);
259 if (FAILED(one_hr)) std::fprintf(stderr, "single subobject %d: 0x%08lx\n", which, static_cast<unsigned long>(one_hr));
260 EXPECT(SUCCEEDED(one_hr));
261 }
262 // State the layer does not build yet.
263 bad = mesh_stream;
264 bad.add(AsSubobject{.inner = vs});
265 EXPECT(create(device.p, bad, refused) == E_NOTIMPL && !refused.p);
266 bad = mesh_stream;
267 D3D12_DEPTH_STENCIL_DESC1 bounds{};
268 bounds.DepthBoundsTestEnable = TRUE;
269 bad.add(DepthStencil1Subobject{.inner = bounds});
270 EXPECT(create(device.p, bad, refused) == E_NOTIMPL && !refused.p);
271
272 const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT};
273 const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD};
274 const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK};
275 Ref<ID3D12Resource> upload, readback, target;
276 const auto upload_desc = buffer_desc(4096);
277 EXPECT(SUCCEEDED(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &upload_desc,
278 D3D12_RESOURCE_STATE_GENERIC_READ, nullptr,
279 IID_PPV_ARGS(&upload.p))));
280 const auto readback_desc = buffer_desc(size * 256);
281 EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc,
282 D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
283 IID_PPV_ARGS(&readback.p))));
284 D3D12_RESOURCE_DESC rt_desc{};
285 rt_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
286 rt_desc.Width = rt_desc.Height = size;
287 rt_desc.DepthOrArraySize = 1;
288 rt_desc.MipLevels = 1;
289 rt_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
290 rt_desc.SampleDesc.Count = 1;
291 rt_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
292 EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &rt_desc,
293 D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&target.p))));
294
295 // Tints at 0 (red stays red), 256 (green) and 512 (white: yellow stays yellow); CBVs are 256-byte aligned.
296 const float tints[3][3] = {{1, 0, 1}, {0, 1, 0}, {1, 1, 1}};
297 std::uint8_t* up = nullptr;
298 EXPECT(SUCCEEDED(upload->Map(0, nullptr, reinterpret_cast<void**>(&up))));
299 for (int i = 0; i < 3; ++i) std::memcpy(up + 256 * i, tints[i], sizeof(tints[i]));
300 const D3D12_GPU_VIRTUAL_ADDRESS upload_va = upload->GetGPUVirtualAddress();
301
302 const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0};
303 Ref<ID3D12DescriptorHeap> rtv_heap;
304 EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&rtv_heap.p))));
305 const D3D12_CPU_DESCRIPTOR_HANDLE rtv{
306 SIZE_T(reinterpret_cast<XboxHeapHandleFn>(slot(rtv_heap.p, 9))(rtv_heap.p))};
307 device->CreateRenderTargetView(target.p, nullptr, rtv);
308
309 D3D12_COMMAND_QUEUE_DESC queue_desc{};
310 Ref<ID3D12CommandQueue> queue;
311 Ref<ID3D12CommandAllocator> allocator;
312 Ref<ID3D12GraphicsCommandList> list;
313 Ref<ID3D12GraphicsCommandList6> list6;
314 Ref<ID3D12Fence> fence;
315 EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p))));
316 EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p))));
317 EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, mesh_pso.p,
318 IID_PPV_ARGS(&list.p))));
319 EXPECT(SUCCEEDED(list->QueryInterface(IID_PPV_ARGS(&list6.p))));
320 EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p))));
321
322 D3D12_RESOURCE_BARRIER to_target =
323 transition(target.p, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_RENDER_TARGET);
324 list->ResourceBarrier(1, &to_target);
325 const FLOAT blue[4] = {0, 0, 1, 1};
326 list->ClearRenderTargetView(rtv, blue, 0, nullptr);
327 list->SetGraphicsRootSignature(root.p);
328 const D3D12_VIEWPORT viewport{0, 0, float(size), float(size), 0, 1};
329 const D3D12_RECT scissor{0, 0, LONG(size), LONG(size)};
330 list->RSSetViewports(1, &viewport);
331 list->RSSetScissorRects(1, &scissor);
332 list->OMSetRenderTargets(1, &rtv, FALSE, nullptr);
333
334 // Mesh draw 1: a 2x2 grid of quads, no offset, red -> the top-left quadrant. No topology was set: a mesh
335 // draw does not need one. An empty grid before it records nothing.
336 const float origin[2] = {0, 0}, down_right[2] = {1, -1};
337 list->SetGraphicsRoot32BitConstants(0, 2, origin, 0);
338 list->SetGraphicsRootConstantBufferView(1, upload_va);
339 list6->DispatchMesh(0, 1, 1);
340 list6->DispatchMesh(2, 2, 1);
341 // Mesh draw 2: groups (0,0,0) and (0,0,1), columns 0 and 1 of row 0, moved by (1, -1), green -> the top half
342 // of the bottom-right quadrant.
343 list->SetGraphicsRoot32BitConstants(0, 2, down_right, 0);
344 list->SetGraphicsRootConstantBufferView(1, upload_va + 256);
345 list6->DispatchMesh(1, 1, 2);
346 // The stream's VS PSO: a full-screen triangle through a viewport on the bottom-left quadrant, yellow.
347 const D3D12_VIEWPORT bottom_left{0, float(size / 2), float(size / 2), float(size / 2), 0, 1};
348 list->RSSetViewports(1, &bottom_left);
349 list->SetPipelineState(vs_pso.p);
350 list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
351 list->SetGraphicsRootConstantBufferView(1, upload_va + 512);
352 list->DrawInstanced(3, 1, 0, 0);
353
354 D3D12_RESOURCE_BARRIER to_copy =
355 transition(target.p, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE);
356 list->ResourceBarrier(1, &to_copy);
357 D3D12_TEXTURE_COPY_LOCATION dst{};
358 dst.pResource = readback.p;
359 dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
360 dst.PlacedFootprint = {0, {DXGI_FORMAT_R8G8B8A8_UNORM, size, size, 1, 256}};
361 D3D12_TEXTURE_COPY_LOCATION src{};
362 src.pResource = target.p;
363 src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
364 list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
365 EXPECT(list->Close() == S_OK);
366 ID3D12CommandList* lists[] = {list.p};
367 queue->ExecuteCommandLists(1, lists);
368 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success);
369 EXPECT(SUCCEEDED(queue->Signal(fence.p, 1)) && SUCCEEDED(fence->SetEventOnCompletion(1, nullptr)));
370 void* mapped = nullptr;
371 EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped)));
372 std::memcpy(pixels.data(), mapped, pixels.size());
373
374 // The wrong kind of draw for the pipeline fails at execution: a vertex draw with the mesh PSO, then
375 // DispatchMesh with the VS PSO.
376 for (const bool vertex_draw : {true, false}) {
377 EXPECT(SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.p, vertex_draw ? mesh_pso.p
378 : vs_pso.p)));
379 list->SetGraphicsRootSignature(root.p);
380 list->RSSetViewports(1, &viewport);
381 list->RSSetScissorRects(1, &scissor);
382 list->OMSetRenderTargets(1, &rtv, FALSE, nullptr);
383 list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
384 if (vertex_draw) list->DrawInstanced(3, 1, 0, 0);
385 else list6->DispatchMesh(1, 1, 1);
386 EXPECT(list->Close() == S_OK);
387 queue->ExecuteCommandLists(1, lists);
388 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::invalid_draw);
389 }
390 // A grid beyond D3D12's limits (65535 per count, 2^22 groups) is a recording error.
391 EXPECT(SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.p, mesh_pso.p)));
392 list->SetGraphicsRootSignature(root.p);
393 list->RSSetViewports(1, &viewport);
394 list6->DispatchMesh(65536, 1, 1);
395 EXPECT(list->Close() == E_INVALIDARG);
396 EXPECT(SUCCEEDED(list->Reset(allocator.p, mesh_pso.p)));
397 list->SetGraphicsRootSignature(root.p);
398 list->RSSetViewports(1, &viewport);
399 list6->DispatchMesh(4096, 1025, 1);
400 EXPECT(list->Close() == E_INVALIDARG);
401 EXPECT(SUCCEEDED(queue->Signal(fence.p, 2)) && SUCCEEDED(fence->SetEventOnCompletion(2, nullptr)));
402
403 // D3D-291: pipeline statistics around mesh draws. Query 0 holds a vertex draw, two mesh draws and another
404 // vertex draw, which the layer splits into a full, a mesh and a full segment; query 1 holds one mesh draw;
405 // query 2 the two vertex draws alone. A mesh draw has no input assembly or vertex shader, so those fields
406 // count only the two full-screen triangles (3 vertices, 1 primitive each). How many clipping and pixel
407 // shader invocations a draw makes is the driver's (RADV's PSInvocations is not the pixel count), so query
408 // 0 is checked against query 2: more of both is the mesh segment's share. Under LEONIDA_VK_VALIDATION=1 the
409 // run must stay free of VUID-vkCmdDrawMeshTasksEXT-pipelineStatistics-07076.
410 if (d.pipeline_statistics_query) {
411 const D3D12_QUERY_HEAP_DESC statistics_desc{D3D12_QUERY_HEAP_TYPE_PIPELINE_STATISTICS, 3, 0};
412 Ref<ID3D12QueryHeap> statistics;
413 EXPECT(SUCCEEDED(device->CreateQueryHeap(&statistics_desc, IID_PPV_ARGS(&statistics.p))));
414 Ref<ID3D12Resource> results;
415 const auto results_desc = buffer_desc(3 * sizeof(D3D12_QUERY_DATA_PIPELINE_STATISTICS));
416 EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &results_desc,
417 D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
418 IID_PPV_ARGS(&results.p))));
419 EXPECT(SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.p, mesh_pso.p)));
420 D3D12_RESOURCE_BARRIER back_to_target =
421 transition(target.p, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_RENDER_TARGET);
422 list->ResourceBarrier(1, &back_to_target);
423 list->SetGraphicsRootSignature(root.p);
424 list->RSSetScissorRects(1, &scissor);
425 list->OMSetRenderTargets(1, &rtv, FALSE, nullptr);
426 list->SetGraphicsRoot32BitConstants(0, 2, origin, 0);
427 list->SetGraphicsRootConstantBufferView(1, upload_va);
428 list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
429 const auto vertex_draw = [&] {
430 list->SetPipelineState(vs_pso.p);
431 list->RSSetViewports(1, &bottom_left);
432 list->DrawInstanced(3, 1, 0, 0);
433 };
434 const auto mesh_draw = [&](UINT x, UINT y) {
435 list->SetPipelineState(mesh_pso.p);
436 list->RSSetViewports(1, &viewport);
437 list6->DispatchMesh(x, y, 1);
438 };
439 list->BeginQuery(statistics.p, D3D12_QUERY_TYPE_PIPELINE_STATISTICS, 0);
440 vertex_draw();
441 mesh_draw(2, 2);
442 mesh_draw(1, 1);
443 vertex_draw();
444 list->EndQuery(statistics.p, D3D12_QUERY_TYPE_PIPELINE_STATISTICS, 0);
445 list->BeginQuery(statistics.p, D3D12_QUERY_TYPE_PIPELINE_STATISTICS, 1);
446 mesh_draw(2, 2);
447 list->EndQuery(statistics.p, D3D12_QUERY_TYPE_PIPELINE_STATISTICS, 1);
448 list->BeginQuery(statistics.p, D3D12_QUERY_TYPE_PIPELINE_STATISTICS, 2);
449 vertex_draw();
450 vertex_draw();
451 list->EndQuery(statistics.p, D3D12_QUERY_TYPE_PIPELINE_STATISTICS, 2);
452 list->ResolveQueryData(statistics.p, D3D12_QUERY_TYPE_PIPELINE_STATISTICS, 0, 3, results.p, 0);
453 EXPECT(list->Close() == S_OK);
454 queue->ExecuteCommandLists(1, lists);
455 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success);
456 EXPECT(SUCCEEDED(queue->Signal(fence.p, 3)) && SUCCEEDED(fence->SetEventOnCompletion(3, nullptr)));
457 D3D12_QUERY_DATA_PIPELINE_STATISTICS data[3]{};
458 void* stats_mapped = nullptr;
459 EXPECT(SUCCEEDED(results->Map(0, nullptr, &stats_mapped)));
460 std::memcpy(data, stats_mapped, sizeof(data));
461 results->Unmap(0, nullptr);
462 const auto& mixed = data[0];
463 const auto& mesh_only = data[1];
464 const auto& vertex_only = data[2];
465 std::printf("statistics, mixed: IA %llu/%llu VS %llu C %llu/%llu PS %llu CS %llu; mesh only: C %llu/%llu "
466 "PS %llu; vertex only: C %llu PS %llu\n",
467 mixed.IAVertices, mixed.IAPrimitives, mixed.VSInvocations, mixed.CInvocations,
468 mixed.CPrimitives, mixed.PSInvocations, mixed.CSInvocations, mesh_only.CInvocations,
469 mesh_only.CPrimitives, mesh_only.PSInvocations, vertex_only.CInvocations,
470 vertex_only.PSInvocations);
471 EXPECT(mixed.IAVertices == 6 && mixed.IAPrimitives == 2 && mixed.VSInvocations >= 1);
472 EXPECT(vertex_only.IAVertices == 6 && vertex_only.IAPrimitives == 2);
473 EXPECT(mixed.GSInvocations == 0 && mixed.GSPrimitives == 0 && mixed.HSInvocations == 0 &&
474 mixed.DSInvocations == 0 && mixed.CSInvocations == 0);
475 EXPECT(mixed.CInvocations > vertex_only.CInvocations && mixed.PSInvocations > vertex_only.PSInvocations);
476 EXPECT(mesh_only.IAVertices == 0 && mesh_only.IAPrimitives == 0 && mesh_only.VSInvocations == 0 &&
477 mesh_only.GSInvocations == 0 && mesh_only.GSPrimitives == 0 && mesh_only.HSInvocations == 0 &&
478 mesh_only.DSInvocations == 0 && mesh_only.CSInvocations == 0);
479 EXPECT(mesh_only.CInvocations > 0 && mesh_only.PSInvocations > 0);
480 } else {
481 std::printf("pipelineStatisticsQuery not available: the D3D-291 statistics check is skipped\n");
482 }
483
484 for (auto* r : {&upload, &readback, &target}) r->reset();
485 for (auto* p : {&mesh_pso, &vs_pso, &refused}) p->reset();
486 root.reset();
487 rtv_heap.reset();
488 list6.reset();
489 list.reset();
490 allocator.reset();
491 queue.reset();
492 fence.reset();
493 EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1);
494 }
495 std::filesystem::remove_all(library);
496
497 unsigned mismatches = 0;
498 for (UINT row = 0; row < size; ++row) {
499 for (UINT col = 0; col < size; ++col) {
500 const bool top = row < size / 2, left = col < size / 2;
501 using Pixel = std::array<std::uint8_t, 4>;
502 const Pixel want = top && left ? Pixel{255, 0, 0, 255}
503 : !top && left ? Pixel{255, 255, 0, 255}
504 : !top && !left && row < size * 3 / 4 ? Pixel{0, 255, 0, 255}
505 : Pixel{0, 0, 255, 255};
506 const std::uint8_t* got = pixels.data() + row * 256 + col * 4;
507 if (std::equal(want.begin(), want.end(), got)) continue;
508 if (mismatches++ < 6)
509 std::fprintf(stderr, "pixel (%u, %u): got %u,%u,%u,%u want %u,%u,%u,%u\n", col, row, got[0], got[1],
510 got[2], got[3], want[0], want[1], want[2], want[3]);
511 }
512 }
513 EXPECT(!mismatches);
514 if (d.validation_errors()) {
515 std::fprintf(stderr, "%u validation errors\n", d.validation_errors());
516 return 1;
517 }
518 std::printf("D3D-29: mesh tier 1; mesh and VS PSOs from pipeline state streams (9 refused as invalid, 2 as not "
519 "implemented); DispatchMesh over X, Y and Z and a stream VS draw matched all %u pixels; wrong-kind "
520 "draws fail at execution, oversized grids at Close; statistics queries around mesh draws resolve\n",
521 size * size);
522 return 0;
523}
diff --git a/runtime/test/device_proxy_test.cpp b/runtime/test/device_proxy_test.cpp
index d5a6ec04e..46a853e7c 100644
--- a/runtime/test/device_proxy_test.cpp
+++ b/runtime/test/device_proxy_test.cpp
@@ -324,6 +324,61 @@ int main(int argc, char** argv) {
324 check(rt::d3d12_xs::device_slot_hits(76) == 2, "slot 76 hit counter is 2"); 324 check(rt::d3d12_xs::device_slot_hits(76) == 2, "slot 76 hit counter is 2");
325 check(rt::d3d12_xs::device_slot_first_call_seen(76), "slot 76 first-call flag is set"); 325 check(rt::d3d12_xs::device_slot_first_call_seen(76), "slot 76 first-call flag is set");
326 326
327 // Xbox device slots from the public HLE. On the Vulkan device the PC entries at 78/79 are
328 // CreateReservedResource2/CreateSampler2 and 80 is past the 80-slot table, so success here can only come from
329 // the routes: frame events return S_OK and a fresh token, CreateCommandQueueX returns a queue proxy and
330 // CreateCommandListX (desc, allocator, initialState, riid, out; no node mask) reaches PC CreateCommandList.
331 {
332 using SetFrameIntervalFn = HRESULT(WINAPI*)(void*, void*, UINT, UINT, UINT);
333 using ScheduleFrameEventFn = HRESULT(WINAPI*)(void*, UINT, UINT, void*, UINT);
334 using WaitFrameEventFn = HRESULT(WINAPI*)(void*, UINT, UINT, void*, UINT, UINT64*);
335 using CreateQueueXFn = HRESULT(WINAPI*)(void*, const D3D12_COMMAND_QUEUE_DESC*, const IID*, void**);
336 using CreateListXFn = HRESULT(WINAPI*)(void*, const void*, ID3D12CommandAllocator*, ID3D12PipelineState*,
337 const IID*, void**);
338
339 hr = reinterpret_cast<SetFrameIntervalFn>(proxy_vtbl[78])(device.Get(), nullptr, 16667, 1, 0);
340 check(hr == S_OK, "slot 78 SetFrameIntervalX returns S_OK");
341 hr = reinterpret_cast<ScheduleFrameEventFn>(proxy_vtbl[79])(device.Get(), 0, 0, nullptr, 0);
342 check(hr == S_OK, "slot 79 ScheduleFrameEventX returns S_OK");
343
344 std::uint64_t token = 0, token2 = 0;
345 hr = reinterpret_cast<WaitFrameEventFn>(proxy_vtbl[80])(device.Get(), 0, INFINITE, nullptr, 0, &token);
346 check(hr == S_OK && token != 0, "slot 80 WaitFrameEventX returns a non-zero token");
347 hr = reinterpret_cast<WaitFrameEventFn>(proxy_vtbl[80])(device.Get(), 0, 0, nullptr, 0, &token2);
348 check(hr == S_OK && token2 != 0 && token2 != token, "slot 80 returns a fresh token on the next wait");
349 hr = reinterpret_cast<WaitFrameEventFn>(proxy_vtbl[80])(device.Get(), 0, 0, nullptr, 0, nullptr);
350 check(hr == E_POINTER, "slot 80 refuses a null token with E_POINTER");
351 check(rt::d3d12_xs::device_slot_hits(78) == 1 && rt::d3d12_xs::device_slot_hits(79) == 1 &&
352 rt::d3d12_xs::device_slot_hits(80) == 3,
353 "slots 78/79/80 hit counters are 1/1/3");
354
355 D3D12_COMMAND_QUEUE_DESC xbox_queue{};
356 xbox_queue.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
357 const IID iid_queue = __uuidof(ID3D12CommandQueue);
358 ComPtr<ID3D12CommandQueue> xbox_queue_proxy;
359 hr = reinterpret_cast<CreateQueueXFn>(proxy_vtbl[48])(device.Get(), &xbox_queue, &iid_queue,
360 reinterpret_cast<void**>(xbox_queue_proxy.GetAddressOf()));
361 check(hr == S_OK && rt::d3d12_xs::is_queue_proxy(xbox_queue_proxy.Get()),
362 "slot 48 CreateCommandQueueX returns a queue proxy");
363 check(rt::d3d12_xs::device_slot_hits(48) == 1, "slot 48 hit counter is 1");
364
365 ComPtr<ID3D12CommandAllocator> xbox_allocator;
366 hr = device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT,
367 IID_PPV_ARGS(xbox_allocator.GetAddressOf()));
368 struct XboxCommandListDesc {
369 UINT Type;
370 UINT NodeMask;
371 } list_desc{D3D12_COMMAND_LIST_TYPE_DIRECT, 7}; // the node mask is ignored by the console call
372 const IID iid_list = __uuidof(ID3D12GraphicsCommandList);
373 ComPtr<ID3D12GraphicsCommandList> xbox_list;
374 hr = SUCCEEDED(hr) ? reinterpret_cast<CreateListXFn>(proxy_vtbl[73])(
375 device.Get(), &list_desc, xbox_allocator.Get(), nullptr, &iid_list,
376 reinterpret_cast<void**>(xbox_list.GetAddressOf()))
377 : hr;
378 check(hr == S_OK && xbox_list != nullptr, "slot 73 CreateCommandListX returns a command list");
379 check(rt::d3d12_xs::device_slot_hits(73) == 1, "slot 73 hit counter is 1");
380 }
381
327 // Slot 62: an empty root signature and a trivial compute shader through the Xbox signature. The PC entry at 382 // Slot 62: an empty root signature and a trivial compute shader through the Xbox signature. The PC entry at
328 // slot 62 is CreateStateObject, so success here proves the override reached CreateComputePipelineState. 383 // slot 62 is CreateStateObject, so success here proves the override reached CreateComputePipelineState.
329 D3D12_ROOT_SIGNATURE_DESC root_desc{}; 384 D3D12_ROOT_SIGNATURE_DESC root_desc{};
diff --git a/runtime/test/dxgi_device_test.cpp b/runtime/test/dxgi_device_test.cpp
index 25e82f92d..a105af571 100644
--- a/runtime/test/dxgi_device_test.cpp
+++ b/runtime/test/dxgi_device_test.cpp
@@ -230,7 +230,19 @@ int check_direct(const char* label, ID3D12Device* real, bool vulkan) {
230 EXPECT(dxgi->GetAdapter(&none) == E_ABORT && !none); 230 EXPECT(dxgi->GetAdapter(&none) == E_ABORT && !none);
231 EXPECT(xs::set_device_adapter_provider(proxy, nullptr)); // back to the default (the host's adapter) 231 EXPECT(xs::set_device_adapter_provider(proxy, nullptr)); // back to the default (the host's adapter)
232 Ref<IDXGIAdapter> host; 232 Ref<IDXGIAdapter> host;
233 EXPECT(dxgi->GetAdapter(&host.p) == S_OK && host.p); 233 const HRESULT default_hr = dxgi->GetAdapter(&host.p);
234 // The default asks the host's DXGI for the adapter with the device's LUID. Under Wine 9 the Vulkan device's
235 // LUID is not one Wine's DXGI enumerates, so the host answers DXGI_ERROR_NOT_FOUND: a host difference (the
236 // Wine 11.22 run in docs/testing.md doesn't list this test as failing), checked as a failure that hands nothing
237 // out.
238 static const bool wine = GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "wine_get_version") != nullptr;
239 if (vulkan && wine && default_hr == DXGI_ERROR_NOT_FOUND) {
240 std::printf("%s: the default adapter provider: Wine's DXGI has no adapter with the Vulkan device's LUID "
241 "(DXGI_ERROR_NOT_FOUND), not compared\n", label);
242 EXPECT(!host.p);
243 } else {
244 EXPECT(default_hr == S_OK && host.p);
245 }
234 void* not_a_proxy = nullptr; // pointer-sized: the helpers read a vtable pointer from what they are given 246 void* not_a_proxy = nullptr; // pointer-sized: the helpers read a vtable pointer from what they are given
235 EXPECT(!xs::set_device_adapter_provider(&not_a_proxy, refuse) && !xs::set_device_adapter_provider(real, refuse)); 247 EXPECT(!xs::set_device_adapter_provider(&not_a_proxy, refuse) && !xs::set_device_adapter_provider(real, refuse));
236 EXPECT(!xs::device_proxy_primary(&not_a_proxy) && !xs::device_proxy_primary(nullptr)); 248 EXPECT(!xs::device_proxy_primary(&not_a_proxy) && !xs::device_proxy_primary(nullptr));
diff --git a/runtime/test/file_system_test.cpp b/runtime/test/file_system_test.cpp
index aa0d1a86e..3ba1482f7 100644
--- a/runtime/test/file_system_test.cpp
+++ b/runtime/test/file_system_test.cpp
@@ -12,6 +12,8 @@
12#include <cstdio> 12#include <cstdio>
13#include <exception> 13#include <exception>
14#include <filesystem> 14#include <filesystem>
15#include <fstream>
16#include <sstream>
15#include <initializer_list> 17#include <initializer_list>
16#include <string> 18#include <string>
17#include <thread> 19#include <thread>
@@ -19,6 +21,7 @@
19 21
20#include "file_system.h" 22#include "file_system.h"
21#include "shims.h" 23#include "shims.h"
24#include "startup_trace.h"
22 25
23namespace { 26namespace {
24 27
@@ -249,6 +252,40 @@ void run_checks(const std::filesystem::path& root) {
249 if (h != INVALID_HANDLE_VALUE) ::CloseHandle(h); 252 if (h != INVALID_HANDLE_VALUE) ::CloseHandle(h);
250 } 253 }
251 254
255 // --trace: a failed open of a guest path is a "file_open_failed" event, a successful one is not, and with the
256 // trace off nothing is written.
257 {
258 const std::wstring trace = (root / "open_trace.jsonl").wstring();
259 const auto events = [&] {
260 std::ifstream in(std::filesystem::path(trace), std::ios::binary);
261 std::stringstream text;
262 text << in.rdbuf();
263 return text.str();
264 };
265 const auto count = [](const std::string& hay, const std::string& needle) {
266 int n = 0;
267 for (size_t at = hay.find(needle); at != std::string::npos; at = hay.find(needle, at + 1)) ++n;
268 return n;
269 };
270 HANDLE h = create_w(L"GAME:\\data\\absent_off.txt", GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr);
271 check(h == INVALID_HANDLE_VALUE && GetLastError() == ERROR_FILE_NOT_FOUND, "a missing open fails with the trace off");
272 check(rt::startup_trace::open(trace.c_str()), "open the startup trace file");
273 h = create_w(L"GAME:\\data\\hello.txt", GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr);
274 check(h != INVALID_HANDLE_VALUE, "an open that succeeds");
275 if (h != INVALID_HANDLE_VALUE) ::CloseHandle(h);
276 check(count(events(), "file_open_failed") == 0, "a successful open writes no file_open_failed event");
277 h = create_w(L"GAME:\\data\\absent_on.txt", GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr);
278 check(h == INVALID_HANDLE_VALUE && GetLastError() == ERROR_FILE_NOT_FOUND,
279 "a missing open still fails the same way with the trace on");
280 rt::startup_trace::close();
281 const std::string log = events();
282 check(count(log, "\"kind\":\"file_open_failed\"") == 1, "one file_open_failed event");
283 check(log.find("\"path\":\"GAME:\\\\data\\\\absent_on.txt\"") != std::string::npos, "the event names the path");
284 check(log.find("\"error\":2,") != std::string::npos, "the event carries error 2");
285 check(log.find("\"caller\":\"host:") != std::string::npos, "the event names a caller");
286 check(count(log, "absent_off") == 0, "nothing was traced before the trace was opened");
287 }
288
252 // Attributes, wide and narrow. 289 // Attributes, wide and narrow.
253 check(attributes_w(L"GAME:\\data\\hello.txt") != INVALID_FILE_ATTRIBUTES, "GetFileAttributesW stats a package file"); 290 check(attributes_w(L"GAME:\\data\\hello.txt") != INVALID_FILE_ATTRIBUTES, "GetFileAttributesW stats a package file");
254 check(attributes_a("GAME:\\data\\hello.txt") != INVALID_FILE_ATTRIBUTES, "GetFileAttributesA stats a package file"); 291 check(attributes_a("GAME:\\data\\hello.txt") != INVALID_FILE_ATTRIBUTES, "GetFileAttributesA stats a package file");
diff --git a/runtime/test/glsl/ms_draw.mesh b/runtime/test/glsl/ms_draw.mesh
new file mode 100644
index 000000000..8bfd21785
--- /dev/null
+++ b/runtime/test/glsl/ms_draw.mesh
@@ -0,0 +1,34 @@
1#version 460
2// A mesh shader written to the translator's runtime contract (docs/design.md, "User data" and "Mesh shaders"),
3// standing in for a translated one in d3d12_mesh_test. Each workgroup emits one quad (4 vertices, 2 triangles) on a
4// 4x4 grid of clip-space cells: column = WorkgroupId.x + WorkgroupId.z, row = WorkgroupId.y, so all three
5// DispatchMesh counts reach the shader. s0, s1 (root constants) move the quad in clip space; the colour is red. The
6// corners are top-left, top-right, bottom-left, bottom-right and the triangles (0,1,2) and (2,1,3), clockwise in D3D
7// screen space as in d3d12_draw_test, so they are front-facing with the default winding.
8#extension GL_EXT_mesh_shader : require
9
10layout(local_size_x = 32) in;
11layout(triangles, max_vertices = 4, max_primitives = 2) out;
12
13layout(location = 0) out vec4 out_color[];
14
15layout(push_constant) uniform UserData {
16 uint s[32];
17 uvec2 heap_base;
18 uvec2 code_base;
19} pc;
20
21void main() {
22 SetMeshOutputsEXT(4, 2);
23 const uint i = gl_LocalInvocationIndex;
24 const float column = float(gl_WorkGroupID.x + gl_WorkGroupID.z), row = float(gl_WorkGroupID.y);
25 const vec2 offset = vec2(uintBitsToFloat(pc.s[0]), uintBitsToFloat(pc.s[1]));
26 if (i < 4) {
27 const vec2 corner = vec2(float(i & 1u), float(i >> 1));
28 const vec2 top_left = vec2(-1.0 + 0.5 * column, 1.0 - 0.5 * row);
29 gl_MeshVerticesEXT[i].gl_Position = vec4(top_left + vec2(0.5, -0.5) * corner + offset, 0.0, 1.0);
30 out_color[i] = vec4(1.0, 0.0, 0.0, 1.0);
31 }
32 if (i == 0) gl_PrimitiveTriangleIndicesEXT[0] = uvec3(0, 1, 2);
33 if (i == 1) gl_PrimitiveTriangleIndicesEXT[1] = uvec3(2, 1, 3);
34}
diff --git a/runtime/test/int3_skip_test.cpp b/runtime/test/int3_skip_test.cpp
new file mode 100644
index 000000000..3c06302eb
--- /dev/null
+++ b/runtime/test/int3_skip_test.cpp
@@ -0,0 +1,65 @@
1// LEONIDA_SKIP_INT3 (shims/startup_trace.h): with the variable set and a trace open, an int3 is logged once per
2// address and stepped over, so execution continues. A separate executable because the variable is read once.
3#include <windows.h>
4
5#include <cstdio>
6#include <fstream>
7#include <sstream>
8#include <string>
9
10#include "shims.h"
11#include "startup_trace.h"
12
13namespace {
14
15int g_failed = 0;
16
17void check(bool ok, const char* what) {
18 std::printf("%s %s\n", ok ? "ok " : "FAIL ", what);
19 if (!ok) ++g_failed;
20}
21
22int count(const std::string& hay, const std::string& needle) {
23 int n = 0;
24 for (size_t at = hay.find(needle); at != std::string::npos; at = hay.find(needle, at + 1)) ++n;
25 return n;
26}
27
28// noinline: the optimizer must not unroll the loop into two separate int3 sites.
29__declspec(noinline) void site_a(int& reached) {
30 __debugbreak();
31 ++reached;
32}
33__declspec(noinline) void site_b(int& reached) {
34 __debugbreak();
35 ++reached;
36}
37
38} // namespace
39
40int main() {
41 SetEnvironmentVariableW(L"LEONIDA_SKIP_INT3", L"1"); // before the first exception: the flag is read once
42 wchar_t temp[MAX_PATH];
43 GetTempPathW(MAX_PATH, temp);
44 const std::wstring path = std::wstring(temp) + L"int3_skip_test_" + std::to_wstring(GetCurrentProcessId()) + L".jsonl";
45 DeleteFileW(path.c_str());
46 check(rt::startup_trace::open(path.c_str()), "open the startup trace file");
47
48 int reached = 0;
49 for (int i = 0; i < 2; ++i) site_a(reached); // the same site twice: one event
50 site_b(reached); // another site
51 check(reached == 3, "execution continues past every int3");
52 rt::startup_trace::close();
53
54 std::ifstream in(path);
55 std::stringstream text;
56 text << in.rdbuf();
57 const std::string log = text.str();
58 in.close();
59 DeleteFileW(path.c_str());
60 check(count(log, "\"kind\":\"int3_skipped\"") == 2, "exactly two int3_skipped events (one per address)");
61 check(count(log, "\"kind\":\"exception\"") == 0, "a skipped int3 is not also logged as an exception");
62 check(log.find("\"at\":\"host:") != std::string::npos, "the event names the address");
63 std::printf("%s\n", g_failed ? "FAILED" : "all checks passed");
64 return g_failed ? 1 : 0;
65}
diff --git a/runtime/test/replay_cpu_bench.cpp b/runtime/test/replay_cpu_bench.cpp
index a271d75d2..a3957d166 100644
--- a/runtime/test/replay_cpu_bench.cpp
+++ b/runtime/test/replay_cpu_bench.cpp
@@ -493,6 +493,7 @@ const char* result_name(ReplayResult r) {
493 case ReplayResult::invalid_predication: return "invalid_predication"; 493 case ReplayResult::invalid_predication: return "invalid_predication";
494 case ReplayResult::invalid_query: return "invalid_query"; 494 case ReplayResult::invalid_query: return "invalid_query";
495 case ReplayResult::invalid_indirect_arguments: return "invalid_indirect_arguments"; 495 case ReplayResult::invalid_indirect_arguments: return "invalid_indirect_arguments";
496 case ReplayResult::invalid_draw: return "invalid_draw";
496 case ReplayResult::unsupported: return "unsupported"; 497 case ReplayResult::unsupported: return "unsupported";
497 } 498 }
498 return "?"; 499 return "?";
diff --git a/runtime/test/replay_query_edges_test.cpp b/runtime/test/replay_query_edges_test.cpp
index 1bd55d237..820dc0dc1 100644
--- a/runtime/test/replay_query_edges_test.cpp
+++ b/runtime/test/replay_query_edges_test.cpp
@@ -239,8 +239,8 @@ struct MockReplay {
239 VkDeviceSize off) { 239 VkDeviceSize off) {
240 helper(false, false, p, f, n, b, off); 240 helper(false, false, p, f, n, b, off);
241 }; 241 };
242 v.sum_statistics = [helper](VkCommandBuffer, VkQueryPool p, unsigned f, unsigned n, VkBuffer b, 242 v.sum_statistics = [helper](VkCommandBuffer, VkQueryPool p, VkQueryPool, const std::uint8_t*, unsigned f,
243 VkDeviceSize off) { 243 unsigned n, VkBuffer b, VkDeviceSize off) {
244 helper(true, false, p, f, n, b, off); 244 helper(true, false, p, f, n, b, off);
245 }; 245 };
246 v.resolve_binary_occlusion = [helper](VkCommandBuffer, VkQueryPool p, unsigned f, unsigned n, VkBuffer b, 246 v.resolve_binary_occlusion = [helper](VkCommandBuffer, VkQueryPool p, unsigned f, unsigned n, VkBuffer b,
@@ -286,7 +286,9 @@ void test_helper_chunks() {
286 const VkDescriptorSet*, unsigned, const unsigned*) {}; 286 const VkDescriptorSet*, unsigned, const unsigned*) {};
287 vk.vkCmdPushConstants = +[](VkCommandBuffer, VkPipelineLayout, VkShaderStageFlags, unsigned off, unsigned size, 287 vk.vkCmdPushConstants = +[](VkCommandBuffer, VkPipelineLayout, VkShaderStageFlags, unsigned off, unsigned size,
288 const void*p) { 288 const void*p) {
289 expect(off == 0 && size == sizeof(unsigned), "chunk push constants"); 289 // The count, then statistics_sum.comp's mesh flag (D3D-291), which no segment here sets.
290 expect(off == 0 && size == 2 * sizeof(unsigned), "chunk push constants");
291 expect(static_cast<const unsigned *>(p)[1] == 0, "chunk push constants: no mesh segment");
290 MockReplay::current->chunks.push_back(*static_cast<const unsigned *>(p)); 292 MockReplay::current->chunks.push_back(*static_cast<const unsigned *>(p));
291 }; 293 };
292 vk.vkCmdDispatch = +[](VkCommandBuffer, unsigned x, unsigned y, unsigned z) { 294 vk.vkCmdDispatch = +[](VkCommandBuffer, unsigned x, unsigned y, unsigned z) {
@@ -346,7 +348,7 @@ void test_helper_chunks() {
346 } 348 }
347 } else { 349 } else {
348 if (mode == MockReplay::statistics) { 350 if (mode == MockReplay::statistics) {
349 helper.sum_statistics({}, qp, first, n, dst, output_offset); 351 helper.sum_statistics({}, qp, VK_NULL_HANDLE, nullptr, first, n, dst, output_offset);
350 } else { 352 } else {
351 helper.sum({}, qp, first, n, dst, output_offset); 353 helper.sum({}, qp, first, n, dst, output_offset);
352 } 354 }
@@ -386,7 +388,7 @@ void test_helper_chunks() {
386 expect(c.word(dst, output_offset) == reset_sum, "sum accumulator reset between calls"); 388 expect(c.word(dst, output_offset) == reset_sum, "sum accumulator reset between calls");
387 c.mode = MockReplay::statistics; 389 c.mode = MockReplay::statistics;
388 c.values[qp][first_query].fill(reset_counter); 390 c.values[qp][first_query].fill(reset_counter);
389 helper.sum_statistics({}, qp, first_query, 1, dst, output_offset); 391 helper.sum_statistics({}, qp, VK_NULL_HANDLE, nullptr, first_query, 1, dst, output_offset);
390 for (unsigned j = 0; j < statistics_counters; ++j) { 392 for (unsigned j = 0; j < statistics_counters; ++j) {
391 expect(c.word(dst, output_offset + word_size * j) == reset_counter, "statistics accumulator reset"); 393 expect(c.word(dst, output_offset + word_size * j) == reset_counter, "statistics accumulator reset");
392 } 394 }
diff --git a/runtime/test/replay_query_predication_test.cpp b/runtime/test/replay_query_predication_test.cpp
index e4a513676..3ef0b484a 100644
--- a/runtime/test/replay_query_predication_test.cpp
+++ b/runtime/test/replay_query_predication_test.cpp
@@ -5,7 +5,9 @@
5// how resolves inside a pipeline-statistics query are replayed; cases 7 and 8 cover the other helper dispatches 5// how resolves inside a pipeline-statistics query are replayed; cases 7 and 8 cover the other helper dispatches
6// and their no-pool fallback (D3D-162). Cases 9 to 13 check overlapping queries: statistics over statistics, binary 6// and their no-pool fallback (D3D-162). Cases 9 to 13 check overlapping queries: statistics over statistics, binary
7// inside ordinary, the composite sum-and-normalize binary resolve, helper dispatches inside overlapping statistics 7// inside ordinary, the composite sum-and-normalize binary resolve, helper dispatches inside overlapping statistics
8// queries, and the single-list refusal (D3D-252) and, with a pool, its replay (D3D-399). No GPU or game data. 8// queries, the single-list refusal (D3D-252) and, with a pool, its replay (D3D-399). Cases 15 and 16 check queries
9// that hold mesh draws, split between the full and the mesh-compatible pool, alone and overlapping (D3D-291). No GPU or
10// game data.
9#include "../src/vulkan_replay.h" 11#include "../src/vulkan_replay.h"
10#include <cstdint> 12#include <cstdint>
11#include <cstdio> 13#include <cstdio>
@@ -125,8 +127,8 @@ int main() {
125 vk.query_pool = [&](QueryHeapId id) -> QueryPool* { 127 vk.query_pool = [&](QueryHeapId id) -> QueryPool* {
126 return id == 1 ? &heap : id == 6 ? &statistics_heap : nullptr; 128 return id == 1 ? &heap : id == 6 ? &statistics_heap : nullptr;
127 }; 129 };
128 vk.sum_statistics = [](VkCommandBuffer, VkQueryPool pool, std::uint32_t first, std::uint32_t count, VkBuffer, 130 vk.sum_statistics = [](VkCommandBuffer, VkQueryPool pool, VkQueryPool, const std::uint8_t*, std::uint32_t first,
129 VkDeviceSize) { 131 std::uint32_t count, VkBuffer, VkDeviceSize) {
130 g_trace->events.push_back(query_event("sum_statistics", pool, first) + "+" + std::to_string(count)); 132 g_trace->events.push_back(query_event("sum_statistics", pool, first) + "+" + std::to_string(count));
131 }; 133 };
132 vk.resolve_binary_occlusion = [](VkCommandBuffer, VkQueryPool, std::uint32_t, std::uint32_t, VkBuffer, 134 vk.resolve_binary_occlusion = [](VkCommandBuffer, VkQueryPool, std::uint32_t, std::uint32_t, VkBuffer,
@@ -619,6 +621,140 @@ int main() {
619 expect(trace.events == want, "pooled: the same segments and sums as the batched path"); 621 expect(trace.events == want, "pooled: the same segments and sums as the batched path");
620 } 622 }
621 623
624 // 15. D3D-291: a pipeline-statistics query around vertex, mesh, mesh and vertex draws is split where the kind
625 // changes, the mesh segment is marked for the mesh pool, and its resolve sums the three segments. A query that
626 // holds only a mesh draw is one mesh segment, still summed so its counters land in their D3D12 fields; one
627 // with only vertex draws is not split.
628 {
629 Trace trace;
630 g_trace = &trace;
631 const auto draw = [](bool mesh) {
632 Draw d{};
633 d.pipeline = 1;
634 d.count = d.instances = d.first = 1;
635 d.mesh = mesh;
636 return d;
637 };
638 CommandList list;
639 expect(list.begin_query({6, d3d12_query::pipeline_statistics, 0}), "record mixed begin"); // 0
640 expect(list.draw(draw(false)), "record vertex draw"); // 1
641 expect(list.draw(draw(true)), "record mesh draw"); // 2
642 expect(list.draw(draw(true)), "record second mesh draw"); // 3
643 expect(list.draw(draw(false)), "record second vertex draw"); // 4
644 expect(list.end_query({6, d3d12_query::pipeline_statistics, 0}), "record mixed end"); // 5
645 expect(list.begin_query({6, d3d12_query::pipeline_statistics, 1}), "record mesh-only begin"); // 6
646 expect(list.draw(draw(true)), "record lone mesh draw"); // 7
647 expect(list.end_query({6, d3d12_query::pipeline_statistics, 1}), "record mesh-only end"); // 8
648 expect(list.begin_query({6, d3d12_query::pipeline_statistics, 0}), "record vertex-only begin"); // 9
649 expect(list.draw(draw(false)), "record lone vertex draw"); // 10
650 expect(list.end_query({6, d3d12_query::pipeline_statistics, 0}), "record vertex-only end"); // 11
651 expect(list.resolve_queries({6, d3d12_query::pipeline_statistics, 1, 1, 1, 0}), "record mesh resolve");
652 expect(list.close(), "close mixed list");
653 expect(list.commands().size() == 13, "mixed list: thirteen commands");
654
655 // The draws need a pipeline and attachments to prepare, so the query plan is built by hand here; the GPU
656 // test d3d12_mesh_test replays the same shape.
657 PreparedList prepared;
658 prepared.list = &list;
659 prepared.commands.assign(list.commands().size(), {});
660 for (std::size_t i : {0, 5, 6, 8, 9, 11, 12}) {
661 const bool begin = std::holds_alternative<BeginQuery>(list.commands()[i]);
662 prepared.queries.push_back({i, &statistics_heap, begin}); // as prepare() records statistics_active
663 }
664 plan_statistics_segments(prepared);
665 expect(prepared.statistics_segment_count == 4, "mixed list: three segments and one for the mesh-only query");
666 expect(prepared.statistics_mesh == std::vector<std::uint8_t>({0, 1, 0, 1}),
667 "mixed list: vertex, mesh, vertex, then the mesh-only query's mesh segment");
668 const auto& c = prepared.commands;
669 constexpr auto none = UINT32_MAX;
670 expect(c[1].statistics_begin == none && c[3].statistics_begin == none && c[7].statistics_begin == none &&
671 c[10].statistics_begin == none,
672 "mixed list: no split before a draw of the segment's own kind");
673 expect(c[2].statistics_end == 0 && c[2].statistics_begin == 1, "mixed list: the first mesh draw splits");
674 expect(c[4].statistics_end == 1 && c[4].statistics_begin == 2, "mixed list: the vertex draw after it splits");
675 const auto& q = prepared.queries;
676 expect(q[0].statistics_begin == 0 && q[1].statistics_end == 2 && q[1].statistics_first == 0 &&
677 q[1].statistics_count == 3,
678 "mixed list: the query ends in its third segment and sums all three");
679 expect(q[2].statistics_begin == 3 && q[3].statistics_end == 3 && q[3].statistics_count == 1,
680 "mixed list: the mesh-only query is one segment");
681 expect(q[4].statistics_begin == detail::PreparedQuery::no_segment &&
682 q[5].statistics_end == detail::PreparedQuery::no_segment,
683 "mixed list: the vertex-only query is not split");
684
685 auto segments = std::make_shared<OcclusionSegmentPool>();
686 segments->pool = handle<VkQueryPool>(9);
687 segments->mesh_pool = handle<VkQueryPool>(10);
688 segments->mesh = prepared.statistics_mesh;
689 segments->destroy = mock_destroy_pool;
690 QueryReplay queries;
691 expect(queries.plan(prepared, {}, 0, true, segments, 0) == ReplayResult::success, "plan mixed list");
692 expect(prepared.statistics_mesh_pool == handle<VkQueryPool>(10), "mixed list: the mesh pool is the list's");
693 expect(q[6].resolves.size() == 1 && q[6].resolves[0].sum && q[6].resolves[0].first == 3 &&
694 q[6].resolves[0].count == 1 && q[6].resolves[0].mesh_pool == handle<VkQueryPool>(10) &&
695 q[6].resolves[0].mesh && q[6].resolves[0].mesh[3] == 1,
696 "mixed list: the mesh-only query's resolve sums its one mesh segment");
697 expect(queries.needs_statistics_sum, "mixed list: the statistics sum helper is needed");
698
699 // Without the mesh-compatible pool, the query cannot run unsplit around a mesh draw.
700 PreparedList again = prepared;
701 again.statistics_pool = again.statistics_mesh_pool = VK_NULL_HANDLE;
702 auto full_only = std::make_shared<OcclusionSegmentPool>();
703 full_only->pool = handle<VkQueryPool>(9);
704 full_only->destroy = mock_destroy_pool;
705 QueryReplay refused;
706 expect(refused.plan(again, {}, 0, true, full_only, 0) == ReplayResult::unsupported,
707 "mixed list: refused without the mesh pool");
708 QueryReplay unsplit;
709 expect(unsplit.plan(again, {}, 0, true, {}, 0) == ReplayResult::unsupported,
710 "mixed list: refused without a segment pool");
711 }
712
713 // 16. D3D-291 with overlapping statistics queries (D3D-252's planner): query 0 holds a vertex and a mesh draw,
714 // query 1 (begun inside it) a mesh draw, then a mesh and a vertex draw after query 0 ends. Every Begin and
715 // End opens a segment as before; the vertex draw after the mesh draws opens one more, so the four segments
716 // are vertex, mesh, mesh, vertex, query 0 sums segments 0-1 and query 1 segments 1-3.
717 {
718 const auto draw = [](bool mesh) {
719 Draw d{};
720 d.pipeline = 1;
721 d.count = d.instances = d.first = 1;
722 d.mesh = mesh;
723 return d;
724 };
725 CommandList list;
726 expect(list.begin_query({6, d3d12_query::pipeline_statistics, 0}), "record overlap-mesh begin 0"); // 0
727 expect(list.draw(draw(false)), "record overlap-mesh vertex draw"); // 1
728 expect(list.begin_query({6, d3d12_query::pipeline_statistics, 1}), "record overlap-mesh begin 1"); // 2
729 expect(list.draw(draw(true)), "record overlap-mesh mesh draw"); // 3
730 expect(list.end_query({6, d3d12_query::pipeline_statistics, 0}), "record overlap-mesh end 0"); // 4
731 expect(list.draw(draw(true)), "record overlap-mesh second mesh draw"); // 5
732 expect(list.draw(draw(false)), "record overlap-mesh second vertex draw"); // 6
733 expect(list.end_query({6, d3d12_query::pipeline_statistics, 1}), "record overlap-mesh end 1"); // 7
734 expect(list.close(), "close overlap-mesh list");
735 PreparedList prepared;
736 prepared.list = &list;
737 prepared.commands.assign(list.commands().size(), {});
738 for (std::size_t i : {0, 2, 4, 7}) {
739 const bool begin = std::holds_alternative<BeginQuery>(list.commands()[i]);
740 prepared.queries.push_back({i, &statistics_heap, begin});
741 }
742 expect(plan_overlapping_statistics_segments(prepared) == ReplayResult::success, "plan overlap-mesh list");
743 expect(prepared.statistics_segment_count == 4, "overlap-mesh: four segments");
744 expect(prepared.statistics_mesh == std::vector<std::uint8_t>({0, 1, 1, 0}),
745 "overlap-mesh: vertex, mesh, mesh, vertex");
746 const auto& c = prepared.commands;
747 constexpr auto none = detail::PreparedQuery::no_segment;
748 expect(c[1].statistics_begin == none && c[3].statistics_begin == none && c[5].statistics_begin == none,
749 "overlap-mesh: a segment's first draw and a draw of its kind do not split");
750 expect(c[6].statistics_end == 2 && c[6].statistics_begin == 3,
751 "overlap-mesh: the vertex draw after the mesh draws splits");
752 const auto& q = prepared.queries;
753 // queries[] follows the commands: Begin 0, Begin 1, End 0, End 1.
754 expect(q[2].statistics_first == 0 && q[2].statistics_count == 2, "overlap-mesh: query 0 sums segments 0-1");
755 expect(q[3].statistics_first == 1 && q[3].statistics_count == 3, "overlap-mesh: query 1 sums segments 1-3");
756 }
757
622 if (failures) return 1; 758 if (failures) return 1;
623 std::puts("replay_query_predication_test: query resolves suspend conditional rendering around fills, copies and dispatches"); 759 std::puts("replay_query_predication_test: query resolves suspend conditional rendering around fills, copies and dispatches");
624 return 0; 760 return 0;
diff --git a/runtime/test/shaders/check.py b/runtime/test/shaders/check.py
index 35bc21a6f..9553776b8 100644
--- a/runtime/test/shaders/check.py
+++ b/runtime/test/shaders/check.py
@@ -85,7 +85,7 @@ WAVE32_DUMPS = ("cs_store", "cs_signed_zero_nan", "cs_smem_soffset_imm", "cs_wqm
85 "cs_w32_lds_subdword", "cs_w32_lds_wide", 85 "cs_w32_lds_subdword", "cs_w32_lds_wide",
86 "cs_w32_partial_scmp", "cs_exec_const", "cs_w32_mask_imm", "cs_w32_int_ext", 86 "cs_w32_partial_scmp", "cs_exec_const", "cs_w32_mask_imm", "cs_w32_int_ext",
87 "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", "cs_w32_sincos", "cs_lds_b64_cmpst", "cs_w32_andn2_exec", 87 "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", "cs_w32_sincos", "cs_lds_b64_cmpst", "cs_w32_andn2_exec",
88 "cs_mask_vgpr_exec", "cs_w32_fcmpswap", "cs_w32_permlane_fi") 88 "cs_mask_vgpr_exec", "cs_w32_buffer_sub16", "cs_w32_buffer_store_sub", "cs_w32_fcmpswap", "cs_w32_permlane_fi")
89# Wave32 lane-mask dumps: their EXEC/VCC masks and lane selects cover 32 lanes, so a device whose widest subgroup is 89# Wave32 lane-mask dumps: their EXEC/VCC masks and lane selects cover 32 lanes, so a device whose widest subgroup is
90# narrower (Mesa llvmpipe: 8) can't produce their words. They are skipped there, as ps_bitmask_perm is. They run with 90# narrower (Mesa llvmpipe: 8) can't produce their words. They are skipped there, as ps_bitmask_perm is. They run with
91# 32 lanes requested (WAVE32_LANE_ENV), as run_gpu_tests.py does: a device with a range like 8..32 (Intel ANV) may 91# 32 lanes requested (WAVE32_LANE_ENV), as run_gpu_tests.py does: a device with a range like 8..32 (Intel ANV) may
@@ -115,6 +115,10 @@ CS_DUMPS = [*CS_DPP, ("cs_store", CS_STORE), ("cs_smem_soffset_imm", CS_SMEM),
115 # 64-bit scalar data ops and v_mad_u64_u32 (derivations in cs_w32_salu64.asm) 115 # 64-bit scalar data ops and v_mad_u64_u32 (derivations in cs_w32_salu64.asm)
116 # more ops with CPU-only checks until now (derivations in cs_w32_misc_ext.asm) 116 # more ops with CPU-only checks until now (derivations in cs_w32_misc_ext.asm)
117 # ops merged on 2026-11-22 with CPU-only checks (derivations in cs_w32_new_ops.asm) 117 # ops merged on 2026-11-22 with CPU-only checks (derivations in cs_w32_new_ops.asm)
118 # plain 8/16-bit MUBUF stores, one crossing a dword (cs_w32_buffer_store_sub.asm)
119 ("cs_w32_buffer_store_sub", [0x1122AB44, 0xCDEF7788, 0x34AABBCC, 0xDDDDDD12, 0x0102035A, 0x05061234, 0xAB, 0xFFFFCDEF]),
120 # 8/16-bit MUBUF d16 loads and stores (cs_w32_buffer_sub16.asm)
121 ("cs_w32_buffer_sub16", [0xBEEF00AA, 0x00AA1234, 0xBEEFFFAA, 0xFFAA1234, 0xBEEF8899, 0x88991234, 0x1122CD44, 0xABCD7788]),
118 # ds_cmpst_f32 and buffer_atomic_fcmpswap: float compare (cs_w32_fcmpswap.asm) 122 # ds_cmpst_f32 and buffer_atomic_fcmpswap: float compare (cs_w32_fcmpswap.asm)
119 ("cs_w32_fcmpswap", [0, 0x3F800000, 0x7FC00000, 0x3F800000, 0x80000000, 0x40400000, 0x3F800000, 0x7FC00000]), 123 ("cs_w32_fcmpswap", [0, 0x3F800000, 0x7FC00000, 0x3F800000, 0x80000000, 0x40400000, 0x3F800000, 0x7FC00000]),
120 ("cs_w32_new_ops", [0x55, 0x8001, 0xC0000000, 0x80014000, 0x4000FFFF, 0x77, 0x99, 0x1234]), 124 ("cs_w32_new_ops", [0x55, 0x8001, 0xC0000000, 0x80014000, 0x4000FFFF, 0x77, 0x99, 0x1234]),
@@ -339,6 +343,8 @@ CVT_F32_SAT_CASES = (
339 (0x7F800001, 0, 0), (0xFFC00000, 0, 0)) 343 (0x7F800001, 0, 0), (0xFFC00000, 0, 0))
340# v_cvt_pk_u8_f32 (cs_cvt_pk_u8.asm), measured natively on RDNA2 (gfx1036): halves round to even, NaN gives 0. 344# v_cvt_pk_u8_f32 (cs_cvt_pk_u8.asm), measured natively on RDNA2 (gfx1036): halves round to even, NaN gives 0.
341CVT_PK_U8_WORDS = [0x1122330C, 0x11220E44, 0x11003344, 0xFE223344, 0x1122330D, 0x11220044, 0x11FF3344, 0x00223344] 345CVT_PK_U8_WORDS = [0x1122330C, 0x11220E44, 0x11003344, 0xFE223344, 0x1122330D, 0x11220044, 0x11FF3344, 0x00223344]
346# v_pk_mul_lo_u16 with a constant operand (cs_pk_mul_lo_const.asm), measured natively on RDNA2 (gfx1036); lanes 0 and 1.
347PK_MUL_LO_WORDS = [0x00009E88, 0x03675433, 0x00230000, 0x00077F6C] * 2
342# Wave64-only dump tests (mostly the x = cross-half checks): exact results need 64 lanes, or an emulation of them 348# Wave64-only dump tests (mostly the x = cross-half checks): exact results need 64 lanes, or an emulation of them
343# on narrower subgroups. cs_dpp_w64 is not cross-half, but its lane id needs both halves. 349# on narrower subgroups. cs_dpp_w64 is not cross-half, but its lane id needs both halves.
344W64_EMULATED = os.environ.get("LEONIDA_W64_EMULATE") == "1" 350W64_EMULATED = os.environ.get("LEONIDA_W64_EMULATE") == "1"
@@ -645,6 +651,14 @@ def run_readback(path, launch, *args, **kwargs):
645 return code, output 651 return code, output
646 652
647 653
654def compute_unsupported(code, output):
655 """A Skip quoting vk_compute_test's "unsupported: ..." line when it exited UNSUPPORTED because the module needs a
656 feature the device lacks (Int64, Float64, OpFmaKHR), in any run mode; None otherwise. Its --require-wave64
657 refusal prints no such line and keeps the callers' own handling, and a 77 without a reason stays a failure."""
658 m = re.search(r"^unsupported: .*", output, re.MULTILINE) if code == UNSUPPORTED else None
659 return Skip(f"SKIP ({m.group(0)})") if m else None
660
661
648def failure(code, output, lines): 662def failure(code, output, lines):
649 details = "\n".join(output.strip().splitlines()[-lines:]) 663 details = "\n".join(output.strip().splitlines()[-lines:])
650 return f"exit {code}: {details or 'no test output'}" 664 return f"exit {code}: {details or 'no test output'}"
@@ -659,6 +673,8 @@ def dump_test(tools, spirv, name, want, words, env=None):
659 child = dict(os.environ if env is None else env, VKC_DUMP=str(dump), VKC_OUT_WORDS=str(words)) 673 child = dict(os.environ if env is None else env, VKC_DUMP=str(dump), VKC_OUT_WORDS=str(words))
660 code, out = run(os.path.join(tools, "vk_compute_test" + EXE), os.path.join(spirv, name + ".spv"), 674 code, out = run(os.path.join(tools, "vk_compute_test" + EXE), os.path.join(spirv, name + ".spv"),
661 "1", "dump", env=child) 675 "1", "dump", env=child)
676 if skip := compute_unsupported(code, out):
677 return skip
662 if code: 678 if code:
663 return failure(code, out, 3) 679 return failure(code, out, 3)
664 if not dump.is_file(): 680 if not dump.is_file():
@@ -886,7 +902,7 @@ def words_match(got, want):
886def compute_test(tools, spirv, name, groups, mode, *, require_wave64=False, expected_words=None, needs_32_lanes=False, 902def compute_test(tools, spirv, name, groups, mode, *, require_wave64=False, expected_words=None, needs_32_lanes=False,
887 env=None): 903 env=None):
888 """Return an empty string for a pass, None for unsupported wave64, a Skip for a wave32 lane-mask test on a device 904 """Return an empty string for a pass, None for unsupported wave64, a Skip for a wave32 lane-mask test on a device
889 narrower than 32 lanes (needs_32_lanes), or a failure diagnostic. `env` adds variables for vk_compute_test 905 narrower than 32 lanes (needs_32_lanes) or a module the device lacks a feature for, or a failure diagnostic. `env` adds variables for vk_compute_test
890 (VKC_SGPRS).""" 906 (VKC_SGPRS)."""
891 shader = os.path.join(spirv, name + ".spv") 907 shader = os.path.join(spirv, name + ".spv")
892 args = [] 908 args = []
@@ -903,6 +919,8 @@ def compute_test(tools, spirv, name, groups, mode, *, require_wave64=False, expe
903 env = {**(env or {}), "VKC_SUBGROUP_SIZE": str(sg)} 919 env = {**(env or {}), "VKC_SUBGROUP_SIZE": str(sg)}
904 extra = {"env": dict(os.environ, **env)} if env else {} 920 extra = {"env": dict(os.environ, **env)} if env else {}
905 code, out = run(os.path.join(tools, "vk_compute_test" + EXE), shader, groups, mode, *args, **extra) 921 code, out = run(os.path.join(tools, "vk_compute_test" + EXE), shader, groups, mode, *args, **extra)
922 if skip := compute_unsupported(code, out):
923 return skip
906 if require_wave64 and code == 77: # vk_compute_test: the device cannot run a 64-wide compute subgroup 924 if require_wave64 and code == 77: # vk_compute_test: the device cannot run a 64-wide compute subgroup
907 return None 925 return None
908 if needs_32_lanes: 926 if needs_32_lanes:
@@ -1746,6 +1764,8 @@ def main():
1746 results.append(("cs_fma_fused", fma_fused_test(tools, spirv))) 1764 results.append(("cs_fma_fused", fma_fused_test(tools, spirv)))
1747 results.append(("cs_cvt_pk_u8", compute_test(tools, spirv, "cs_cvt_pk_u8", "1", "dump", 1765 results.append(("cs_cvt_pk_u8", compute_test(tools, spirv, "cs_cvt_pk_u8", "1", "dump",
1748 expected_words=CVT_PK_U8_WORDS))) 1766 expected_words=CVT_PK_U8_WORDS)))
1767 results.append(("cs_pk_mul_lo_const", compute_test(tools, spirv, "cs_pk_mul_lo_const", "1", "dump",
1768 expected_words=PK_MUL_LO_WORDS)))
1749 for name, want in W64X_DUMPS: # without --require-wave64 when LEONIDA_W64_EMULATE=1 1769 for name, want in W64X_DUMPS: # without --require-wave64 when LEONIDA_W64_EMULATE=1
1750 results.append((name, compute_test(tools, spirv, name, "1", "dump", require_wave64=not W64_EMULATED, 1770 results.append((name, compute_test(tools, spirv, name, "1", "dump", require_wave64=not W64_EMULATED,
1751 expected_words=want))) 1771 expected_words=want)))
diff --git a/runtime/test/shaders/cs_pk_mul_lo_const.asm b/runtime/test/shaders/cs_pk_mul_lo_const.asm
new file mode 100644
index 000000000..6bf4c9238
--- /dev/null
+++ b/runtime/test/shaders/cs_pk_mul_lo_const.asm
@@ -0,0 +1,37 @@
1; group: 32,1,1
2; v_pk_mul_lo_u16 with a constant operand (an SGPR, a literal, an inline constant), one half of the constant 0 or
3; small, the other operand computed at run time from the output buffer's 0xEEEEEEEE fill (so no compiler can fold it).
4; Each 16-bit half of D is the low 16 bits of the product of the selected source halves (RDNA2 ISA, V_PK_MUL_LO_U16;
5; op_sel picks the half of each source for the low result, op_sel_hi for the high one; defaults [0,0] and [1,1]):
6; 0: v_pk_mul_lo_u16 v30, v3, s8 op_sel:[0,1] op_sel_hi:[0,0] v3.lo = 0x1234, s8 = 0xaaaa0000
7; lo = 0x1234 * 0xaaaa & 0xffff = 0x9e88, hi = 0x1234 * 0x0000 = 0 -> 0x00009E88
8; 1: v_pk_mul_lo_u16 v31, s7, v15 op_sel_hi:[1,0] s7 = 0x0003ffff, v15.lo = 0xabcd
9; lo = 0xffff * 0xabcd & 0xffff, hi = 0x0003 * 0xabcd & 0xffff -> 0x03675433
10; 2: v_pk_mul_lo_u16 v32, v2, 0x00050000 v2 = 0x0007beef: lo = 0xbeef * 0 = 0,
11; hi = 0x0007 * 0x0005 = 0x23 -> 0x00230000
12; 3: v_pk_mul_lo_u16 v33, v3, 7 op_sel_hi:[1,0] v3 = 0x00011234: lo = 0x1234 * 7,
13; hi = v3.hi * 7.lo (op_sel_hi[1] = 0: the low half of the constant 7) -> 0x00077F6C
14; Measured natively on RDNA2 (gfx1036, Ryzen 9 9950X3D iGPU, driver 26.10.1) through tools/hw_oracle (raw HIP kernel).
15; On the AMD Windows driver the translated (x * y) & 0xffff of case 0 came out 0x0c229e88: the mask was dropped when the
16; other half was a constant 0. The translator now computes the low 16 bits as ((x << 16) * y) >> 16.
17; Run: vk_compute_test cs_pk_mul_lo_const.spv 1 dump
18; out[0..7] = 00009E88 03675433 00230000 00077F6C 00009E88 03675433 00230000 00077F6C (hex)
19s_mov_b32 exec_lo, -1
20v_mov_b32_e32 v20, v0
21v_lshlrev_b32_e32 v21, 4, v20
22buffer_load_dword v22, v21, s[0:3], 0 offen
23s_waitcnt vmcnt(0)
24v_xor_b32_e32 v3, 0xeeeffcda, v22
25v_xor_b32_e32 v15, 0xfcda4523, v22
26v_xor_b32_e32 v2, 0xeee95001, v22
27s_mov_b32 s8, 0xaaaa0000
28s_mov_b32 s7, 0x0003ffff
29v_pk_mul_lo_u16 v30, v3, s8 op_sel:[0,1] op_sel_hi:[0,0]
30v_pk_mul_lo_u16 v31, s7, v15 op_sel_hi:[1,0]
31v_pk_mul_lo_u16 v32, v2, 0x00050000
32v_pk_mul_lo_u16 v33, v3, 7 op_sel_hi:[1,0]
33buffer_store_dword v30, v21, s[0:3], 0 offen
34buffer_store_dword v31, v21, s[0:3], 0 offen offset:4
35buffer_store_dword v32, v21, s[0:3], 0 offen offset:8
36buffer_store_dword v33, v21, s[0:3], 0 offen offset:12
37s_endpgm
diff --git a/runtime/test/shaders/cs_w32_buffer_store_sub.asm b/runtime/test/shaders/cs_w32_buffer_store_sub.asm
new file mode 100644
index 000000000..6efcd197f
--- /dev/null
+++ b/runtime/test/shaders/cs_w32_buffer_store_sub.asm
@@ -0,0 +1,86 @@
1; Plain 8/16-bit MUBUF stores (#1864): buffer_store_byte / buffer_store_short, the forms docs/embedded_shaders.md names
2; as Box16Rehydration's blocker (cs_w32_buffer_sub16 covers the d16 forms; @YaBulochka on #1864). On the output V#
3; (base 0, num_records 0xFFFFFFFF) lane 0 seeds dwords 0x40..0x54, stores into them and reads them back. A store writes
4; only its own bytes; a short at byte 3 of a dword writes its high byte into the next one. Eight dwords:
5; out[0] = dword 0x40 (0x11223344) after buffer_store_byte 0xAB to byte 0x41 = 0x1122AB44
6; out[1] = dword 0x44 (0x55667788) after buffer_store_short 0xCDEF to byte 0x46 = 0xCDEF7788
7; out[2] = dword 0x48 (0x99AABBCC) after buffer_store_short 0x1234 to byte 0x4B: its low byte = 0x34AABBCC
8; out[3] = dword 0x4C (0xDDDDDDDD) after the same store: the high byte crossed into byte 0x4C = 0xDDDDDD12
9; out[4] = dword 0x50 (0x01020304) after buffer_store_byte of 0xFFFFFF5A to byte 0x50 (low byte) = 0x0102035A
10; out[5] = dword 0x54 (0x05060708) after buffer_store_short of 0xABCD1234 to byte 0x54 (low half) = 0x05061234
11; out[6] = buffer_load_ubyte of byte 0x41 afterwards = 0x000000AB
12; out[7] = buffer_load_sshort of bytes 0x46..0x47 afterwards (0xCDEF, sign-extended) = 0xFFFFCDEF
13; EXEC is cut to lane 0 first (one address per op).
14; group: 32,1,1
15; Run: vk_compute_test cs_w32_buffer_store_sub.spv 1 dump -> out[0..7] = 287484740 3455022984 883604428 3722304786 16909146 84283956 171 4294954479
16; mattr: +wavefrontsize32,-wavefrontsize64
17v_cmpx_eq_u32_e32 0, v0
18v_mov_b32_e32 v20, 0x40
19v_mov_b32_e32 v21, 0x11223344
20buffer_store_dword v21, v20, s[0:3], 0 offen
21v_mov_b32_e32 v20, 0x44
22v_mov_b32_e32 v21, 0x55667788
23buffer_store_dword v21, v20, s[0:3], 0 offen
24v_mov_b32_e32 v20, 0x48
25v_mov_b32_e32 v21, 0x99aabbcc
26buffer_store_dword v21, v20, s[0:3], 0 offen
27v_mov_b32_e32 v20, 0x4c
28v_mov_b32_e32 v21, 0xdddddddd
29buffer_store_dword v21, v20, s[0:3], 0 offen
30v_mov_b32_e32 v20, 0x50
31v_mov_b32_e32 v21, 0x1020304
32buffer_store_dword v21, v20, s[0:3], 0 offen
33v_mov_b32_e32 v20, 0x54
34v_mov_b32_e32 v21, 0x5060708
35buffer_store_dword v21, v20, s[0:3], 0 offen
36s_waitcnt_vscnt null, 0
37v_mov_b32_e32 v20, 0x41
38v_mov_b32_e32 v21, 0xab
39buffer_store_byte v21, v20, s[0:3], 0 offen
40v_mov_b32_e32 v20, 0x46
41v_mov_b32_e32 v21, 0xcdef
42buffer_store_short v21, v20, s[0:3], 0 offen
43v_mov_b32_e32 v20, 0x4b
44v_mov_b32_e32 v21, 0x1234
45buffer_store_short v21, v20, s[0:3], 0 offen
46v_mov_b32_e32 v20, 0x50
47v_mov_b32_e32 v21, 0xffffff5a
48buffer_store_byte v21, v20, s[0:3], 0 offen
49v_mov_b32_e32 v20, 0x54
50v_mov_b32_e32 v21, 0xabcd1234
51buffer_store_short v21, v20, s[0:3], 0 offen
52s_waitcnt_vscnt null, 0
53v_mov_b32_e32 v20, 0x40
54buffer_load_dword v10, v20, s[0:3], 0 offen
55v_mov_b32_e32 v20, 0x44
56buffer_load_dword v11, v20, s[0:3], 0 offen
57v_mov_b32_e32 v20, 0x48
58buffer_load_dword v12, v20, s[0:3], 0 offen
59v_mov_b32_e32 v20, 0x4c
60buffer_load_dword v13, v20, s[0:3], 0 offen
61v_mov_b32_e32 v20, 0x50
62buffer_load_dword v14, v20, s[0:3], 0 offen
63v_mov_b32_e32 v20, 0x54
64buffer_load_dword v15, v20, s[0:3], 0 offen
65v_mov_b32_e32 v20, 0x41
66buffer_load_ubyte v16, v20, s[0:3], 0 offen
67v_mov_b32_e32 v20, 0x46
68buffer_load_sshort v17, v20, s[0:3], 0 offen
69s_waitcnt vmcnt(0)
70v_mov_b32_e32 v20, 0
71buffer_store_dword v10, v20, s[0:3], 0 offen
72v_mov_b32_e32 v20, 4
73buffer_store_dword v11, v20, s[0:3], 0 offen
74v_mov_b32_e32 v20, 8
75buffer_store_dword v12, v20, s[0:3], 0 offen
76v_mov_b32_e32 v20, 12
77buffer_store_dword v13, v20, s[0:3], 0 offen
78v_mov_b32_e32 v20, 16
79buffer_store_dword v14, v20, s[0:3], 0 offen
80v_mov_b32_e32 v20, 20
81buffer_store_dword v15, v20, s[0:3], 0 offen
82v_mov_b32_e32 v20, 24
83buffer_store_dword v16, v20, s[0:3], 0 offen
84v_mov_b32_e32 v20, 28
85buffer_store_dword v17, v20, s[0:3], 0 offen
86s_endpgm
diff --git a/runtime/test/shaders/cs_w32_buffer_sub16.asm b/runtime/test/shaders/cs_w32_buffer_sub16.asm
new file mode 100644
index 000000000..d8d992d81
--- /dev/null
+++ b/runtime/test/shaders/cs_w32_buffer_sub16.asm
@@ -0,0 +1,70 @@
1; 8/16-bit MUBUF d16 loads and stores (#1864, BUFFER_SUB16), on the output V# (base 0, num_records 0xFFFFFFFF). Lane 0
2; seeds dword 0x40 = 0x8899AABB, 0x50 = 0x11223344, 0x60 = 0x55667788, and loads into a register holding 0xBEEF1234, so
3; each d16 load shows the half it writes and the half it keeps. Eight dwords:
4; out[0] = buffer_load_ubyte_d16 of byte 0x41 (0xAA): low half 0x00AA, high kept = 0xBEEF00AA
5; out[1] = buffer_load_ubyte_d16_hi of byte 0x41: high half 0x00AA, low kept = 0x00AA1234
6; out[2] = buffer_load_sbyte_d16 of byte 0x41: 0xAA sign-extended to 16 bits = 0xBEEFFFAA
7; out[3] = buffer_load_sbyte_d16_hi of byte 0x41 = 0xFFAA1234
8; out[4] = buffer_load_short_d16 of bytes 0x42..0x43 (0x8899) = 0xBEEF8899
9; out[5] = buffer_load_short_d16_hi of bytes 0x42..0x43 = 0x88991234
10; out[6] = dword 0x50 after buffer_store_byte_d16_hi of 0x00CD0000 to byte 0x51: bits 23:16 = 0x1122CD44
11; out[7] = dword 0x60 after buffer_store_short_d16_hi of 0xABCD0000 to byte 0x62: bits 31:16 = 0xABCD7788
12; EXEC is cut to lane 0 first (one address per op).
13; group: 32,1,1
14; Run: vk_compute_test cs_w32_buffer_sub16.spv 1 dump -> out[0..7] = 3203334314 11145780 3203399594 4289335860 3203369113 2291733044 287493444 2882369416
15; mattr: +wavefrontsize32,-wavefrontsize64
16v_cmpx_eq_u32_e32 0, v0
17v_mov_b32_e32 v20, 0x40
18v_mov_b32_e32 v21, 0x8899aabb
19buffer_store_dword v21, v20, s[0:3], 0 offen
20v_mov_b32_e32 v20, 0x50
21v_mov_b32_e32 v21, 0x11223344
22buffer_store_dword v21, v20, s[0:3], 0 offen
23v_mov_b32_e32 v20, 0x60
24v_mov_b32_e32 v21, 0x55667788
25buffer_store_dword v21, v20, s[0:3], 0 offen
26s_waitcnt_vscnt null, 0
27v_mov_b32_e32 v1, 0x41
28v_mov_b32_e32 v2, 0x42
29v_mov_b32_e32 v10, 0xbeef1234
30v_mov_b32_e32 v11, 0xbeef1234
31v_mov_b32_e32 v12, 0xbeef1234
32v_mov_b32_e32 v13, 0xbeef1234
33v_mov_b32_e32 v14, 0xbeef1234
34v_mov_b32_e32 v15, 0xbeef1234
35buffer_load_ubyte_d16 v10, v1, s[0:3], 0 offen
36buffer_load_ubyte_d16_hi v11, v1, s[0:3], 0 offen
37buffer_load_sbyte_d16 v12, v1, s[0:3], 0 offen
38buffer_load_sbyte_d16_hi v13, v1, s[0:3], 0 offen
39buffer_load_short_d16 v14, v2, s[0:3], 0 offen
40buffer_load_short_d16_hi v15, v2, s[0:3], 0 offen
41v_mov_b32_e32 v20, 0x51
42v_mov_b32_e32 v21, 0xcd0000
43buffer_store_byte_d16_hi v21, v20, s[0:3], 0 offen
44v_mov_b32_e32 v20, 0x62
45v_mov_b32_e32 v21, 0xabcd0000
46buffer_store_short_d16_hi v21, v20, s[0:3], 0 offen
47s_waitcnt vmcnt(0)
48s_waitcnt_vscnt null, 0
49v_mov_b32_e32 v20, 0x50
50buffer_load_dword v16, v20, s[0:3], 0 offen
51v_mov_b32_e32 v20, 0x60
52buffer_load_dword v17, v20, s[0:3], 0 offen
53s_waitcnt vmcnt(0)
54v_mov_b32_e32 v20, 0
55buffer_store_dword v10, v20, s[0:3], 0 offen
56v_mov_b32_e32 v20, 4
57buffer_store_dword v11, v20, s[0:3], 0 offen
58v_mov_b32_e32 v20, 8
59buffer_store_dword v12, v20, s[0:3], 0 offen
60v_mov_b32_e32 v20, 12
61buffer_store_dword v13, v20, s[0:3], 0 offen
62v_mov_b32_e32 v20, 16
63buffer_store_dword v14, v20, s[0:3], 0 offen
64v_mov_b32_e32 v20, 20
65buffer_store_dword v15, v20, s[0:3], 0 offen
66v_mov_b32_e32 v20, 24
67buffer_store_dword v16, v20, s[0:3], 0 offen
68v_mov_b32_e32 v20, 28
69buffer_store_dword v17, v20, s[0:3], 0 offen
70s_endpgm
diff --git a/runtime/test/spirv_capability.h b/runtime/test/spirv_capability.h
new file mode 100644
index 000000000..db7232197
--- /dev/null
+++ b/runtime/test/spirv_capability.h
@@ -0,0 +1,49 @@
1// What a SPIR-V module declares, read before the device is created, so a test tool enables only the optional features
2// the module needs and reports 77 (unsupported) when the device lacks one, instead of asking for every feature a
3// translated shader might use. rdna2spirv.py lowers buffer addresses to 32-bit pairs (SHADER-423), so most memory
4// shaders no longer declare Int64; asking for shaderInt64 regardless made the tools fail on devices without it (Intel
5// UHD/Arc) before the shader ran (TEST-468).
6#pragma once
7
8#include <cstddef>
9#include <cstdint>
10#include <cstring>
11#include <vector>
12
13namespace leonida::vk_test {
14
15// Capability numbers from spirv/unified1/spirv.h.
16inline constexpr std::uint32_t spirv_capability_float64 = 10;
17inline constexpr std::uint32_t spirv_capability_int64 = 11;
18inline constexpr std::uint32_t spirv_capability_int64_atomics = 12;
19
20// Whether the module declares capability `cap`. OpCapability instructions (2 words each) come first, right after the
21// 5-word header, so the scan stops at the first other instruction. `bytes` may be any length; a partial word is ignored.
22inline bool declares_capability(const void* code, std::size_t bytes, std::uint32_t cap) {
23 const auto* p = static_cast<const unsigned char*>(code);
24 const std::size_t words = bytes / 4;
25 auto word = [&](std::size_t i) {
26 std::uint32_t w;
27 std::memcpy(&w, p + 4 * i, 4);
28 return w;
29 };
30 for (std::size_t i = 5; i + 1 < words && word(i) == (2u << 16 | 17u); i += 2) // OpCapability
31 if (word(i + 1) == cap) return true;
32 return false;
33}
34
35inline bool declares_capability(const std::vector<std::uint32_t>& spv, std::uint32_t cap) {
36 return declares_capability(spv.data(), spv.size() * 4, cap);
37}
38
39// 64-bit integer types need shaderInt64: the Int64 capability, or Int64Atomics, which implicitly declares it.
40inline bool needs_shader_int64(const void* code, std::size_t bytes) {
41 return declares_capability(code, bytes, spirv_capability_int64) ||
42 declares_capability(code, bytes, spirv_capability_int64_atomics);
43}
44
45inline bool needs_shader_int64(const std::vector<std::uint32_t>& spv) {
46 return needs_shader_int64(spv.data(), spv.size() * 4);
47}
48
49} // namespace leonida::vk_test
diff --git a/runtime/test/spirv_capability_test.cpp b/runtime/test/spirv_capability_test.cpp
new file mode 100644
index 000000000..37de4ace2
--- /dev/null
+++ b/runtime/test/spirv_capability_test.cpp
@@ -0,0 +1,71 @@
1// CPU-only tests for spirv_capability.h, which the standalone GPU tools use to enable shaderInt64 only for modules
2// with 64-bit integers (TEST-468). The modules are hand-built word lists; no Vulkan instance or GPU is needed.
3#include "spirv_capability.h"
4
5#include <cstdint>
6#include <cstdio>
7#include <cstring>
8#include <initializer_list>
9#include <vector>
10
11namespace {
12
13int failures = 0;
14
15void expect(const char* what, bool got, bool want) {
16 if (got == want) return;
17 std::fprintf(stderr, "FAIL %s: got %d, expected %d\n", what, got, want);
18 ++failures;
19}
20
21// A 5-word header, one OpCapability per entry of `caps`, then OpMemoryModel Logical GLSL450.
22std::vector<std::uint32_t> module(std::initializer_list<std::uint32_t> caps) {
23 std::vector<std::uint32_t> w{0x07230203u, 0x00010000u, 0u, 1u, 0u};
24 for (std::uint32_t c : caps) {
25 w.push_back(2u << 16 | 17u); // OpCapability
26 w.push_back(c);
27 }
28 w.push_back(3u << 16 | 14u); // OpMemoryModel
29 w.push_back(0u);
30 w.push_back(1u);
31 return w;
32}
33
34} // namespace
35
36int main() {
37 using namespace leonida::vk_test;
38 constexpr std::uint32_t shader = 1, physical_storage_buffer = 5347;
39
40 // SHADER-423's output: buffer addresses as 32-bit pairs, PhysicalStorageBufferAddresses but no Int64.
41 expect("address pairs need no shaderInt64", needs_shader_int64(module({shader, physical_storage_buffer})), false);
42 expect("Int64 needs shaderInt64", needs_shader_int64(module({shader, spirv_capability_int64})), true);
43 expect("Int64 after other capabilities", needs_shader_int64(module({shader, physical_storage_buffer, 10, 11})), true);
44 expect("Int64Atomics implicitly declares Int64", needs_shader_int64(module({shader, spirv_capability_int64_atomics})),
45 true);
46 // cs_f64_add (vk_compute_test enables shaderFloat64 for it): Float64 without Int64.
47 const std::vector<std::uint32_t> f64 = module({shader, spirv_capability_float64});
48 expect("Float64", declares_capability(f64, spirv_capability_float64), true);
49 expect("Float64 needs no shaderInt64", needs_shader_int64(f64), false);
50
51 // Only the leading OpCapability run counts: a later word equal to 11 is an operand, not a capability.
52 std::vector<std::uint32_t> later = module({shader});
53 later.push_back(2u << 16 | 17u);
54 later.push_back(spirv_capability_int64);
55 expect("a capability after OpMemoryModel is ignored", needs_shader_int64(later), false);
56
57 // A short or empty file (a missing module reads as empty) declares nothing and doesn't read past its end.
58 expect("empty", needs_shader_int64(std::vector<std::uint32_t>{}), false);
59 const std::vector<std::uint32_t> truncated{0x07230203u, 0x00010000u, 0u, 1u, 0u, 2u << 16 | 17u};
60 expect("truncated OpCapability", needs_shader_int64(truncated), false);
61
62 // The byte form the tools use for std::vector<char>, including a trailing partial word.
63 const std::vector<std::uint32_t> m = module({shader, spirv_capability_int64});
64 std::vector<char> bytes(m.size() * 4 + 3, 0);
65 std::memcpy(bytes.data(), m.data(), m.size() * 4);
66 expect("bytes with a partial word", needs_shader_int64(bytes.data(), bytes.size()), true);
67
68 if (failures) return 1;
69 std::printf("spirv_capability: all checks passed\n");
70 return 0;
71}
diff --git a/runtime/test/vk_bindless_test.cpp b/runtime/test/vk_bindless_test.cpp
index 90a8b4049..1b3a609ef 100644
--- a/runtime/test/vk_bindless_test.cpp
+++ b/runtime/test/vk_bindless_test.cpp
@@ -23,6 +23,7 @@
23#include "vk_device_pick.h" 23#include "vk_device_pick.h"
24#include "vk_shader_fma.h" 24#include "vk_shader_fma.h"
25#include "vk_pc_tail.h" 25#include "vk_pc_tail.h"
26#include "spirv_capability.h"
26#include "../src/vulkan_bindless.h" 27#include "../src/vulkan_bindless.h"
27 28
28#include <algorithm> 29#include <algorithm>
@@ -177,18 +178,25 @@ int main(int argc, char** argv) {
177 vkEnumeratePhysicalDevices(inst, &n, nullptr); 178 vkEnumeratePhysicalDevices(inst, &n, nullptr);
178 std::vector<VkPhysicalDevice> pds(n); 179 std::vector<VkPhysicalDevice> pds(n);
179 vkEnumeratePhysicalDevices(inst, &n, pds.data()); 180 vkEnumeratePhysicalDevices(inst, &n, pds.data());
180 VkPhysicalDevice pd = VK_NULL_HANDLE; 181 // The same choice as the other tools (vk_device_pick.h): the best-ranked Vulkan 1.2 device that LEONIDA_VK_DEVICE
181 int best_rank = -1; 182 // allows. It used to rank every device and ignore the filter, so a run meant for one GPU took another (TEST-469).
183 // A filter that matches nothing fails, as in vk_compute_test and vk_test_device.h (as #2657 does it).
184 std::vector<VkPhysicalDeviceProperties> candidates;
185 std::vector<VkPhysicalDevice> eligible;
182 for (auto d : pds) { 186 for (auto d : pds) {
183 VkPhysicalDeviceProperties p; 187 VkPhysicalDeviceProperties p;
184 vkGetPhysicalDeviceProperties(d, &p); 188 vkGetPhysicalDeviceProperties(d, &p);
185 if (p.apiVersion < VK_API_VERSION_1_2) continue; 189 if (p.apiVersion < VK_API_VERSION_1_2) continue;
186 if (const int rank = leonida::vk_test::device_rank(p.deviceType, p.vendorID); rank > best_rank) { 190 candidates.push_back(p);
187 pd = d; 191 eligible.push_back(d);
188 best_rank = rank;
189 }
190 } 192 }
193 const std::size_t chosen = leonida::vk_test::pick_device(candidates);
194 VkPhysicalDevice pd = chosen < eligible.size() ? eligible[chosen] : VK_NULL_HANDLE;
191 if (!pd) { 195 if (!pd) {
196 if (!leonida::vulkan_device_filter().empty()) {
197 leonida::vk_test::report_no_device();
198 return 1;
199 }
192 std::printf("unsupported: no Vulkan 1.2 device\n"); 200 std::printf("unsupported: no Vulkan 1.2 device\n");
193 return unsupported; 201 return unsupported;
194 } 202 }
@@ -209,16 +217,19 @@ int main(int argc, char** argv) {
209 return unsupported; 217 return unsupported;
210 } 218 }
211 219
212 // The features ps_tex's metadata names (bufferDeviceAddress, runtimeDescriptorArray, shaderInt64), dynamic 220 // The features ps_tex's metadata names (bufferDeviceAddress, runtimeDescriptorArray), dynamic indexing of the
213 // indexing of the image array, and whichever descriptor-indexing flags the set can use. 221 // image array, and whichever descriptor-indexing flags the set can use. shaderInt64 only when a stage has 64-bit
222 // integers: SHADER-423's address pairs need none (TEST-468).
214 VkPhysicalDeviceVulkan11Features have11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES}; 223 VkPhysicalDeviceVulkan11Features have11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES};
215 VkPhysicalDeviceVulkan12Features have12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, &have11}; 224 VkPhysicalDeviceVulkan12Features have12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, &have11};
216 VkPhysicalDeviceFeatures2 have{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &have12}; 225 VkPhysicalDeviceFeatures2 have{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &have12};
217 vkGetPhysicalDeviceFeatures2(pd, &have); 226 vkGetPhysicalDeviceFeatures2(pd, &have);
218 if (!have12.bufferDeviceAddress || !have12.runtimeDescriptorArray || !have.features.shaderInt64 || 227 const bool int64 = leonida::vk_test::needs_shader_int64(read_spv(argv[1])) ||
228 leonida::vk_test::needs_shader_int64(read_spv(argv[2]));
229 if (!have12.bufferDeviceAddress || !have12.runtimeDescriptorArray || (int64 && !have.features.shaderInt64) ||
219 !have.features.shaderSampledImageArrayDynamicIndexing) { 230 !have.features.shaderSampledImageArrayDynamicIndexing) {
220 std::printf("unsupported: the device lacks bufferDeviceAddress, runtimeDescriptorArray, shaderInt64 or " 231 std::printf("unsupported: the device lacks bufferDeviceAddress, runtimeDescriptorArray, %s"
221 "shaderSampledImageArrayDynamicIndexing\n"); 232 "shaderSampledImageArrayDynamicIndexing\n", int64 ? "shaderInt64 (a stage declares Int64) or " : "");
222 return unsupported; 233 return unsupported;
223 } 234 }
224 BindlessFeatures device_flags; 235 BindlessFeatures device_flags;
@@ -238,7 +249,7 @@ int main(int argc, char** argv) {
238 enable12.descriptorBindingStorageBufferUpdateAfterBind = device_flags.update_after_bind; 249 enable12.descriptorBindingStorageBufferUpdateAfterBind = device_flags.update_after_bind;
239 enable12.descriptorBindingPartiallyBound = device_flags.partially_bound; 250 enable12.descriptorBindingPartiallyBound = device_flags.partially_bound;
240 VkPhysicalDeviceFeatures2 enable{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &enable12}; 251 VkPhysicalDeviceFeatures2 enable{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &enable12};
241 enable.features.shaderInt64 = VK_TRUE; 252 enable.features.shaderInt64 = int64 ? VK_TRUE : VK_FALSE;
242 enable.features.shaderSampledImageArrayDynamicIndexing = VK_TRUE; 253 enable.features.shaderSampledImageArrayDynamicIndexing = VK_TRUE;
243 const std::vector<std::uint32_t> shader_code[] = {read_spv(argv[1]), read_spv(argv[2])}; 254 const std::vector<std::uint32_t> shader_code[] = {read_spv(argv[1]), read_spv(argv[2])};
244 bool dynamic_storage = false; 255 bool dynamic_storage = false;
diff --git a/runtime/test/vk_compute_test.cpp b/runtime/test/vk_compute_test.cpp
index d588723a8..ef8446878 100644
--- a/runtime/test/vk_compute_test.cpp
+++ b/runtime/test/vk_compute_test.cpp
@@ -30,6 +30,7 @@
30#include "vk_pc_tail.h" 30#include "vk_pc_tail.h"
31#include "vk_validation.h" 31#include "vk_validation.h"
32#include "cs_wave_probe_spv.h" 32#include "cs_wave_probe_spv.h"
33#include "spirv_capability.h"
33 34
34#include <cctype> 35#include <cctype>
35#include <cmath> 36#include <cmath>
@@ -255,8 +256,10 @@ static int run(int argc, char** argv) {
255 VkDeviceQueueCreateInfo qci{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO}; 256 VkDeviceQueueCreateInfo qci{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO};
256 qci.queueFamilyIndex = qi; qci.queueCount = 1; qci.pQueuePriorities = &prio; 257 qci.queueFamilyIndex = qi; qci.queueCount = 1; qci.pQueuePriorities = &prio;
257 VkPhysicalDeviceVulkan13Features f13q{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES}; 258 VkPhysicalDeviceVulkan13Features f13q{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES};
259 VkPhysicalDeviceVulkan12Features f12q{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES};
260 f12q.pNext = &f13q;
258 VkPhysicalDeviceFeatures2 f2q{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2}; 261 VkPhysicalDeviceFeatures2 f2q{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2};
259 f2q.pNext = &f13q; 262 f2q.pNext = &f12q;
260 vkGetPhysicalDeviceFeatures2(pd, &f2q); 263 vkGetPhysicalDeviceFeatures2(pd, &f2q);
261 const char* sg_env = std::getenv("VKC_SUBGROUP_SIZE"); 264 const char* sg_env = std::getenv("VKC_SUBGROUP_SIZE");
262 const uint32_t req_sg = require_wave64 ? 64u : (sg_env ? uint32_t(std::atoi(sg_env)) : 0u); 265 const uint32_t req_sg = require_wave64 ? 64u : (sg_env ? uint32_t(std::atoi(sg_env)) : 0u);
@@ -267,6 +270,8 @@ static int run(int argc, char** argv) {
267 std::fprintf(stderr, "full 64-wide compute subgroups unavailable\n"); 270 std::fprintf(stderr, "full 64-wide compute subgroups unavailable\n");
268 return 77; 271 return 77;
269 } 272 }
273 // shaderFloat64 and shaderInt64 only for a module that declares them: SHADER-423's address pairs need no
274 // 64-bit integers (TEST-468).
270 const bool needs_float64 = leonida::vk_test::spirv_declares_capability(code.data(), code.size(), 10); // Float64 275 const bool needs_float64 = leonida::vk_test::spirv_declares_capability(code.data(), code.size(), 10); // Float64
271 if (needs_float64 && !f2q.features.shaderFloat64) { 276 if (needs_float64 && !f2q.features.shaderFloat64) {
272 std::fprintf(stderr, "unsupported: %s uses Float64 and the device has no shaderFloat64\n", argv[1]); 277 std::fprintf(stderr, "unsupported: %s uses Float64 and the device has no shaderFloat64\n", argv[1]);
@@ -286,17 +291,35 @@ static int run(int argc, char** argv) {
286 subgroup.subgroupSize == req_sg && spirv_version && spirv_version < 0x00010600u && 291 subgroup.subgroupSize == req_sg && spirv_version && spirv_version < 0x00010600u &&
287 local_total && local_total <= 1024; 292 local_total && local_total <= 1024;
288 const bool observed_full = observed && f13q.computeFullSubgroups && local[0] % sgProps.maxSubgroupSize == 0; 293 const bool observed_full = observed && f13q.computeFullSubgroups && local[0] % sgProps.maxSubgroupSize == 0;
294 const bool int64 = leonida::vk_test::needs_shader_int64(code.data(), code.size());
295 if (int64 && !f2q.features.shaderInt64) {
296 std::fprintf(stderr, "unsupported: %s declares Int64 and the device has no shaderInt64\n", argv[1]);
297 return 77;
298 }
299 // 64-bit atomics: the translator's are buffer atomics (rdna2spirv.py --int64-atomics, *_atomic_swap_x2 on
300 // PhysicalStorageBuffer memory), which need shaderBufferInt64Atomics. Without the check a device that lacks it
301 // (MoltenVK) failed the pipeline instead of reporting 77. A shared-memory one gets shaderSharedInt64Atomics too
302 // where the device has it.
303 const bool int64_atomics = leonida::vk_test::declares_capability(code.data(), code.size(),
304 leonida::vk_test::spirv_capability_int64_atomics);
305 if (int64_atomics && !f12q.shaderBufferInt64Atomics) {
306 std::fprintf(stderr, "unsupported: %s declares Int64Atomics and the device has no shaderBufferInt64Atomics\n",
307 argv[1]);
308 return 77;
309 }
289 VkPhysicalDeviceVulkan13Features f13{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES}; 310 VkPhysicalDeviceVulkan13Features f13{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES};
290 VkPhysicalDeviceVulkan12Features f12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES}; 311 VkPhysicalDeviceVulkan12Features f12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES};
291 f12.bufferDeviceAddress = VK_TRUE; 312 f12.bufferDeviceAddress = VK_TRUE;
313 f12.shaderBufferInt64Atomics = int64_atomics ? VK_TRUE : VK_FALSE;
314 f12.shaderSharedInt64Atomics = int64_atomics && f12q.shaderSharedInt64Atomics ? VK_TRUE : VK_FALSE;
292 if (f13q.subgroupSizeControl || require_wave64) { 315 if (f13q.subgroupSizeControl || require_wave64) {
293 f13.subgroupSizeControl = f13q.subgroupSizeControl; 316 f13.subgroupSizeControl = f13q.subgroupSizeControl;
294 f13.computeFullSubgroups = require_wave64 || observed_full ? VK_TRUE : VK_FALSE; 317 f13.computeFullSubgroups = require_wave64 || observed_full ? VK_TRUE : VK_FALSE;
295 f12.pNext = &f13; 318 f12.pNext = &f13;
296 } 319 }
297 VkPhysicalDeviceFeatures2 f2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2}; 320 VkPhysicalDeviceFeatures2 f2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2};
298 f2.features.shaderInt64 = VK_TRUE; 321 f2.features.shaderInt64 = int64 ? VK_TRUE : VK_FALSE;
299 f2.features.shaderFloat64 = needs_float64; 322 f2.features.shaderFloat64 = needs_float64 ? VK_TRUE : VK_FALSE;
300 f2.pNext = &f12; 323 f2.pNext = &f12;
301 // OpFmaKHR (rdna2spirv.py --fma khr): VK_KHR_shader_fma, when the device has it. 324 // OpFmaKHR (rdna2spirv.py --fma khr): VK_KHR_shader_fma, when the device has it.
302 leonida::vk_test::ShaderFma fma; 325 leonida::vk_test::ShaderFma fma;
diff --git a/runtime/test/vk_harness.cpp b/runtime/test/vk_harness.cpp
index 836b198e6..23d58bc70 100644
--- a/runtime/test/vk_harness.cpp
+++ b/runtime/test/vk_harness.cpp
@@ -36,6 +36,7 @@
36#include "vk_pc_tail.h" 36#include "vk_pc_tail.h"
37#include "../src/descriptor_table.h" 37#include "../src/descriptor_table.h"
38#include "../src/gfx10_descriptors.h" 38#include "../src/gfx10_descriptors.h"
39#include "spirv_capability.h"
39 40
40#include <cctype> 41#include <cctype>
41#include <cstddef> 42#include <cstddef>
@@ -507,9 +508,18 @@ int main(int argc, char** argv) {
507 } 508 }
508 feats.shaderFloat64 = VK_TRUE; 509 feats.shaderFloat64 = VK_TRUE;
509 } 510 }
510 if (need_heap || mesh_compute) { 511 // shaderInt64 only when a stage has 64-bit integers. Heap and --mesh-compute addresses are 64-bit, but rdna2spirv.py
511 if (!f2q.features.shaderInt64) { std::fprintf(stderr, "unsupported: 64-bit addresses need shaderInt64\n"); return 77; } 512 // builds them from 32-bit pairs unless the shader also does 64-bit arithmetic (SHADER-423), so the module decides,
512 feats.shaderInt64 = VK_TRUE; // heap and --mesh-compute output addresses are 64-bit 513 // not VKH_HEAP (TEST-468).
514 bool needs_int64 = leonida::vk_test::needs_shader_int64(fs_code);
515 for (const char* p : std::initializer_list<const char*>{argv[1], mesh_vs_path, gs_path})
516 if (p && !needs_int64) needs_int64 = leonida::vk_test::needs_shader_int64(read_spv(p));
517 if (needs_int64) {
518 if (!f2q.features.shaderInt64) {
519 std::fprintf(stderr, "unsupported: a stage declares Int64 and the device has no shaderInt64\n");
520 return 77;
521 }
522 feats.shaderInt64 = VK_TRUE;
513 } 523 }
514 if (tex_rgba_path) { 524 if (tex_rgba_path) {
515 if (!f2q.features.shaderSampledImageArrayDynamicIndexing) { 525 if (!f2q.features.shaderSampledImageArrayDynamicIndexing) {
diff --git a/runtime/test/vk_store_test.cpp b/runtime/test/vk_store_test.cpp
index 0a7639fc4..15e8fe71b 100644
--- a/runtime/test/vk_store_test.cpp
+++ b/runtime/test/vk_store_test.cpp
@@ -20,6 +20,7 @@
20#include "vk_device_pick.h" 20#include "vk_device_pick.h"
21#include "vk_shader_fma.h" 21#include "vk_shader_fma.h"
22#include "vk_pc_tail.h" 22#include "vk_pc_tail.h"
23#include "spirv_capability.h"
23#include "../src/gfx10_descriptors.h" 24#include "../src/gfx10_descriptors.h"
24 25
25#include <cmath> 26#include <cmath>
@@ -100,9 +101,8 @@ int main(int argc, char** argv) {
100 // as vk_compute_test does) instead of failing vkCreateDevice. Typed loads need no storage image feature. 101 // as vk_compute_test does) instead of failing vkCreateDevice. Typed loads need no storage image feature.
101 VkPhysicalDeviceFeatures have{}; 102 VkPhysicalDeviceFeatures have{};
102 vkGetPhysicalDeviceFeatures(pd, &have); 103 vkGetPhysicalDeviceFeatures(pd, &have);
103 if (!have.shaderStorageImageWriteWithoutFormat || !have.shaderInt64) { 104 if (!have.shaderStorageImageWriteWithoutFormat) {
104 std::printf("unsupported: shaderStorageImageWriteWithoutFormat=%u shaderInt64=%u\n", 105 std::printf("unsupported: shaderStorageImageWriteWithoutFormat=0\n");
105 have.shaderStorageImageWriteWithoutFormat, have.shaderInt64);
106 return 77; 106 return 77;
107 } 107 }
108 VkPhysicalDeviceVulkan12Features f12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES}; 108 VkPhysicalDeviceVulkan12Features f12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES};
@@ -132,6 +132,12 @@ int main(int argc, char** argv) {
132 std::ifstream f(argv[1], std::ios::binary); 132 std::ifstream f(argv[1], std::ios::binary);
133 std::vector<char> code((std::istreambuf_iterator<char>(f)), {}); 133 std::vector<char> code((std::istreambuf_iterator<char>(f)), {});
134 if (code.size() < 20 || code.size() % 4) { std::fprintf(stderr, "%s: not a SPIR-V module\n", argv[1]); return 1; } 134 if (code.size() < 20 || code.size() % 4) { std::fprintf(stderr, "%s: not a SPIR-V module\n", argv[1]); return 1; }
135 // shaderInt64 only for a module with 64-bit integers: SHADER-423's address pairs need none (TEST-468).
136 const bool int64 = leonida::vk_test::needs_shader_int64(code.data(), code.size());
137 if (int64 && !have.shaderInt64) {
138 std::printf("unsupported: %s declares Int64 and the device has no shaderInt64\n", argv[1]);
139 return 77;
140 }
135 using leonida::vk_test::spirv_declares_capability; 141 using leonida::vk_test::spirv_declares_capability;
136 const bool dynamic_sampled = spirv_declares_capability(code.data(), code.size(), 142 const bool dynamic_sampled = spirv_declares_capability(code.data(), code.size(),
137 leonida::vk_test::spv_sampled_image_array_dynamic_indexing); 143 leonida::vk_test::spv_sampled_image_array_dynamic_indexing);
@@ -152,7 +158,7 @@ int main(int argc, char** argv) {
152 std::printf("FAILED: the module declares StorageImageReadWithoutFormat\n"); 158 std::printf("FAILED: the module declares StorageImageReadWithoutFormat\n");
153 return 1; 159 return 1;
154 } 160 }
155 f2.features.shaderInt64 = VK_TRUE; 161 f2.features.shaderInt64 = int64 ? VK_TRUE : VK_FALSE;
156 f2.pNext = &f12; 162 f2.pNext = &f12;
157 leonida::vk_test::ShaderFma fma; // OpFmaKHR (rdna2spirv.py --fma khr) 163 leonida::vk_test::ShaderFma fma; // OpFmaKHR (rdna2spirv.py --fma khr)
158 fma.query(gipa, inst, pd); 164 fma.query(gipa, inst, pd);
diff --git a/runtime/test/vk_test_device.h b/runtime/test/vk_test_device.h
index 114ca187f..949e5abfb 100644
--- a/runtime/test/vk_test_device.h
+++ b/runtime/test/vk_test_device.h
@@ -116,6 +116,8 @@ public:
116 bool request_buffer_device_address = false; // set before create(): enable bufferDeviceAddress where supported 116 bool request_buffer_device_address = false; // set before create(): enable bufferDeviceAddress where supported
117 bool buffer_device_address = false; // enabled: buffer() memory and buffers can be addressed (device_address()) 117 bool buffer_device_address = false; // enabled: buffer() memory and buffers can be addressed (device_address())
118 bool conservative_rasterization = false; // VK_EXT_conservative_rasterization enabled where available 118 bool conservative_rasterization = false; // VK_EXT_conservative_rasterization enabled where available
119 bool request_mesh_shader = false; // set before create(): enable VK_EXT_mesh_shader (meshShader) where available
120 bool mesh_shader = false; // VK_EXT_mesh_shader and meshShader are enabled
119 bool debug_utils = false; // VK_EXT_debug_utils is enabled on the instance 121 bool debug_utils = false; // VK_EXT_debug_utils is enabled on the instance
120 // The subgroup sizes of the device, with subgroupSizeControl and computeFullSubgroups enabled where it has them. 122 // The subgroup sizes of the device, with subgroupSizeControl and computeFullSubgroups enabled where it has them.
121 leonida::SubgroupSizeCaps subgroup; 123 leonida::SubgroupSizeCaps subgroup;
@@ -511,6 +513,20 @@ public:
511 } 513 }
512 } 514 }
513#endif 515#endif
516 // VK_EXT_mesh_shader (meshShader only), for the tests that ask for it.
517 VkPhysicalDeviceMeshShaderFeaturesEXT mesh_features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT};
518 if (request_mesh_shader && std::any_of(extensions.begin(), extensions.end(), [](const auto& e) {
519 return std::strcmp(e.extensionName, VK_EXT_MESH_SHADER_EXTENSION_NAME) == 0;
520 })) {
521 VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &mesh_features};
522 instance_fn<PFN_vkGetPhysicalDeviceFeatures2>("vkGetPhysicalDeviceFeatures2")(physical, &query);
523 mesh_shader = mesh_features.meshShader == VK_TRUE;
524 }
525 if (mesh_shader) {
526 mesh_features = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT, *v13_.next()};
527 mesh_features.meshShader = VK_TRUE;
528 *v13_.next() = &mesh_features;
529 }
514 enable.occlusionQueryPrecise = features.features.occlusionQueryPrecise; // query heaps, where available 530 enable.occlusionQueryPrecise = features.features.occlusionQueryPrecise; // query heaps, where available
515 enable.pipelineStatisticsQuery = features.features.pipelineStatisticsQuery; 531 enable.pipelineStatisticsQuery = features.features.pipelineStatisticsQuery;
516 occlusion_query_precise = features.features.occlusionQueryPrecise == VK_TRUE; 532 occlusion_query_precise = features.features.occlusionQueryPrecise == VK_TRUE;
@@ -576,6 +592,7 @@ public:
576 if (shader_fma) device_extensions.push_back(VK_KHR_SHADER_FMA_EXTENSION_NAME); 592 if (shader_fma) device_extensions.push_back(VK_KHR_SHADER_FMA_EXTENSION_NAME);
577#endif 593#endif
578 if (custom_border_color) device_extensions.push_back(custom_border_color_name); 594 if (custom_border_color) device_extensions.push_back(custom_border_color_name);
595 if (mesh_shader) device_extensions.push_back(VK_EXT_MESH_SHADER_EXTENSION_NAME);
579 device_info.enabledExtensionCount = std::uint32_t(device_extensions.size()); 596 device_info.enabledExtensionCount = std::uint32_t(device_extensions.size());
580 device_info.ppEnabledExtensionNames = device_extensions.data(); 597 device_info.ppEnabledExtensionNames = device_extensions.data();
581 result = instance_fn<PFN_vkCreateDevice>("vkCreateDevice")(physical, &device_info, nullptr, &device); 598 result = instance_fn<PFN_vkCreateDevice>("vkCreateDevice")(physical, &device_info, nullptr, &device);
diff --git a/runtime/test/vk_texture_test.cpp b/runtime/test/vk_texture_test.cpp
index 2435b6347..c6657508e 100644
--- a/runtime/test/vk_texture_test.cpp
+++ b/runtime/test/vk_texture_test.cpp
@@ -26,6 +26,7 @@
26#include "vk_device_pick.h" 26#include "vk_device_pick.h"
27#include "vk_shader_fma.h" 27#include "vk_shader_fma.h"
28#include "vk_pc_tail.h" 28#include "vk_pc_tail.h"
29#include "spirv_capability.h"
29 30
30#include <algorithm> 31#include <algorithm>
31#include <cmath> 32#include <cmath>
@@ -211,7 +212,6 @@ int main(int argc, char** argv) {
211 f12.pNext = &f11; 212 f12.pNext = &f11;
212 f12.bufferDeviceAddress = VK_TRUE; f12.runtimeDescriptorArray = VK_TRUE; f12.descriptorIndexing = VK_TRUE; 213 f12.bufferDeviceAddress = VK_TRUE; f12.runtimeDescriptorArray = VK_TRUE; f12.descriptorIndexing = VK_TRUE;
213 VkPhysicalDeviceFeatures2 f2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2}; f2.pNext = &f12; 214 VkPhysicalDeviceFeatures2 f2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2}; f2.pNext = &f12;
214 f2.features.shaderInt64 = VK_TRUE;
215 // Texel offsets: the limits the shader's Offset operands must stay inside, and the two optional features. 215 // Texel offsets: the limits the shader's Offset operands must stay inside, and the two optional features.
216 LI(vkEnumerateDeviceExtensionProperties); LI(vkGetPhysicalDeviceFeatures); 216 LI(vkEnumerateDeviceExtensionProperties); LI(vkGetPhysicalDeviceFeatures);
217 VkPhysicalDeviceProperties pdp; vkGetPhysicalDeviceProperties(pd, &pdp); 217 VkPhysicalDeviceProperties pdp; vkGetPhysicalDeviceProperties(pd, &pdp);
@@ -230,6 +230,14 @@ int main(int argc, char** argv) {
230 f2.features.shaderSampledImageArrayDynamicIndexing = dynamic_sampled; 230 f2.features.shaderSampledImageArrayDynamicIndexing = dynamic_sampled;
231 f2.features.shaderImageGatherExtended = have.shaderImageGatherExtended; 231 f2.features.shaderImageGatherExtended = have.shaderImageGatherExtended;
232 f2.features.shaderResourceMinLod = have.shaderResourceMinLod; 232 f2.features.shaderResourceMinLod = have.shaderResourceMinLod;
233 // shaderInt64 only when a stage has 64-bit integers: SHADER-423's address pairs need none (TEST-468).
234 const bool int64 = leonida::vk_test::needs_shader_int64(read_spv(vs_path.c_str())) ||
235 leonida::vk_test::needs_shader_int64(fragment_code);
236 if (int64 && !have.shaderInt64) {
237 std::printf("unsupported: shaderInt64 (a stage declares Int64)\n");
238 return 77;
239 }
240 f2.features.shaderInt64 = int64 ? VK_TRUE : VK_FALSE;
233 if (spirv_declares_capability(fragment_code.data(), fragment_code.size() * 4, 42) && 241 if (spirv_declares_capability(fragment_code.data(), fragment_code.size() * 4, 42) &&
234 !have.shaderResourceMinLod) { // 42 = MinLod 242 !have.shaderResourceMinLod) { // 42 = MinLod
235 std::printf("unsupported: shaderResourceMinLod (the shader clamps its LOD with MinLod)\n"); 243 std::printf("unsupported: shaderResourceMinLod (the shader clamps its LOD with MinLod)\n");
diff --git a/runtime/test/xgameruntime_store_test.cpp b/runtime/test/xgameruntime_store_test.cpp
index 6163d4360..732f864a0 100644
--- a/runtime/test/xgameruntime_store_test.cpp
+++ b/runtime/test/xgameruntime_store_test.cpp
@@ -3,6 +3,7 @@
3// arguments follow the public GDK reference. No game data; nothing online. 3// arguments follow the public GDK reference. No game data; nothing online.
4#include <windows.h> 4#include <windows.h>
5 5
6#include <cstddef>
6#include <cstdint> 7#include <cstdint>
7#include <cstdio> 8#include <cstdio>
8#include <cstring> 9#include <cstring>
@@ -30,7 +31,7 @@ void check(bool condition, const char* what) {
30} 31}
31 32
32using Handle = void*; 33using Handle = void*;
33struct GameLicense { // XStoreGameLicense with the UNVERIFIED sizes of xgameruntime_store.cpp 34struct GameLicense { // XStoreGameLicense with the measured sizes of xgameruntime_store.cpp
34 char skuStoreId[18]; 35 char skuStoreId[18];
35 bool isActive; 36 bool isActive;
36 bool isTrialOwnedByThisUser; 37 bool isTrialOwnedByThisUser;
@@ -40,6 +41,10 @@ struct GameLicense { // XStoreGameLicense with the UNVERIFIED sizes of xgameru
40 char trialUniqueId[64]; 41 char trialUniqueId[64];
41 time_t expirationDate; 42 time_t expirationDate;
42}; 43};
44static_assert(sizeof(GameLicense) == 104, "XStoreGameLicense is 104 bytes");
45static_assert(offsetof(GameLicense, isTrialOwnedByThisUser) == 0x13, "measured flag offset");
46static_assert(offsetof(GameLicense, trialUniqueId) == 0x1C, "measured trial-id offset");
47static_assert(offsetof(GameLicense, expirationDate) == 0x60, "measured expiration offset");
43struct CanAcquire { 48struct CanAcquire {
44 char licensableSku[5]; 49 char licensableSku[5];
45 uint32_t status; 50 uint32_t status;
@@ -110,9 +115,12 @@ int main() {
110 XAsyncBlock async{}; 115 XAsyncBlock async{};
111 GameLicense license; 116 GameLicense license;
112 std::memset(&license, 0xCD, sizeof(license)); 117 std::memset(&license, 0xCD, sizeof(license));
113 check(at<CtxAsync>(store, 28)(store, context, &async) == S_OK && finished(&async) && 118 check(at<CtxAsync>(store, 28)(store, context, &async) == S_OK && finished(&async),
114 at<LicenseResult>(store, 29)(store, &async, &license) == S_OK, 119 "XStoreQueryGameLicenseAsync completes");
115 "XStoreQueryGameLicenseAsync / Result"); 120 size_t license_size = 0;
121 check(XAsyncGetResultSize(&async, &license_size) == S_OK && license_size == 104,
122 "the game license result size is the measured 104 bytes");
123 check(at<LicenseResult>(store, 29)(store, &async, &license) == S_OK, "XStoreQueryGameLicenseResult");
116 check(license.isActive && !license.isTrial && !license.isTrialOwnedByThisUser && !license.isDiscLicense && 124 check(license.isActive && !license.isTrial && !license.isTrialOwnedByThisUser && !license.isDiscLicense &&
117 license.trialTimeRemainingInSeconds == 0 && license.trialUniqueId[0] == '\0' && 125 license.trialTimeRemainingInSeconds == 0 && license.trialUniqueId[0] == '\0' &&
118 std::strcmp(license.skuStoreId, "0010") == 0, 126 std::strcmp(license.skuStoreId, "0010") == 0,
diff --git a/runtime/test/xmem_test.cpp b/runtime/test/xmem_test.cpp
index aa9ba1d31..edc5fd33c 100644
--- a/runtime/test/xmem_test.cpp
+++ b/runtime/test/xmem_test.cpp
@@ -224,14 +224,35 @@ void test_virtual_alloc(XMemVirtualAllocFn virtual_alloc, XMemGetWriteWatchFn ge
224 check(large_page == nullptr && GetLastError() == ERROR_NOT_SUPPORTED, 224 check(large_page == nullptr && GetLastError() == ERROR_NOT_SUPPORTED,
225 "unsupported large-page allocation is rejected before host allocation"); 225 "unsupported large-page allocation is rejected before host allocation");
226 226
227 SetLastError(ERROR_SUCCESS); 227 // The retail executable's GPU pools: the attribute word is recorded, and the PAGE_GRAPHICS_* bits are dropped.
228 void* const attributed = virtual_alloc(nullptr, page_size, MEM_RESERVE | MEM_COMMIT, 1, PAGE_READWRITE); 228 MEMORY_BASIC_INFORMATION mbi{};
229 check(attributed == nullptr && GetLastError() == ERROR_NOT_SUPPORTED, 229 void* const pool = virtual_alloc(nullptr, SIZE_T{8} << 30, MEM_RESERVE | 0x20400000, 0x21, PAGE_READWRITE);
230 "nonzero XMem allocation attributes are rejected before host allocation"); 230 check(pool != nullptr, "attributes 0x21 with 64 KiB pages reserves 8 GiB");
231 if (pool) {
232 check(VirtualQuery(pool, &mbi, sizeof mbi) && mbi.State == MEM_RESERVE, "the 8 GiB pool is reserve-only");
233 check(VirtualFree(pool, 0, MEM_RELEASE), "release the 8 GiB pool");
234 }
235
236 void* const noaccess = virtual_alloc(nullptr, 0x10000, MEM_RESERVE | 0x20400000, 0x3, 0x801);
237 check(noaccess != nullptr, "attributes 0x3 with protect PAGE_GRAPHICS_NOACCESS|PAGE_NOACCESS succeeds");
238 if (noaccess) {
239 check(VirtualQuery(noaccess, &mbi, sizeof mbi) && mbi.AllocationProtect == PAGE_NOACCESS,
240 "protect 0x801 becomes PAGE_NOACCESS");
241 check(VirtualFree(noaccess, 0, MEM_RELEASE), "release the PAGE_NOACCESS pool");
242 }
243
244 void* const gpu = virtual_alloc(nullptr, 0x10000, MEM_RESERVE | MEM_COMMIT, 0x183, 0x22004);
245 check(gpu != nullptr, "attributes 0x183 with protect 0x22004 succeeds");
246 if (gpu) {
247 check(VirtualQuery(gpu, &mbi, sizeof mbi) && mbi.Protect == PAGE_READWRITE, "protect 0x22004 becomes PAGE_READWRITE");
248 static_cast<volatile uint8_t*>(gpu)[0] = 0x5a;
249 check(static_cast<volatile uint8_t*>(gpu)[0] == 0x5a, "the 0x183 allocation is writable");
250 check(VirtualFree(gpu, 0, MEM_RELEASE), "release the 0x183 allocation");
251 }
231} 252}
232 253
233// gta6rt --trace: one "xmem_attributes" event per distinct raw attribute word and API, none with the trace off. 254// gta6rt --trace: one "xmem_attributes" event per distinct raw attribute word and API, none with the trace off.
234void test_attribute_trace(XMemAllocFn alloc, XMemFreeFn free_mem) { 255void test_attribute_trace(XMemAllocFn alloc, XMemFreeFn free_mem, XMemVirtualAllocFn virtual_alloc) {
235 wchar_t temp[MAX_PATH]; 256 wchar_t temp[MAX_PATH];
236 GetTempPathW(MAX_PATH, temp); 257 GetTempPathW(MAX_PATH, temp);
237 const std::wstring path = 258 const std::wstring path =
@@ -250,6 +271,9 @@ void test_attribute_trace(XMemAllocFn alloc, XMemFreeFn free_mem) {
250 free_mem(b, 0x5e50000); // same word again: no second event 271 free_mem(b, 0x5e50000); // same word again: no second event
251 free_mem(c, 0x99); 272 free_mem(c, 0x99);
252 free_mem(nullptr, 0x77); // a free-only word is recorded too 273 free_mem(nullptr, 0x77); // a free-only word is recorded too
274 void* const v = virtual_alloc ? virtual_alloc(nullptr, 0x10000, MEM_RESERVE | MEM_COMMIT, 0x183, PAGE_READWRITE)
275 : nullptr;
276 if (v) VirtualFree(v, 0, MEM_RELEASE);
253 rt::startup_trace::close(); 277 rt::startup_trace::close();
254 278
255 std::ifstream in(path); 279 std::ifstream in(path);
@@ -261,14 +285,16 @@ void test_attribute_trace(XMemAllocFn alloc, XMemFreeFn free_mem) {
261 for (size_t at = log.find(needle); at != std::string::npos; at = log.find(needle, at + 1)) ++n; 285 for (size_t at = log.find(needle); at != std::string::npos; at = log.find(needle, at + 1)) ++n;
262 return n; 286 return n;
263 }; 287 };
264 check(count("\"kind\":\"xmem_attributes\"") == 5, "five events: two XMemAlloc words and three XMemFree words"); 288 check(count("\"kind\":\"xmem_attributes\"") == 6, "six events: two XMemAlloc words, three XMemFree words and one XMemVirtualAlloc word");
289 check(count("\"api\":\"XMemVirtualAlloc\",\"attributes\":\"0x183\",\"size\":65536") == 1,
290 "XMemVirtualAlloc 0x183 is recorded once, with its size");
265 check(count("\"api\":\"XMemAlloc\",\"attributes\":\"0x5e50000\",\"size\":4096") == 1, 291 check(count("\"api\":\"XMemAlloc\",\"attributes\":\"0x5e50000\",\"size\":4096") == 1,
266 "XMemAlloc 0x5e50000 is recorded once, with the size of the first call"); 292 "XMemAlloc 0x5e50000 is recorded once, with the size of the first call");
267 check(count("\"api\":\"XMemAlloc\",\"attributes\":\"0x99\",\"size\":16") == 1, "XMemAlloc 0x99 is recorded once"); 293 check(count("\"api\":\"XMemAlloc\",\"attributes\":\"0x99\",\"size\":16") == 1, "XMemAlloc 0x99 is recorded once");
268 check(count("\"api\":\"XMemFree\",\"attributes\":\"0x5e50000\"") == 1, "XMemFree 0x5e50000 is recorded once"); 294 check(count("\"api\":\"XMemFree\",\"attributes\":\"0x5e50000\"") == 1, "XMemFree 0x5e50000 is recorded once");
269 check(count("\"api\":\"XMemFree\",\"attributes\":\"0x77\"") == 1, "XMemFree 0x77 is recorded"); 295 check(count("\"api\":\"XMemFree\",\"attributes\":\"0x77\"") == 1, "XMemFree 0x77 is recorded");
270 check(count("\"attributes\":\"0x1111\"") == 0, "nothing was recorded while the trace was off"); 296 check(count("\"attributes\":\"0x1111\"") == 0, "nothing was recorded while the trace was off");
271 check(count("\"caller\":\"") == 5, "every event names its caller"); 297 check(count("\"caller\":\"") == 6, "every event names its caller");
272 DeleteFileW(path.c_str()); 298 DeleteFileW(path.c_str());
273} 299}
274 300
@@ -369,6 +395,14 @@ void test_title_virtual_alloc() {
369 check(alloc != nullptr, what); 395 check(alloc != nullptr, what);
370 if (!alloc) continue; 396 if (!alloc) continue;
371 397
398 void* const gfx = alloc(nullptr, 0x10000, MEM_RESERVE | MEM_COMMIT, 0x2004); // PAGE_GRAPHICS_READWRITE
399 check(gfx != nullptr, "title VirtualAlloc with protect 0x2004 succeeds");
400 if (gfx) {
401 MEMORY_BASIC_INFORMATION mbi{};
402 check(VirtualQuery(gfx, &mbi, sizeof mbi) && mbi.Protect == PAGE_READWRITE,
403 "protect 0x2004 commits PAGE_READWRITE");
404 VirtualFree(gfx, 0, MEM_RELEASE);
405 }
372 for (const DWORD bits : {kMemGraphics, kMemTitle, kMemGraphics | kMemTitle, DWORD{0}}) { 406 for (const DWORD bits : {kMemGraphics, kMemTitle, kMemGraphics | kMemTitle, DWORD{0}}) {
373 void* const p = alloc(nullptr, 0x10000, MEM_RESERVE | MEM_COMMIT | bits, PAGE_READWRITE); 407 void* const p = alloc(nullptr, 0x10000, MEM_RESERVE | MEM_COMMIT | bits, PAGE_READWRITE);
374 std::snprintf(what, sizeof what, "%s!VirtualAlloc with type bits %#lx returns memory", dll, 408 std::snprintf(what, sizeof what, "%s!VirtualAlloc with type bits %#lx returns memory", dll,
@@ -430,7 +464,7 @@ int main() {
430 if (virtual_alloc && get_write_watch && reset_write_watch) { 464 if (virtual_alloc && get_write_watch && reset_write_watch) {
431 test_virtual_alloc(virtual_alloc, get_write_watch, reset_write_watch); 465 test_virtual_alloc(virtual_alloc, get_write_watch, reset_write_watch);
432 } 466 }
433 test_attribute_trace(alloc, free_mem); 467 test_attribute_trace(alloc, free_mem, virtual_alloc);
434 if (transfer) { 468 if (transfer) {
435 test_transfer_memory(transfer); 469 test_transfer_memory(transfer);
436 test_transfer_trace(transfer); 470 test_transfer_trace(transfer);
diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp
index f115b6655..f0030116b 100644
--- a/runtime/test/xs_proxy_mock_test.cpp
+++ b/runtime/test/xs_proxy_mock_test.cpp
@@ -70,7 +70,7 @@ namespace xs = rt::d3d12_xs;
70 70
71// ---- Mocks ---- 71// ---- Mocks ----
72 72
73enum class Kind { device, queue, fence, resource, allocator }; 73enum class Kind { device, queue, fence, resource, allocator, command_list };
74 74
75constexpr unsigned kMockSlots = 128; 75constexpr unsigned kMockSlots = 128;
76constexpr std::uint64_t kFenceHandle = 0x1000, kResourceHandle = 0x2000; // the handles the mock device opens 76constexpr std::uint64_t kFenceHandle = 0x1000, kResourceHandle = 0x2000; // the handles the mock device opens
@@ -116,7 +116,23 @@ bool mock_has(const Mock* m, REFIID iid) {
116 if (IsEqualIID(iid, __uuidof(ID3D12Device))) return true; 116 if (IsEqualIID(iid, __uuidof(ID3D12Device))) return true;
117 const IID levels[] = {__uuidof(ID3D12Device1), __uuidof(ID3D12Device2), __uuidof(ID3D12Device3), 117 const IID levels[] = {__uuidof(ID3D12Device1), __uuidof(ID3D12Device2), __uuidof(ID3D12Device3),
118 __uuidof(ID3D12Device4), __uuidof(ID3D12Device5), __uuidof(ID3D12Device6), 118 __uuidof(ID3D12Device4), __uuidof(ID3D12Device5), __uuidof(ID3D12Device6),
119 __uuidof(ID3D12Device7), __uuidof(ID3D12Device8), __uuidof(ID3D12Device9)}; 119 __uuidof(ID3D12Device7), __uuidof(ID3D12Device8), __uuidof(ID3D12Device9),
120#ifdef __ID3D12Device10_INTERFACE_DEFINED__
121 __uuidof(ID3D12Device10),
122#endif
123#ifdef __ID3D12Device11_INTERFACE_DEFINED__
124 __uuidof(ID3D12Device11),
125#endif
126#ifdef __ID3D12Device12_INTERFACE_DEFINED__
127 __uuidof(ID3D12Device12),
128#endif
129#ifdef __ID3D12Device13_INTERFACE_DEFINED__
130 __uuidof(ID3D12Device13),
131#endif
132#ifdef __ID3D12Device14_INTERFACE_DEFINED__
133 __uuidof(ID3D12Device14),
134#endif
135 };
120 for (int i = 0; i < m->device_level && i < static_cast<int>(std::size(levels)); ++i) 136 for (int i = 0; i < m->device_level && i < static_cast<int>(std::size(levels)); ++i)
121 if (IsEqualIID(iid, levels[i])) return true; 137 if (IsEqualIID(iid, levels[i])) return true;
122 return false; 138 return false;
@@ -127,6 +143,9 @@ bool mock_has(const Mock* m, REFIID iid) {
127 case Kind::fence: 143 case Kind::fence:
128 return IsEqualIID(iid, __uuidof(ID3D12Fence)) || (m->fence1 && IsEqualIID(iid, __uuidof(ID3D12Fence1))); 144 return IsEqualIID(iid, __uuidof(ID3D12Fence)) || (m->fence1 && IsEqualIID(iid, __uuidof(ID3D12Fence1)));
129 case Kind::resource: return IsEqualIID(iid, __uuidof(ID3D12Resource)); 145 case Kind::resource: return IsEqualIID(iid, __uuidof(ID3D12Resource));
146 case Kind::command_list:
147 return IsEqualIID(iid, __uuidof(ID3D12CommandList)) ||
148 IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList));
130 case Kind::allocator: 149 case Kind::allocator:
131 return IsEqualIID(iid, __uuidof(ID3D12CommandAllocator)) || 150 return IsEqualIID(iid, __uuidof(ID3D12CommandAllocator)) ||
132 (m->allocator_tag && IsEqualIID(iid, xs::kLeonidaCommandAllocatorTag)); 151 (m->allocator_tag && IsEqualIID(iid, xs::kLeonidaCommandAllocatorTag));
@@ -208,6 +227,25 @@ std::uint64_t WINAPI mock_slot(Mock* self, std::uint64_t a1, std::uint64_t a2, s
208 } 227 }
209} 228}
210 229
230// PC ID3D12Device::CreateCommandList takes six words after `this`, one more than the generic mock thunk declares, so
231// it gets its own entry in the table: the out pointer is a6 (first stack argument on x64) and has to be written.
232HRESULT WINAPI mock_create_command_list(Mock* self, std::uint64_t node_mask, std::uint64_t type,
233 std::uint64_t allocator, std::uint64_t initial_state, const IID* riid,
234 void** out) {
235 ++self->calls[12];
236 self->args[12][0] = node_mask;
237 self->args[12][1] = type;
238 self->args[12][2] = allocator;
239 self->args[12][3] = initial_state;
240 self->args[12][4] = reinterpret_cast<std::uint64_t>(riid);
241 if (!out) return S_FALSE;
242 *out = nullptr;
243 if (self->create_null || FAILED(self->create_result)) return self->create_result;
244 Mock* child = new_mock(Kind::command_list);
245 self->last_child = child;
246 return mock_query(child, riid, out);
247}
248
211template <std::size_t... I> 249template <std::size_t... I>
212void fill_mock_vtable(void** vtable, std::index_sequence<I...>) { 250void fill_mock_vtable(void** vtable, std::index_sequence<I...>) {
213 ((vtable[I] = reinterpret_cast<void*>(&mock_slot<static_cast<unsigned>(I)>)), ...); 251 ((vtable[I] = reinterpret_cast<void*>(&mock_slot<static_cast<unsigned>(I)>)), ...);
@@ -217,6 +255,7 @@ void** mock_vtable() {
217 static void* table[kMockSlots]; 255 static void* table[kMockSlots];
218 static const bool filled = [] { 256 static const bool filled = [] {
219 fill_mock_vtable(table, std::make_index_sequence<kMockSlots>{}); 257 fill_mock_vtable(table, std::make_index_sequence<kMockSlots>{});
258 table[12] = reinterpret_cast<void*>(&mock_create_command_list);
220 return true; 259 return true;
221 }(); 260 }();
222 (void)filled; 261 (void)filled;
@@ -648,7 +687,141 @@ int check_allocators() {
648 return 0; 687 return 0;
649} 688}
650 689
651// ---- 7. The refused tail and the guard region ---- 690// ---- 7. Xbox device slots from the public HLE (48, 73, 78, 79, 80) ----
691//
692// A device that answers ID3D12Device11 (80 PC slots) is the Vulkan layer's shape: slots 78/79 are inside its table
693// (CreateReservedResource2/CreateSampler2 there) and 80 is just past it. None of the five may reach the mock's own
694// slot: the mock's call counter proves the route, and the returned token/queue/list proves the handler ran.
695int check_xbox_slots() {
696#ifdef __ID3D12Device11_INTERFACE_DEFINED__
697 Mock* mock = nullptr;
698 void* device = make_device(mock, 11, true);
699 EXPECT(device && xs::device_proxy_slot_count(device) == 80);
700 xs::reset_device_proxy_stats();
701
702 // 78 SetFrameIntervalX(output, interval_us, latency, flags): S_OK, not forwarded to PC slot 78.
703 EXPECT(hr_of(raw(device, 78, 0, 16667, 1, 0)) == S_OK);
704 EXPECT(mock->calls[78] == 0 && xs::device_slot_hits(78) == 1);
705 // 79 ScheduleFrameEventX(event, offset_us, pEvent, flags): S_OK, not forwarded to PC slot 79.
706 EXPECT(hr_of(raw(device, 79, 0, 0, 0x1234, 0)) == S_OK);
707 EXPECT(mock->calls[79] == 0 && xs::device_slot_hits(79) == 1);
708
709 // 80 WaitFrameEventX(event, timeout_ms, pEvent, flags, &token): a fresh non-zero token each time; a null token
710 // pointer is E_POINTER; the call never blocks (this test would hang otherwise).
711 std::uint64_t token = 0, token2 = 0;
712 EXPECT(hr_of(raw(device, 80, 0, 0xffffffffu, 0, 0, word(&token))) == S_OK && token != 0);
713 EXPECT(hr_of(raw(device, 80, 0, 0, 0, 0, word(&token2))) == S_OK && token2 != 0 && token2 != token);
714 EXPECT(hr_of(raw(device, 80, 0, 0, 0, 0, 0)) == E_POINTER);
715 EXPECT(mock->calls[80] == 0 && xs::device_slot_hits(80) == 3);
716
717 // 48 CreateCommandQueueX(desc, riid, out): the queue proxy, created through the PC slot 8 path.
718 void* queue = nullptr;
719 EXPECT(hr_of(raw(device, 48, word(&kQueueDesc), word(&kQueueIid), word(&queue))) == S_OK);
720 EXPECT(xs::is_queue_proxy(queue) && mock->calls[48] == 0 && mock->calls[8] == 1);
721 EXPECT(mock->args[8][0] == word(&kQueueDesc));
722
723 // 73 CreateCommandListX(desc, allocator, initialState, riid, out): the type is desc's first word, the allocator
724 // proxy is unwrapped, the node mask is 0 and the PC six-argument CreateCommandList (slot 12) is reached.
725 const IID allocator_iid = __uuidof(ID3D12CommandAllocator);
726 void* allocator = nullptr;
727 EXPECT(hr_of(raw(device, 9, 0, word(&allocator_iid), word(&allocator))) == S_OK);
728 EXPECT(xs::is_allocator_proxy(allocator));
729 Mock* const real_allocator = reinterpret_cast<Mock*>(xs::allocator_proxy_real_allocator(allocator));
730 struct XboxCommandListDesc {
731 std::uint32_t type;
732 std::uint32_t node_mask;
733 std::uint64_t reserved[2];
734 } desc{};
735 desc.type = D3D12_COMMAND_LIST_TYPE_DIRECT;
736 desc.node_mask = 7; // ignored by the console call, as the HLE does
737 const IID list_iid = __uuidof(ID3D12GraphicsCommandList);
738 void* list = nullptr;
739 EXPECT(hr_of(raw(device, 73, word(&desc), word(allocator), 0, word(&list_iid), word(&list))) == S_OK);
740 EXPECT(list && reinterpret_cast<Mock*>(list)->kind == Kind::command_list);
741 EXPECT(mock->calls[73] == 0 && mock->calls[12] == 1 && xs::device_slot_hits(73) == 1);
742 EXPECT(mock->args[12][0] == 0 && mock->args[12][1] == D3D12_COMMAND_LIST_TYPE_DIRECT);
743 EXPECT(mock->args[12][2] == word(real_allocator) && mock->args[12][3] == 0);
744 EXPECT(mock->args[12][4] == word(&list_iid));
745
746 // Release the list before the refusal calls below: the COM convention (and the handler) nulls the caller's
747 // output on failure, so an invalid call would clear this pointer.
748 EXPECT(release(list) == 0);
749
750 // Missing description, allocator or output: E_INVALIDARG/E_POINTER before the real device is called.
751 EXPECT(hr_of(raw(device, 73, 0, word(allocator), 0, word(&list_iid), word(&list))) == E_INVALIDARG);
752 EXPECT(hr_of(raw(device, 73, word(&desc), 0, 0, word(&list_iid), word(&list))) == E_INVALIDARG);
753 EXPECT(hr_of(raw(device, 73, word(&desc), word(allocator), 0, word(&list_iid), 0)) == E_POINTER);
754
755 EXPECT(xs::device_slot_overridden(48) && xs::device_slot_overridden(73) && xs::device_slot_overridden(78) &&
756 xs::device_slot_overridden(79) && xs::device_slot_overridden(80));
757
758 EXPECT(release(allocator) == 0 && real_allocator->refs == 0);
759 EXPECT(release(queue) == 0);
760 EXPECT(release(device) == 0 && mock->refs == 0);
761 std::printf("%s: device slots 48/73/78/79/80 route to a queue, a list and frame-event tokens without reaching "
762 "the mock's own PC slots\n", g_label);
763 return 0;
764#else
765 std::printf("%s: ID3D12Device11 is not in this SDK; Xbox slot 80's beyond-table case is not built\n", g_label);
766 return 0;
767#endif
768}
769
770// ---- 8. Environment overrides for the Xbox device slots (one process each, read once) ----
771
772int run_env_slots(bool valid) {
773 const char* frame_interval = valid ? "96" : "2";
774 const char* schedule_event = valid ? "97" : "2";
775 const char* wait_event = valid ? "98" : "2";
776 const char* queue_x = valid ? "99" : "2";
777 const char* list_x = valid ? "100" : "2";
778 EXPECT(SetEnvironmentVariableA("LEONIDA_XS_FRAME_INTERVAL_SLOT", frame_interval) != FALSE);
779 EXPECT(SetEnvironmentVariableA("LEONIDA_XS_SCHEDULE_EVENT_SLOT", schedule_event) != FALSE);
780 EXPECT(SetEnvironmentVariableA("LEONIDA_XS_WAIT_EVENT_SLOT", wait_event) != FALSE);
781 EXPECT(SetEnvironmentVariableA("LEONIDA_XS_QUEUE_X_SLOT", queue_x) != FALSE);
782 EXPECT(SetEnvironmentVariableA("LEONIDA_XS_LIST_X_SLOT", list_x) != FALSE);
783
784 Mock* mock = nullptr;
785 void* device = make_device(mock, 11, true);
786 EXPECT(device);
787 xs::reset_device_proxy_stats();
788 std::uint64_t token = 0;
789 if (valid) {
790 // Every route moved: the new slot is handled, the default slot is forwarded to the mock.
791 EXPECT(hr_of(raw(device, 96, 0, 16667, 1, 0)) == S_OK && mock->calls[96] == 0);
792 EXPECT(hr_of(raw(device, 97, 0, 0, 0, 0)) == S_OK && mock->calls[97] == 0);
793 EXPECT(hr_of(raw(device, 98, 0, 0, 0, 0, word(&token))) == S_OK && token && mock->calls[98] == 0);
794 void* queue = nullptr;
795 EXPECT(hr_of(raw(device, 99, word(&kQueueDesc), word(&kQueueIid), word(&queue))) == S_OK);
796 EXPECT(xs::is_queue_proxy(queue) && mock->calls[99] == 0);
797 const IID allocator_iid = __uuidof(ID3D12CommandAllocator);
798 void* allocator = nullptr;
799 EXPECT(hr_of(raw(device, 9, 0, word(&allocator_iid), word(&allocator))) == S_OK);
800 struct {
801 std::uint32_t type, node_mask;
802 } desc{static_cast<std::uint32_t>(D3D12_COMMAND_LIST_TYPE_DIRECT), 0};
803 const IID list_iid = __uuidof(ID3D12GraphicsCommandList);
804 void* list = nullptr;
805 EXPECT(hr_of(raw(device, 100, word(&desc), word(allocator), 0, word(&list_iid), word(&list))) == S_OK);
806 EXPECT(hr_of(raw(device, 78, 0, 16667, 1, 0)) == S_OK && mock->calls[78] == 1);
807 EXPECT(release(list) == 0);
808 EXPECT(release(allocator) == 0);
809 EXPECT(release(queue) == 0);
810 } else {
811 // Values outside 3..127 are ignored: the five defaults still answer, and a PC slot that is not a default is
812 // forwarded unchanged.
813 EXPECT(hr_of(raw(device, 78, 0, 16667, 1, 0)) == S_OK && mock->calls[78] == 0);
814 EXPECT(hr_of(raw(device, 79, 0, 0, 0, 0)) == S_OK && mock->calls[79] == 0);
815 EXPECT(hr_of(raw(device, 80, 0, 0, 0, 0, word(&token))) == S_OK && token && mock->calls[80] == 0);
816 EXPECT(hr_of(raw(device, 70)) == S_OK && mock->calls[70] == 1); // not an Xbox slot: forwarded
817 }
818 EXPECT(release(device) == 0 && mock->refs == 0);
819 std::printf("%s: environment slot overrides %s\n", g_label,
820 valid ? "move all five routes" : "outside 3..127 are ignored");
821 return 0;
822}
823
824// ---- 9. The refused tail and the guard region ----
652 825
653int check_tail(bool want_guarded) { 826int check_tail(bool want_guarded) {
654 Mock* mock = nullptr; 827 Mock* mock = nullptr;
@@ -768,10 +941,14 @@ static void no_dialogs() {
768int main(int argc, char** argv) { 941int main(int argc, char** argv) {
769 no_dialogs(); 942 no_dialogs();
770 std::setvbuf(stdout, nullptr, _IONBF, 0); 943 std::setvbuf(stdout, nullptr, _IONBF, 0);
771 if (argc == 2) return run_fault_mode(argv[1]); 944 if (argc == 2) {
945 if (std::strcmp(argv[1], "--env-slots") == 0) return run_env_slots(true);
946 if (std::strcmp(argv[1], "--env-slots-invalid") == 0) return run_env_slots(false);
947 return run_fault_mode(argv[1]);
948 }
772 if (argc != 1) return 2; 949 if (argc != 1) return 2;
773 if (check_tail(true) || check_levels() || check_fence1() || check_create_failures() || check_open_shared() || 950 if (check_tail(true) || check_levels() || check_fence1() || check_create_failures() || check_open_shared() ||
774 check_alloc_failures() || check_allocators()) 951 check_alloc_failures() || check_allocators() || check_xbox_slots())
775 return 1; 952 return 1;
776 std::printf("xs_proxy_mock_test: PASS (%d allocations refused on purpose)\n", g_failed_news); 953 std::printf("xs_proxy_mock_test: PASS (%d allocations refused on purpose)\n", g_failed_news);
777 return 0; 954 return 0;